Exemplo n.º 1
0
        public HResult Shutdown()
        {
            Debug.WriteLine("StreamSink:Shutdown");

            lock (this)
            {
                HResult hr = CheckShutdown();
                if (Failed(hr))
                {
                    return(hr);
                }

                if (EventQueue != null)
                {
                    hr = EventQueue.Shutdown();
                    if (hr.Failed())
                    {
                        Debug.WriteLine("Could not shutdown EventQueue: " + hr.ToString() + " " + hr.GetDescription());
                        Debug.WriteLine("EventQueue Shutdown: " + hr.ToString() + " " + hr.GetDescription());
                    }
                }

                SafeRelease(MediaType);
                MediaType = null;

                SafeRelease(BaseSink);
                BaseSink = null;

                SafeRelease(EventQueue);
                EventQueue = null;

                State = StreamState.Finalized;
            }
            return(S_OK);
        }
Exemplo n.º 2
0
    public void ToString_FormatsNumberAsDecimalOrName()
    {
        HResult hr = 0x80000000;

        Assert.Equal("2147483648", hr.ToString());
        hr = HResult.Code.E_INVALIDARG;
        Assert.Equal("E_INVALIDARG", hr.ToString());
    }
Exemplo n.º 3
0
        /// <include file='doc\COMException.uex' path='docs/doc[@for="COMException.ToString"]/*' />
        public override String ToString()
        {
            String message = Message;
            String s;
            String _className = GetType().ToString();

            s = _className + " (0x" + HResult.ToString("X8") + ")";

            if (!(message == null || message.Length <= 0))
            {
                s = s + ": " + message;
            }

            Exception _innerException = InnerException;

            if (_innerException != null)
            {
                s = s + " ---> " + _innerException.ToString();
            }


            if (StackTrace != null)
            {
                s += Environment.NewLine + StackTrace;
            }

            return(s);
        }
Exemplo n.º 4
0
 private void LogIfFailed(HResult hr)
 {
     if (Failed(hr))
     {
         Debug.WriteLine("HResult Error: " + hr.ToString() + " " + hr.GetDescription());
     }
 }
Exemplo n.º 5
0
        public override String ToString()
        {
            String message = Message;
            String s;
            String _className = GetType().ToString();

            s = _className + " (0x" + HResult.ToString("X8", CultureInfo.InvariantCulture) + ")";

            if (!(String.IsNullOrEmpty(message)))
            {
                s = s + ": " + message;
            }

            Exception _innerException = InnerException;

            if (_innerException != null)
            {
                s = s + " ---> " + _innerException.ToString();
            }


            if (StackTrace != null)
            {
                s += Environment.NewLine + StackTrace;
            }

            return(s);
        }
