/// <summary> /// Retrieves an array of the sub-conditions. /// </summary> public IEnumerable <SearchCondition> GetSubConditions() { // Our list that we'll return var subConditionsList = new List <SearchCondition>(); // Get the sub-conditions from the native API object subConditionObj; var guid = new Guid(InterfaceGuids.IEnumUnknown); HResult hr = NativeSearchCondition.GetSubConditions(ref guid, out subConditionObj); if (hr != HResult.S_OK) { throw new Exception(hr.ToString()); } // Convert each ICondition to SearchCondition if (subConditionObj != null) { var enumUnknown = subConditionObj as IEnumUnknown; IntPtr buffer = IntPtr.Zero; uint fetched = 0; while (hr == HResult.S_OK) { hr = enumUnknown.Next(1, ref buffer, ref fetched); if (hr == HResult.S_OK && fetched == 1) { subConditionsList.Add(new SearchCondition((ICondition)Marshal.GetObjectForIUnknown(buffer))); } } } return(subConditionsList); }
/// <summary> /// Retrieves an array of the sub-conditions. /// </summary> public IEnumerable <SearchCondition> GetSubConditions() { // Our list that we'll return List <SearchCondition> subConditionsList = new List <SearchCondition>(); // Get the sub-conditions from the native API object subConditionObj; Guid guid = new Guid(ShellIIDGuid.IEnumUnknown); HResult hr = NativeSearchCondition.GetSubConditions(ref guid, out subConditionObj); if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); } // Convert each ICondition to SearchCondition if (subConditionObj != null) { IEnumUnknown enumUnknown = subConditionObj as IEnumUnknown; IntPtr buffer = IntPtr.Zero; uint fetched = 0; while (hr == HResult.Ok) { hr = enumUnknown.Next(1, ref buffer, ref fetched); if (hr == HResult.Ok && fetched == 1) { subConditionsList.Add(new SearchCondition((ICondition)Marshal.GetObjectForIUnknown(buffer))); } } } return(subConditionsList); }
private static IEnumerable <string> GetFolderPlaceholdersFromDisk(ITracer tracer, PhysicalFileSystem fileSystem, string path) { if (!fileSystem.IsSymLink(path)) { foreach (string directory in fileSystem.EnumerateDirectories(path)) { if (!directory.EndsWith(Path.DirectorySeparatorChar + GVFSConstants.DotGit.Root)) { OnDiskFileState fileState = OnDiskFileState.Full; HResult result = Utils.GetOnDiskFileState(directory, out fileState); if (result == HResult.Ok) { if (IsPlaceholder(fileState)) { yield return(directory); } // Recurse into placeholders and full folders skipping the tombstones if (!IsTombstone(fileState)) { foreach (string placeholderPath in GetFolderPlaceholdersFromDisk(tracer, fileSystem, directory)) { yield return(placeholderPath); } } } else if (result != HResult.FileNotFound) { // FileNotFound is returned for tombstones when the filter is attached to the volume so we want to // just skip those folders. Any other HResults may cause valid folder placeholders not to be written // to the placeholder database so we want to error out on those. throw new InvalidDataException($"Error getting on disk file state. HResult = {result} for {directory}"); } } } } }
private void SetSafeArray(Array value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value.Rank > 1) { throw new NotSupportedException("Multidimensional arrays are not supported."); } var bounds = new SafeArrayBound[1]; bounds[0] = new SafeArrayBound(value.GetLength(0), value.GetLowerBound(0)); var arrayPtr = NativeMethods.OleAut32.SafeArrayCreate(VarType.Unknown, 1, bounds); IntPtr arrayDataPtr; HResult.Try(NativeMethods.OleAut32.SafeArrayAccessData(arrayPtr, out arrayDataPtr)); try { for (var i = bounds[0].LowerBound; i < bounds[0].LowerBound + bounds[0].NumElements; i++) { var element = value.GetValue(i); var elementPtr = (element != null) ? Marshal.GetIUnknownForObject(element) : IntPtr.Zero; Marshal.WriteIntPtr(arrayDataPtr, i * IntPtr.Size, elementPtr); } } finally { HResult.Try(NativeMethods.OleAut32.SafeArrayUnaccessData(arrayPtr)); } varType = VarType.Flag_Array | VarType.Unknown; pointerUnion.Pointer1 = arrayPtr; }
/// <summary> /// Given a native KnownFolder (IKnownFolderNative), create the right type of /// IKnownFolder object (FileSystemKnownFolder or NonFileSystemKnownFolder) /// </summary> /// <param name="knownFolderNative">Native Known Folder</param> /// <returns></returns> private static IKnownFolder GetKnownFolder(IKnownFolderNative knownFolderNative) { Debug.Assert(knownFolderNative != null, "Native IKnownFolder should not be null."); // Get the native IShellItem2 from the native IKnownFolder IShellItem2 shellItem; Guid guid = new Guid(ShellIIDGuid.IShellItem2); HResult hr = knownFolderNative.GetShellItem(0, ref guid, out shellItem); if (!CoreErrorHelper.Succeeded(hr)) { return(null); } bool isFileSystem = false; // If we have a valid IShellItem, try to get the FileSystem attribute. if (shellItem != null) { ShellNativeMethods.ShellFileGetAttributesOptions sfgao; shellItem.GetAttributes(ShellNativeMethods.ShellFileGetAttributesOptions.FileSystem, out sfgao); // Is this item a FileSystem item? isFileSystem = (sfgao & ShellNativeMethods.ShellFileGetAttributesOptions.FileSystem) != 0; } // If it's FileSystem, create a FileSystemKnownFolder, else NonFileSystemKnownFolder if (isFileSystem) { FileSystemKnownFolder kf = new FileSystemKnownFolder(knownFolderNative); return(kf); } NonFileSystemKnownFolder knownFsFolder = new NonFileSystemKnownFolder(knownFolderNative); return(knownFsFolder); }
private static SearchCondition CreateLeafCondition(string propertyName, PropVariant propVar, string valueType, SearchConditionOperation operation) { IConditionFactory nativeConditionFactory = null; SearchCondition condition = null; try { // Same as the native "IConditionFactory:MakeLeaf" method nativeConditionFactory = (IConditionFactory) new ConditionFactoryCoClass(); ICondition nativeCondition = null; if (string.IsNullOrEmpty(propertyName) || propertyName.ToUpperInvariant() == "SYSTEM.NULL") { propertyName = null; } HResult hr = HResult.Fail; hr = nativeConditionFactory.MakeLeaf(propertyName, operation, valueType, propVar, null, null, null, false, out nativeCondition); if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); } // Create our search condition and set the various properties. condition = new SearchCondition(nativeCondition); } finally { if (nativeConditionFactory != null) { Marshal.ReleaseComObject(nativeConditionFactory); } } return(condition); }
/// <summary> /// Creates a condition node that is a logical conjunction ("AND") or disjunction ("OR") /// of a collection of subconditions. /// </summary> /// <param name="conditionType">The SearchConditionType of the condition node. /// Must be either AndCondition or OrCondition.</param> /// <param name="simplify">TRUE to logically simplify the result, if possible; /// then the result will not necessarily to be of the specified kind. FALSE if the result should /// have exactly the prescribed structure. An application that plans to execute a query based on the /// condition tree would typically benefit from setting this parameter to TRUE. </param> /// <param name="conditionNodes">Array of subconditions</param> /// <returns>New SearchCondition based on the operation</returns> public static SearchCondition CreateAndOrCondition(SearchConditionType conditionType, bool simplify, params SearchCondition[] conditionNodes) { // Same as the native "IConditionFactory:MakeAndOr" method IConditionFactory nativeConditionFactory = (IConditionFactory) new ConditionFactoryCoClass(); ICondition result = null; try { // List <ICondition> conditionList = new List <ICondition>(); if (conditionNodes != null) { foreach (SearchCondition c in conditionNodes) { conditionList.Add(c.NativeSearchCondition); } } IEnumUnknown subConditions = new EnumUnknownClass(conditionList.ToArray()); HResult hr = nativeConditionFactory.MakeAndOr(conditionType, subConditions, simplify, out result); if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); } } finally { if (nativeConditionFactory != null) { Marshal.ReleaseComObject(nativeConditionFactory); } } return(new SearchCondition(result)); }
public HResult GetSymbolByOffset(int moduleIndex, ulong address, out string symbol, out ulong displacement) { symbol = null; // Get the symbol length first HResult hr = VTable.GetSymbolByOffset(Self, moduleIndex, address, null, 0, out uint symbolSize, out displacement); if (hr == HResult.S_OK) { if (symbolSize > 0) { // Now get the symbol byte[] symbolBuffer = new byte[symbolSize]; fixed(byte *symbolBufferPtr = symbolBuffer) { hr = VTable.GetSymbolByOffset(Self, moduleIndex, address, symbolBufferPtr, symbolBuffer.Length, out symbolSize, out displacement); if (hr == HResult.S_OK) { symbol = Encoding.ASCII.GetString(symbolBufferPtr, (int)symbolSize - 1); if (_hostType == HostType.DbgEng) { int index = symbol.IndexOf('!'); if (index != -1) { symbol = symbol.Remove(0, index + 1); } } } } } else { hr = HResult.E_INVALIDARG; } } return(hr); }
private void AppendTaskList() { if (userTasks == null || userTasks.Count == 0) { return; } IObjectCollection taskContent = (IObjectCollection) new CEnumerableObjectCollection(); // Add each task's shell representation to the object array foreach (JumpListTask task in userTasks) { JumpListSeparator seperator; JumpListLink link = task as JumpListLink; if (link != null) { taskContent.AddObject(link.NativeShellLink); } else if ((seperator = task as JumpListSeparator) != null) { taskContent.AddObject(seperator.NativeShellLink); } } // Add tasks to the taskbar HResult hr = customDestinationList.AddUserTasks((IObjectArray)taskContent); if (!CoreErrorHelper.Succeeded(hr)) { if ((uint)hr == 0x80040F03) { throw new InvalidOperationException(LocalizedMessages.JumpListFileTypeNotRegistered); } throw new ShellException(hr); } }
private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options) { IShellItem nativeShellItem; Guid shellItem2Guid = new Guid(IShellItem2Guid); int retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem); if (retCode != 0) { throw Marshal.GetExceptionForHR(retCode); } NativeSize nativeSize = new NativeSize { Width = width, Height = height }; IntPtr hBitmap; HResult hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap); // if extracting image thumbnail and failed, extract shell icon if (options == ThumbnailOptions.ThumbnailOnly && hr == HResult.ExtractionFailed) { hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, ThumbnailOptions.IconOnly, out hBitmap); } Marshal.ReleaseComObject(nativeShellItem); if (hr == HResult.Ok) { return(hBitmap); } throw new COMException($"Error while extracting thumbnail for {fileName}", Marshal.GetExceptionForHR((int)hr)); }
public HResult SetOutputBounds( long hnsLowerBound, long hnsUpperBound ) { HResult hr = HResult.S_OK; try { Trace("SetOutputBounds"); lock (m_TransformLockObject) { // Output bounds not supported hr = HResult.E_NOTIMPL; } } catch (Exception e) { hr = (HResult)Marshal.GetHRForException(e); } return(CheckReturn(hr)); }
public HResult AddInputStreams( int cStreams, int[] adwStreamIDs ) { HResult hr = HResult.S_OK; try { Trace("AddInputStreams"); lock (m_TransformLockObject) { // Adding streams not supported. hr = HResult.E_NOTIMPL; } } catch (Exception e) { hr = (HResult)Marshal.GetHRForException(e); } return(CheckReturn(hr)); }
public HResult GetAttributes( out IMFAttributes pAttributes ) { pAttributes = null; HResult hr = HResult.S_OK; try { // Trace("GetAttributes"); not interesting lock (m_TransformLockObject) { hr = HResult.E_NOTIMPL; } } catch (Exception e) { hr = (HResult)Marshal.GetHRForException(e); } return(hr); // CheckReturn(hr); }
/// <summary> /// Given a native KnownFolder (IKnownFolderNative), create the right type of /// IKnownFolder object (FileSystemKnownFolder or NonFileSystemKnownFolder) /// </summary> /// <param name="knownFolderNative">Native Known Folder</param> /// <returns></returns> private static IKnownFolder GetKnownFolder(IKnownFolderNative knownFolderNative) { Debug.Assert(knownFolderNative != null, "Native IKnownFolder should not be null."); // Get the native IShellItem2 from the native IKnownFolder IShellItem shellItem; Guid guid = new Guid(InterfaceGuids.IShellItem); HResult hr = knownFolderNative.GetShellItem(0, ref guid, out shellItem); if (hr != HResult.S_OK) { return(null); } bool isFileSystem = false; // If we have a valid IShellItem, try to get the FileSystem attribute. if (shellItem != null) { SFGAO sfgao; shellItem.GetAttributes(SFGAO.FILESYSTEM, out sfgao); // Is this item a FileSystem item? isFileSystem = (sfgao & SFGAO.FILESYSTEM) != 0; } // If it's FileSystem, create a FileSystemKnownFolder, else NonFileSystemKnownFolder if (isFileSystem) { return(FileSystemKnownFolder.Create(knownFolderNative)); } var knownFsFolder = new NonFileSystemKnownFolder(knownFolderNative); return(knownFsFolder); }
private void ApplyComplete(object sender, ApplyCompleteEventArgs e) { App.Current.Result = e.Status; if (App.Current.Command.Display != Display.Full) { if (App.Current.Command.Display == Display.Passive) { App.Current.Engine.Log(LogLevel.Verbose, "Automatically closing the window for non-interactive install"); App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => App.Current.Finish())); } else { App.Current.Dispatcher.InvokeShutdown(); } } if (State != PreApplyState) { State = e.Restart != ApplyRestart.None ? InstallationState.RebootRequired : HResult.Succeeded(e.Status) ? InstallationState.Successful : InstallationState.Failed; } }
public static IVsHierarchy GetNestedHierarchy(IVsHierarchy hierarchy, uint itemId, out uint nestedItemId) { var iidHierarchyNested = IID_IVsHierarchy; IntPtr ppHierarchyNested; var nestedHierarchy = hierarchy.GetNestedHierarchy(itemId, ref iidHierarchyNested, out ppHierarchyNested, out nestedItemId); IVsHierarchy vsHierarchy = null; try { if (HResult.Succeeded(nestedHierarchy)) { if (ppHierarchyNested != IntPtr.Zero) { vsHierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(ppHierarchyNested); } } } finally { TFCommonUtil.SafeRelease(ppHierarchyNested); } return(vsHierarchy); }
public unsafe void FindName() { HResult result = LoadStdOle2(out ITypeLib typeLib); result.Should().Be(HResult.S_OK); typeLib.Should().NotBeNull(); string name = "picture"; char * nameBuffer = stackalloc char[name.Length + 1]; Span <char> nameSpan = new Span <char>(nameBuffer, name.Length); name.AsSpan().CopyTo(nameSpan); nameBuffer[name.Length] = '\0'; IntPtr * typeInfos = stackalloc IntPtr[1]; MemberId *memberIds = stackalloc MemberId[1]; ushort found = 1; result = typeLib.FindName( nameBuffer, lHashVal: 0, typeInfos, memberIds, &found); result.Should().Be(HResult.S_OK); found.Should().Be(1); memberIds[0].Should().Be(new MemberId { Value = -1 }); typeInfos[0].Should().NotBe(IntPtr.Zero); Marshal.Release(typeInfos[0]); // Find gives back the right casing nameSpan.ToString().Should().Be("Picture"); }
private void mPlayPauseBtn_Click(object sender, RoutedEventArgs e) { mIsSeek = false; mNewValue = -1.0; if (mIsPlaying) { HResult hr = m_pSession.Pause(); if (hr == HResult.S_OK) { mImageBtn.Source = new BitmapImage(new Uri("pack://application:,,,/WPFMediaFoundationPlayer;component/Images/play-button.png", UriKind.Absolute)); mIsPlaying = false; mTickTimer.Stop(); } } else { StartPlayback(); } }
private static HResult CreateMediaSource(string videoFile, out IMFMediaSource source) { IMFSourceResolver resolver = null; source = null; HResult hr = MF.CreateSourceResolver(out resolver); if (Failed(hr)) { return(hr); } hr = resolver.CreateObjectFromURL(videoFile, MFResolution.MediaSource, null, out source); if (Failed(hr)) { SafeRelease(source); } SafeRelease(resolver); return(hr); }
/// <summary> /// Gets the start and stop times for the media item. /// </summary> /// <param name="mediaItem">A valid IMFPMediaItem instance.</param> /// <param name="startValue">Receives the start position.</param> /// <param name="stopValue">Receives the stop position.</param> /// <returns>If this function succeeds, it returns the S_OK member. Otherwise, it returns another HResult's member that describe the error.</returns> public static HResult GetStartStopPosition(this IMFPMediaItem mediaItem, out TimeSpan startValue, out TimeSpan stopValue) { if (mediaItem == null) { throw new ArgumentNullException("mediaItem"); } using (PropVariant resultStart = new PropVariant(), resultStop = new PropVariant()) { HResult hr = mediaItem.GetStartStopPosition(Guid.Empty, resultStart, Guid.Empty, resultStop); if (hr.Succeeded()) { startValue = TimeSpan.FromTicks((long)resultStart.GetULong()); stopValue = TimeSpan.FromTicks((long)resultStop.GetULong()); } else { startValue = default(TimeSpan); stopValue = default(TimeSpan); } return(hr); } }
/// <summary> /// Registers an application for recovery by Application Restart and Recovery. /// </summary> /// <param name="settings">An object that specifies /// the callback method, an optional parameter to pass to the callback /// method and a time interval.</param> /// <exception cref="System.ArgumentException"> /// The registration failed due to an invalid parameter. /// </exception> /// <exception cref="System.ComponentModel.Win32Exception"> /// The registration failed.</exception> /// <remarks>The time interval is the period of time within /// which the recovery callback method /// calls the <see cref="ApplicationRecoveryInProgress"/> method to indicate /// that it is still performing recovery work.</remarks> public static void RegisterForApplicationRecovery(RecoverySettings settings) { CoreHelpers.ThrowIfNotVista(); if (settings == null) { throw new ArgumentNullException("settings"); } GCHandle handle = GCHandle.Alloc(settings.RecoveryData); HResult hr = AppRestartRecoveryNativeMethods.RegisterApplicationRecoveryCallback( AppRestartRecoveryNativeMethods.InternalCallback, (IntPtr)handle, settings.PingInterval, (uint)0); if (!CoreErrorHelper.Succeeded(hr)) { if (hr == HResult.InvalidArguments) { throw new ArgumentException(LocalizedMessages.ApplicationRecoveryBadParameters, "settings"); } throw new ApplicationRecoveryException(LocalizedMessages.ApplicationRecoveryFailedToRegister); } }
private string RemoveCustomCategoryItem(IShellItem item) { string path = null; if (customCategoriesCollection != null) { IntPtr pszString = IntPtr.Zero; HResult hr = item.GetDisplayName(ShellItemDesignNameOptions.FileSystemPath, out pszString); if (hr == HResult.Ok && pszString != IntPtr.Zero) { path = Marshal.PtrToStringAuto(pszString); // Free the string Marshal.FreeCoTaskMem(pszString); } // Remove this item from each category foreach (JumpListCustomCategory category in customCategoriesCollection) { category.RemoveJumpListItem(path); } } return(path); }
/// <summary> /// Initializes an exception with custom message and error code. /// </summary> /// <param name="message"></param> /// <param name="errorCode"></param> internal ShellException(string message, HResult errorCode) : this(message, (int)errorCode) { }
/// <summary> /// Initializes a new exception using an HResult /// </summary> /// <param name="result">HResult error</param> internal ShellException(HResult result) : this((int)result) { }
public static void RaiseComError(HResult hr, string message) { throw new System.Runtime.InteropServices.COMException(message,(int)hr); }
public HResultException(HResult hResult, string message) : base(message) { HResult = hResult; }
/// <summary> /// Initializes an exception with custom message and error code. /// </summary> /// <param name="message"></param> /// <param name="errorCode"></param> public CommonControlException(string message, HResult errorCode) : this(message, (int)errorCode) { }
/// <summary> /// This is intended for Library Internal use only. /// </summary> /// <param name="result">The error code.</param> /// <returns>True if the error code indicates success.</returns> public static bool Succeeded(HResult result) { return(Succeeded((int)result)); }
public void WindowsErrorToHresultMappings(WindowsError error, HResult expected) { HResult result = error.ToHResult(); result.Should().Be(expected); }
/// <summary>This is intended for Library Internal use only.</summary> /// <param name="result">The error code.</param> /// <returns>True if the error code indicates failure.</returns> public static bool Failed(HResult result) => !Succeeded(result);
/// <summary> /// Parses an input string that contains Structured Query keywords (using Advanced Query Syntax /// or Natural Query Syntax) and produces a SearchCondition object. /// </summary> /// <param name="query">The query to be parsed</param> /// <param name="cultureInfo">The culture used to select the localized language for keywords.</param> /// <returns>Search condition resulting from the query</returns> /// <remarks>For more information on structured query syntax, visit http://msdn.microsoft.com/en-us/library/bb233500.aspx and /// http://www.microsoft.com/windows/products/winfamily/desktopsearch/technicalresources/advquery.mspx</remarks> public static SearchCondition ParseStructuredQuery(string query, CultureInfo cultureInfo) { if (string.IsNullOrEmpty(query)) { throw new ArgumentNullException(nameof(query)); } IQueryParserManager nativeQueryParserManager = (IQueryParserManager) new QueryParserManagerCoClass(); IQueryParser queryParser = null; IQuerySolution querySolution = null; ICondition result = null; IEntity mainType = null; SearchCondition searchCondition = null; try { // First, try to create a new IQueryParser using IQueryParserManager Guid guid = new Guid(ShellIIDGuid.IQueryParser); HResult hr = nativeQueryParserManager.CreateLoadedParser( "SystemIndex", cultureInfo == null ? (ushort)0 : (ushort)cultureInfo.LCID, ref guid, out queryParser); if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); } if (queryParser != null) { // If user specified natural query, set the option on the query parser using (PropVariant optionValue = new PropVariant(true)) { hr = queryParser.SetOption(StructuredQuerySingleOption.NaturalSyntax, optionValue); } if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); } // Next, try to parse the query. // Result would be IQuerySolution that we can use for getting the ICondition and other // details about the parsed query. hr = queryParser.Parse(query, null, out querySolution); if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); } if (querySolution != null) { // Lastly, try to get the ICondition from this parsed query hr = querySolution.GetQuery(out result, out mainType); if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); } } } searchCondition = new SearchCondition(result); return(searchCondition); } catch { if (searchCondition != null) { searchCondition.Dispose(); } throw; } finally { if (nativeQueryParserManager != null) { Marshal.ReleaseComObject(nativeQueryParserManager); } if (queryParser != null) { Marshal.ReleaseComObject(queryParser); } if (querySolution != null) { Marshal.ReleaseComObject(querySolution); } if (mainType != null) { Marshal.ReleaseComObject(mainType); } } }
//Initializes the Hauppauge interfaces /// <summary> /// Constructor: Require the Hauppauge capture filter, and the deviceid for the card to be passed in /// </summary> public Hauppauge(IBaseFilter filter, string tuner) { try { //Don't create the class if we don't have any filter; if (filter == null) { return; } //Load Library hauppaugelib = LoadLibrary("hauppauge.dll"); //Get Proc addresses, and set the delegates for each function IntPtr procaddr = GetProcAddress(hauppaugelib, "Init"); _Init = (Init)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (Init)); procaddr = GetProcAddress(hauppaugelib, "DeInit"); _DeInit = (DeInit)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (DeInit)); procaddr = GetProcAddress(hauppaugelib, "IsHauppauge"); _IsHauppauge = (IsHauppauge)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (IsHauppauge)); procaddr = GetProcAddress(hauppaugelib, "SetVidBitRate"); _SetVidBitRate = (SetVidBitRate)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (SetVidBitRate)); procaddr = GetProcAddress(hauppaugelib, "GetVidBitRate"); _GetVidBitRate = (GetVidBitRate)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (GetVidBitRate)); procaddr = GetProcAddress(hauppaugelib, "SetAudBitRate"); _SetAudBitRate = (SetAudBitRate)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (SetAudBitRate)); procaddr = GetProcAddress(hauppaugelib, "GetAudBitRate"); _GetAudBitRate = (GetAudBitRate)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (GetAudBitRate)); procaddr = GetProcAddress(hauppaugelib, "SetStreamType"); _SetStreamType = (SetStreamType)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (SetStreamType)); procaddr = GetProcAddress(hauppaugelib, "GetStreamType"); _GetStreamType = (GetStreamType)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (GetStreamType)); procaddr = GetProcAddress(hauppaugelib, "SetDNRFilter"); _SetDNRFilter = (SetDNRFilter)Marshal.GetDelegateForFunctionPointer(procaddr, typeof (SetDNRFilter)); //Hack //The following is strangely necessary when using delegates instead of P/Invoke - linked to MP using utf-8 //Hack byte[] encodedstring = Encoding.UTF32.GetBytes(tuner); string card = Encoding.Unicode.GetString(encodedstring); hr = new HResult(_Init(filter, card)); Log.Log.WriteFile("Hauppauge Quality Control Initializing " + hr.ToDXString()); } catch (Exception ex) { Log.Log.WriteFile("Hauppauge Init failed " + ex.Message); } }
public void GetException(HResult.Code hrCode) { HResult hr = hrCode; Exception expected = Marshal.GetExceptionForHR(hr); Exception actual = hr.GetException(); if (expected == null) { Assert.Null(actual); } else { Assert.IsType(expected.GetType(), actual); Assert.Equal(expected.Message, actual.Message); } }
public void GetExceptionWithErrorInfo(HResult.Code hrCode) { HResult hr = hrCode; Exception expected = Marshal.GetExceptionForHR(hr); Exception actual = hr.GetException(IntPtr.Zero); // Consider actually initializing this. if (expected == null) { Assert.Null(actual); } else { Assert.IsType(expected.GetType(), actual); Assert.Equal(expected.Message, actual.Message); } }
public static bool ThrowOnFailure(HResult hr) { Marshal.ThrowExceptionForHR((int)hr); return hr != HResult.False; }
public HMessage BuildMessage(string actor, string type, HResult payload, HMessageOptions mOptions) { return InnerBuildMessage(actor, type, payload, mOptions); }
public HResultException(HResult hResult) : base() { HResult = hResult; }
//---private methods--- private HMessage InnerBuildResult(string actor, string @ref, ResultStatus? status, JToken result, HMessageOptions mOptions) { if (actor == null || actor.Length <= 0) throw new MissingAttrException("actor"); if (@ref == null || @ref.Length <= 0) throw new MissingAttrException("ref"); if (status == null) throw new MissingAttrException("status"); HResult hResult = new HResult(); hResult.SetResult(result); hResult.SetStatus(status); if (mOptions == null) mOptions = new HMessageOptions(); mOptions.Ref = @ref; return BuildMessage(actor, "hResult", hResult, mOptions); }
public HResultException(HResult hResult, string message, Exception innerException) : base(message, innerException) { HResult = hResult; }
private void notifyResultError(string @ref, ResultStatus resultStatus, string errorMsg, Action<HMessage> messageDelegate) { JObject obj = new JObject(); obj["errorMsg"] = errorMsg; HResult result = new HResult(); result.SetStatus(resultStatus); result.SetResult(obj); HMessage message = new HMessage(); message.SetRef(@ref); message.SetType("hResult"); message.SetPayload(result); this.notifyMessage(message, messageDelegate); }
/// <summary> /// This is intended for Library Internal use only. /// </summary> /// <param name="result">The error code.</param> /// <returns>True if the error code indicates failure.</returns> public static bool Failed(HResult result) { return !Succeeded(result); }
public static void RaiseComError(HResult hr) { throw new System.Runtime.InteropServices.COMException("",(int)hr); }
public static bool IsError(this HResult result) { //Return != OK because there are come errors with lower values than HResult.False return(result != HResult.OK); }
/// <summary> /// This is intended for Library Internal use only. /// </summary> /// <param name="result">The error code.</param> /// <returns>True if the error code indicates success.</returns> public static bool Succeeded(HResult result) { return Succeeded((int)result); }
/// <summary>This is intended for Library Internal use only.</summary> /// <param name="result">The error code.</param> /// <returns>True if the error code indicates success.</returns> public static bool Succeeded(HResult result) => Succeeded((int)result);
public static bool Failure(HResult hr) { return hr < 0; }
/// <summary> /// This is intended for Library Internal use only. /// </summary> /// <param name="result">The error code.</param> /// <returns>True if the error code indicates failure.</returns> public static bool Failed(HResult result) { return(!Succeeded(result)); }
public static bool Success(HResult hr) { return hr >= 0; }
private void Throw(HResult hr) { MFError.ThrowExceptionForHR(hr); }
/// <summary> /// Initializes a new exception using an HResult /// </summary> /// <param name="result">HResult error</param> public ShellException(HResult result) : this((int)result) { }