void UpdateFiles(string tempDir, string progDir, string backupFolder, List <FileFolder> rollbackList, ref int totalDone, ref int totalFiles) { DirectoryInfo tempDirInf = new DirectoryInfo(tempDir); //create an array of files using FileInfo object //get all files for the current directory FileInfo[] tempFiles = tempDirInf.GetFiles("*"); for (int i = 0; i < tempFiles.Length; i++) { if (IsCancelled()) { break; } int unweightedProgress = (totalDone * 100) / totalFiles; bw.ReportProgress(0, new object[] { GetRelativeProgess(4, unweightedProgress), unweightedProgress, "Updating " + tempFiles[i].Name, ProgressStatus.None, null }); if (File.Exists(Path.Combine(progDir, tempFiles[i].Name))) { int retriedTimes = 0; while (true) { try { string origFile = Path.Combine(progDir, tempFiles[i].Name); // backup File.Copy(origFile, Path.Combine(backupFolder, tempFiles[i].Name), true); FileAttributes atr = File.GetAttributes(origFile); bool resetAttributes = (atr & FileAttributes.Hidden) != 0 || (atr & FileAttributes.ReadOnly) != 0 || (atr & FileAttributes.System) != 0; // remove the ReadOnly & Hidden atributes temporarily if (resetAttributes) { File.SetAttributes(origFile, FileAttributes.Normal); } // replace File.Copy(tempFiles[i].FullName, origFile, true); if (resetAttributes) { File.SetAttributes(origFile, atr); } } catch (IOException IOEx) { int HResult = Marshal.GetHRForException(IOEx); int hr = (HResult & 0xFFFF); // if sharing violation, or "The requested operation cannot be performed on a file with a user-mapped section open." if (hr == 32 || hr == 1224) { if (!SkipUIReporting) { // notify main window of sharing violation bw.ReportProgress(0, new object[] { -1, -1, string.Empty, ProgressStatus.SharingViolation, Path.Combine(progDir, tempFiles[i].Name) }); } // sleep for 1 second Thread.Sleep(1000); // stop waiting if cancelled if (IsCancelled()) { break; } // if we're skipping UI and we've already waited 20 seconds for a file to be released // then throw the exception, rollback updates, etc if (SkipUIReporting && retriedTimes == 20) { throw; } // otherwise, retry file copy ++retriedTimes; continue; } throw; } break; } } else { //copy the file (don't "File.Move" because that doesn't properly inherit ACL settings) File.Copy(tempFiles[i].FullName, Path.Combine(progDir, tempFiles[i].Name), true); //add filename to "rollback" list rollbackList.Add(new FileFolder(Path.Combine(progDir, tempFiles[i].Name))); } //update % done totalDone++; } if (IsCancelled()) { return; } DirectoryInfo[] tempDirs = tempDirInf.GetDirectories("*"); for (int i = 0; i < tempDirs.Length; i++) { if (IsCancelled()) { break; } string newProgDir = Path.Combine(progDir, tempDirs[i].Name); if (!Directory.Exists(newProgDir)) { //create the prog subdirectory (no backup folder needed) Directory.CreateDirectory(newProgDir); //add to "rollback" list rollbackList.Add(new FileFolder(newProgDir, true)); } else { //prog subdirectory exists, create a backup folder Directory.CreateDirectory(Path.Combine(backupFolder, tempDirs[i].Name)); } //backup all of the files in that directory UpdateFiles(tempDirs[i].FullName, newProgDir, Path.Combine(backupFolder, tempDirs[i].Name), rollbackList, ref totalDone, ref totalFiles); } }
internal static bool IsDiskFullException(IOException exception) { uint hrforException = (uint)Marshal.GetHRForException(exception); return(hrforException == 2147942512U); }
private bool IsErrorFileExists(Exception e) => (Marshal.GetHRForException(e) & ((1 << 16) - 1)) == ErrorFileExists;
// Token: 0x06000320 RID: 800 RVA: 0x0000D81C File Offset: 0x0000BA1C public static string GetMessageWithHResult(this Exception ex) { return(string.Format(SharedDiag.s_exceptionMessageWithHrFormatString, ex.Message, Marshal.GetHRForException(ex))); }
public void Process(IntPtr hFile, string sFile, ISXMLElement pXML) { bool success = true; try { success = (Path.GetExtension(sFile) == @".fb2") && hFile != IntPtr.Zero; } catch { } if (!success) { Marshal.ThrowExceptionForHR(Hresults.E_INVALIDARG); } XmlReader reader = null; FictionBook book = null; Stream fs = null; try { XmlSerializer s = new XmlSerializer(typeof(FictionBook)); s.UnknownNode += new XmlNodeEventHandler(OnUnknownNode); s.UnknownAttribute += new XmlAttributeEventHandler(OnUnknownAttribute); fs = new FileStream(sFile, FileMode.Open, FileAccess.Read); reader = new XmlTextReader(fs); book = (FictionBook)s.Deserialize(reader); } catch (Exception e) { Trace.WriteLine(e.Message); Exception inner = e.InnerException; while (inner != null) { Trace.WriteLine(inner.Message); inner = inner.InnerException; } } finally { if (reader != null) { reader.Close(); } if (fs != null) { fs.Close(); } } if (book == null) { Marshal.ThrowExceptionForHR(Hresults.E_FAIL); } int result = Hresults.S_OK; try { CreatePeerProjectXml(book, ref pXML); } catch (Exception e) { Trace.WriteLine(e.Message); Exception inner = e.InnerException; while (inner != null) { Trace.WriteLine(inner.Message); inner = inner.InnerException; } result = Marshal.GetHRForException(e); } if (result != 0) { Trace.WriteLine("Error HRESULT=" + result.ToString()); Marshal.ThrowExceptionForHR(result); } }
/// <summary> /// Removes the items from the group that have been marked as deleted. /// </summary> public void RemoveItems() { // count the number of items to remove. List <GroupItem> itemsToRemove = new List <GroupItem>(); lock (Lock) { List <GroupItem> itemsToKeep = new List <GroupItem>(); for (int ii = 0; ii < m_items.Count; ii++) { if (m_items[ii].Deleted && m_items[ii].Created) { itemsToRemove.Add(m_items[ii]); continue; } itemsToKeep.Add(m_items[ii]); } m_items = itemsToKeep; } // check if nothing to do. if (itemsToRemove.Count == 0) { return; } // build list of items to remove. int count = itemsToRemove.Count; int[] serverHandles = new int[count]; for (int ii = 0; ii < itemsToRemove.Count; ii++) { serverHandles[ii] = itemsToRemove[ii].ServerHandle; // remove the associated monitored items. if (m_monitoredItems != null) { lock (m_monitoredItems) { m_monitoredItems.Remove(itemsToRemove[ii].ClientHandle); } } } IntPtr pErrors = IntPtr.Zero; string methodName = "IOPCItemMgt.RemoveItems"; try { IOPCItemMgt server = BeginComCall <IOPCItemMgt>(methodName, true); // remove items. server.RemoveItems( count, serverHandles, out pErrors); } catch (Exception e) { ComUtils.TraceComError(e, methodName); for (int ii = 0; ii < itemsToRemove.Count; ii++) { itemsToRemove[ii].Created = false; itemsToRemove[ii].ErrorId = Marshal.GetHRForException(e); } return; } finally { EndComCall(methodName); } // free returned error array. int[] errors = ComUtils.GetInt32s(ref pErrors, count, true); // save error codes. for (int ii = 0; ii < count; ii++) { itemsToRemove[ii].Created = false; itemsToRemove[ii].ErrorId = errors[ii]; } /* * Utils.Trace( * "Group {0} RemoveItems({4}/{5}) {1}/{2}ms {3}%", * m_clientHandle, * m_samplingInterval, * m_actualSamplingInterval, * m_deadband, * itemsToRemove.Count, * m_items.Count); */ }
private static bool IsFileLockedError(Exception exception) { var code = Marshal.GetHRForException(exception) & ((1 << 16) - 1); return(code == 32 || code == 33); }
public NtStatus CreateFile(string fileName, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, DokanFileInfo info) { var filePath = GetPath(fileName); if (info.IsDirectory) { try { switch (mode) { case FileMode.Open: if (!Directory.Exists(filePath)) { try { if (!File.GetAttributes(filePath).HasFlag(FileAttributes.Directory)) { return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, NtStatus.NotADirectory)); } } catch (Exception) { return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.FileNotFound)); } return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.PathNotFound)); } new DirectoryInfo(filePath).EnumerateFileSystemInfos().Any(); // you can't list the directory break; case FileMode.CreateNew: if (Directory.Exists(filePath)) { return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.FileExists)); } try { File.GetAttributes(filePath).HasFlag(FileAttributes.Directory); return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.AlreadyExists)); } catch (IOException) { } Directory.CreateDirectory(GetPath(fileName)); break; } } catch (UnauthorizedAccessException) { return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.AccessDenied)); } } else { var pathExists = true; var pathIsDirectory = false; var readWriteAttributes = (access & DataAccess) == 0; var readAccess = (access & DataWriteAccess) == 0; try { pathExists = (Directory.Exists(filePath) || File.Exists(filePath)); pathIsDirectory = File.GetAttributes(filePath).HasFlag(FileAttributes.Directory); } catch (IOException) { } switch (mode) { case FileMode.Open: if (pathExists) { if (readWriteAttributes || pathIsDirectory) // check if driver only wants to read attributes, security info, or open directory { if (pathIsDirectory && (access & FileAccess.Delete) == FileAccess.Delete && (access & FileAccess.Synchronize) != FileAccess.Synchronize) { //It is a DeleteFile request on a directory return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.AccessDenied)); } info.IsDirectory = pathIsDirectory; info.Context = new object(); // must set it to someting if you return DokanError.Success return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.Success)); } } else { return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.FileNotFound)); } break; case FileMode.CreateNew: if (pathExists) { return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.FileExists)); } break; case FileMode.Truncate: if (!pathExists) { return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.FileNotFound)); } break; } try { info.Context = new FileStream(filePath, mode, readAccess ? System.IO.FileAccess.Read : System.IO.FileAccess.ReadWrite, share, 4096, options); if (mode == FileMode.CreateNew || mode == FileMode.Create) //Files are always created as Archive { attributes |= FileAttributes.Archive; } File.SetAttributes(filePath, attributes); } catch (UnauthorizedAccessException) // don't have access rights { return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.AccessDenied)); } catch (DirectoryNotFoundException) { return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.PathNotFound)); } catch (Exception ex) { var hr = (uint)Marshal.GetHRForException(ex); switch (hr) { case 0x80070020: //Sharing violation return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.SharingViolation)); default: throw; } } } return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.Success)); }
private int Callback(IntPtr hwnd, uint uNotification, UIntPtr wParam, IntPtr lParam, IntPtr lpRefData) { try { switch ((NativeMethods.TASKDIALOG_NOTIFICATION)uNotification) { case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_CREATED: foreach (var btn in this._buttons.Where(b => b.ElevationRequired)) { NativeMethods.SendMessage( hwnd, (int)NativeMethods.TASKDIALOG_MESSAGE.TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE, new IntPtr(GetButtonId(btn, this._buttons)), new IntPtr(1) ); } break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_NAVIGATED: break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_BUTTON_CLICKED: break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_HYPERLINK_CLICKED: var url = Marshal.PtrToStringUni(lParam); var hevt = HyperlinkClicked; if (hevt != null) { hevt(this, new TaskDialogHyperlinkClickedEventArgs(url)); } else { Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true }); } break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_TIMER: break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_DESTROYED: break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_RADIO_BUTTON_CLICKED: break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_DIALOG_CONSTRUCTED: break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_VERIFICATION_CLICKED: break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_HELP: break; case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_EXPANDO_BUTTON_CLICKED: break; default: break; } return(VSConstants.S_OK); } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } return(Marshal.GetHRForException(ex)); } }
private void RenameComponentDirectory(CyPhy.Component component, string oldPath) { if (string.IsNullOrEmpty(oldPath) || Path.GetFullPath(oldPath) == Path.GetFullPath(component.Attributes.Path)) { return; } // CPMDecorator may hold handle to icon. Try to free it. (Doesn't work if still open in the model editor) CoFreeUnusedLibraries(); // Check to see if this "changed" path is the same one we saw last time we were in this function, post-normalization. // If so, then don't consider this a rename, and return. var componentGuid = component.Guid.ToString(); String lastPath; if (lastObservedPaths.TryGetValue(componentGuid, out lastPath) && lastPath.Equals(component.Attributes.Path)) { return; } var project = component.Impl.Project; var projectRoot = Path.GetFullPath(project.GetRootDirectoryPath()); if (Directory.Exists(Path.Combine(projectRoot, component.Attributes.Path))) { var console = GMEConsole.CreateFromProject(project); if (console.gme != null) { console.Error.WriteLine(String.Format("Cannot move component directory to {0}: this directory already exists.", component.Attributes.Path)); Marshal.FinalReleaseComObject(console.gme); } Marshal.ThrowExceptionForHR(-2023391233); // E_MGA_CONSTRAINT_VIOLATION = 0x87657fff } if (Directory.Exists(Path.Combine(projectRoot, oldPath))) { // Normalize path syntax if (component.Attributes.Path.Contains("\\")) { component.Attributes.Path = component.Attributes.Path.Replace("\\", "/"); } if (component.Attributes.Path.EndsWith("/") == false) { component.Attributes.Path = component.Attributes.Path + "/"; } var pathWithoutTrailingSlash = Path.GetDirectoryName(component.Attributes.Path); // Directory.CreateDirectory(Path.Combine(projectRoot, Path.GetDirectoryName(pathWithoutTrailingSlash))); try { Directory.Move(Path.Combine(projectRoot, oldPath), Path.Combine(projectRoot, pathWithoutTrailingSlash)); } catch (IOException e) { var console = GMEConsole.CreateFromProject(project); if (console.gme != null) { string msg = String.Format("Cannot move component directory {0}.", oldPath); const int E_SHARING_VIOLATION = unchecked ((int)0x80070020); const int E_ACCESS_DENIED = unchecked ((int)0x80070005); if (Marshal.GetHRForException(e) == E_SHARING_VIOLATION || Marshal.GetHRForException(e) == E_ACCESS_DENIED) { msg = msg + " Check that the folder and files it contains are not open in another program."; } console.Info.WriteLine(msg); //Marshal.FinalReleaseComObject(console.gme); } throw; } var iconPath = (component.Impl as GME.MGA.IMgaFCO).get_RegistryValue("icon"); if (String.IsNullOrWhiteSpace(iconPath) == false) { iconPath = iconPath.Replace(oldPath, component.Attributes.Path); (component.Impl as GME.MGA.IMgaFCO).set_RegistryValue("icon", iconPath); } { var console = GMEConsole.CreateFromProject(project); if (console.gme != null) { console.Info.WriteLine(String.Format("Moved component directory from {0} to {1}", oldPath, component.Attributes.Path)); //Marshal.FinalReleaseComObject(console.gme); } } } lastObservedPaths[componentGuid] = component.Attributes.Path; }
internal static void ImportExportEncryptedFileDirectoryRawCore(bool isExport, bool isFolder, Stream stream, string destinationPath, PathFormat pathFormat, bool overwriteHidden) { string destinationPathLp = Path.GetExtendedLengthPathCore(null, destinationPath, pathFormat, GetFullPathOptions.FullCheck | GetFullPathOptions.TrimEnd); NativeMethods.EncryptedFileRawMode mode = isExport ? NativeMethods.EncryptedFileRawMode.CreateForExport : NativeMethods.EncryptedFileRawMode.CreateForImport; if (isFolder) { mode = mode | NativeMethods.EncryptedFileRawMode.CreateForDir; } if (overwriteHidden) { mode = mode | NativeMethods.EncryptedFileRawMode.OverwriteHidden; } // OpenEncryptedFileRaw() // 2015-08-02: MSDN does not confirm LongPath usage but a Unicode version of this function exists. SafeEncryptedFileRawHandle context; var lastError = NativeMethods.OpenEncryptedFileRaw(destinationPathLp, mode, out context); try { if (lastError != Win32Errors.ERROR_SUCCESS) { NativeError.ThrowException(lastError, destinationPathLp); } lastError = isExport ? NativeMethods.ReadEncryptedFileRaw((pbData, pvCallbackContext, length) => { try { var data = new byte[length]; Marshal.Copy(pbData, data, 0, (int)length); stream.Write(data, 0, (int)length); } catch (Exception ex) { return(Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift); } return((int)Win32Errors.ERROR_SUCCESS); }, IntPtr.Zero, context) : NativeMethods.WriteEncryptedFileRaw((IntPtr pbData, IntPtr pvCallbackContext, ref uint length) => { try { var data = new byte[length]; length = (uint)stream.Read(data, 0, (int)length); if (length == 0) { return((int)Win32Errors.ERROR_SUCCESS); } Marshal.Copy(data, 0, pbData, (int)length); } catch (Exception ex) { return(Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift); } return((int)Win32Errors.ERROR_SUCCESS); }, IntPtr.Zero, context); if (lastError != Win32Errors.ERROR_SUCCESS) { NativeError.ThrowException(lastError, destinationPathLp); } } finally { if (context != null) { context.Dispose(); } } }
public NtStatus UnsafeCreateFile(string fileName, DokanNet.FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, DokanFileInfo info) { string writePath = GetWritePath(fileName); string readOnlyPath = GetReadOnlyPath(fileName); if (info.IsDirectory) { if (mode == FileMode.CreateNew) { if (Directory.Exists(writePath)) { return(DokanResult.FileExists); } else if (File.Exists(writePath)) { return(DokanResult.AlreadyExists); } else if (Directory.Exists(readOnlyPath)) { return(DokanResult.FileExists); } else if (File.Exists(readOnlyPath)) { return(DokanResult.AlreadyExists); } info.Context = new LayeredDirectoryContext(fileName) { WriteDirInfo = Directory.CreateDirectory(writePath) }; return(DokanResult.Success); } else if (mode == FileMode.Open) { var context = new LayeredDirectoryContext(fileName); if (Directory.Exists(writePath)) { context.WriteDirInfo = new DirectoryInfo(writePath); } else if (File.Exists(writePath)) { return(DokanResult.NotADirectory); } if (Directory.Exists(readOnlyPath)) { context.ReadOnlyDirInfo = new DirectoryInfo(readOnlyPath); } else if (context.WriteDirInfo == null) { if (File.Exists(readOnlyPath)) { return(DokanResult.NotADirectory); } else { return(DokanResult.PathNotFound); } } info.Context = context; return(DokanResult.Success); } else { // unkown operation return(DokanResult.Unsuccessful); } } else { var writable = false; var pathExists = false; var pathIsDirectory = Directory.Exists(writePath); if (pathIsDirectory) { pathExists = true; } else if (File.Exists(writePath)) { writable = true; pathExists = true; } else { if (pathIsDirectory = Directory.Exists(readOnlyPath)) { pathExists = true; pathIsDirectory = true; } else { pathExists = File.Exists(readOnlyPath); } } var readAttributes = (access & ReadAttributes) == 0; var readAccess = (access & DataWriteAccess) == 0; switch (mode) { case FileMode.Open: if (!pathExists) { return(DokanResult.FileNotFound); } else { if (pathIsDirectory) { info.IsDirectory = true; if ((access & FileAccess.Delete) == FileAccess.Delete && (access & FileAccess.Synchronize) != FileAccess.Synchronize) { // it is a DeleteFile request on a directory return(DokanResult.AccessDenied); } // call it again, with the IsDirectory set to true return(UnsafeCreateFile(fileName, access, share, mode, options, attributes, info)); } else if (readAttributes) { info.Context = new LayeredReadAttributesContext(fileName, writable ? writePath : readOnlyPath, pathIsDirectory); return(DokanResult.Success); } } break; case FileMode.CreateNew: if (writable) { if (pathExists) { return(DokanResult.FileExists); } } writable = true; break; case FileMode.Create: writable = true; break; case FileMode.Truncate: if (!pathExists) { return(DokanResult.FileNotFound); } break; case FileMode.OpenOrCreate: if (!pathExists) { writable = true; } break; default: throw new Exception($"Unhandled FileMode {mode.ToString("g")}"); } if (writable) { var path = Path.GetDirectoryName(writePath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } else if (!readAccess) { var path = Path.GetDirectoryName(writePath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.Copy(readOnlyPath, writePath, true); FileInfo finfo = new FileInfo(readOnlyPath); File.SetCreationTime(writePath, finfo.CreationTime); File.SetLastAccessTime(writePath, finfo.LastAccessTime); File.SetLastWriteTime(writePath, finfo.LastWriteTime); writable = true; } LayeredFileContext context = new LayeredFileContext(fileName, writable ? writePath : readOnlyPath, writable); info.Context = context; try { context.Stream = new FileStream(writable ? writePath : readOnlyPath, mode, readAccess ? System.IO.FileAccess.Read : System.IO.FileAccess.ReadWrite, share, 4096, options); } catch (Exception ex) { var hr = (uint)Marshal.GetHRForException(ex); switch (hr) { case 0x80070020: //Sharing violation return(DokanResult.SharingViolation); default: throw; } } if (mode == FileMode.CreateNew || mode == FileMode.Create) // files are always created as Archive { attributes |= FileAttributes.Archive; context.SetAttributes(attributes); } return(DokanResult.Success); } }
//----------------------------------------------------------------------------- // PresentSample // // Presents a video frame. // // pSample: Pointer to the sample that contains the surface to present. If // this parameter is NULL, the method paints a black rectangle. // llTarget: Target presentation time. // // This method is called by the scheduler and/or the presenter. //----------------------------------------------------------------------------- public void PresentSample(IMFSample pSample, long llTarget) { HResult hr; IMFMediaBuffer pBuffer = null; IDirect3DSurface9 pSurface = null; IDirect3DSwapChain9 pSwapChain = null; object o; try { if (pSample != null) { // Get the buffer from the sample. hr = pSample.GetBufferByIndex(0, out pBuffer); MFError.ThrowExceptionForHR(hr); // Get the surface from the buffer. hr = MFExtern.MFGetService(pBuffer, MFServices.MR_BUFFER_SERVICE, typeof(IDirect3DSurface9).GUID, out o); MFError.ThrowExceptionForHR(hr); pSurface = o as IDirect3DSurface9; } else if (m_pSurfaceRepaint != null) { // Redraw from the last surface. pSurface = m_pSurfaceRepaint; } if (pSurface != null) { // Get the swap chain from the surface. pSurface.GetContainer(typeof(IDirect3DSwapChain9).GUID, out o); pSwapChain = o as IDirect3DSwapChain9; // Present the swap chain. PresentSwapChain(pSwapChain, pSurface); // Store this pointer in case we need to repaint the surface. if (m_pSurfaceRepaint != pSurface) { SafeRelease(m_pSurfaceRepaint); m_pSurfaceRepaint = pSurface; } } else { // No surface. All we can do is paint a black rectangle. PaintFrameWithGDI(); } } catch (Exception e) { hr = (HResult)Marshal.GetHRForException(e); if (hr == (HResult)D3DError.DeviceLost || hr == (HResult)D3DError.DeviceNotReset || hr == (HResult)D3DError.DeviceHung) { // We failed because the device was lost. Fill the destination rectangle. PaintFrameWithGDI(); // Ignore. We need to reset or re-create the device, but this method // is probably being called from the scheduler thread, which is not the // same thread that created the device. The Reset(Ex) method must be // called from the thread that created the device. // The presenter will detect the state when it calls CheckDeviceState() // on the next sample. } } finally { SafeRelease(pSwapChain); pSwapChain = null; //SafeRelease(pSurface); pSurface = null; SafeRelease(pBuffer); pBuffer = null; } }
public static bool IsFileLocked(IOException exception) { int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1); return(errorCode == 32 || errorCode == 33); }
/// <summary> /// Adds all items to the group that have not already been added. /// </summary> public void AddItems() { // count the number of items to add. List <GroupItem> itemsToAdd = new List <GroupItem>(); lock (Lock) { for (int ii = 0; ii < m_items.Count; ii++) { if (!m_items[ii].Created) { itemsToAdd.Add(m_items[ii]); } } } // check if nothing to do. if (itemsToAdd.Count == 0) { return; } // create item definitions. int count = itemsToAdd.Count; OpcRcw.Da.OPCITEMDEF[] definitions = new OpcRcw.Da.OPCITEMDEF[count]; for (int ii = 0; ii < count; ii++) { definitions[ii] = new OpcRcw.Da.OPCITEMDEF(); definitions[ii].szItemID = itemsToAdd[ii].ItemId; definitions[ii].bActive = (itemsToAdd[ii].Active) ? 1 : 0; definitions[ii].szAccessPath = String.Empty; definitions[ii].vtRequestedDataType = (short)VarEnum.VT_EMPTY; definitions[ii].hClient = itemsToAdd[ii].ClientHandle; } // initialize output parameters. IntPtr pResults = IntPtr.Zero; IntPtr pErrors = IntPtr.Zero; // add items to group. string methodName = "IOPCItemMgt.AddItems"; try { IOPCItemMgt server = BeginComCall <IOPCItemMgt>(methodName, true); server.AddItems( count, definitions, out pResults, out pErrors); } catch (Exception e) { ComUtils.TraceComError(e, methodName); for (int ii = 0; ii < itemsToAdd.Count; ii++) { itemsToAdd[ii].ErrorId = Marshal.GetHRForException(e); } return; } finally { EndComCall(methodName); } // unmarshal output parameters. int[] serverHandles = GetItemResults(ref pResults, count, true); int[] errors = ComUtils.GetInt32s(ref pErrors, count, true); // save handles and error codes. for (int ii = 0; ii < count; ii++) { GroupItem item = itemsToAdd[ii]; item.ServerHandle = serverHandles[ii]; item.ErrorId = errors[ii]; if (item.ErrorId >= 0) { itemsToAdd[ii].Created = true; } } /* * Utils.Trace( * "Group {0} AddItems({4}/{5}) {1}/{2}ms {3}%", * m_clientHandle, * m_samplingInterval, * m_actualSamplingInterval, * m_deadband, * itemsToAdd.Count, * m_items.Count); */ }
static bool IsFileBusyException(IOException exc) { var hr = (uint)Marshal.GetHRForException(exc); return(hr == 0x80070020); // The process cannot access the file because it is being used by another process. }
/// <summary> /// Sets the active state for a set of items in a group. /// </summary> public void ActivateItems(bool active) { // count the number of items to activate. List <GroupItem> itemsToActivate = new List <GroupItem>(); lock (Lock) { for (int ii = 0; ii < m_items.Count; ii++) { if (m_items[ii].ActiveChanged && m_items[ii].Active == active && m_items[ii].Created) { itemsToActivate.Add(m_items[ii]); } } } // check if nothing to do. if (itemsToActivate.Count == 0) { return; } // build list of items to remove. int count = itemsToActivate.Count; int[] serverHandles = new int[count]; for (int ii = 0; ii < itemsToActivate.Count; ii++) { serverHandles[ii] = itemsToActivate[ii].ServerHandle; } // initialize output parameters. IntPtr pErrors = IntPtr.Zero; string methodName = "IOPCItemMgt.SetActiveState"; try { IOPCItemMgt server = BeginComCall <IOPCItemMgt>(methodName, true); server.SetActiveState( count, serverHandles, (active) ? 1 : 0, out pErrors); } catch (Exception e) { ComUtils.TraceComError(e, methodName); for (int ii = 0; ii < itemsToActivate.Count; ii++) { itemsToActivate[ii].ActiveChanged = false; itemsToActivate[ii].ErrorId = Marshal.GetHRForException(e); } } finally { EndComCall(methodName); } // free returned error array. int[] errors = ComUtils.GetInt32s(ref pErrors, count, true); // save error codes. for (int ii = 0; ii < count; ii++) { itemsToActivate[ii].ActiveChanged = false; itemsToActivate[ii].ErrorId = errors[ii]; } /* * Utils.Trace( * "Group {0} ActivateItems({4}/{5}) {1}/{2}ms {3}%", * m_clientHandle, * m_samplingInterval, * m_actualSamplingInterval, * m_deadband, * active, * itemsToActivate.Count); */ }
// Token: 0x0600034D RID: 845 RVA: 0x00018928 File Offset: 0x00016B28 private static uint _HRForException(Exception ex1) { return((uint)Marshal.GetHRForException(ex1)); }
static void Main(string[] Args) { try { String RawDiskFile = null; UInt32 BlockCount = 1024 * 1024; UInt32 BlockLength = 512; String ProductId = "RawDisk-dotnet"; String ProductRevision = "1.0"; UInt32 WriteAllowed = 1; UInt32 CacheSupported = 1; UInt32 UnmapSupported = 1; UInt32 DebugFlags = 0; String DebugLogFile = null; String PipeName = null; StorageUnitHost Host = null; RawDisk RawDisk = null; int I; for (I = 0; Args.Length > I; I++) { String Arg = Args[I]; if ('-' != Arg[0]) break; switch (Arg[1]) { case '?': throw new CommandLineUsageException(); case 'c': argtol(Args, ref I, ref BlockCount); break; case 'C': argtol(Args, ref I, ref CacheSupported); break; case 'd': argtol(Args, ref I, ref DebugFlags); break; case 'D': argtos(Args, ref I, ref DebugLogFile); break; case 'f': argtos(Args, ref I, ref RawDiskFile); break; case 'i': argtos(Args, ref I, ref ProductId); break; case 'l': argtol(Args, ref I, ref BlockLength); break; case 'p': argtos(Args, ref I, ref PipeName); break; case 'r': argtos(Args, ref I, ref ProductRevision); break; case 'U': argtol(Args, ref I, ref UnmapSupported); break; case 'W': argtol(Args, ref I, ref WriteAllowed); break; default: throw new CommandLineUsageException(); } } if (Args.Length > I) throw new CommandLineUsageException(); if (null == RawDiskFile) throw new CommandLineUsageException(); if (null != DebugLogFile) if (0 != StorageUnitHost.SetDebugLogFile(DebugLogFile)) throw new CommandLineUsageException("cannot open debug log file"); Host = new StorageUnitHost(RawDisk = new RawDisk(RawDiskFile, BlockCount, BlockLength)); Host.ProductId = ProductId; Host.ProductRevisionLevel = ProductRevision; Host.WriteProtected = 0 == WriteAllowed; Host.CacheSupported = 0 != CacheSupported; Host.UnmapSupported = 0 != UnmapSupported; if (0 != Host.Start(PipeName, DebugFlags)) throw new IOException("cannot start storage unit"); StorageUnitHost.Log(StorageUnitHost.EVENTLOG_INFORMATION_TYPE, String.Format( "{0} -f {1} -c {2} -l {3} -i {4} -r {5} -W {6} -C {7} -U {8}{9}{10}", PROGNAME, RawDiskFile, BlockCount, BlockLength, ProductId, ProductRevision, 0 != WriteAllowed ? 1 : 0, 0 != CacheSupported ? 1 : 0, 0 != UnmapSupported ? 1 : 0, null != PipeName ? " -p " : "", null != PipeName ? PipeName : "")); Console.CancelKeyPress += delegate (Object Sender, ConsoleCancelEventArgs Event) { Host.Shutdown(); Event.Cancel = true; }; Host.Wait(); } catch (CommandLineUsageException ex) { StorageUnitHost.Log(StorageUnitHost.EVENTLOG_ERROR_TYPE, String.Format( "{0}" + "usage: {1} OPTIONS\n" + "\n" + "options:\n" + " -f RawDiskFile Storage unit data file\n" + " -c BlockCount Storage unit size in blocks\n" + " -l BlockLength Storage unit block length\n" + " -i ProductId 1-16 chars\n" + " -r ProductRevision 1-4 chars\n" + " -W 0|1 Disable/enable writes (deflt: enable)\n" + " -C 0|1 Disable/enable cache (deflt: enable)\n" + " -U 0|1 Disable/enable unmap (deflt: enable)\n" + " -d -1 Debug flags\n" + " -D DebugLogFile Debug log file; - for stderr\n" + " -p \\\\.\\pipe\\PipeName Listen on pipe; omit to use driver\n", ex.HasMessage ? ex.Message + "\n" : "", PROGNAME)); Environment.ExitCode = 87/*ERROR_INVALID_PARAMETER*/; } catch (Exception ex) { if (ex is TypeInitializationException && null != ex.InnerException) ex = ex.InnerException; StorageUnitHost.Log(StorageUnitHost.EVENTLOG_ERROR_TYPE, ex.Message); int hr = Marshal.GetHRForException(ex); Environment.ExitCode = Marshal.GetHRForException(ex); if ((hr & 0xffff0000) == 0x80070000) Environment.ExitCode = hr & 0xffff; else Environment.ExitCode = 574/*ERROR_UNHANDLED_EXCEPTION*/; } }
public HotkeyAlreadyRegisteredException(string name, Exception inner) : base(inner.Message, inner) { _name = name; HResult = Marshal.GetHRForException(inner); }
/// <summary> /// Rename the underlying document based on the change the user just made to the edit label. /// </summary> protected internal override int SetEditLabel(string label, string relativePath) { int returnValue = VSConstants.S_OK; uint oldId = this.ID; string strSavePath = Path.GetDirectoryName(relativePath); strSavePath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectMgr.ProjectHome, strSavePath); string newName = Path.Combine(strSavePath, label); if (String.Equals(newName, this.Url, StringComparison.Ordinal)) { // This is really a no-op (including changing case), so there is nothing to do return(VSConstants.S_FALSE); } else if (String.Equals(newName, this.Url, StringComparison.OrdinalIgnoreCase)) { // This is a change of file casing only. } else { // If the renamed file already exists then quit (unless it is the result of the parent having done the move). if (IsFileOnDisk(newName) && (IsFileOnDisk(this.Url) || !String.Equals(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.OrdinalIgnoreCase))) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, CultureInfo.CurrentUICulture), label)); } else if (newName.Length > NativeMethods.MAX_PATH) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.PathTooLong, CultureInfo.CurrentUICulture), label)); } } string oldName = this.Url; // must update the caption prior to calling RenameDocument, since it may // cause queries of that property (such as from open editors). string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include); try { if (!RenameDocument(oldName, newName)) { this.ItemNode.Rename(oldrelPath); } if (this is DependentFileNode) { ProjectMgr.OnInvalidateItems(this.Parent); } } catch (Exception e) { // Just re-throw the exception so we don't get duplicate message boxes. Trace.WriteLine("Exception : " + e.Message); this.RecoverFromRenameFailure(newName, oldrelPath); returnValue = Marshal.GetHRForException(e); throw; } // Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale // hierarchy item id. if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED) { return((oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE); } return(returnValue); }
/// <summary> /// Updates database with signatures from external cabinets. /// </summary> /// <param name="databaseFile">Path to MSI database.</param> /// <param name="outputFile">Ouput for updated MSI database.</param> /// <param name="tidy">Clean up files.</param> /// <returns>True if database is updated.</returns> public bool InscribeDatabase(string databaseFile, string outputFile, bool tidy) { // Keeps track of whether we've encountered at least one signed cab or not - we'll throw a warning if no signed cabs were encountered bool foundUnsignedExternals = false; bool shouldCommit = false; FileAttributes attributes = File.GetAttributes(databaseFile); if (FileAttributes.ReadOnly == (attributes & FileAttributes.ReadOnly)) { this.OnMessage(WixErrors.ReadOnlyOutputFile(databaseFile)); return(shouldCommit); } using (Database database = new Database(databaseFile, OpenDatabase.Transact)) { // Just use the English codepage, because the tables we're importing only have binary streams / MSI identifiers / other non-localizable content int codepage = 1252; // reset list of certificates seen for this database Dictionary <string, object> certificates = new Dictionary <string, object>(); // Reset the in-memory tables for this new database Table digitalSignatureTable = new Table(null, this.tableDefinitions["MsiDigitalSignature"]); Table digitalCertificateTable = new Table(null, this.tableDefinitions["MsiDigitalCertificate"]); using (View mediaView = database.OpenExecuteView("SELECT * FROM Media")) { while (true) { using (Record mediaRecord = mediaView.Fetch()) { if (null == mediaRecord) { break; } X509Certificate2 cert2 = null; Row digitalSignatureRow = null; string cabName = mediaRecord.GetString(4); // get the name of the cab // If there is no cabinet or it's an internal cab, skip it. if (String.IsNullOrEmpty(cabName) || cabName.StartsWith("#", StringComparison.Ordinal)) { continue; } string cabId = mediaRecord.GetString(1); // get the ID of the cab string cabPath = Path.Combine(Path.GetDirectoryName(databaseFile), cabName); // If the cabs aren't there, throw an error but continue to catch the other errors if (!File.Exists(cabPath)) { this.OnMessage(WixErrors.WixFileNotFound(cabPath)); continue; } try { // Get the certificate from the cab X509Certificate signedFileCert = X509Certificate.CreateFromSignedFile(cabPath); cert2 = new X509Certificate2(signedFileCert); } catch (System.Security.Cryptography.CryptographicException e) { uint HResult = unchecked ((uint)Marshal.GetHRForException(e)); // If the file has no cert, continue, but flag that we found at least one so we can later give a warning if (0x80092009 == HResult) // CRYPT_E_NO_MATCH { foundUnsignedExternals = true; continue; } // todo: exactly which HRESULT corresponds to this issue? // If it's one of these exact platforms, warn the user that it may be due to their OS. if ((5 == Environment.OSVersion.Version.Major && 2 == Environment.OSVersion.Version.Minor) || // W2K3 (5 == Environment.OSVersion.Version.Major && 1 == Environment.OSVersion.Version.Minor)) // XP { this.OnMessage(WixErrors.UnableToGetAuthenticodeCertOfFileDownlevelOS(cabPath, String.Format(CultureInfo.InvariantCulture, "HRESULT: 0x{0:x8}", HResult))); } else // otherwise, generic error { this.OnMessage(WixErrors.UnableToGetAuthenticodeCertOfFile(cabPath, String.Format(CultureInfo.InvariantCulture, "HRESULT: 0x{0:x8}", HResult))); } } // If we haven't added this cert to the MsiDigitalCertificate table, set it up to be added if (!certificates.ContainsKey(cert2.Thumbprint)) { // Add it to our "add to MsiDigitalCertificate" table dictionary Row digitalCertificateRow = digitalCertificateTable.CreateRow(null); digitalCertificateRow[0] = cert2.Thumbprint; // Export to a file, because the MSI API's require us to provide a file path on disk string certPath = Path.Combine(this.TempFilesLocation, "MsiDigitalCertificate"); Directory.CreateDirectory(certPath); certPath = Path.Combine(certPath, cert2.Thumbprint + ".cer"); File.Delete(certPath); using (BinaryWriter writer = new BinaryWriter(File.Open(certPath, FileMode.Create))) { writer.Write(cert2.RawData); writer.Close(); } // Now set the file path on disk where this binary stream will be picked up at import time digitalCertificateRow[1] = cert2.Thumbprint + ".cer"; certificates.Add(cert2.Thumbprint, certPath); } digitalSignatureRow = digitalSignatureTable.CreateRow(null); digitalSignatureRow[0] = "Media"; digitalSignatureRow[1] = cabId; digitalSignatureRow[2] = cert2.Thumbprint; } } } if (digitalSignatureTable.Rows.Count > 0) { database.ImportTable(codepage, (IMessageHandler)this, digitalSignatureTable, this.TempFilesLocation, true); shouldCommit = true; } if (digitalCertificateTable.Rows.Count > 0) { database.ImportTable(codepage, (IMessageHandler)this, digitalCertificateTable, this.TempFilesLocation, true); shouldCommit = true; } certificates = null; // If we did find external cabs but none of them were signed, give a warning if (foundUnsignedExternals) { this.OnMessage(WixWarnings.ExternalCabsAreNotSigned(databaseFile)); } if (shouldCommit) { database.Commit(); } } return(shouldCommit); }
public static int GetHResult(this Exception exception) { return(Marshal.GetHRForException(exception)); }
public override IMessage Invoke(IMessage message) { RealProxy proxy = null; IMethodCallMessage mcm = message as IMethodCallMessage; try { proxy = this.serviceChannelCreator.CreateChannel(); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } return(new ReturnMessage(DiagnosticUtility.ExceptionUtility.ThrowHelperError(new COMException(exception.GetBaseException().Message, Marshal.GetHRForException(exception.GetBaseException()))), mcm)); } MethodBase methodBase = mcm.MethodBase; IRemotingTypeInfo info = proxy as IRemotingTypeInfo; if (info == null) { throw Fx.AssertAndThrow("Type Info cannot be null"); } if (info.CanCastTo(methodBase.DeclaringType, null)) { IMessage message3 = proxy.Invoke(message); ReturnMessage message4 = message3 as ReturnMessage; if ((message4 != null) && (message4.Exception != null)) { return(new ReturnMessage(DiagnosticUtility.ExceptionUtility.ThrowHelperError(new COMException(message4.Exception.GetBaseException().Message, Marshal.GetHRForException(message4.Exception.GetBaseException()))), mcm)); } return(message3); } return(new ReturnMessage(DiagnosticUtility.ExceptionUtility.ThrowHelperError(new COMException(System.ServiceModel.SR.GetString("OperationNotFound", new object[] { methodBase.Name }), HR.DISP_E_UNKNOWNNAME)), mcm)); }
internal static bool IsVolumeLockedException(IOException exception) { int hrforException = Marshal.GetHRForException(exception); return(FileOperations.IsVolumeLockedHResult(hrforException)); }
public void DoSplit() { HResult hr; bool bHasVideo = false; IMFByteStream pStream = null; IMFASFContentInfo pContentInfo = null; IMFASFSplitter pSplitter = null; Console.WriteLine(string.Format("Opening {0}.", m_sFileName)); try { // Start the Media Foundation platform. hr = MFExtern.MFStartup(0x10070, MFStartup.Full); MFError.ThrowExceptionForHR(hr); // Open the file. OpenFile(m_sFileName, out pStream); // Read the ASF header. CreateContentInfo(pStream, out pContentInfo); // Create the ASF splitter. CreateASFSplitter(pContentInfo, out pSplitter); // Select the first video stream. SelectVideoStream(pContentInfo, pSplitter, out bHasVideo); // Parse the ASF file. if (bHasVideo) { DisplayKeyFrames(pStream, pSplitter); } else { Console.WriteLine("No video stream."); } } catch (Exception e) { hr = (HResult)Marshal.GetHRForException(e); string s = MFError.GetErrorText(hr); if (s == null) { s = e.Message; } else { s = string.Format("{0} ({1})", s, e.Message); } Console.WriteLine(string.Format("Exception 0x{0:x}: {1}", hr, s)); } finally { // Clean up. SafeRelease(pSplitter); SafeRelease(pContentInfo); SafeRelease(pStream); } // Shut down the Media Foundation platform. hr = MFExtern.MFShutdown(); MFError.ThrowExceptionForHR(hr); }
int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { RoslynDebug.AssertNotNull(_batchElements); RoslynDebug.AssertNotNull(_invisibleEditor); List <ValueTuple <AbstractKeyedCodeElement, SyntaxPath> >?elementAndPaths = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPaths ??= new List <ValueTuple <AbstractKeyedCodeElement, SyntaxPath> >(); elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = State.ThreadingContext.JoinableTaskFactory.Run(() => Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None)); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPaths != null) { foreach (var elementAndPath in elementAndPaths) { // make sure the element is there. if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement)) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return(VSConstants.S_OK); } catch (Exception ex) { return(Marshal.GetHRForException(ex)); } finally { ReleaseEditor(); } }
public static bool IsFileLocked(Exception exception) { int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1); return(errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION); }
/// <summary> /// Called by the vs shell to start debugging (managed or unmanaged). /// Override this method to support other debug engines. /// </summary> /// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns> /*public override int DebugLaunch(uint grfLaunch) * { * // System.Windows.Forms.MessageBox.Show("SquirrelProjectConfig.DebugLaunch", "Debugger debugging", System.Windows.Forms.MessageBoxButtons.OK, 0); * * //CCITracing.TraceCall(); * * try * { * * VsDebugTargetInfo info = new VsDebugTargetInfo(); * info.cbSize = (uint)Marshal.SizeOf(info); * info.dlo = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess; * * string interpreter; * string workingdirectory; * bool localhost = false; * int port = 1234; * string targetaddress; * string commandlineoptions; * string pathfixup; * bool suspendonstartup = false; * bool autoruninterpreter = true; * * string projectfolder = ProjectMgr.ProjectFolder; * interpreter = FetchStringProperty("Interpreter", ""); * workingdirectory = FetchStringProperty("WorkingDirectory", Path.GetDirectoryName(interpreter)); * suspendonstartup = FetchBoolProperty("SuspendOnStartup", false); * autoruninterpreter = true;//FetchBoolProperty("AutorunInterpreter", true); * * localhost = FetchBoolProperty("Localhost", true); * targetaddress = FetchStringProperty("TargetAddress", "127.0.0.1"); * pathfixup = FetchStringProperty("PathFixup", ""); * pathfixup = pathfixup.Replace(',', '#'); * if (localhost) * { * //overrides the setting if localhost is true * targetaddress = "127.0.0.1"; * } * commandlineoptions = FetchStringProperty("CommandLineOptions", ""); * port = FetchIntProperty("Port", 1234); * * info.bstrExe = interpreter; * info.bstrCurDir = workingdirectory; * info.bstrArg = commandlineoptions; * info.bstrOptions = targetaddress + "," + port.ToString() + "," + autoruninterpreter.ToString() + "," + suspendonstartup.ToString() + "," + projectfolder + "," + pathfixup; * * * //squirrel debugger * info.bstrPortName = "SquirrelPort"; * info.clsidPortSupplier = SQProjectGuids.guidPortSupplier; * info.clsidCustom = SQProjectGuids.guidDebugEngine; * info.grfLaunch = grfLaunch; * VsShellUtilities.LaunchDebugger(this.ProjectMgr.Site, info); * } * catch (Exception e) * { * Trace.WriteLine("Exception : " + e.Message); * * return Marshal.GetHRForException(e); * } * * return VSConstants.S_OK; * }*/ public override int DebugLaunch(uint grfLaunch) { //CCITracing.TraceCall(); try { EnvDTE.DTE dte = ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; // EnvDTE.DTE dte = (EnvDTE.DTE)_ls.GetService(typeof(EnvDTE.DTE)); List <KeyValuePair <string, string> > pns = new List <KeyValuePair <string, string> >(); EnvDTE.Projects projects = dte.Solution.Projects; foreach (object prj in projects) { SQAutomationProject p = prj as SQAutomationProject; if (p != null) { ProjectNode spn = p.Project as ProjectNode; string pathfixup = spn.GetProjectProperty(Resources.PathFixup);//.BuildProject.EvaluatedProperties; if (string.IsNullOrEmpty(pathfixup)) { continue; } //string pathfixup = (string)bpg["PathFixup"]; string projfolder = spn.ProjectFolder; if (!projfolder.EndsWith("\\")) { projfolder += "\\"; } KeyValuePair <string, string> pair = new KeyValuePair <string, string>(projfolder, pathfixup); pns.Add(pair); } else { //this sometimes happens even if there is only 1 project, is wierdm, who knows!? //Console.WriteLine(prj.ToString()); } } VsDebugTargetInfo info = new VsDebugTargetInfo(); info.cbSize = (uint)Marshal.SizeOf(info); info.dlo = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess; string interpreter; string workingdirectory; bool localhost = false; int port = 1234; string targetaddress; string commandlineoptions; //string pathfixup; bool suspendonstartup = false; bool autoruninterpreter = true; string projectfolder = ProjectMgr.ProjectFolder; interpreter = FetchStringProperty("Interpreter", ""); if (string.IsNullOrEmpty(interpreter) || !File.Exists(interpreter)) { throw new Exception("The Interpreter path is invalid. Please change this in the Project Settings > Debugger > Interpreter."); } workingdirectory = FetchStringProperty("WorkingDirectory", Path.GetDirectoryName(interpreter)); suspendonstartup = FetchBoolProperty("SuspendOnStartup", false); autoruninterpreter = FetchBoolProperty("AutorunInterpreter", true); localhost = FetchBoolProperty("Localhost", true); targetaddress = FetchStringProperty("TargetAddress", "127.0.0.1"); //string pathfixup = FetchStringProperty("PathFixup", ""); //pathfixup = pathfixup.Replace(',', '#'); if (localhost) { //overrides the setting if localhost is true targetaddress = "127.0.0.1"; } commandlineoptions = FetchStringProperty("CommandLineOptions", ""); port = FetchIntProperty("Port", 1234); int connectiondelay = FetchIntProperty("ConnectionDelay", 1000); int connectiontries = FetchIntProperty("ConnectionTries", 3); StringBuilder sb = new StringBuilder(); XmlWriterSettings xws = new XmlWriterSettings(); xws.Indent = true; xws.OmitXmlDeclaration = true; XmlWriter w = XmlWriter.Create(sb, xws); w.WriteStartDocument(); w.WriteStartElement("params"); w.WriteAttributeString("targetaddress", targetaddress); w.WriteAttributeString("port", port.ToString()); w.WriteAttributeString("autoruninterpreter", autoruninterpreter.ToString()); w.WriteAttributeString("suspendonstartup", suspendonstartup.ToString()); w.WriteAttributeString("connectiondelay", connectiondelay.ToString()); w.WriteAttributeString("connectiontries", connectiontries.ToString()); foreach (KeyValuePair <string, string> kv in pns) { w.WriteStartElement("context"); w.WriteAttributeString("rootpath", kv.Key); w.WriteAttributeString("pathfixup", kv.Value); w.WriteEndElement(); } w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); w.Close(); info.bstrExe = interpreter; info.bstrCurDir = workingdirectory; info.bstrArg = commandlineoptions; info.bstrOptions = sb.ToString();// targetaddress + "," + port.ToString() + "," + autoruninterpreter.ToString() + "," + suspendonstartup.ToString() + "," + projectfolder + "," + pathfixup; //squirrel debugger info.bstrPortName = "SquirrelPort"; info.clsidPortSupplier = SQProjectGuids.guidPortSupplier; //new Guid("{C419451D-BC37-44f7-901E-880E74B7D886}"); info.clsidCustom = SQProjectGuids.guidDebugEngine; //new Guid("{3F1D8F51-4A1C-4ac2-962B-BA96794D8373}"); info.grfLaunch = grfLaunch; VsShellUtilities.LaunchDebugger(this.ProjectMgr.Site, info); } catch (Exception e) { Trace.WriteLine("Exception : " + e.Message); return(Marshal.GetHRForException(e)); } return(VSConstants.S_OK); }
/// <summary> /// Get IO error code from IOException /// </summary> /// <param name="e">the IOException to be interpreted</param> /// <returns>corresponding IO error code</returns> private static int GetIOErrorCode(IOException e) { return(Marshal.GetHRForException(e) & 0xffff); }