Exemplo n.º 6
0
        /// <summary>
        ///     Returns a formatted, Unicode string representation of a property value.
        /// </summary>
        /// <param name="format">
        ///     One or more of the PropertyDescriptionFormat flags
        ///     that indicate the desired format.
        /// </param>
        /// <returns>
        ///     The formatted value as a string, or null if this property
        ///     cannot be formatted for display.
        /// </returns>
        public string FormatForDisplay(PropertyDescriptionFormatOptions format)
        {
            string formattedString;

            if (Description == null || Description.NativePropertyDescription == null)
            {
                // We cannot do anything without a property description
                return(null);
            }

            IPropertyStore store = ShellPropertyCollection.CreateDefaultPropertyStore(ParentShellObject);

            using (PropVariant propVar = new PropVariant())
            {
                store.GetValue(ref propertyKey, propVar);

                // Release the Propertystore
                Marshal.ReleaseComObject(store);
                store = null;

                HResult hr = Description.NativePropertyDescription.FormatForDisplay(propVar, ref format,
                                                                                    out formattedString);

                // Sometimes, the value cannot be displayed properly, such as for blobs
                // or if we get argument exception
                if (!CoreErrorHelper.Succeeded(hr))
                {
                    throw new Exception(hr.ToString());
                }

                return(formattedString);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Returns a string that contains the HRESULT of the error.
        /// </summary>
        /// <returns>A string that represents the HRESULT.</returns>
        public override string ToString()
        {
            var builder = new StringBuilder();

            builder.Append(GetType())
            .Append(" (0x")
            .Append(HResult.ToString("X8", CultureInfo.InvariantCulture))
            .Append(")");

            if (!string.IsNullOrEmpty(Message))
            {
                builder.Append(": ")
                .Append(Message);
            }

            if (InnerException != null)
            {
                builder.Append(" ---> ")
                .Append(InnerException);
            }

            if (StackTrace != null)
            {
                builder.Append(Environment.NewLine)
                .Append(StackTrace);
            }

            return(builder.ToString());
        }
Exemplo n.º 8
0
 internal static void CheckHr(HResult hr, string message)
 {
     if (hr != 0)
     {
         throw new COMException(message + " (" + hr.ToString() + ")", (int)hr);
     }
 }
Exemplo n.º 9
0
        public override string ToString()
        {
            string message   = Message;
            string className = GetType().ToString();

            string s = className + " (0x" + HResult.ToString("X8", CultureInfo.InvariantCulture) + ")";

            if (!string.IsNullOrEmpty(message))
            {
                s = s + ": " + message;
            }

            Exception?innerException = InnerException;

            if (innerException != null)
            {
                s = s + Environment.NewLine + InnerExceptionPrefix + innerException.ToString();
            }

            if (StackTrace != null)
            {
                s += Environment.NewLine + StackTrace;
            }

            return(s);
        }
        public override bool TryStartVirtualizationInstance(Enlistment enlistment, out string error)
        {
            this.virtualizationInstance.OnStartDirectoryEnumeration = this.StartDirectoryEnumeration;
            this.virtualizationInstance.OnEndDirectoryEnumeration   = this.EndDirectoryEnumeration;
            this.virtualizationInstance.OnGetDirectoryEnumeration   = this.GetDirectoryEnumeration;
            this.virtualizationInstance.OnQueryFileName             = this.QueryFileName;

            this.virtualizationInstance.OnGetPlaceholderInformation = this.GetPlaceholderInformation;
            this.virtualizationInstance.OnGetFileStream             = this.GetFileStream;
            this.virtualizationInstance.OnNotifyFileHandleClosedFileModifiedOrDeleted = this.OnFileModifiedOrDeleted;

            uint threadCount = (uint)Environment.ProcessorCount * 2;

            NotificationMapping[] notificationMappings = new NotificationMapping[]
            {
                new NotificationMapping(NotificationType.FileHandleClosedFileModified, string.Empty),
            };

            HResult result = this.virtualizationInstance.StartVirtualizationInstance(
                enlistment.SrcRoot,
                poolThreadCount: threadCount,
                concurrentThreadCount: threadCount,
                enableNegativePathCache: false,
                notificationMappings: notificationMappings);

            if (result == HResult.Ok)
            {
                return(base.TryStartVirtualizationInstance(enlistment, out error));
            }

            error = result.ToString("F");
            return(false);
        }
        public override string ToString()
        {
            StringBuilder s = new StringBuilder();

            string className = GetType().ToString();

            s.Append(className).Append(" (0x").Append(HResult.ToString("X8", CultureInfo.InvariantCulture)).Append(')');

            string message = Message;

            if (!string.IsNullOrEmpty(message))
            {
                s.Append(": ").Append(message);
            }

            Exception?innerException = InnerException;

            if (innerException != null)
            {
                s.Append(Environment.NewLineConst + InnerExceptionPrefix).Append(innerException.ToString());
            }

            string?stackTrace = StackTrace;

            if (stackTrace != null)
            {
                s.AppendLine().Append(stackTrace);
            }

            return(s.ToString());
        }
Exemplo n.º 12
0
        /// <summary>
        /// Sets folder logical view mode. The default settings are based on the FolderTypeID which is set
        /// by the SearchFolder::SetFolderTypeID method.
        /// </summary>
        /// <param name="mode">The logical view mode to set.</param>
        public void SetFolderLogicalViewMode(FolderLogicalViewMode mode)
        {
            HResult hr = NativeSearchFolderItemFactory.SetFolderLogicalViewMode(mode);

            if (hr != HResult.S_OK)
            {
                throw new Exception(hr.ToString());
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Sets the search folder display name.
        /// </summary>
        public void SetDisplayName(string displayName)
        {
            HResult hr = NativeSearchFolderItemFactory.SetDisplayName(displayName);

            if (hr != HResult.S_OK)
            {
                throw new Exception(hr.ToString());
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Sets a search folder type ID, as specified.
        /// </summary>
        public void SetFolderTypeID(Guid value)
        {
            HResult hr = NativeSearchFolderItemFactory.SetFolderTypeID(value);

            if (hr != HResult.S_OK)
            {
                throw new Exception(hr.ToString());
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Sets the search folder icon size.
        /// The default settings are based on the FolderTypeID which is set by the
        /// SearchFolder::SetFolderTypeID method.
        /// </summary>
        public void SetIconSize(int value)
        {
            HResult hr = NativeSearchFolderItemFactory.SetIconSize(value);

            if (hr != HResult.S_OK)
            {
                throw new Exception(hr.ToString());
            }
        }
Exemplo n.º 16
0
        public override bool TryConvertVirtualizationRoot(string directory, out string error)
        {
            error = string.Empty;
            HResult result = VirtualizationInstance.ConvertDirectoryToVirtualizationRoot(Guid.NewGuid(), directory);

            if (result != HResult.Ok)
            {
                error = result.ToString("F");
                return(false);
            }

            return(true);
        }
Exemplo n.º 17
0
        /// <summary>
        ///     Updates the native shell item that maps to this shell object. This is necessary when the shell item
        ///     changes after the shell object has been created. Without this method call, the retrieval of properties will
        ///     return stale data.
        /// </summary>
        /// <param name="bindContext">Bind context object</param>
        public void Update(IBindCtx bindContext)
        {
            HResult hr = HResult.Ok;

            if (NativeShellItem2 != null)
            {
                hr = NativeShellItem2.Update(bindContext);
            }

            if (CoreErrorHelper.Failed(hr))
            {
                throw new Exception(hr.ToString());
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Inject a <see cref="Assembly">Assembly</see> in the target process and
        /// invoke the specified method.
        /// </summary>
        /// <param name="AssemblyPath">The <see cref="Assembly">Assembly</see> file path</param>
        /// <param name="TypeName">The Full Name to the method class</param>
        /// <param name="MethodName">The Method Name in the Class</param>
        /// <param name="Argument">A Argument to give to the invoke method</param>
        /// <returns>The returned value from the invoked method</returns>
        public int CLRInvoke(string AssemblyPath, string TypeName, string MethodName, string Argument)
        {
            if (!(MIntPtr)ExecuteInDefaultAppDomain)
            {
                StartCLR();
            }

            IntPtr Ret = Target.MAlloc(new byte[4]);

            IntPtr AsmPath  = Target.MAllocString(AssemblyPath, true);
            IntPtr TpName   = Target.MAllocString(TypeName, true);
            IntPtr MthdName = Target.MAllocString(MethodName, true);
            IntPtr Arg      = Target.MAllocString(Argument, true);

            HResult Failed = (MIntPtr <HResult>)Invoke(ExecuteInDefaultAppDomain, CLRRuntimeHost, AsmPath, TpName, MthdName, Arg, Ret);

            switch (Failed)
            {
            case HResult.S_OK:
                break;

            case HResult.HOST_E_CLRNOTAVAILABLE:
                if (CLRNOTAVAILABLE)
                {
                    goto default;
                }

                CLRNOTAVAILABLE           = true;
                ExecuteInDefaultAppDomain = IntPtr.Zero;
                return(CLRInvoke(AssemblyPath, TypeName, MethodName, Argument));

            default:
                throw new Exception($"Error: {Failed.ToString()} (0x{((uint)Failed).ToString("X8")})");
            }
            int Result = Target.Read(Ret, 4).ToInt32();

            Target.MFree(AsmPath);
            Target.MFree(TpName);
            Target.MFree(MthdName);
            Target.MFree(Arg);
            Target.MFree(Ret);

            return(Result);
        }
        /// <summary>
        /// Returns a known folder given a globally unique identifier.
        /// </summary>
        /// <param name="knownFolderId">A GUID for the requested known folder.</param>
        /// <returns>A known folder representing the specified name.</returns>
        /// <exception cref="System.ArgumentException">Thrown if the given Known Folder ID is invalid.</exception>
        public static IKnownFolder FromKnownFolderId(Guid knownFolderId)
        {
            IKnownFolderNative      knownFolderNative;
            KnownFolderManagerClass knownFolderManager = new KnownFolderManagerClass();

            HResult hr = knownFolderManager.GetFolder(knownFolderId, out knownFolderNative);

            if (hr != HResult.S_OK)
            {
                throw new Exception(hr.ToString());
            }

            IKnownFolder kf = GetKnownFolder(knownFolderNative);

            if (kf == null)
            {
                throw new ArgumentException("Invalid GUID", "knownFolderId");
            }
            return(kf);
        }
        public override bool TryStartVirtualizationInstance(Enlistment enlistment, out string error)
        {
            this.virtualizationInstance.OnQueryFileName        = this.QueryFileName;
            this.virtualizationInstance.OnNotifyPreDelete      = this.OnPreDelete;
            this.virtualizationInstance.OnNotifyNewFileCreated = this.OnNewFileCreated;
            this.virtualizationInstance.OnNotifyFileHandleClosedFileModifiedOrDeleted = this.OnFileModifiedOrDeleted;
            this.virtualizationInstance.OnNotifyFileRenamed          = this.OnFileRenamed;
            this.virtualizationInstance.OnNotifyHardlinkCreated      = this.OnHardlinkCreated;
            this.virtualizationInstance.OnNotifyFilePreConvertToFull = this.OnFilePreConvertToFull;

            uint threadCount = (uint)Environment.ProcessorCount * 2;

            NotificationMapping[] notificationMappings = new NotificationMapping[]
            {
                new NotificationMapping(
                    NotificationType.NewFileCreated |
                    NotificationType.PreDelete |
                    NotificationType.FileRenamed |
                    NotificationType.HardlinkCreated |
                    NotificationType.FileHandleClosedFileModified,
                    string.Empty),
            };

            this.virtualizationInstance = new VirtualizationInstance(
                enlistment.SrcRoot,
                poolThreadCount: threadCount,
                concurrentThreadCount: threadCount,
                enableNegativePathCache: false,
                notificationMappings: notificationMappings);

            HResult result = this.virtualizationInstance.StartVirtualizing(this);

            if (result == HResult.Ok)
            {
                return(base.TryStartVirtualizationInstance(enlistment, out error));
            }

            error = result.ToString("F");
            return(false);
        }
Exemplo n.º 21
0
        /// <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);
        }
Exemplo n.º 22
0
        // Using an Impl method allows TryPrepareFolderForCallbacks to catch any ProjFS dependency related exceptions
        // thrown in the process of calling this method.
        private bool TryPrepareFolderForCallbacksImpl(string folderPath, out string error)
        {
            error = string.Empty;
            Guid    virtualizationInstanceGuid = Guid.NewGuid();
            HResult result = VirtualizationInstance.ConvertDirectoryToVirtualizationRoot(virtualizationInstanceGuid, folderPath);

            if (result != HResult.Ok)
            {
                error = "Failed to prepare \"" + folderPath + "\" for callbacks, error: " + result.ToString("F");
                return(false);
            }

            return(true);
        }
        /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
        /// <summary>
        /// This gets called when a Called IMFSourceReader.ReadSample method completes
        /// (assuming the SourceReader has been given this class during setup with
        /// an attribute of MFAttributesClsid.MF_SOURCE_READER_ASYNC_CALLBACK).
        ///
        /// The first ReadSample triggers it after that it continues by itself
        /// </summary>
        /// <param name="hrStatus">The status code. If an error occurred while processing the next sample, this parameter contains the error code.</param>
        /// <param name="streamIndex">The zero-based index of the stream that delivered the sample.</param>
        /// <param name="streamFlags">A bitwise OR of zero or more flags from the MF_SOURCE_READER_FLAG enumeration.</param>
        /// <param name="sampleTimeStamp">The time stamp of the sample, or the time of the stream event indicated in streamFlags. The time is given in 100-nanosecond units. </param>
        /// <param name="mediaSample">A pointer to the IMFSample interface of a media sample. This parameter might be NULL.</param>
        /// <returns>Returns an HRESULT value. Reputedly, the source reader ignores the return value.</returns>
        /// <history>
        ///    01 Nov 18  Cynic - Started
        /// </history>
        public HResult OnReadSample(HResult hrStatus, int streamIndex, MF_SOURCE_READER_FLAG streamFlags, long sampleTimeStamp, IMFSample mediaSample)
        {
            HResult hr = HResult.S_OK;

            try
            {
                lock (this)
                {
                    // are we capturing? if not leave
                    if (IsCapturing() == false)
                    {
                        return(HResult.S_OK);
                    }

                    // have we got an error?
                    if (Failed(hrStatus))
                    {
                        string errMsg = "OnReadSample, Error on call =" + hrStatus.ToString();
                        SourceReaderAsyncCallBackError(this, errMsg, null);
                        return(hrStatus);
                    }

                    // have we got a sample? It seems this can be null on the first sample
                    // in after the ReadSample that triggered this. So we just ignore it
                    // and request the next to get things rolling
                    if (mediaSample != null)
                    {
/*  This rebases the timestamps coming off the webcam so that
 *  the first one starts at zero. Not needed in later versions
 *  of WMF apparently. It seems the Media Sink now does this automatically
 *
 *  If the data is not being written correctly, try uncommenting this.
 *
 *                      // we have a sample, if so is it the first non null one?
 *                      if (isFirstSample)
 *                      {
 *                          // yes it is set up our timestamp
 *                          firstSampleBaseTime = sampleTimeStamp;
 *                          isFirstSample = false;
 *                      }
 *
 *                      // Samples have a time stamp and a duration. The time stamp indicates when the data in the sample
 *                      // should be rendered, relative to the presentation clock. The duration is the length of time
 *                      // for which the data should be rendered.
 *                      //
 *                      // We now set the presentation time of the sample. This is the presentation time
 *                      // in 100-nanosecond units. We rebase this using the first sample
 *                      // processed as zero.
 *
 *                      // rebase the time stamp
 *                      sampleTimeStamp -= firstSampleBaseTime;
 *                      hr = mediaSample.SetSampleTime(sampleTimeStamp);
 *                      if (Failed(hr))
 *                      {
 *                          string errMsg = "OnReadSample, Error on SetSampleTime =" + hr.ToString();
 *                          SourceReaderAsyncCallBackError(this, errMsg, null);
 *                          return hr;
 *                      } */

                        // write the sample out
                        hr = sinkWriter.WriteSample(0, mediaSample);
                        if (Failed(hr))
                        {
                            string errMsg = "OnReadSample, Error on WriteSample =" + hr.ToString();
                            SourceReaderAsyncCallBackError(this, errMsg, null);
                            return(hr);
                        }
                    }

                    // Read another sample.
                    hr = (sourceReader as IMFSourceReaderAsync).ReadSample(
                        TantaWMFUtils.MF_SOURCE_READER_FIRST_VIDEO_STREAM,
                        0,
                        IntPtr.Zero,   // actual
                        IntPtr.Zero,   // flags
                        IntPtr.Zero,   // timestamp
                        IntPtr.Zero    // sample
                        );
                    if (Failed(hr))
                    {
                        string errMsg = "OnReadSample, Error on ReadSample =" + hr.ToString();
                        SourceReaderAsyncCallBackError(this, errMsg, null);
                        return(hr);
                    }
                }
            }
            catch (Exception ex)
            {
                if (SourceReaderAsyncCallBackError != null)
                {
                    SourceReaderAsyncCallBackError(this, ex.Message, ex);
                }
            }
            finally
            {
                SafeRelease(mediaSample);
            }

            return(hr);
        }
Exemplo n.º 24
0
 // NotifyState: Notifies the application when an error occurs.
 protected void NotifyError(HResult hr)
 {
     TRACE("NotifyError: 0x" + hr.ToString("X"));
     PostMessage(m_hwndEvent, WM_APP_PREVIEW_ERROR, new IntPtr((int)hr), IntPtr.Zero);
 }
Exemplo n.º 25
0
        /// <summary>
        /// Inject the CLR in the target process
        /// </summary>
        /// <param name="Version">Version to load in the target process</param>
        /// <returns>A Pointer to the <a href="https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/hosting/iclrruntimehost-executeindefaultappdomain-method">ExecuteInDefaultAppDomain</a> function</returns>
        public void StartCLR(FrameworkVersion Version = FrameworkVersion.DotNet40)
        {
            if (!IsCompatibleProcess())
            {
                throw new Exception($"The Target Process isn't an {(Environment.Is64BitProcess ? "x64" : "x32")} Process");
            }

            if (Debugging)
            {
                WaitInitialize();
            }

            if (IsManaged)
            {
                ResumeProcess();
            }


            IntPtr ICLRMetaHost    = Target.MAlloc(new byte[IntPtr.Size]); //http://source.roslyn.codeplex.com/#Microsoft.CodeAnalysis/Interop/IClrMetaHost.cs
            IntPtr ICLRRuntimeInfo = Target.MAlloc(new byte[IntPtr.Size]); //http://source.roslyn.codeplex.com/#microsoft.codeanalysis/Interop/IClrRuntimeInfo.cs,485a48c96d61baeb,references
            IntPtr ICLRRuntimeHost = Target.MAlloc(new byte[IntPtr.Size]); //https://github.com/CentroEPiaggio/SoftLEGS-Project/blob/5b2eb55b8f43f07189118e477bd4e5c0114f6c8e/casadi-matlabR2013a-v3.1.1/casadi/jit/mingw/mscoree.h#L1230

            IntPtr CLSID_CLRMetaHost    = Target.MAlloc(new Guid("9280188D-0E8E-4867-B30C-7FA83884E8DE").ToByteArray());
            IntPtr CLSID_CLRRuntimeHost = Target.MAlloc(new Guid("90F1A06E-7712-4762-86B5-7A5EBA6BDB02").ToByteArray());
            IntPtr IID_ICLRMetaHost     = Target.MAlloc(new Guid("D332DB9E-B9B3-4125-8207-A14884F53216").ToByteArray());
            IntPtr IID_ICLRRuntimeInfo  = Target.MAlloc(new Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891").ToByteArray());
            IntPtr IID_ICLRRuntimeHost  = Target.MAlloc(new Guid("90F1A06C-7712-4762-86B5-7A5EBA6BDB02").ToByteArray());

            HResult Result = (MIntPtr <HResult>)Invoke("mscoree.dll", "CLRCreateInstance", CLSID_CLRMetaHost, IID_ICLRMetaHost, ICLRMetaHost);

            if (Result != HResult.S_OK)
            {
                throw new Exception($"Error: {Result.ToString()} (0x{((uint)Result).ToString("X8")})");
            }

            byte[] Data            = Target.Read(ICLRMetaHost, (uint)IntPtr.Size);
            IntPtr GetRuntime      = Data.ToIntPtr(x64Bits);
            IntPtr MetaHostIntance = GetRuntime;

            Data       = Target.Read(GetRuntime, (uint)IntPtr.Size);
            GetRuntime = Data.ToIntPtr(x64Bits).Sum(IntPtr.Size * 3);//1st function, The vTable have 3 pointers before the first function

            Data       = Target.Read(GetRuntime, (uint)IntPtr.Size);
            GetRuntime = Data.ToIntPtr(x64Bits);

            IntPtr pVersion = Target.MAllocString(DotNetVerName(FrameworkVersion.DotNet40), true);


            Result = (MIntPtr <HResult>)Invoke(GetRuntime, MetaHostIntance, pVersion, IID_ICLRRuntimeInfo, ICLRRuntimeInfo);
            if (Result != HResult.S_OK)
            {
                throw new Exception($"Error: {Result.ToString()} (0x{((uint)Result).ToString("X8")})");
            }

            Data = Target.Read(ICLRRuntimeInfo, (uint)IntPtr.Size);
            IntPtr GetInterface        = Data.ToIntPtr(x64Bits);
            IntPtr RuntimeInfoInstance = GetInterface;

            Data         = Target.Read(GetInterface, (uint)IntPtr.Size);
            GetInterface = Data.ToIntPtr(x64Bits);

            Data         = Target.Read(GetInterface.Sum(IntPtr.Size * 9), (uint)IntPtr.Size);//6th Function + vTable Prefix
            GetInterface = Data.ToIntPtr(x64Bits);

            Result = (MIntPtr <HResult>)Invoke(GetInterface, RuntimeInfoInstance, CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, ICLRRuntimeHost);
            if (Result != HResult.S_OK)
            {
                throw new Exception($"Error: {Result.ToString()} (0x{((uint)Result).ToString("X8")})");
            }

            Data = Target.Read(ICLRRuntimeHost, (uint)IntPtr.Size);
            IntPtr Start        = Data.ToIntPtr(x64Bits);
            IntPtr HostInstance = Start;

            Data  = Target.Read(Start, (uint)IntPtr.Size);
            Start = Data.ToIntPtr(x64Bits);

            if (IsManaged || (CLRAvaliable() && !CLRNOTAVAILABLE))
            {
                Data = Target.Read(Start.Sum(IntPtr.Size * 11), (uint)IntPtr.Size);
                ExecuteInDefaultAppDomain = Data.ToIntPtr(x64Bits);

                Target.MFree(ICLRMetaHost);
                Target.MFree(ICLRRuntimeInfo);
                Target.MFree(ICLRRuntimeHost);
                Target.MFree(CLSID_CLRMetaHost);
                Target.MFree(CLSID_CLRRuntimeHost);
                Target.MFree(IID_ICLRMetaHost);
                Target.MFree(IID_ICLRRuntimeHost);
                Target.MFree(pVersion);

                return;
            }

            Data  = Target.Read(Start.Sum(IntPtr.Size * 3), (uint)IntPtr.Size);
            Start = Data.ToIntPtr(x64Bits);

            Result = (MIntPtr <HResult>)Invoke(Start, HostInstance);
            if (Result != HResult.S_OK)
            {
                throw new Exception($"Error: {Result.ToString()} (0x{((uint)Result).ToString("X8")})");
            }

            Data = Target.Read(ICLRRuntimeHost, (uint)IntPtr.Size);
            ExecuteInDefaultAppDomain = Data.ToIntPtr(x64Bits);
            CLRRuntimeHost            = ExecuteInDefaultAppDomain;
            Data = Target.Read(ExecuteInDefaultAppDomain, (uint)IntPtr.Size);
            ExecuteInDefaultAppDomain = Data.ToIntPtr(x64Bits);
            Data = Target.Read(ExecuteInDefaultAppDomain.Sum(IntPtr.Size * 11), (uint)IntPtr.Size);
            ExecuteInDefaultAppDomain = Data.ToIntPtr(x64Bits);

            Target.MFree(ICLRMetaHost);
            Target.MFree(ICLRRuntimeInfo);
            Target.MFree(ICLRRuntimeHost);
            Target.MFree(CLSID_CLRMetaHost);
            Target.MFree(CLSID_CLRRuntimeHost);
            Target.MFree(IID_ICLRMetaHost);
            Target.MFree(IID_ICLRRuntimeHost);
            Target.MFree(pVersion);
        }
Exemplo n.º 26
0
 // NotifyState: Notifies the application when an error occurs.
 protected void NotifyError(HResult hr)
 {
     TRACE("NotifyError: 0x" + hr.ToString("X"));
     m_state = PlayerState.Ready;
     PostMessage(m_hwndEvent, WM_APP_ERROR, new IntPtr((int)hr), IntPtr.Zero);
 }
Exemplo n.º 27
0
        /// <summary>
        /// This is the routine that performs the transform. Unless the sinkWriter object
        /// is set all we do is pass the sample on. If the sink writer object is set
        /// we give the sample to it for writing. There are two modes - one where we just
        /// give the sinkwriter the input sample and the other where we clone the input
        /// sample and rebase the timestamps.
        ///
        /// An override of the abstract version in MFTBase_Sync.
        /// </summary>
        /// <param name="pOutputSamples">The structure to populate with output values.</param>
        /// <returns>S_Ok unless error.</returns>
        protected override HResult OnProcessOutput(ref MFTOutputDataBuffer outputSampleDataStruct)
        {
            HResult        hr = HResult.S_OK;
            IMFMediaBuffer inputMediaBuffer = null;
            IMFSample      sinkWriterSample = null;
            IMFAttributes  sampleAttributes;

            // in this MFT we are processing in place, the input sample is the output sample, the media buffer of the
            // input sample is the media buffer of the output sample. Thats for the pipeline. If a sink writer exists
            // we also write the sample data out to the sink writer. This provides the effect of displaying on the
            // screen and simultaneously recording.
            // There are two ways the sink writer can be given the media sample data. It can just be given the
            // input sample directly or a copy of the sample can be made and that copy given to the sink writer.
            // There is also an additional complication - the sample has a timestamp and video cameras tend
            // to just use the current date and time as a timestamp. There are several reports that MP4 files
            // need to have their first frame starting at zero and then every subsequent frame adjusted to that
            // new base time. Certainly the Microsoft supplied example code (and see the
            // CaptureToFileViaReaderWriter also) take great care to do this. This requirement does not
            // seem to exist - my tests indicate it is not necessary to start from 0 in the mp4 file. Maybe the
            // Sink Writer has been improved and now does this automatically. For demonstration purposes
            // the timebase-rebase functionality has been included and choosing that mode copies the sample
            // and resets the time. If the user does not rebase the time we simply send the input sample
            // to the Sink Writer as-is.
            try
            {
                // Set status flags.
                outputSampleDataStruct.dwStatus = MFTOutputDataBufferFlags.None;
                // The output sample is the input sample. We get a new IUnknown for the Input
                // sample since we are going to release it below. The client will release this
                // new IUnknown
                outputSampleDataStruct.pSample = Marshal.GetIUnknownForObject(InputSample);
                // are we recording?
                if (workingSinkWriter != null)
                {
                    // we do everything in a lock
                    lock (sinkWriterLockObject)
                    {
                        // are we in timebase rebase mode?
                        if (wantTimebaseRebase == false)
                        {
                            // we are not. Just give the input sample to the Sink Writer which will
                            // write it out.
                            hr = workingSinkWriter.WriteSample(sinkWriterVideoStreamId, InputSample);
                            if (hr != HResult.S_OK)
                            {
                                throw new Exception("OnProcessOutput call to WriteSample(a) failed. Err=" + hr.ToString());
                            }
                        }
                        else
                        {
                            // the timebase rebase option has been chosen. We need to create a copy of the input sample
                            // so we can adjust the time on it.
                            // Get the data buffer from the input sample. If the sample contains more than one buffer,
                            // this method copies the data from the original buffers into a new buffer, and replaces
                            // the original buffer list with the new buffer. The new buffer is returned in the inputMediaBuffer parameter.
                            // If the sample contains a single buffer, this method returns a pointer to the original buffer.
                            // In typical use, most samples do not contain multiple buffers.
                            hr = InputSample.ConvertToContiguousBuffer(out inputMediaBuffer);
                            if (hr != HResult.S_OK)
                            {
                                throw new Exception("OnProcessOutput call to InputSample.ConvertToContiguousBuffer failed. Err=" + hr.ToString());
                            }
                            // get some other things from the input sample
                            hr = InputSample.GetSampleDuration(out long sampleDuration);
                            if (hr != HResult.S_OK)
                            {
                                throw new Exception("OnProcessOutput call to InputSample.GetSampleDuration failed. Err=" + hr.ToString());
                            }
                            hr = InputSample.GetTotalLength(out int sampleSize);
                            if (hr != HResult.S_OK)
                            {
                                throw new Exception("OnProcessOutput call to InputSample.GetTotalLength failed. Err=" + hr.ToString());
                            }
                            hr = InputSample.GetSampleTime(out long sampleTimeStamp);
                            if (hr != HResult.S_OK)
                            {
                                throw new Exception("OnProcessOutput call to InputSample.GetSampleTime failed. Err=" + hr.ToString());
                            }
                            // get the attributes from the input sample
                            if (InputSample is IMFAttributes)
                            {
                                sampleAttributes = (InputSample as IMFAttributes);
                            }
                            else
                            {
                                sampleAttributes = null;
                            }
                            // we have all the information we need to create a new output sample
                            sinkWriterSample = WMFUtils.CreateMediaSampleFromBuffer(sampleTimeStamp, sampleDuration, inputMediaBuffer, sampleSize, sampleAttributes);
                            if (sinkWriterSample == null)
                            {
                                throw new Exception("OnProcessOutput, Error on call to CreateMediaSampleFromBuffer sinkWriterSample == null");
                            }
                            // we have a sample, if so is it the first non null one?
                            if (isFirstSample)
                            {
                                // yes it is set up our timestamp
                                firstSampleBaseTime = sampleTimeStamp;
                                isFirstSample       = false;
                            }
                            // rebase the time stamp
                            sampleTimeStamp -= firstSampleBaseTime;
                            hr = sinkWriterSample.SetSampleTime(sampleTimeStamp);
                            if (hr != HResult.S_OK)
                            {
                                throw new Exception("OnProcessOutput call to InputSample.SetSampleTime failed. Err=" + hr.ToString());
                            }
                            // write the sample out
                            hr = workingSinkWriter.WriteSample(sinkWriterVideoStreamId, sinkWriterSample);
                            if (hr != HResult.S_OK)
                            {
                                throw new Exception("OnProcessOutput call to WriteSample(b) failed. Err=" + hr.ToString());
                            }
                        }
                    }
                }
            }
            finally
            {
                // clean up
                if (inputMediaBuffer != null)
                {
                    Marshal.ReleaseComObject(inputMediaBuffer);
                }
                if (sinkWriterSample != null)
                {
                    Marshal.ReleaseComObject(sinkWriterSample);
                }
                // Release the current input sample so we can get another one.
                // the act of setting it to null releases it because the property
                // is coded that way
                InputSample = null;
            }
            return(HResult.S_OK);
        }
Exemplo n.º 28
0
        /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
        /// <summary>
        /// Constructor
        /// </summary>
        /// <history>
        ///    01 Nov 18  Cynic - Originally Written
        /// </history>
        public frmMain()
        {
            bool    retBOOL = false;
            HResult hr      = 0;

            if (DesignMode == false)
            {
                // set the current directory equal to the exe directory. We do this because
                // people can start from a link and if the start-in directory is not right
                // it can put the log file in strange places
                Directory.SetCurrentDirectory(Application.StartupPath);

                // set up the Singleton g_Logger instance. Simply using it in a test
                // creates it.
                if (g_Logger == null)
                {
                    // did not work, nothing will start say so now in a generic way
                    MessageBox.Show("Logger Class Failed to Initialize. Nothing will work well.");
                    return;
                }
                // record this in the logger for everybodys use
                g_Logger.ApplicationMainForm   = this;
                g_Logger.DefaultDialogBoxTitle = APPLICATION_NAME;
                try
                {
                    // set the icon for this form and for all subsequent forms
                    g_Logger.AppIcon = new Icon(GetType(), "App.ico");
                    this.Icon        = new Icon(GetType(), "App.ico");
                }
                catch (Exception)
                {
                }

                // Register the global error handler as soon as we can in Main
                // to make sure that we catch as many exceptions as possible
                // this is a last resort. All execeptions should really be trapped
                // and handled by the code.
                OISGlobalExceptions ex1 = new OISGlobalExceptions();
                Application.ThreadException += new ThreadExceptionEventHandler(ex1.OnThreadException);

                // set the culture so our numbers convert consistently
                System.Threading.Thread.CurrentThread.CurrentCulture = g_Logger.GetDefaultCulture();
            }

            InitializeComponent();

            if (DesignMode == false)
            {
                // set up our logging
                retBOOL = g_Logger.InitLogging(DEFAULTLOGDIR, APPLICATION_NAME, false);
                if (retBOOL == false)
                {
                    // did not work, nothing will start say so now in a generic way
                    MessageBox.Show("The log file failed to create. No log file will be recorded.");
                }
                // pump out the header
                g_Logger.EmitStandardLogfileheader(APPLICATION_NAME);
                LogMessage("");
                LogMessage("Version: " + APPLICATION_VERSION);
                LogMessage("");

                // we always have to initialize MF. The 0x00020070 here is the WMF version
                // number used by the MF.Net samples. Not entirely sure if it is appropriate
                hr = MFExtern.MFStartup(0x00020070, MFStartup.Full);
                if (hr != 0)
                {
                    LogMessage("Constructor: call to MFExtern.MFStartup returned " + hr.ToString());
                }

                // some initial configuration
                this.textBoxVideoFileNameAndPath.Text         = INITIALFILE;
                ctlTantaEVRFilePlayer1.VideoFileAndPathToPlay = INITIALFILE;

                // set our heartbeat going
                LaunchHeartBeat();
            }
        }
Exemplo n.º 29
0
 public static string GetDescription(this HResult HResult)
 {
     return(HResult.GetType().GetField(HResult.ToString())?.GetCustomAttribute <DescriptionAttribute>()?.Description);
 }
Exemplo n.º 30
0
    protected void CreateOutputNode(
        IMFStreamDescriptor pSourceSD,
        out IMFTopologyNode ppNode
        )
    {
        IMFTopologyNode     pNode             = null;
        IMFMediaTypeHandler pHandler          = null;
        IMFActivate         pRendererActivate = null;

        Guid    guidMajorType = Guid.Empty;
        HResult hr            = HResult.S_OK;

        // Get the stream ID.
        int streamID = 0;

        try
        {
            try
            {
                hr = pSourceSD.GetStreamIdentifier(out streamID); // Just for debugging, ignore any failures.
                MFError.ThrowExceptionForHR(hr);
            }
            catch
            {
                TRACE("IMFStreamDescriptor::GetStreamIdentifier" + hr.ToString());
            }

            // Get the media type handler for the stream.
            hr = pSourceSD.GetMediaTypeHandler(out pHandler);
            MFError.ThrowExceptionForHR(hr);

            // Get the major media type.
            hr = pHandler.GetMajorType(out guidMajorType);
            MFError.ThrowExceptionForHR(hr);

            // Create a downstream node.
            hr = MFExtern.MFCreateTopologyNode(MFTopologyType.OutputNode, out pNode);
            MFError.ThrowExceptionForHR(hr);

            // Create an IMFActivate object for the renderer, based on the media type.
            if (MFMediaType.Audio == guidMajorType)
            {
                // Create the audio renderer.
                TRACE(string.Format("Stream {0}: audio stream", streamID));
                hr = MFExtern.MFCreateAudioRendererActivate(out pRendererActivate);
                MFError.ThrowExceptionForHR(hr);
            }
            else if (MFMediaType.Video == guidMajorType)
            {
                // Create the video renderer.
                TRACE(string.Format("Stream {0}: video stream", streamID));
                hr = MFExtern.MFCreateVideoRendererActivate(m_hwndVideo, out pRendererActivate);
                MFError.ThrowExceptionForHR(hr);
            }
            else
            {
                TRACE(string.Format("Stream {0}: Unknown format", streamID));
                throw new COMException("Unknown format", (int)HResult.E_FAIL);
            }

            // Set the IActivate object on the output node.
            hr = pNode.SetObject(pRendererActivate);
            MFError.ThrowExceptionForHR(hr);

            // Return the IMFTopologyNode pointer to the caller.
            ppNode = pNode;
        }
        catch
        {
            // If we failed, release the pNode
            SafeRelease(pNode);
            throw;
        }
        finally
        {
            // Clean up.
            SafeRelease(pHandler);
            SafeRelease(pRendererActivate);
        }
    }