/// <summary> /// Attempt to load dictionary from provided directory, first trying coredict.mem, failing back on coredict.dct /// </summary> /// <param name="dctFileRoot">path to dictionary directory</param> public virtual void Load(string dctFileRoot) { string dctFilePath = System.IO.Path.Combine(dctFileRoot, "coredict.dct"); FileInfo serialObj = new FileInfo(System.IO.Path.Combine(dctFileRoot, "coredict.mem")); if (serialObj.Exists && LoadFromObj(serialObj)) { } else { try { wordIndexTable = new short[PRIME_INDEX_LENGTH]; charIndexTable = new char[PRIME_INDEX_LENGTH]; for (int i = 0; i < PRIME_INDEX_LENGTH; i++) { charIndexTable[i] = (char)0; wordIndexTable[i] = -1; } wordItem_charArrayTable = new char[GB2312_CHAR_NUM][][]; wordItem_frequencyTable = new int[GB2312_CHAR_NUM][]; // int total = LoadMainDataFromFile(dctFilePath); ExpandDelimiterData(); MergeSameWords(); SortEachItems(); // log.info("load dictionary: " + dctFilePath + " total:" + total); } catch (Exception e) when(e.IsIOException()) { throw RuntimeException.Create(e); // LUCENENET: Passing class so we can wrap it } SaveToObj(serialObj); } }
private static string ExtractExecutableName(string cmdLine, out int argsPosition) { bool inQuotes = false; int startIdx = 0; int i; for (i = 0; i < cmdLine.Length; i++) { var symb = cmdLine[i]; if (symb == '\"') { if (inQuotes) { argsPosition = i + 1; return(cmdLine.Substring(startIdx, i - startIdx)); } inQuotes = true; startIdx = i + 1; } else if (symb == ' ' && !inQuotes) { argsPosition = i + 1; return(cmdLine.Substring(startIdx, i - startIdx)); } } if (inQuotes) { throw RuntimeException.InvalidArgumentValue(); } argsPosition = i + 1; return(cmdLine.Substring(startIdx, i - startIdx)); }
public ArrayImpl Get(bool deleteMessages, ArrayImpl ids, bool markAsRead) { if (markAsRead != true) { throw RuntimeException.InvalidArgumentValue(); // TODO: Внятное сообщение } var result = new ArrayImpl(); var processedMessages = GetMessagesList(ids); foreach (var i in processedMessages) { var mimeMessage = client.GetMessage(i); var iMessage = new InternetMailMessage(mimeMessage, client.GetMessageUid(i)); result.Add(iMessage); } if (deleteMessages && processedMessages.Count > 0) { client.DeleteMessages(processedMessages); Relogon(); } return(result); }
public override void Finish(FieldInfos fis, int numDocs) { if (numBufferedDocs > 0) { Flush(); } else { if (Debugging.AssertsEnabled) { Debugging.Assert(bufferedDocs.Length == 0); } } if (docBase != numDocs) { throw RuntimeException.Create("Wrote " + docBase + " docs, finish called with numDocs=" + numDocs); } indexWriter.Finish(numDocs, fieldsStream.Position); // LUCENENET specific: Renamed from getFilePointer() to match FileStream CodecUtil.WriteFooter(fieldsStream); if (Debugging.AssertsEnabled) { Debugging.Assert(bufferedDocs.Length == 0); } }
private Collection <PSObject> GetLocalDCMembership(string localDcDn, string pdcHostName) { Collection <PSObject> pSObjects; string[] strArrays = new string[5]; strArrays[0] = "Get-ADPrincipalGroupMembership -Identity \""; strArrays[1] = localDcDn; strArrays[2] = "\" -Server \""; strArrays[3] = pdcHostName; strArrays[4] = "\""; string str = string.Concat(strArrays); Collection <PSObject> pSObjects1 = null; try { pSObjects1 = base.InvokeCommand.InvokeScript(str); goto Label0; } catch (RuntimeException runtimeException1) { RuntimeException runtimeException = runtimeException1; base.WriteError(new ErrorRecord(runtimeException, "0", ErrorCategory.ReadError, str)); pSObjects = null; } return(pSObjects); Label0: if (pSObjects1 == null || pSObjects1.Count == 0) { return(null); } else { return(pSObjects1); } }
public void ReplaceLine(int number, string newLine) { if (number > _lines.Count) { return; } if (number < 1) { throw RuntimeException.InvalidArgumentValue(); } var newLines = ParseInputString(newLine); if (newLines.Count == 1) { _lines[number - 1] = newLines[0]; } else { _lines[number - 1] = newLines[0]; _lines.InsertRange(number, newLines.Skip(1)); } }
public void Open(IValue filenameOrStream, string password = null, FileNamesEncodingInZipFile encoding = FileNamesEncodingInZipFile.Auto) { // f**k non-russian encodings on non-ascii files ZipFile.DefaultEncoding = Encoding.GetEncoding(866); if (filenameOrStream.DataType == DataType.String) { _zip = ZipFile.Read(filenameOrStream.AsString(), new ReadOptions { Encoding = ChooseEncoding(encoding) }); } else if (filenameOrStream.AsObject() is IStreamWrapper stream) { _zip = ZipFile.Read(stream.GetUnderlyingStream(), new ReadOptions { Encoding = ChooseEncoding(encoding) }); } else { throw RuntimeException.InvalidArgumentType(nameof(filenameOrStream)); } _zip.Password = password; }
private void SetMinOccurs(XmlSchemaParticle particle, IValue minOccurs) { if (minOccurs.DataType == DataType.Undefined) { particle.MinOccursString = null; } else if (minOccurs.DataType == DataType.Number) { decimal number = minOccurs.AsNumber(); if (number >= 0) { particle.MinOccurs = number; } else { throw RuntimeException.InvalidArgumentValue(); } } else { throw RuntimeException.InvalidArgumentType(); } }
private void RemoveFromJobDefinition(IEnumerable <ScheduledJobDefinition> definitions) { foreach (ScheduledJobDefinition definition in definitions) { List <Int32> notFoundIds = new List <int>(); try { notFoundIds = definition.RemoveTriggers(_triggerIds, true); } catch (ScheduledJobException e) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantRemoveTriggersFromDefinition, definition.Name); Exception reason = new RuntimeException(msg, e); ErrorRecord errorRecord = new ErrorRecord(reason, "CantRemoveTriggersFromScheduledJobDefinition", ErrorCategory.InvalidOperation, definition); WriteError(errorRecord); } // Report not found errors. foreach (Int32 idNotFound in notFoundIds) { WriteTriggerNotFoundError(idNotFound, definition.Name, definition); } } }
public virtual void AddValue(int docID, BytesRef value) { if (docID < addedValues) { throw new ArgumentOutOfRangeException(nameof(docID), "DocValuesField \"" + fieldInfo.Name + "\" appears more than once in this document (only one value is allowed per field)"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention) } if (value is null) { throw new ArgumentNullException("field=\"" + fieldInfo.Name + "\": null value not allowed"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentNullException (.NET convention) } if (value.Length > MAX_LENGTH) { throw new ArgumentException("DocValuesField \"" + fieldInfo.Name + "\" is too large, must be <= " + MAX_LENGTH); } // Fill in any holes: while (addedValues < docID) { addedValues++; lengths.Add(0); } addedValues++; lengths.Add(value.Length); try { bytesOut.WriteBytes(value.Bytes, value.Offset, value.Length); } catch (Exception ioe) when(ioe.IsIOException()) { // Should never happen! throw RuntimeException.Create(ioe); } docsWithField = FixedBitSet.EnsureCapacity(docsWithField, docID); docsWithField.Set(docID); UpdateBytesUsed(); }
internal static void ThrowExceptionOnError( string errorId, ConcurrentBag <string> errors, Category category) { if (errors.IsEmpty) { return; } StringBuilder allErrors = new StringBuilder(); allErrors.Append('\n'); foreach (string error in errors) { allErrors.Append(error); allErrors.Append('\n'); } string message = string.Empty; if (category == Category.Types) { message = StringUtil.Format(ExtendedTypeSystem.TypesXmlError, allErrors.ToString()); } else if (category == Category.Formats) { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, allErrors.ToString()); } RuntimeException ex = new RuntimeException(message); ex.SetErrorId(errorId); throw ex; }
private static Task <int> Execute( CommandTree leaf, CommandTree tree, CommandContext context, ITypeResolver resolver) { // Create the command and the settings. var settings = leaf.CreateSettings(resolver); // Bind the command tree against the settings. CommandBinder.Bind(tree, ref settings, resolver); // Create and validate the command. var command = leaf.CreateCommand(resolver); var validationResult = command.Validate(context, settings); if (!validationResult.Successful) { throw RuntimeException.ValidationFailed(validationResult); } // Execute the command. return(command.Execute(context, settings)); }
public override void Run() { try { long totHits = 0; long totSearch = 0; long stopAt = (J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond) + outerInstance.RUN_TIME_MSEC; // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results while (J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond < stopAt && !failed) // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results { s.Search(new TermQuery(new Term("body", "aaa")), col); totHits += col.TotalHits; s.Search(new TermQuery(new Term("body", "bbb")), col); totHits += col.TotalHits; totSearch++; } Assert.IsTrue(totSearch > 0 && totHits > 0); netSearch.AddAndGet(totSearch); } catch (Exception exc) when(exc.IsException()) { failed.Value = (true); throw RuntimeException.Create(exc); } }
public void Move(IValue item, int offset) { int index_source = IndexByValue(item); int index_dest = index_source + offset; if (index_dest < 0 || index_dest >= _items.Count()) { throw RuntimeException.InvalidNthArgumentValue(2); } ValueListItem itemObject = _items[index_source]; if (index_source < index_dest) { _items.Insert(index_dest + 1, itemObject); _items.RemoveAt(index_source); } else { _items.RemoveAt(index_source); _items.Insert(index_dest, itemObject); } }
private static IValue[] GetArgsToPass(ArrayImpl arguments, MethodInfo methInfo) { var argsToPass = arguments == null ? new IValue[0] : arguments.ToArray(); if (methInfo.ArgCount < argsToPass.Length) { throw RuntimeException.TooManyArgumentsPassed(); } if (methInfo.ArgCount > argsToPass.Length) { throw RuntimeException.TooLittleArgumentsPassed(); } for (int i = 0; i < argsToPass.Length; i++) { if (!methInfo.Params[i].IsByValue) { argsToPass[i] = Variable.Create(argsToPass[i]); } } return(argsToPass); }
/// <summary> /// Lookup suggestions to <paramref name="key"/>. /// </summary> /// <param name="key"> /// The prefix to which suggestions should be sought. </param> /// <param name="num"> /// At most this number of suggestions will be returned. </param> /// <returns> Returns the suggestions, sorted by their approximated weight first /// (decreasing) and then alphabetically (UTF-8 codepoint order). </returns> public virtual IList <Completion> DoLookup(string key, int num) { // LUCENENET: Added guard clause for null if (key is null) { throw new ArgumentNullException(nameof(key)); } if (key.Length == 0 || automaton is null) { return(EMPTY_RESULT); } try { var keyUtf8 = new BytesRef(key); if (!higherWeightsFirst && rootArcs.Length > 1) { // We could emit a warning here (?). An optimal strategy for // alphabetically sorted // suggestions would be to add them with a constant weight -- this saves // unnecessary // traversals and sorting. return(LookupSortedAlphabetically(keyUtf8, num)); } else { return(LookupSortedByWeight(keyUtf8, num, false)); } } catch (Exception e) when(e.IsIOException()) { // Should never happen, but anyway. throw RuntimeException.Create(e); } }
public static ArrayImpl Constructor(IValue[] dimensions) { if (dimensions.Length == 1 && dimensions[0].GetRawValue() is FixedArrayImpl) { return(Constructor(dimensions[0])); } ArrayImpl cloneable = null; for (int dim = dimensions.Length - 1; dim >= 0; dim--) { if (dimensions[dim] == null) { throw RuntimeException.InvalidNthArgumentType(dim + 1); } int bound = (int)dimensions[dim].AsNumber(); if (bound <= 0) { throw RuntimeException.InvalidNthArgumentValue(dim + 1); } var newInst = new ArrayImpl(); FillArray(newInst, bound); if (cloneable != null) { for (int i = 0; i < bound; i++) { newInst._values[i] = CloneArray(cloneable); } } cloneable = newInst; } return(cloneable); }
public virtual int Compare(SegmentCommitInfo o1, SegmentCommitInfo o2) { try { long sz1 = outerInstance.Size(o1); long sz2 = outerInstance.Size(o2); if (sz1 > sz2) { return(-1); } else if (sz2 > sz1) { return(1); } else { return(o1.Info.Name.CompareToOrdinal(o2.Info.Name)); } } catch (Exception ioe) when(ioe.IsIOException()) { throw RuntimeException.Create(ioe); } }
private void WriteDisconnectFailed(Exception e = null) { if (_writeStream.ObjectWriter.IsOpen) { string msg; if (e != null && !string.IsNullOrWhiteSpace(e.Message)) { msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailedWithReason, _remoteSession.InstanceId, e.Message); } else { msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailed, _remoteSession.InstanceId); } Exception reason = new RuntimeException(msg, e); ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionDisconnectFailed", ErrorCategory.InvalidOperation, _remoteSession); Action <Cmdlet> errorWriter = delegate(Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; _writeStream.ObjectWriter.Write(errorWriter); } }
public override void Run() { try { long totHits = 0; long totSearch = 0; long stopAt = Environment.TickCount + outerInstance.RUN_TIME_MSEC; while (Environment.TickCount < stopAt && !failed) { s.Search(new TermQuery(new Term("body", "aaa")), col); totHits += col.TotalHits; s.Search(new TermQuery(new Term("body", "bbb")), col); totHits += col.TotalHits; totSearch++; } Assert.IsTrue(totSearch > 0 && totHits > 0); netSearch.AddAndGet(totSearch); } catch (Exception exc) when(exc.IsException()) { failed.Value = (true); throw RuntimeException.Create(exc); } }
private void WriteConnectFailed( Exception e, PSSession session) { if (_writeStream.ObjectWriter.IsOpen) { string FQEID = "PSSessionConnectFailed"; Exception reason; if (e != null && !string.IsNullOrEmpty(e.Message)) { // Update fully qualified error Id if we have a transport error. PSRemotingTransportException transportException = e as PSRemotingTransportException; if (transportException != null) { FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(transportException.ErrorCode, FQEID); } reason = new RuntimeException( StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailedWithMessage, session.Name, e.Message), e); } else { reason = new RuntimeException( StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailed, session.Name, session.Runspace.RunspaceStateInfo.State.ToString()), null); } ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, null); Action <Cmdlet> errorWriter = delegate(Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; _writeStream.ObjectWriter.Write(errorWriter); } }
public override void Run() { try { int docCount = 0; while (J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond < stopTime) // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results { Document doc = new Document(); doc.Add(newStringField("dc", "" + docCount, Field.Store.YES)); doc.Add(newTextField("field", "here is some text", Field.Store.YES)); w.AddDocument(doc); if (docCount % 13 == 0) { w.Commit(); } docCount++; } } catch (Exception e) when(e.IsException()) { throw RuntimeException.Create(e); } }
/// <summary> /// Return 'key' string. 'key' is the field name of the <see cref="Query"/>. /// If not fieldMatch, 'key' will be null. /// </summary> private string GetKey(Query query) { if (!fieldMatch) { return(null); } if (query is TermQuery termQuery) { return(termQuery.Term.Field); } else if (query is PhraseQuery pq) { Term[] terms = pq.GetTerms(); return(terms[0].Field); } else if (query is MultiTermQuery multiTermQuery) { return(multiTermQuery.Field); } else { throw RuntimeException.Create("query \"" + query.ToString() + "\" must be flatten first."); } }
internal PSSession QueryForSession(PSSession session) { Collection <WSManConnectionInfo> wsManConnectionInfos = new Collection <WSManConnectionInfo>(); wsManConnectionInfos.Add(session.Runspace.ConnectionInfo as WSManConnectionInfo); Exception ex = null; Collection <PSSession> sessions = null; try { sessions = _queryRunspaces.GetDisconnectedSessions(wsManConnectionInfos, _host, _writeStream, null, 0, SessionFilterState.Disconnected, new Guid[] { session.InstanceId }, null, null); } catch (RuntimeException e) { ex = e; } if (ex != null) { WriteConnectFailed(ex, session); return(null); } if (sessions.Count != 1) { ex = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.CannotFindSessionForConnect, session.Name, session.ComputerName)); WriteConnectFailed(ex, session); return(null); } return(sessions[0]); }
public void AddModule(string file, string moduleName) { if (!Utils.IsValidIdentifier(moduleName)) { throw RuntimeException.InvalidArgumentValue(); } _delayLoadedScripts.Add(new DelayLoadedScriptData() { path = file, identifier = moduleName, asClass = false }); try { _env.InjectGlobalProperty(null, moduleName, true); } catch (InvalidOperationException e) { // символ уже определен throw new RuntimeException(String.Format("Невозможно загрузить модуль {0}. Такой символ уже определен.", moduleName), e); } }
/// <summary> /// Builds the <see cref="NormalizeCharMap"/>; call this once you /// are done calling <see cref="Add"/>. /// </summary> public virtual NormalizeCharMap Build() { FST <CharsRef> map; try { Outputs <CharsRef> outputs = CharSequenceOutputs.Singleton; Builder <CharsRef> builder = new Builder <CharsRef>(FST.INPUT_TYPE.BYTE2, outputs); Int32sRef scratch = new Int32sRef(); foreach (var ent in pendingPairs) { builder.Add(Lucene.Net.Util.Fst.Util.ToUTF16(ent.Key, scratch), new CharsRef(ent.Value)); } map = builder.Finish(); pendingPairs.Clear(); } catch (Exception ioe) when(ioe.IsIOException()) { // Bogus FST IOExceptions!! (will never happen) throw RuntimeException.Create("Should never happen", ioe); } return(new NormalizeCharMap(map)); }
// TODO: change FieldComparer.setScorer to throw IOException and remove this try-catch public override void SetScorer(Scorer scorer) { base.SetScorer(scorer); // TODO: might be cleaner to lazy-init 'source' and set scorer after? if (Debugging.AssertsEnabled) { Debugging.Assert(readerContext != null); } try { var context = new Dictionary <string, object>(); if (Debugging.AssertsEnabled) { Debugging.Assert(scorer != null); } context["scorer"] = scorer; scores = source.GetValues(context, readerContext); } catch (Exception e) when(e.IsIOException()) { throw RuntimeException.Create(e); } }
private EncryptionAlgorithm MakeZipEncryption(SelfAwareEnumValue <ZipEncryptionMethodEnum> encryptionMethod) { if (encryptionMethod == null) { return(EncryptionAlgorithm.PkzipWeak); } var enumOwner = (ZipEncryptionMethodEnum)encryptionMethod.Owner; if (encryptionMethod == enumOwner.Zip20) { return(EncryptionAlgorithm.PkzipWeak); } if (encryptionMethod == enumOwner.Aes128) { return(EncryptionAlgorithm.WinZipAes128); } if (encryptionMethod == enumOwner.Aes256) { return(EncryptionAlgorithm.WinZipAes256); } throw RuntimeException.InvalidArgumentValue(); }
private CompressionLevel MakeZipCompressionLevel(SelfAwareEnumValue <ZipCompressionLevelEnum> compressionLevel) { if (compressionLevel == null) { return(CompressionLevel.Default); } var owner = (ZipCompressionLevelEnum)compressionLevel.Owner; if (compressionLevel == owner.Minimal) { return(CompressionLevel.BestSpeed); } if (compressionLevel == owner.Optimal) { return(CompressionLevel.Default); } if (compressionLevel == owner.Maximal) { return(CompressionLevel.BestCompression); } throw RuntimeException.InvalidArgumentValue(); }
public override void Run() { try { foreach (var mapping in this.map) { string term = mapping.Key; BytesRef expected = mapping.Value; Exception priorException = null; // LUCENENET: No need to cast to IOExcpetion TokenStream ts = this.analyzer.GetTokenStream("fake", new StringReader(term)); try { ITermToBytesRefAttribute termAtt = ts.AddAttribute <ITermToBytesRefAttribute>(); BytesRef bytes = termAtt.BytesRef; ts.Reset(); Assert.IsTrue(ts.IncrementToken()); termAtt.FillBytesRef(); Assert.AreEqual(expected, bytes); Assert.IsFalse(ts.IncrementToken()); ts.End(); } catch (Exception e) when(e.IsIOException()) { priorException = e; } finally { IOUtils.DisposeWhileHandlingException(priorException, ts); } } } catch (Exception e) when(e.IsIOException()) { throw RuntimeException.Create(e); } }
internal static void ThrowExceptionOnError( string errorId, ConcurrentBag<string> errors, RunspaceConfigurationCategory category) { if (errors.Count == 0) { return; } StringBuilder allErrors = new StringBuilder(); allErrors.Append('\n'); foreach (string error in errors) { allErrors.Append(error); allErrors.Append('\n'); } string message = ""; if (category == RunspaceConfigurationCategory.Types) { message = StringUtil.Format(ExtendedTypeSystem.TypesXmlError, allErrors.ToString()); } else if (category == RunspaceConfigurationCategory.Formats) { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, allErrors.ToString()); } RuntimeException ex = new RuntimeException(message); ex.SetErrorId(errorId); throw ex; }
/// <summary> /// Handles a robust connection layer notification from the transport /// manager. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void HandleRobustConnectionNotification( object sender, ConnectionStatusEventArgs e) { // Create event arguments and warnings/errors for this robust connection notification. PSConnectionRetryStatusEventArgs connectionRetryStatusArgs = null; WarningRecord warningRecord = null; ErrorRecord errorRecord = null; int maxRetryConnectionTimeMSecs = this.runspacePool.MaxRetryConnectionTime; int maxRetryConnectionTimeMinutes = maxRetryConnectionTimeMSecs / 60000; switch (e.Notification) { case ConnectionStatus.NetworkFailureDetected: warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDNetworkFailureDetected, StringUtil.Format(RemotingErrorIdStrings.RCNetworkFailureDetected, this.computerName, maxRetryConnectionTimeMinutes)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.NetworkFailureDetected, this.computerName, maxRetryConnectionTimeMSecs, warningRecord); break; case ConnectionStatus.ConnectionRetryAttempt: warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDConnectionRetryAttempt, StringUtil.Format(RemotingErrorIdStrings.RCConnectionRetryAttempt, this.computerName)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetryAttempt, this.computerName, maxRetryConnectionTimeMSecs, warningRecord); break; case ConnectionStatus.ConnectionRetrySucceeded: warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDConnectionRetrySucceeded, StringUtil.Format(RemotingErrorIdStrings.RCReconnectSucceeded, this.computerName)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetrySucceeded, this.computerName, maxRetryConnectionTimeMinutes, warningRecord); break; case ConnectionStatus.AutoDisconnectStarting: { warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectStarting, StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingWarning, this.computerName)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectStarting, this.computerName, maxRetryConnectionTimeMinutes, warningRecord); } break; case ConnectionStatus.AutoDisconnectSucceeded: warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectSucceeded, StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnected, this.computerName)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectSucceeded, this.computerName, maxRetryConnectionTimeMinutes, warningRecord); break; case ConnectionStatus.InternalErrorAbort: { string msg = StringUtil.Format(RemotingErrorIdStrings.RCInternalError, this.computerName); RuntimeException reason = new RuntimeException(msg); errorRecord = new ErrorRecord(reason, PSConnectionRetryStatusEventArgs.FQIDNetworkOrDisconnectFailed, ErrorCategory.InvalidOperation, this); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.InternalErrorAbort, this.computerName, maxRetryConnectionTimeMinutes, errorRecord); } break; } if (connectionRetryStatusArgs == null) { return; } // Update connection status. _connectionRetryStatus = connectionRetryStatusArgs.Notification; if (warningRecord != null) { RemotingWarningRecord remotingWarningRecord = new RemotingWarningRecord( warningRecord, new OriginInfo(this.computerName, this.InstanceId)); // Add warning record to information channel. HandleInformationalMessageReceived(this, new RemoteDataEventArgs<InformationalMessage>( new InformationalMessage(remotingWarningRecord, RemotingDataType.PowerShellWarning))); // Write warning to host. RemoteHostCall writeWarning = new RemoteHostCall( -100, RemoteHostMethodId.WriteWarningLine, new object[] { warningRecord.Message }); try { HandleHostCallReceived(this, new RemoteDataEventArgs<RemoteHostCall>(writeWarning)); } catch (PSNotImplementedException) { } } if (errorRecord != null) { RemotingErrorRecord remotingErrorRecord = new RemotingErrorRecord( errorRecord, new OriginInfo(this.computerName, this.InstanceId)); // Add error record to error channel, will also be written to host. HandleErrorReceived(this, new RemoteDataEventArgs<ErrorRecord>(remotingErrorRecord)); } // Raise event. RCConnectionNotification.SafeInvoke(this, connectionRetryStatusArgs); }
internal static void ThrowExceptionOnError( string errorId, Collection<string> independentErrors, Collection<PSSnapInTypeAndFormatErrors> PSSnapinFilesCollection, RunspaceConfigurationCategory category) { Collection<string> errors = new Collection<string>(); if (independentErrors != null) { foreach (string error in independentErrors) { errors.Add(error); } } foreach (PSSnapInTypeAndFormatErrors PSSnapinFiles in PSSnapinFilesCollection) { foreach (string error in PSSnapinFiles.Errors) { errors.Add(error); } } if (errors.Count == 0) { return; } StringBuilder allErrors = new StringBuilder(); allErrors.Append('\n'); foreach (string error in errors) { allErrors.Append(error); allErrors.Append('\n'); } string message = ""; if (category == RunspaceConfigurationCategory.Types) { message = StringUtil.Format(ExtendedTypeSystem.TypesXmlError, allErrors.ToString()); } else if (category == RunspaceConfigurationCategory.Formats) { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, allErrors.ToString()); } RuntimeException ex = new RuntimeException(message); ex.SetErrorId(errorId); throw ex; }
} // AddCommand( CommandProcessorBase commandProcessor, int readFromCommand, bool readErrorQueue ) // 2005/03/08-JonN: This is an internal API /// <summary> /// Execute the accumulated commands and clear the pipeline. /// SynchronousExecute does not return until all commands have /// completed. There is no asynchronous variant; instead, once the /// pipeline is set up, the caller can spawn a thread and call /// SynchronousExecute from that thread. This does not mean that /// PipelineProcessor is thread-safe; once SynchronousExecute is /// running, PipelineProcessor should not be accessed through any /// other means. This variant of the routine looks at it's input /// object to see if it's enumerable or not. /// </summary> /// <param name="input"> /// Input objects for first stage. If this is AutomationNull.Value, the /// first cmdlet is the beginning of the pipeline. /// </param> /// <returns> /// Results from last pipeline stage. This will be empty if /// ExternalSuccessOutput is set. /// </returns> /// <exception cref="InvalidOperationException"> /// ExecutionAlreadyStarted: pipeline has already started or completed /// </exception> /// <exception cref="InvalidOperationException"> /// PipelineExecuteRequiresAtLeastOneCommand /// </exception> /// <exception cref="CmdletInvocationException"> /// A cmdlet encountered a terminating error /// </exception> /// <exception cref="PipelineStoppedException"> /// The pipeline was stopped asynchronously /// </exception> /// <exception cref="ActionPreferenceStopException"> /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. /// </exception> /// <exception cref="ParameterBindingException"> /// If any parameters fail to bind, /// or /// If any mandatory parameters are missing. /// </exception> /// <exception cref="MetadataException"> /// If there is an error generating the metadata for dynamic parameters. /// </exception> /// <exception cref="ExtendedTypeSystemException"> /// An error occurred clearing the error variable. /// </exception> /// <exception cref="HaltCommandException"> /// HaltCommandException will cause the command /// to stop, but should not be reported as an error. /// </exception> internal Array SynchronousExecuteEnumerate(object input) { if (Stopping) { throw new PipelineStoppedException(); } ExceptionDispatchInfo toRethrowInfo; try { CommandProcessorBase commandRequestingUpstreamCommandsToStop = null; try { // If the caller specified an input object array, // we run assuming there is an incoming "stream" // of objects. This will prevent the one default call // to ProcessRecord on the first command. Start(input != AutomationNull.Value); // Start has already validated firstcommandProcessor CommandProcessorBase firstCommandProcessor = _commands[0]; // Add any input to the first command. if (null != ExternalInput) { firstCommandProcessor.CommandRuntime.InputPipe.ExternalReader = ExternalInput; } Inject(input, enumerate: true); } catch (PipelineStoppedException) { StopUpstreamCommandsException stopUpstreamCommandsException = _firstTerminatingError != null ? _firstTerminatingError.SourceException as StopUpstreamCommandsException : null; if (stopUpstreamCommandsException == null) { throw; } else { _firstTerminatingError = null; commandRequestingUpstreamCommandsToStop = stopUpstreamCommandsException.RequestingCommandProcessor; } } DoCompleteCore(commandRequestingUpstreamCommandsToStop); // By this point, we are sure all commandProcessors hosted by the current pipelineProcess are done execution, // so if there are any redirection pipelineProcessors associated with any of those commandProcessors, we should // call DoComplete on them. if (_redirectionPipes != null) { foreach (PipelineProcessor redirectPipelineProcessor in _redirectionPipes) { redirectPipelineProcessor.DoCompleteCore(null); } } return RetrieveResults(); } catch (RuntimeException e) { // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. toRethrowInfo = _firstTerminatingError ?? ExceptionDispatchInfo.Capture(e); this.LogExecutionException(toRethrowInfo.SourceException); } // NTRAID#Windows Out Of Band Releases-929020-2006/03/14-JonN catch (System.Runtime.InteropServices.InvalidComObjectException comException) { // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. if (null != _firstTerminatingError) { toRethrowInfo = _firstTerminatingError; } else { string message = StringUtil.Format(ParserStrings.InvalidComObjectException, comException.Message); var rte = new RuntimeException(message, comException); rte.SetErrorId("InvalidComObjectException"); toRethrowInfo = ExceptionDispatchInfo.Capture(rte); } this.LogExecutionException(toRethrowInfo.SourceException); } finally { DisposeCommands(); } // By rethrowing the exception outside of the handler, // we allow the CLR on X64/IA64 to free from the stack // the exception records related to this exception. // The only reason we should get here is if // an exception should be rethrown. Diagnostics.Assert(null != toRethrowInfo, "Alternate protocol path failure"); toRethrowInfo.Throw(); return null; // UNREACHABLE } // internal Array SynchronousExecuteEnumerate()
/// <summary> /// Implements DoComplete as a stand-alone function for completing /// the execution of a steppable pipeline. /// </summary> /// <returns>The results of the execution</returns> internal Array DoComplete() { if (Stopping) { throw new PipelineStoppedException(); } if (!_executionStarted) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.PipelineNotStarted); } ExceptionDispatchInfo toRethrowInfo; try { DoCompleteCore(null); return RetrieveResults(); } catch (RuntimeException e) { // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. toRethrowInfo = _firstTerminatingError ?? ExceptionDispatchInfo.Capture(e); this.LogExecutionException(toRethrowInfo.SourceException); } // NTRAID#Windows Out Of Band Releases-929020-2006/03/14-JonN catch (System.Runtime.InteropServices.InvalidComObjectException comException) { // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. if (null != _firstTerminatingError) { toRethrowInfo = _firstTerminatingError; } else { string message = StringUtil.Format(ParserStrings.InvalidComObjectException, comException.Message); var rte = new RuntimeException(message, comException); rte.SetErrorId("InvalidComObjectException"); toRethrowInfo = ExceptionDispatchInfo.Capture(rte); } this.LogExecutionException(toRethrowInfo.SourceException); } finally { DisposeCommands(); } // By rethrowing the exception outside of the handler, // we allow the CLR on X64/IA64 to free from the stack // the exception records related to this exception. // The only reason we should get here is if // an exception should be rethrown. Diagnostics.Assert(null != toRethrowInfo, "Alternate protocol path failure"); toRethrowInfo.Throw(); return null; // UNREACHABLE } // internal Array DoComplete()
public void Log(RuntimeException runtimeError) { if (runtimeError == null) { return; } try { using (var ctx = SuiteEntitiesUtility.GetODataValidationSuiteEntities()) { var runtimeException = EngineRuntimeException.CreateEngineRuntimeException( runtimeError.JobId, runtimeError.RuleName, runtimeError.Timestamp, runtimeError.DestinationEndpoint, 0); runtimeException.Message = runtimeError.Message; runtimeException.StackTrace = runtimeError.StackTrace; runtimeException.Detail = runtimeError.Detail; ctx.AddToEngineRuntimeExceptions(runtimeException); ctx.SaveChanges(); } } catch (Exception ex) { if (!RuleEngine.Common.ExceptionHelper.IsCatchableExceptionType(ex)) { throw; } // swallows the exception since logging is considered low-prio task } }
/** * Finds the node causing a NPE for diadic operators. * @param xrt the RuntimeException * @param node the parent node * @param left the left argument * @param right the right argument * @return the left, right or parent node */ protected JexlNode findNullOperand(RuntimeException xrt, JexlNode node, Object left, Object right) { if (xrt instanceof ArithmeticException && JexlException.NULL_OPERAND == xrt.getMessage()) { if (left == null) { return node.jjtGetChild(0); } if (right == null) { return node.jjtGetChild(1); } } return node; }