public CharStreamIOException(IOException io) : base(io.Message) { this.io = io; }
/// <summary> Try to unmap the buffer, this method silently fails if no support /// for that in the JVM. On Windows, this leads to the fact, /// that mmapped files cannot be modified or deleted. /// </summary> internal void CleanMapping(System.IO.MemoryStream buffer) { if (useUnmapHack) { try { // {{Aroush-2.9}} Not converted: java.security.AccessController.doPrivileged() System.Diagnostics.Debug.Fail("Port issue:", "java.security.AccessController.doPrivileged()"); // {{Aroush-2.9}} // AccessController.DoPrivileged(new AnonymousClassPrivilegedExceptionAction(buffer, this)); } catch (System.Exception e) { System.IO.IOException ioe = new System.IO.IOException("unable to unmap the mapped buffer", e.InnerException); throw ioe; } } }
public static bool ConnectionLost(System.IO.IOException ex) { // // In some cases the IOException has an inner exception that we can pass directly // to the other overloading of connectionLost(). // if (ex.InnerException != null && ex.InnerException is SocketException) { return(ConnectionLost((SocketException)ex.InnerException)); } // // In other cases the IOException has no inner exception. We could examine the // exception's message, but that is fragile due to localization issues. We // resort to extracting the value of the protected HResult member via reflection. // int hr = (int)ex.GetType().GetProperty("HResult", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public).GetValue(ex, null); // // This value corresponds to the following errors: // // "Authentication failed because the remote party has closed the transport stream" // if (hr == -2146232800) { return(true); } return(false); }
/// <summary> Close the Channel. The channel is only closed, it is /// the responsibility of the "closer" to remove the channel from /// the channel table. /// </summary> internal virtual void close() { System.IO.IOException ex = null; if (input != null) { try { input.close(); } catch (System.IO.IOException e) { ex = e; } input = null; } if (output != null) { try { output.close(); } catch (System.IO.IOException e) { ex = e; } output = null; } if (ex != null) { throw ex; } }
/// <summary> /// Map a .Net IOException to the matching JSimple platform independent exception. If there's a specific exception /// type for the subclass (because it's an error we're likely to care about), return that. Otherwise, just return a /// JSimple IOException. /// </summary> public static IOException jSimpleExceptionFromDotNetIOException(System.IO.IOException e) { IOException jSimpleIOException; string message = e.Message ?? ""; // TODO: Map the other exceptions /* * if (e is java.net.SocketTimeoutException) * jSimpleIOException = new SocketTimeoutException(message); * else if (e is UnknownHostException) * jSimpleIOException = new UnknownHostException(message); */ // TODO: Include DirectoryNotFoundException for .Net apps if (e is System.IO.FileNotFoundException) { jSimpleIOException = new PathNotFoundException(message, e); } else { jSimpleIOException = new IOException(message, e); } /* * // Replace the stack trace with the original one, so it looks like the original code threw the exception. * // In some ways that's not technically correct, but it generally makes the stack traces easier to read * // and more standard Java-like, since the nested exception wrapping doesn't add any real info in error output * // and in practice tends to make error output a bit harder to understand, not easier * StackTraceElement[] stackTrace = e.getStackTrace(); * jSimpleIOException.setStackTrace(stackTrace); */ return(jSimpleIOException); }
/// <summary> /// <inheritDoc/> /// <br/> /// Closes all of the underlying sources. /// </summary> public virtual void Close() { System.IO.IOException firstThrownIOExc = null; foreach (GroupedRandomAccessSource.SourceEntry entry in sources) { try { entry.source.Close(); } catch (System.IO.IOException ex) { if (firstThrownIOExc == null) { firstThrownIOExc = ex; } else { ILog logger = LogManager.GetLogger(typeof(iText.IO.Source.GroupedRandomAccessSource)); logger.Error(iText.IO.LogMessageConstant.ONE_OF_GROUPED_SOURCES_CLOSING_FAILED, ex); } } catch (Exception ex) { ILog logger = LogManager.GetLogger(typeof(iText.IO.Source.GroupedRandomAccessSource)); logger.Error(iText.IO.LogMessageConstant.ONE_OF_GROUPED_SOURCES_CLOSING_FAILED, ex); } } if (firstThrownIOExc != null) { throw firstThrownIOExc; } }
protected internal override void DoClose() { System.IO.IOException ioe = null; // close the reader, record exception try { base.DoClose(); } catch (System.IO.IOException e) { ioe = e; } // close the directory, record exception if (ref_Renamed.DecRef() == 0) { try { in_Renamed.Directory().Close(); } catch (System.IO.IOException e) { if (ioe == null) { ioe = e; } } } // throw the first exception if (ioe != null) { throw ioe; } }
protected internal override object DoBody(string segmentFileName) { var sis = new SegmentInfos(); sis.Read(directory, segmentFileName); var readers = new SegmentReader[sis.Count]; for (int i = sis.Count - 1; i >= 0; i--) { System.IO.IOException prior = null; bool success = false; try { readers[i] = new SegmentReader(sis.Info(i), termInfosIndexDivisor, IOContext.READ); success = true; } catch (System.IO.IOException ex) { prior = ex; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(prior, readers); } } } return(new StandardDirectoryReader(directory, readers, null, sis, termInfosIndexDivisor, false)); }
private void Log() { LoggType loggType; Exception exception = null; if (this.comboBox2.SelectedIndex > 0) { switch (this.comboBox2.SelectedIndex) { case 1: exception = new System.IO.IOException(); break; case 2: exception = new Exception(); break; } } if (Enum.TryParse<LoggType>(this.comboBox1.Text, out loggType)) { YAL.Logger.Default.Log(loggType, this.textBox1.Text, exception); } else { YAL.Logger.Default.Log(LoggType.General, this.textBox1.Text, exception); } MessageBox.Show("Error logged"); }
protected override void GetChildItems(Path path, bool recurse) { if (string.IsNullOrEmpty(path)) { throw new Exception("Path can't be empty"); } path = NormalizePath(path); System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(path); if (directory.Exists) { GetDirectoryContent(directory, recurse); } else { System.IO.FileInfo item = new System.IO.FileInfo(path); if (item.Exists) { if ((item.Attributes & System.IO.FileAttributes.Hidden) == 0) { WriteItemObject(item, path, false); } } else { Exception exception = new System.IO.IOException("Path doesn't exist: " + path); WriteError(new ErrorRecord(exception, "ItemDoesNotExist", ErrorCategory.ObjectNotFound, path)); } } }
/// <summary>check that the query weight is serializable. </summary> /// <throws> IOException if serialization check fail. </throws> private static void CheckSerialization(Query q, Searcher s) { Weight w = q.Weight(s, null); try { System.IO.MemoryStream bos = new System.IO.MemoryStream(); System.IO.BinaryWriter oos = new System.IO.BinaryWriter(bos); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(oos.BaseStream, w); oos.Close(); System.IO.BinaryReader ois = new System.IO.BinaryReader(new System.IO.MemoryStream(bos.ToArray())); formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Deserialize(ois.BaseStream); ois.Close(); //skip equals() test for now - most weights don't override equals() and we won't add this just for the tests. //TestCase.Assert.AreEqual(w2,w,"writeObject(w) != w. ("+w+")"); } catch (System.Exception e) { System.IO.IOException e2 = new System.IO.IOException("Serialization failed for " + w, e); throw e2; } }
/// <summary>Close all streams. </summary> public /*internal*/ void Close() { try { CloseDocument(); } finally { // make an effort to close all streams we can but remember and re-throw // the first exception encountered in this process System.IO.IOException keep = null; if (tvx != null) { try { tvx.Close(); } catch (System.IO.IOException e) { if (keep == null) { keep = e; } } } if (tvd != null) { try { tvd.Close(); } catch (System.IO.IOException e) { if (keep == null) { keep = e; } } } if (tvf != null) { try { tvf.Close(); } catch (System.IO.IOException e) { if (keep == null) { keep = e; } } } if (keep != null) { throw new System.IO.IOException(keep.StackTrace); } } }
public void SaveChangesErrorDetectionStrategyTestIOException() { var exception = new System.IO.IOException(); bool actual = new SaveChangesErrorDetectionStrategy().IsTransient(exception); Assert.IsFalse(actual); }
internal static int GetErrorCode(System.IO.IOException ioe) { #if !WindowsCE return(System.Runtime.InteropServices.Marshal.GetHRForException(ioe) & 0xFFFF); #else return(0); #endif }
public static bool Timeout(System.IO.IOException ex) { // // TODO: Instead of testing for an English substring, we need to examine the inner // exception (if there is one). // return(ex.Message.IndexOf("period of time", StringComparison.Ordinal) >= 0); }
public static bool IsFileLocked(this System.IO.IOException e) { #if XB1 Debug.Assert(false, "Implement per platform"); return(false); #else var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1); return(errorCode == 32 || errorCode == 33); #endif }
override public void Run() { try { docs = (sort == null)?searchable.Search(weight, filter, nDocs):searchable.Search(weight, filter, nDocs, sort); } // Store the IOException for later use by the caller of this thread catch (System.IO.IOException ioe) { this.ioe = ioe; } if (this.ioe == null) { // if we are sorting by fields, we need to tell the field sorted hit queue // the actual type of fields, in case the original list contained AUTO. // if the searchable returns null for fields, we'll have problems. if (sort != null) { TopFieldDocs docsFields = (TopFieldDocs)docs; // If one of the Sort fields is FIELD_DOC, need to fix its values, so that // it will break ties by doc Id properly. Otherwise, it will compare to // 'relative' doc Ids, that belong to two different searchables. for (int j = 0; j < docsFields.fields.Length; j++) { if (docsFields.fields[j].GetType() == SortField.DOC) { // iterate over the score docs and change their fields value for (int j2 = 0; j2 < docs.scoreDocs.Length; j2++) { FieldDoc fd = (FieldDoc)docs.scoreDocs[j2]; fd.fields[j] = (System.Int32)(((System.Int32)fd.fields[j]) + starts[i]); } break; } } ((FieldDocSortedHitQueue)hq).SetFields(docsFields.fields); } ScoreDoc[] scoreDocs = docs.scoreDocs; for (int j = 0; j < scoreDocs.Length; j++) { // merge scoreDocs into hq ScoreDoc scoreDoc = scoreDocs[j]; scoreDoc.doc += starts[i]; // convert doc //it would be so nice if we had a thread-safe insert lock (hq) { if (!hq.Insert(scoreDoc)) { break; } } // no more scores > minScore } } }
internal static int GetErrorCode(System.IO.IOException ioe) { #if !WindowsCE && !SILVERLIGHT var permission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode); permission.Demand(); return(System.Runtime.InteropServices.Marshal.GetHRForException(ioe) & 0xFFFF); #else return(0); #endif }
public override void Sync(System.String name) { EnsureOpen(); System.IO.FileInfo fullFile = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name)); bool success = false; int retryCount = 0; System.IO.IOException exc = null; while (!success && retryCount < 5) { retryCount++; System.IO.FileStream file = null; try { try { file = new System.IO.FileStream(fullFile.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); SupportClass.FileSupport.Sync(file); success = true; } finally { if (file != null) { file.Close(); } } } catch (System.IO.IOException ioe) { if (exc == null) { exc = ioe; } try { // Pause 5 msec System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 5)); } catch (System.Threading.ThreadInterruptedException ie) { // In 3.0 we will change this to throw // InterruptedException instead SupportClass.ThreadClass.Current().Interrupt(); throw new System.SystemException(ie.ToString(), ie); } } } if (!success) { // Throw original exception throw exc; } }
/// <nodoc /> public static EnumerateDirectoryResult CreateFromException(string directoryPath, Exception ex) { var findHandleOpenStatus = ex switch { UnauthorizedAccessException _ => EnumerateDirectoryStatus.AccessDenied, System.IO.DirectoryNotFoundException _ => EnumerateDirectoryStatus.SearchDirectoryNotFound, System.IO.IOException _ => EnumerateDirectoryStatus.CannotEnumerateFile, _ => EnumerateDirectoryStatus.UnknownError, }; return(new EnumerateDirectoryResult(directoryPath, findHandleOpenStatus, ex.HResult, ex)); }
void HandleIOException(System.IO.IOException ioe, RemoteHostState state) { if (ioe.InnerException.GetType() == typeof(System.Net.Sockets.SocketError)) { System.Net.Sockets.SocketException se = (System.Net.Sockets.SocketException)ioe.InnerException; CloseConnection(state, (se.SocketErrorCode == SocketError.Interrupted) ? null : se); } else { CloseConnection(state, ioe); } }
internal virtual void Close() { // make all effort to close up. Keep the first exception // and throw it as a new one. System.IO.IOException keep = null; if (tvx != null) { try { tvx.Close(); } catch (System.IO.IOException e) { if (keep == null) { keep = e; } } } if (tvd != null) { try { tvd.Close(); } catch (System.IO.IOException e) { if (keep == null) { keep = e; } } } if (tvf != null) { try { tvf.Close(); } catch (System.IO.IOException e) { if (keep == null) { keep = e; } } } if (keep != null) { throw new System.IO.IOException(keep.StackTrace); } }
/// <summary> A search implementation allowing sorting which spans a new thread for each /// Searchable, waits for each search to complete and merges /// the results back together. /// </summary> public override TopFieldDocs Search(Weight weight, Filter filter, int nDocs, Sort sort) { // don't specify the fields - we'll wait to do this until we get results FieldDocSortedHitQueue hq = new FieldDocSortedHitQueue(null, nDocs); int totalHits = 0; MultiSearcherThread[] msta = new MultiSearcherThread[searchables.Length]; for (int i = 0; i < searchables.Length; i++) { // search each searchable // Assume not too many searchables and cost of creating a thread is by far inferior to a search msta[i] = new MultiSearcherThread(searchables[i], weight, filter, nDocs, hq, sort, i, starts, "MultiSearcher thread #" + (i + 1)); msta[i].Start(); } float maxScore = System.Single.NegativeInfinity; for (int i = 0; i < searchables.Length; i++) { try { msta[i].Join(); } catch (System.Threading.ThreadInterruptedException ie) { // In 3.0 we will change this to throw // InterruptedException instead SupportClass.ThreadClass.Current().Interrupt(); throw new System.SystemException(ie.Message, ie); } System.IO.IOException ioe = msta[i].GetIOException(); if (ioe == null) { totalHits += msta[i].Hits(); maxScore = System.Math.Max(maxScore, msta[i].GetMaxScore()); } else { // if one search produced an IOException, rethrow it throw ioe; } } ScoreDoc[] scoreDocs = new ScoreDoc[hq.Size()]; for (int i = hq.Size() - 1; i >= 0; i--) { // put docs in array scoreDocs[i] = (ScoreDoc)hq.Pop(); } return(new TopFieldDocs(totalHits, scoreDocs, hq.GetFields(), maxScore)); }
public static string ReadFileTextSync(string filePath, float timeoutSeconds = 2f) { bool sourceLoaded = false; string fileText = ""; System.DateTime startTime = System.DateTime.Now; while (true) { System.IO.IOException exception = null; try { fileText = System.IO.File.ReadAllText(filePath); sourceLoaded = true; } catch (System.IO.IOException e) { exception = e; if (e is System.IO.FileNotFoundException || e is System.IO.DirectoryNotFoundException) { throw e; } } if (sourceLoaded) { break; } else { System.Threading.Thread.Sleep(20); } System.TimeSpan timeFromStart = System.DateTime.Now - startTime; if (timeFromStart.TotalSeconds > timeoutSeconds) { UnityEngine.Debug.LogError($"Timeout when attempting to read file {filePath}"); if (exception != null) { throw exception; } } } return(fileText); }
/// <summary>Close all streams. </summary> public void Dispose() { // Move to a protected method if class becomes unsealed // make an effort to close all streams we can but remember and re-throw // the first exception encountered in this process System.IO.IOException keep = null; if (tvx != null) { try { tvx.Close(); } catch (System.IO.IOException e) { keep = e; } } if (tvd != null) { try { tvd.Close(); } catch (System.IO.IOException e) { if (keep == null) { keep = e; } } } if (tvf != null) { try { tvf.Close(); } catch (System.IO.IOException e) { if (keep == null) { keep = e; } } } if (keep != null) { throw new System.IO.IOException(keep.StackTrace); } }
public void Resend() { try { if (m_comm.Transport.Send(m_transmit_buffer, m_comm.Transport.HeaderLength, m_transmit_length, m_adr, m_wait_for_transmit, m_transmit_timeout) < 0) { Error = new System.IO.IOException("Write Timeout"); } } catch (Exception ex) { Error = new Exception("Write Exception: " + ex.Message); } }
/// <summary> A search implementation which spans a new thread for each /// Searchable, waits for each search to complete and merge /// the results back together. /// </summary> public override TopDocs Search(Weight weight, Filter filter, int nDocs) { HitQueue hq = new HitQueue(nDocs, false); int totalHits = 0; MultiSearcherThread[] msta = new MultiSearcherThread[searchables.Length]; for (int i = 0; i < searchables.Length; i++) { // search each searchable // Assume not too many searchables and cost of creating a thread is by far inferior to a search msta[i] = new MultiSearcherThread(searchables[i], weight, filter, nDocs, hq, i, starts, "MultiSearcher thread #" + (i + 1)); msta[i].Start(); } for (int i = 0; i < searchables.Length; i++) { try { msta[i].Join(); } catch (System.Threading.ThreadInterruptedException ie) { // In 3.0 we will change this to throw // InterruptedException instead Support.ThreadClass.Current().Interrupt(); throw new System.SystemException(ie.Message, ie); } System.IO.IOException ioe = msta[i].GetIOException(); if (ioe == null) { totalHits += msta[i].Hits(); } else { // if one search produced an IOException, rethrow it throw ioe; } } ScoreDoc[] scoreDocs = new ScoreDoc[hq.Size()]; for (int i = hq.Size() - 1; i >= 0; i--) { // put docs in array scoreDocs[i] = (ScoreDoc)hq.Pop(); } float maxScore = (totalHits == 0)?System.Single.NegativeInfinity:scoreDocs[0].Score; return(new TopDocs(totalHits, scoreDocs, maxScore)); }
static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if (LuaAPI.lua_gettop(L) == 1) { System.IO.IOException gen_ret = new System.IO.IOException(); translator.Push(L, gen_ret); return(1); } if (LuaAPI.lua_gettop(L) == 2 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)) { string _message = LuaAPI.lua_tostring(L, 2); System.IO.IOException gen_ret = new System.IO.IOException(_message); translator.Push(L, gen_ret); return(1); } if (LuaAPI.lua_gettop(L) == 3 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3)) { string _message = LuaAPI.lua_tostring(L, 2); int _hresult = LuaAPI.xlua_tointeger(L, 3); System.IO.IOException gen_ret = new System.IO.IOException(_message, _hresult); translator.Push(L, gen_ret); return(1); } if (LuaAPI.lua_gettop(L) == 3 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <System.Exception>(L, 3)) { string _message = LuaAPI.lua_tostring(L, 2); System.Exception _innerException = (System.Exception)translator.GetObject(L, 3, typeof(System.Exception)); System.IO.IOException gen_ret = new System.IO.IOException(_message, _innerException); translator.Push(L, gen_ret); return(1); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } return(LuaAPI.luaL_error(L, "invalid arguments to System.IO.IOException constructor!")); }
public override void RenameFile(System.String from, System.String to) { lock (this) { EnsureOpen(); System.IO.FileInfo old = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, from)); try { old.MoveTo(System.IO.Path.Combine(directory.FullName, to)); } catch (System.IO.IOException ioe) { System.IO.IOException newExc = new System.IO.IOException("Cannot rename " + old + " to " + directory, ioe); throw newExc; } } }
/// <summary> A search implementation allowing sorting which spans a new thread for each /// Searchable, waits for each search to complete and merges /// the results back together. /// </summary> public override TopFieldDocs Search(Query query, Filter filter, int nDocs, Sort sort) { // don't specify the fields - we'll wait to do this until we get results FieldDocSortedHitQueue hq = new FieldDocSortedHitQueue(null, nDocs); int totalHits = 0; MultiSearcherThread[] msta = new MultiSearcherThread[searchables.Length]; for (int i = 0; i < searchables.Length; i++) { // search each searcher // Assume not too many searchables and cost of creating a thread is by far inferior to a search msta[i] = new MultiSearcherThread(searchables[i], query, filter, nDocs, hq, sort, i, starts, "MultiSearcher thread #" + (i + 1)); msta[i].Start(); } for (int i = 0; i < searchables.Length; i++) { try { msta[i].Join(); } catch (System.Threading.ThreadInterruptedException ie) { ; // TODO: what should we do with this??? } System.IO.IOException ioe = msta[i].GetIOException(); if (ioe == null) { totalHits += msta[i].Hits(); } else { // if one search produced an IOException, rethrow it throw ioe; } } ScoreDoc[] scoreDocs = new ScoreDoc[hq.Size()]; for (int i = hq.Size() - 1; i >= 0; i--) { // put docs in array scoreDocs[i] = (ScoreDoc)hq.Pop(); } return(new TopFieldDocs(totalHits, scoreDocs, hq.GetFields())); }
/// <summary> /// Closes all resources and writes the entry table /// </summary> /// <exception cref="InvalidOperationException"> /// if close() had been called before or if no file has been added to /// this object </exception> public void Dispose() { if (Closed) { return; } System.IO.IOException priorException = null; IndexOutput entryTableOut = null; // TODO this code should clean up after itself // (remove partial .cfs/.cfe) try { if (PendingEntries.Count > 0 || OutputTaken.Get()) { throw new InvalidOperationException("CFS has pending open files"); } Closed = true; // open the compound stream GetOutput(); Debug.Assert(DataOut != null); CodecUtil.WriteFooter(DataOut); } catch (System.IO.IOException e) { priorException = e; } finally { IOUtils.CloseWhileHandlingException(priorException, DataOut); } try { entryTableOut = Directory_Renamed.CreateOutput(EntryTableName, IOContext.DEFAULT); WriteEntryTable(Entries.Values, entryTableOut); } catch (System.IO.IOException e) { priorException = e; } finally { IOUtils.CloseWhileHandlingException(priorException, entryTableOut); } }
// Simple test to verify locking system is "working". On // NFS, if it's misconfigured, you can hit long (35 // second) timeouts which cause Lock.obtain to take far // too long (it assumes the obtain() call takes zero // time). Since it's a configuration problem, we test up // front once on creating the LockFactory: private void AcquireTestLock() { System.String randomLockName = "lucene-" + System.Convert.ToString(new System.Random().Next(), 16) + "-test.lock"; Lock l = MakeLock(randomLockName); try { l.Obtain(); } catch (System.IO.IOException e) { System.IO.IOException e2 = new System.IO.IOException("Failed to acquire random test lock; please verify filesystem for lock directory '" + lockDir + "' supports locking", e); throw e2; } l.Release(); }
} // RenameItem /// <summary> /// Creates a new registry key or value at the specified <paramref name="path"/>. /// </summary> /// /// <param name="path"> /// The path to the new key to create. /// </param> /// /// <param name="type"> /// The type is ignored because this provider only creates /// registry keys. /// </param> /// /// <param name="newItem"> /// The newItem is ignored because the provider creates the /// key based on the path. /// </param> protected override void NewItem( string path, string type, object newItem) { if (String.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } // Confirm the new item with the user string action = RegistryProviderStrings.NewItemAction; string resourceTemplate = RegistryProviderStrings.NewItemResourceTemplate; string resource = String.Format( Host.CurrentCulture, resourceTemplate, path); if (ShouldProcess(resource, action)) { // Check to see if the key already exists IRegistryWrapper resultKey = GetRegkeyForPath(path, false); if (resultKey != null) { if (!Force) { Exception e = new System.IO.IOException(RegistryProviderStrings.KeyAlreadyExists); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.ResourceExists, resultKey)); resultKey.Close(); return; } else { // Remove the existing key before creating the new one resultKey.Close(); RemoveItem(path, false); } } if (Force) { if (!CreateIntermediateKeys(path)) { // We are unable to create Intermediate keys. Just return. return; } } // Get the parent and child portions of the path string parentPath = GetParentPath(path, null); string childName = GetChildName(path); // Get the key at the specified path IRegistryWrapper key = GetRegkeyForPathWriteIfError(parentPath, true); if (key == null) { return; } try { // Create the new subkey IRegistryWrapper newKey = key.CreateSubKey(childName); key.Close(); try { // Set the default key value if the value and type were specified if (newItem != null) { RegistryValueKind kind; if (!ParseKind(type, out kind)) { return; } SetRegistryValue(newKey, String.Empty, newItem, kind, path, false); } } catch (Exception exception) { // The key has been created, but the default value failed to be set. // If possible, just write an error instead of failing the entire operation. if ((exception is ArgumentException) || (exception is InvalidCastException) || (exception is System.IO.IOException) || (exception is System.Security.SecurityException) || (exception is System.UnauthorizedAccessException) || (exception is NotSupportedException)) { ErrorRecord rec = new ErrorRecord( exception, exception.GetType().FullName, ErrorCategory.WriteError, newKey); rec.ErrorDetails = new ErrorDetails(StringUtil.Format(RegistryProviderStrings.KeyCreatedValueFailed, childName)); WriteError(rec); } else throw; } // Write the new key out. WriteRegistryItemObject(newKey, path); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (ArgumentException argException) { WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, path)); } catch (NotSupportedException notSupportedException) { WriteError(new ErrorRecord(notSupportedException, notSupportedException.GetType().FullName, ErrorCategory.InvalidOperation, path)); } } // ShouldProcess } // NewItem
public void WebRequestTransientErrorDetectionStrategyTestIOException() { var exception = new System.IO.IOException(); bool actual = new WebRequestTransientErrorDetectionStrategy().IsTransient(exception); Assert.IsFalse(actual); }
public void close() { if (!closed) { closed = true; try { if (_out is java.io.Closeable) { ((java.io.Closeable)_out).close(); } } catch (System.IO.IOException e) { lastIOException = e; } } }
/// <summary>Just like {@link #ExpungeDeletes()}, except you can /// specify whether the call should block until the /// operation completes. This is only meaningful with a /// {@link MergeScheduler} that is able to run merges in /// background threads. /// /// <p/><b>NOTE</b>: if this method hits an OutOfMemoryError /// you should immediately close the writer. See <a /// href="#OOME">above</a> for details.<p/> /// </summary> public virtual void ExpungeDeletes(bool doWait) { EnsureOpen(); if (infoStream != null) Message("expungeDeletes: index now " + SegString()); MergePolicy.MergeSpecification spec; lock (this) { spec = mergePolicy.FindMergesToExpungeDeletes(segmentInfos); if (spec != null) { int numMerges = spec.merges.Count; for (int i = 0; i < numMerges; i++) RegisterMerge((MergePolicy.OneMerge) spec.merges[i]); } } mergeScheduler.Merge(this); if (spec != null && doWait) { int numMerges = spec.merges.Count; lock (this) { bool running = true; while (running) { if (hitOOM) { throw new System.SystemException("this writer hit an OutOfMemoryError; cannot complete expungeDeletes"); } // Check each merge that MergePolicy asked us to // do, to see if any of them are still running and // if any of them have hit an exception. running = false; for (int i = 0; i < numMerges; i++) { MergePolicy.OneMerge merge = (MergePolicy.OneMerge) spec.merges[i]; if (pendingMerges.Contains(merge) || runningMerges.Contains(merge)) running = true; System.Exception t = merge.GetException(); if (t != null) { System.IO.IOException ioe = new System.IO.IOException("background merge hit exception: " + merge.SegString(directory), t); throw ioe; } } // If any of our merges are still running, wait: if (running) DoWait(); } } } // NOTE: in the ConcurrentMergeScheduler case, when // doWait is false, we can return immediately while // background threads accomplish the optimization }
/// <summary> /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException. /// and in winrt and marshal APIs as Exception. /// </summary> /// <param name="errorCode"></param> /// <param name="message"></param> /// <param name="createCOMException"></param> /// <returns></returns> internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo) { if (errorCode >= 0) { return null; } Exception exception = null; bool shouldDisplayHR = false; switch (errorCode) { case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException case __HResults.COR_E_ARITHMETIC: exception = new ArithmeticException(); break; case __HResults.COR_E_ARGUMENT: case unchecked((int)0x800A01C1): case unchecked((int)0x800A01C2): case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT: exception = new ArgumentException(); if (errorCode != __HResults.COR_E_ARGUMENT) shouldDisplayHR = true; break; case __HResults.E_BOUNDS: case __HResults.COR_E_ARGUMENTOUTOFRANGE: case __HResults.ERROR_NO_UNICODE_TRANSLATION: exception = new ArgumentOutOfRangeException(); if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_ARRAYTYPEMISMATCH: exception = new ArrayTypeMismatchException(); break; case __HResults.COR_E_BADIMAGEFORMAT: case __HResults.CLDB_E_FILE_OLDVER: case __HResults.CLDB_E_INDEX_NOTFOUND: case __HResults.CLDB_E_FILE_CORRUPT: case __HResults.COR_E_NEWER_RUNTIME: case __HResults.COR_E_ASSEMBLYEXPECTED: case __HResults.ERROR_BAD_EXE_FORMAT: case __HResults.ERROR_EXE_MARKED_INVALID: case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT: case __HResults.ERROR_NOACCESS: case __HResults.ERROR_INVALID_ORDINAL: case __HResults.ERROR_INVALID_DLL: case __HResults.ERROR_FILE_CORRUPT: case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY: case __HResults.META_E_BAD_SIGNATURE: exception = new BadImageFormatException(); // Always show HR for BadImageFormatException shouldDisplayHR = true; break; case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT: exception = new FormatException(); break; // CustomAttributeFormatException case __HResults.COR_E_DATAMISALIGNED: exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here? break; case __HResults.COR_E_DIVIDEBYZERO: case __HResults.CTL_E_DIVISIONBYZERO: exception = new DivideByZeroException(); if (errorCode != __HResults.COR_E_DIVIDEBYZERO) shouldDisplayHR = true; break; case __HResults.COR_E_DLLNOTFOUND: #if ENABLE_WINRT exception = new DllNotFoundException(); #endif break; case __HResults.COR_E_DUPLICATEWAITOBJECT: exception = new ArgumentException(); break; // DuplicateWaitObjectException case __HResults.COR_E_ENDOFSTREAM: case unchecked((int)0x800A003E): exception = new System.IO.EndOfStreamException(); if (errorCode != __HResults.COR_E_ENDOFSTREAM) shouldDisplayHR = true; break; case __HResults.COR_E_TYPEACCESS: // TypeAccessException case __HResults.COR_E_ENTRYPOINTNOTFOUND: exception = new TypeLoadException(); break; // EntryPointNotFoundException case __HResults.COR_E_EXCEPTION: exception = new Exception(); break; case __HResults.COR_E_DIRECTORYNOTFOUND: case __HResults.STG_E_PATHNOTFOUND: case __HResults.CTL_E_PATHNOTFOUND: exception = new System.IO.DirectoryNotFoundException(); if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND) shouldDisplayHR = true; break; case __HResults.COR_E_FILELOAD: case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION: case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED: case __HResults.FUSION_E_LOADFROM_BLOCKED: case __HResults.FUSION_E_CACHEFILE_FAILED: case __HResults.FUSION_E_ASM_MODULE_MISSING: case __HResults.FUSION_E_INVALID_NAME: case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED: case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH: case __HResults.COR_E_MODULE_HASH_CHECK_FAILED: case __HResults.FUSION_E_REF_DEF_MISMATCH: case __HResults.SECURITY_E_INCOMPATIBLE_SHARE: case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE: case __HResults.SECURITY_E_UNVERIFIABLE: case __HResults.COR_E_FIXUPSINEXE: case __HResults.ERROR_TOO_MANY_OPEN_FILES: case __HResults.ERROR_SHARING_VIOLATION: case __HResults.ERROR_LOCK_VIOLATION: case __HResults.ERROR_OPEN_FAILED: case __HResults.ERROR_DISK_CORRUPT: case __HResults.ERROR_UNRECOGNIZED_VOLUME: case __HResults.ERROR_DLL_INIT_FAILED: case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED: case __HResults.CORSEC_E_MISSING_STRONGNAME: case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS: case __HResults.ERROR_FILE_INVALID: exception = new System.IO.FileLoadException(); shouldDisplayHR = true; break; case __HResults.COR_E_PATHTOOLONG: exception = new System.IO.PathTooLongException(); break; case __HResults.COR_E_IO: case __HResults.CTL_E_DEVICEIOERROR: case unchecked((int)0x800A793C): case unchecked((int)0x800A793D): exception = new System.IO.IOException(); if (errorCode != __HResults.COR_E_IO) shouldDisplayHR = true; break; case __HResults.ERROR_FILE_NOT_FOUND: case __HResults.ERROR_MOD_NOT_FOUND: case __HResults.ERROR_INVALID_NAME: case __HResults.CTL_E_FILENOTFOUND: case __HResults.ERROR_BAD_NET_NAME: case __HResults.ERROR_BAD_NETPATH: case __HResults.ERROR_NOT_READY: case __HResults.ERROR_WRONG_TARGET_NAME: case __HResults.INET_E_UNKNOWN_PROTOCOL: case __HResults.INET_E_CONNECTION_TIMEOUT: case __HResults.INET_E_CANNOT_CONNECT: case __HResults.INET_E_RESOURCE_NOT_FOUND: case __HResults.INET_E_OBJECT_NOT_FOUND: case __HResults.INET_E_DOWNLOAD_FAILURE: case __HResults.INET_E_DATA_NOT_AVAILABLE: case __HResults.ERROR_DLL_NOT_FOUND: case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW: case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH: case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND: exception = new System.IO.FileNotFoundException(); shouldDisplayHR = true; break; case __HResults.COR_E_FORMAT: exception = new FormatException(); break; case __HResults.COR_E_INDEXOUTOFRANGE: case unchecked((int)0x800a0009): exception = new IndexOutOfRangeException(); if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_INVALIDCAST: exception = new InvalidCastException(); break; case __HResults.COR_E_INVALIDCOMOBJECT: exception = new InvalidComObjectException(); break; case __HResults.COR_E_INVALIDOLEVARIANTTYPE: exception = new InvalidOleVariantTypeException(); break; case __HResults.COR_E_INVALIDOPERATION: case __HResults.E_ILLEGAL_STATE_CHANGE: case __HResults.E_ILLEGAL_METHOD_CALL: case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT: case __HResults.APPMODEL_ERROR_NO_PACKAGE: exception = new InvalidOperationException(); if (errorCode != __HResults.COR_E_INVALIDOPERATION) shouldDisplayHR = true; break; case __HResults.COR_E_MARSHALDIRECTIVE: exception = new MarshalDirectiveException(); break; case __HResults.COR_E_METHODACCESS: // MethodAccessException case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException case __HResults.COR_E_FIELDACCESS: case __HResults.COR_E_MEMBERACCESS: exception = new MemberAccessException(); if (errorCode != __HResults.COR_E_METHODACCESS) shouldDisplayHR = true; break; case __HResults.COR_E_MISSINGFIELD: // MissingFieldException case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException case __HResults.COR_E_MISSINGMEMBER: case unchecked((int)0x800A01CD): exception = new MissingMemberException(); break; case __HResults.COR_E_MISSINGMANIFESTRESOURCE: exception = new System.Resources.MissingManifestResourceException(); break; case __HResults.COR_E_NOTSUPPORTED: case unchecked((int)0x800A01B6): case unchecked((int)0x800A01BD): case unchecked((int)0x800A01CA): case unchecked((int)0x800A01CB): exception = new NotSupportedException(); if (errorCode != __HResults.COR_E_NOTSUPPORTED) shouldDisplayHR = true; break; case __HResults.COR_E_NULLREFERENCE: exception = new NullReferenceException(); break; case __HResults.COR_E_OBJECTDISPOSED: case __HResults.RO_E_CLOSED: // No default constructor exception = new ObjectDisposedException(String.Empty); break; case __HResults.COR_E_OPERATIONCANCELED: #if ENABLE_WINRT exception = new OperationCanceledException(); #endif break; case __HResults.COR_E_OVERFLOW: case __HResults.CTL_E_OVERFLOW: exception = new OverflowException(); break; case __HResults.COR_E_PLATFORMNOTSUPPORTED: exception = new PlatformNotSupportedException(message); break; case __HResults.COR_E_RANK: exception = new RankException(); break; case __HResults.COR_E_REFLECTIONTYPELOAD: #if ENABLE_WINRT exception = new System.Reflection.ReflectionTypeLoadException(null, null); #endif break; case __HResults.COR_E_SECURITY: case __HResults.CORSEC_E_INVALID_STRONGNAME: case __HResults.CTL_E_PERMISSIONDENIED: case unchecked((int)0x800A01A3): case __HResults.CORSEC_E_INVALID_PUBLICKEY: case __HResults.CORSEC_E_SIGNATURE_MISMATCH: exception = new System.Security.SecurityException(); break; case __HResults.COR_E_SAFEARRAYRANKMISMATCH: exception = new SafeArrayRankMismatchException(); break; case __HResults.COR_E_SAFEARRAYTYPEMISMATCH: exception = new SafeArrayTypeMismatchException(); break; case __HResults.COR_E_SERIALIZATION: exception = new System.Runtime.Serialization.SerializationException(message); break; case __HResults.COR_E_SYNCHRONIZATIONLOCK: exception = new System.Threading.SynchronizationLockException(); break; case __HResults.COR_E_TARGETINVOCATION: exception = new System.Reflection.TargetInvocationException(null); break; case __HResults.COR_E_TARGETPARAMCOUNT: exception = new System.Reflection.TargetParameterCountException(); break; case __HResults.COR_E_TYPEINITIALIZATION: exception = InteropExtensions.CreateTypeInitializationException(message); break; case __HResults.COR_E_TYPELOAD: case __HResults.RO_E_METADATA_NAME_NOT_FOUND: case __HResults.CLR_E_BIND_TYPE_NOT_FOUND: exception = new TypeLoadException(); if (errorCode != __HResults.COR_E_TYPELOAD) shouldDisplayHR = true; break; case __HResults.COR_E_UNAUTHORIZEDACCESS: case __HResults.CTL_E_PATHFILEACCESSERROR: case unchecked((int)0x800A014F): exception = new UnauthorizedAccessException(); shouldDisplayHR = true; break; case __HResults.COR_E_VERIFICATION: exception = new System.Security.VerificationException(); break; case __HResults.E_NOTIMPL: exception = new NotImplementedException(); break; case __HResults.E_OUTOFMEMORY: case __HResults.CTL_E_OUTOFMEMORY: case unchecked((int)0x800A7919): exception = new OutOfMemoryException(); if (errorCode != __HResults.E_OUTOFMEMORY) shouldDisplayHR = true; break; #if ENABLE_WINRT case __HResults.E_XAMLPARSEFAILED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTAVAILABLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTENABLED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_LAYOUTCYCLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; #endif // ENABLE_WINRT case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException case __HResults.COR_E_APPLICATION: // ApplicationException case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException case __HResults.COR_E_CODECONTRACTFAILED: // ContractException case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException case __HResults.CORSEC_E_CRYPTO: // CryptographicException case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException case __HResults.COR_E_REMOTING: // RemotingException case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException case __HResults.COR_E_SERVER: // ServerException case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException case __HResults.COR_E_SYSTEM: // SystemException case __HResults.COR_E_TARGET: // TargetException case __HResults.COR_E_THREADABORTED: // TargetException case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException case __HResults.COR_E_THREADSTATE: // ThreadStateException case __HResults.COR_E_THREADSTART: // ThreadStartException case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException case __HResults.ISS_E_CALLER: // IsolatedStorageException case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException case __HResults.ISS_E_MACHINE: // IsolatedStorageException case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException case __HResults.E_FAIL: default: break; } if (exception == null) { if (createCOMException) { exception = new COMException(); if (errorCode != __HResults.E_FAIL) shouldDisplayHR = true; } else { exception = new Exception(); if (errorCode != __HResults.COR_E_EXCEPTION) shouldDisplayHR = true; } } bool shouldConstructMessage = false; if (hasErrorInfo) { // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if // the message is not available and do not use the shouldDisplayHR setting if (message == null) shouldConstructMessage = true; } else { // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above shouldConstructMessage = shouldDisplayHR; } if (shouldConstructMessage) { // // Append the HR into error message, just in case the app wants to look at the HR in // message to determine behavior. We didn't expose HResult property until v4.5 and // GetHRFromException has side effects so probably Message was their only choice. // This behavior is probably not exactly the same as in desktop but it is fine to append // more message at the end. In any case, having the HR in the error message are helpful // to developers. // This makes sure: // 1. We always have a HR 0xNNNNNNNN in the message // 2. Put in a nice "Exception thrown from HRESULT" message if we can // 3. Wrap it in () if there is an existing message // // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString()); message = ExternalInterop.GetMessage(errorCode); // Always make sure we have at least the HRESULT part in retail build or when the message // is empty. if (message == null) message = hrMessage; else message = message + " (" + hrMessage + ")"; } if (message != null) { // Set message explicitly rather than calling constructor because certain ctors would append a // prefix to the message and that is not what we want InteropExtensions.SetExceptionMessage(exception, message); } InteropExtensions.SetExceptionErrorCode(exception, errorCode); return exception; }
/// <summary>Renames an existing file in the directory. /// Warning: This is not atomic. /// </summary> /// <deprecated> /// </deprecated> public override void RenameFile(System.String from, System.String to) { lock (this) { EnsureOpen(); System.IO.FileInfo old = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, from)); System.IO.FileInfo nu = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, to)); /* This is not atomic. If the program crashes between the call to delete() and the call to renameTo() then we're screwed, but I've been unable to figure out how else to do this... */ bool tmpBool; if (System.IO.File.Exists(nu.FullName)) tmpBool = true; else tmpBool = System.IO.Directory.Exists(nu.FullName); if (tmpBool) { bool tmpBool2; if (System.IO.File.Exists(nu.FullName)) { System.IO.File.Delete(nu.FullName); tmpBool2 = true; } else if (System.IO.Directory.Exists(nu.FullName)) { System.IO.Directory.Delete(nu.FullName); tmpBool2 = true; } else tmpBool2 = false; if (!tmpBool2) throw new System.IO.IOException("Cannot delete " + nu); } // Rename the old file to the new one. Unfortunately, the renameTo() // method does not work reliably under some JVMs. Therefore, if the // rename fails, we manually rename by copying the old file to the new one try { old.MoveTo(nu.FullName); } catch { System.IO.Stream in_Renamed = null; System.IO.Stream out_Renamed = null; try { in_Renamed = new System.IO.FileStream(old.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read); out_Renamed = new System.IO.FileStream(nu.FullName, System.IO.FileMode.Create); // see if the buffer needs to be initialized. Initialization is // only done on-demand since many VM's will never run into the renameTo // bug and hence shouldn't waste 1K of mem for no reason. if (buffer == null) { buffer = new byte[1024]; } int len; while ((len = in_Renamed.Read(buffer, 0, buffer.Length)) >= 0) { out_Renamed.Write(buffer, 0, len); } // delete the old file. bool tmpBool3; if (System.IO.File.Exists(old.FullName)) { System.IO.File.Delete(old.FullName); tmpBool3 = true; } else if (System.IO.Directory.Exists(old.FullName)) { System.IO.Directory.Delete(old.FullName); tmpBool3 = true; } else tmpBool3 = false; bool generatedAux = tmpBool3; } catch (System.IO.IOException ioe) { System.IO.IOException newExc = new System.IO.IOException("Cannot rename " + old + " to " + nu, ioe); throw newExc; } finally { try { if (in_Renamed != null) { try { in_Renamed.Close(); } catch (System.IO.IOException e) { throw new System.SystemException("Cannot close input stream: " + e.ToString(), e); } } } finally { if (out_Renamed != null) { try { out_Renamed.Close(); } catch (System.IO.IOException e) { throw new System.SystemException("Cannot close output stream: " + e.ToString(), e); } } } } } } }
internal Network(string msg, System.IO.IOException ioe) : base(msg, ioe) { _ioe = ioe; }
public virtual void ReportError(IOException e) { Console.Error.WriteLine(e); ExceptionExtensions.PrintStackTrace(e, Console.Error); }
/// <summary>Just like {@link #Optimize(int)}, except you can /// specify whether the call should block until the /// optimize completes. This is only meaningful with a /// {@link MergeScheduler} that is able to run merges in /// background threads. /// /// <p/><b>NOTE</b>: if this method hits an OutOfMemoryError /// you should immediately close the writer. See <a /// href="#OOME">above</a> for details.<p/> /// </summary> public virtual void Optimize(int maxNumSegments, bool doWait) { EnsureOpen(); if (maxNumSegments < 1) throw new System.ArgumentException("maxNumSegments must be >= 1; got " + maxNumSegments); if (infoStream != null) Message("optimize: index now " + SegString()); Flush(true, false, true); lock (this) { ResetMergeExceptions(); segmentsToOptimize = new System.Collections.Hashtable(); optimizeMaxNumSegments = maxNumSegments; int numSegments = segmentInfos.Count; for (int i = 0; i < numSegments; i++) SupportClass.CollectionsHelper.AddIfNotContains(segmentsToOptimize, segmentInfos.Info(i)); // Now mark all pending & running merges as optimize // merge: System.Collections.IEnumerator it = pendingMerges.GetEnumerator(); while (it.MoveNext()) { MergePolicy.OneMerge merge = (MergePolicy.OneMerge) it.Current; merge.optimize = true; merge.maxNumSegmentsOptimize = maxNumSegments; } it = runningMerges.GetEnumerator(); while (it.MoveNext()) { MergePolicy.OneMerge merge = (MergePolicy.OneMerge) it.Current; merge.optimize = true; merge.maxNumSegmentsOptimize = maxNumSegments; } } MaybeMerge(maxNumSegments, true); if (doWait) { lock (this) { while (true) { if (hitOOM) { throw new System.SystemException("this writer hit an OutOfMemoryError; cannot complete optimize"); } if (mergeExceptions.Count > 0) { // Forward any exceptions in background merge // threads to the current thread: int size = mergeExceptions.Count; for (int i = 0; i < size; i++) { MergePolicy.OneMerge merge = (MergePolicy.OneMerge) mergeExceptions[0]; if (merge.optimize) { System.IO.IOException err; System.Exception t = merge.GetException(); if (t != null) err = new System.IO.IOException("background merge hit exception: " + merge.SegString(directory), t); else err = new System.IO.IOException("background merge hit exception: " + merge.SegString(directory)); throw err; } } } if (OptimizeMergesPending()) DoWait(); else break; } } // If close is called while we are still // running, throw an exception so the calling // thread will know the optimize did not // complete EnsureOpen(); } // NOTE: in the ConcurrentMergeScheduler case, when // doWait is false, we can return immediately while // background threads accomplish the optimization }
public void flush() { checkNotClosed(); if (_out is java.io.Flushable) { try { ((java.io.Flushable)_out).flush(); } catch (System.IO.IOException e) { lastIOException = e; } } }
/// <summary> /// Creates a new property on the specified item /// </summary> /// /// <param name="path"> /// The path to the item on which the new property should be created. /// </param> /// /// <param name="propertyName"> /// The name of the property that should be created. /// </param> /// /// <param name="type"> /// The type of the property that should be created. /// </param> /// /// <param name="value"> /// The new value of the property that should be created. /// </param> /// /// <returns> /// Nothing. A PSObject representing the property that was created should /// be passed to the WriteObject() method. /// </returns> /// /// <!-- /// Implement this method when you are providing access to a data store /// that allows dynamic creation of properties. /// --> public void NewProperty( string path, string propertyName, string type, object value) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } if (!CheckOperationNotAllowedOnHiveContainer(path)) { return; } IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); if (key == null) { return; } // Confirm the set item with the user string action = RegistryProviderStrings.NewPropertyAction; string resourceTemplate = RegistryProviderStrings.NewPropertyResourceTemplate; string resource = String.Format( Host.CurrentCulture, resourceTemplate, path, propertyName); if (ShouldProcess(resource, action)) { // convert the type to a RegistryValueKind RegistryValueKind kind; if (!ParseKind(type, out kind)) { key.Close(); return; } try { // Check to see if the property already exists // or overwrite if frce is on if (Force || key.GetValue(propertyName) == null) { // Create the value SetRegistryValue(key, propertyName, value, kind, path); } else { // The property already exists System.IO.IOException e = new System.IO.IOException( RegistryProviderStrings.PropertyAlreadyExists); WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.ResourceExists, path)); key.Close(); return; } } catch (ArgumentException argumentException) { WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (InvalidCastException invalidCast) { WriteError(new ErrorRecord(invalidCast, invalidCast.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } key.Close(); }
/// <summary>Just like {@link #Optimize(int)}, except you can /// specify whether the call should block until the /// optimize completes. This is only meaningful with a /// {@link MergeScheduler} that is able to run merges in /// background threads. /// </summary> public virtual void Optimize(int maxNumSegments, bool doWait) { EnsureOpen(); if (maxNumSegments < 1) throw new System.ArgumentException("maxNumSegments must be >= 1; got " + maxNumSegments); if (infoStream != null) Message("optimize: index now " + SegString()); Flush(); lock (this) { ResetMergeExceptions(); segmentsToOptimize = new System.Collections.Hashtable(); int numSegments = segmentInfos.Count; for (int i = 0; i < numSegments; i++) if (!segmentsToOptimize.ContainsKey(segmentInfos.Info(i))) segmentsToOptimize.Add(segmentInfos.Info(i), segmentInfos.Info(i)); // Now mark all pending & running merges as optimize // merge: System.Collections.IEnumerator it = pendingMerges.GetEnumerator(); while (it.MoveNext()) { MergePolicy.OneMerge merge = (MergePolicy.OneMerge) it.Current; merge.optimize = true; merge.maxNumSegmentsOptimize = maxNumSegments; } it = runningMerges.GetEnumerator(); while (it.MoveNext()) { MergePolicy.OneMerge merge = (MergePolicy.OneMerge)((DictionaryEntry)it.Current).Value; merge.optimize = true; merge.maxNumSegmentsOptimize = maxNumSegments; } } MaybeMerge(maxNumSegments, true); if (doWait) { lock (this) { while (OptimizeMergesPending()) { try { System.Threading.Monitor.Wait(this); } catch (System.Threading.ThreadInterruptedException ie) { } if (mergeExceptions.Count > 0) { // Forward any exceptions in background merge // threads to the current thread: int size = mergeExceptions.Count; for (int i = 0; i < size; i++) { MergePolicy.OneMerge merge = (MergePolicy.OneMerge) mergeExceptions[0]; if (merge.optimize) { System.IO.IOException err = new System.IO.IOException("background merge hit exception: " + merge.SegString(directory), merge.GetException()); throw err; } } } } } } // NOTE: in the ConcurrentMergeScheduler case, when // doWait is false, we can return immediately while // background threads accomplish the optimization }
override public void Run() { try { docs = (sort == null) ? searchable.Search(weight, filter, nDocs) : searchable.Search(weight, filter, nDocs, sort); } // Store the IOException for later use by the caller of this thread catch (System.IO.IOException ioe) { this.ioe = ioe; } if (this.ioe == null) { // if we are sorting by fields, we need to tell the field sorted hit queue // the actual type of fields, in case the original list contained AUTO. // if the searchable returns null for fields, we'll have problems. if (sort != null) { ((FieldDocSortedHitQueue) hq).SetFields(((TopFieldDocs) docs).fields); } ScoreDoc[] scoreDocs = docs.scoreDocs; for (int j = 0; j < scoreDocs.Length; j++) { // merge scoreDocs into hq ScoreDoc scoreDoc = scoreDocs[j]; scoreDoc.doc += starts[i]; // convert doc //it would be so nice if we had a thread-safe insert lock (hq) { if (!hq.Insert(scoreDoc)) break; } // no more scores > minScore } } }
/// <summary>check that the query weight is serializable. </summary> /// <throws> IOException if serialization check fail. </throws> private static void CheckSerialization(Query q, Searcher s) { Weight w = q.Weight(s); try { System.IO.MemoryStream bos = new System.IO.MemoryStream(); System.IO.BinaryWriter oos = new System.IO.BinaryWriter(bos); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(oos.BaseStream, w); oos.Close(); System.IO.BinaryReader ois = new System.IO.BinaryReader(new System.IO.MemoryStream(bos.ToArray())); formatter.Deserialize(ois.BaseStream); ois.Close(); //skip rquals() test for now - most weights don't overide equals() and we won't add this just for the tests. //TestCase.assertEquals("writeObject(w) != w. ("+w+")",w2,w); } catch (System.Exception e) { System.IO.IOException e2 = new System.IO.IOException("Serialization failed for " + w, e); throw e2; } }
public override void Run() { try { docs = (sort == null)?searchable.Search(weight, filter, nDocs):searchable.Search(weight, filter, nDocs, sort); } // Store the IOException for later use by the caller of this thread catch (System.IO.IOException ioe) { this.ioe = ioe; } if (this.ioe == null) { // if we are sorting by fields, we need to tell the field sorted hit queue // the actual type of fields, in case the original list contained AUTO. // if the searchable returns null for fields, we'll have problems. if (sort != null) { TopFieldDocs docsFields = (TopFieldDocs) docs; // If one of the Sort fields is FIELD_DOC, need to fix its values, so that // it will break ties by doc Id properly. Otherwise, it will compare to // 'relative' doc Ids, that belong to two different searchables. for (int j = 0; j < docsFields.fields.Length; j++) { if (docsFields.fields[j].GetType() == SortField.DOC) { // iterate over the score docs and change their fields value for (int j2 = 0; j2 < docs.scoreDocs.Length; j2++) { FieldDoc fd = (FieldDoc) docs.scoreDocs[j2]; fd.fields[j] = (System.Int32) (((System.Int32) fd.fields[j]) + starts[i]); } break; } } ((FieldDocSortedHitQueue) hq).SetFields(docsFields.fields); } ScoreDoc[] scoreDocs = docs.scoreDocs; for (int j = 0; j < scoreDocs.Length; j++) { // merge scoreDocs into hq ScoreDoc scoreDoc = scoreDocs[j]; scoreDoc.doc += starts[i]; // convert doc //it would be so nice if we had a thread-safe insert lock (hq) { if (!hq.Insert(scoreDoc)) break; } // no more scores > minScore } } }
// Fixes http://code.google.com/p/android/issues/detail?id=1767. private void outputCharSequence(java.lang.CharSequence cs, int start, int end) { try { _out.append(cs, start, end); } catch (System.IO.IOException e) { lastIOException = e; } }