public OpcDaVQTE[] Read(IList<string> itemIds, IList<TimeSpan> maxAge) { if (maxAge == null) maxAge = new TimeSpan[itemIds.Count]; if (itemIds.Count != maxAge.Count) throw new ArgumentException("Invalid size of maxAge", "maxAge"); int[] intMaxAge = ArrayHelpers.CreateMaxAgeArray(maxAge, itemIds.Count); string[] pszItemIDs = itemIds.ToArray(); var ppvValues = new object[pszItemIDs.Length]; var ppwQualities = new short[pszItemIDs.Length]; var ppftTimeStamps = new FILETIME[pszItemIDs.Length]; var ppErrors = new HRESULT[pszItemIDs.Length]; DoComCall(ComObject, "IOPCItemIO::Read", () => ComObject.Read(pszItemIDs.Length, pszItemIDs, intMaxAge, out ppvValues, out ppwQualities, out ppftTimeStamps, out ppErrors), pszItemIDs.Length, pszItemIDs, maxAge); var result = new OpcDaVQTE[itemIds.Count]; for (int i = 0; i < ppvValues.Length; i++) { var vqte = new OpcDaVQTE { Value = ppvValues[i], Quality = ppwQualities[i], Timestamp = FileTimeConverter.FromFileTime(ppftTimeStamps[i]), Error = ppErrors[i] }; result[i] = vqte; } return result; }
public void SetItemBufferEnable( int[] serverHandles, bool[] enable, out HRESULT[] errors) { throw new NotImplementedException(); }
internal static OpcDaItemValue[] Create(OpcDaGroup opcDaGroup, OPCITEMSTATE[] ppItemValues, HRESULT[] ppErrors) { try { var result = new OpcDaItemValue[ppItemValues.Length]; for (var i = 0; i < result.Length; i++) { result[i] = new OpcDaItemValue { Timestamp = FileTimeConverter.FromFileTime(ppItemValues[i].ftTimeStamp), Value = ppItemValues[i].vDataValue, Quality = ppItemValues[i].wQuality, Error = ppErrors[i], Item = opcDaGroup.GetItem(ppItemValues[i].hClient) }; } return result; } catch (Exception ex) { Log.Error("Cannot create OpcDaItemValue object.", ex); return new OpcDaItemValue[0]; } }
internal static OpcDaItemValue[] Create(IList<OpcDaItem> items, object[] ppvValues, OpcDaQuality[] ppwQualities, DateTimeOffset[] ppftTimeStamps, HRESULT[] ppErrors) { try { var result = new OpcDaItemValue[items.Count]; for (var i = 0; i < ppvValues.Length; i++) { var tagValue = new OpcDaItemValue { Value = ppvValues[i], Quality = ppwQualities[i], Timestamp = ppftTimeStamps[i], Error = ppErrors[i], Item = items[i] }; result[i] = tagValue; } return result; } catch (Exception ex) { Log.Error("Cannot create OpcDaItemValue object.", ex); return new OpcDaItemValue[0]; } }
internal static OpcDaItemValue[] Create(OpcDaGroup opcDaGroup, int dwCount, int[] phClientItems, object[] pvValues, short[] pwQualities, FILETIME[] pftTimeStamps, HRESULT[] pErrors) { try { var values = new OpcDaItemValue[dwCount]; for (var i = 0; i < values.Length; i++) { values[i] = new OpcDaItemValue { Value = pvValues[i], Item = opcDaGroup.GetItem(phClientItems[i]), Quality = pwQualities[i], Timestamp = FileTimeConverter.FromFileTime(pftTimeStamps[i]), Error = pErrors[i] }; } return values; } catch (Exception ex) { Log.Error("Cannot create OpcDaItemValue object.", ex); return new OpcDaItemValue[0]; } }
public HRESULT[] WriteVQT(IList<string> itemIds, IList<OpcDaVQT> values) { if (itemIds.Count != values.Count) throw new ArgumentException("Invalid size of values", "values"); var vqts = new OPCITEMVQT[values.Count]; for (int i = 0; i < values.Count; i++) { OpcDaVQT opcItemValue = values[i]; vqts[i].bQualitySpecified = false; if (opcItemValue.Quality != short.MinValue) { vqts[i].bQualitySpecified = true; vqts[i].wQuality = opcItemValue.Quality; } vqts[i].bTimeStampSpecified = false; if (opcItemValue.Timestamp != DateTimeOffset.MinValue) { vqts[i].bTimeStampSpecified = true; vqts[i].ftTimeStamp = FileTimeConverter.ToFileTime(opcItemValue.Timestamp); } vqts[i].vDataValue = opcItemValue.Value; } string[] pszItemIDs = itemIds.ToArray(); var ppErrors = new HRESULT[pszItemIDs.Length]; DoComCall(ComObject, "IOPCItemIO::WriteVQT", () => ComObject.WriteVQT(pszItemIDs.Length, pszItemIDs, vqts, out ppErrors), pszItemIDs.Length, pszItemIDs); return ppErrors; }
public void OnWriteComplete(int dwTransid, int hGroup, HRESULT hrMastererr, int dwCount, int[] pClienthandles, HRESULT[] pErrors) { var f = WriteComplete; if (f != null) { f(dwTransid, hGroup, hrMastererr, dwCount, pClienthandles, pErrors); } }
public string[] LookupItemIDs(string itemId, int[] propertyIds, out HRESULT[] ppErrors) { string[] ppszNewItemIDs = {}; HRESULT[] _ppErrors = {}; DoComCall(ComObject,"IOpcItemProperties::LookupItemIds", () => ComObject.LookupItemIDs(itemId, propertyIds.Length, propertyIds, out ppszNewItemIDs, out _ppErrors), itemId, propertyIds); ppErrors = _ppErrors; return ppszNewItemIDs; }
public void OnDataChange(int dwTransid, int hGroup, HRESULT hrMasterquality, HRESULT hrMastererror, int dwCount, int[] phClientItems, object[] pvValues, short[] pwQualities, FILETIME[] pftTimeStamps, HRESULT[] pErrors) { var f = DataChange; if (f != null) { f(dwTransid, hGroup, hrMasterquality, hrMastererror, dwCount, phClientItems, pvValues, pwQualities, pftTimeStamps, pErrors); } }
public int Write(int[] serverHandles, object[] values, int transactionId, out HRESULT[] errors) { var _errors = new HRESULT[serverHandles.Length]; int result = DoComCall(ComObject, "IOpcAsyncIO3::Write", () => { int dwCancelId; ComObject.Write(serverHandles.Length, serverHandles, values, transactionId, out dwCancelId, out _errors); return dwCancelId; }, serverHandles, values, transactionId); errors = _errors; return result; }
public object[] GetItemProperties(string itemId, int[] propertyIds, out HRESULT[] errors) { HRESULT[] _errors = {}; object[] results = DoComCall(ComObject, "IOpcItemProperties::GetItemProperties", () => { object[] ppvData; ComObject.GetItemProperties(itemId, propertyIds.Length, propertyIds, out ppvData, out _errors); return ppvData; }, itemId, propertyIds.Length, propertyIds); errors = _errors; return results; }
public OPCITEMSTATE[] Read(OPCDATASOURCE dataSource, int[] serverHandles, out HRESULT[] errors) { HRESULT[] _errors = {}; OPCITEMSTATE[] results = DoComCall(ComObject, "IOpcSyncIO::Read", () => { OPCITEMSTATE[] ppItemValues; ComObject.Read(dataSource, serverHandles.Length, serverHandles, out ppItemValues, out _errors); return ppItemValues; }, dataSource, serverHandles.Length, serverHandles); errors = _errors; return results; }
public int Read(int[] serverHandles, int transactionId, out HRESULT[] errors) { var _errors = new HRESULT[serverHandles.Length]; int result = DoComCall(ComObject, "IOpcAsyncIO2::Read", () => { int dwCancelId; ComObject.Read(serverHandles.Length, serverHandles, transactionId, out dwCancelId, out _errors); return dwCancelId; }, serverHandles, transactionId); errors = _errors; return result; }
public TimeSpan[] SetItemSamplingRate( int[] serverHandles, TimeSpan[] requestedSamplingRate, out HRESULT[] errors) { throw new NotImplementedException(); int[] pdwRequestedSamplingRate = ArrayHelpers.CreateMaxAgeArray(requestedSamplingRate, requestedSamplingRate.Length); IntPtr ppdwRevisedSamplingRate; IntPtr ppErrors; ComObject.SetItemSamplingRate(serverHandles.Length, serverHandles, pdwRequestedSamplingRate, out ppdwRevisedSamplingRate, out ppErrors); return null; }
public OPCITEMRESULT[] AddItems( OPCITEMDEF[] itemDefinitions, out HRESULT[] errors) { var _errors = new HRESULT[itemDefinitions.Length]; OPCITEMRESULT[] result = DoComCall(ComObject, "IOPCItemMgt::AddItems", () => { IntPtr ppAddResults; ComObject.AddItems(itemDefinitions.Length, itemDefinitions, out ppAddResults, out _errors); OPCITEMRESULT[] opcDaItemResults = ArrayHelpers.CreateOpcItemResults(itemDefinitions, ppAddResults); Marshal.FreeCoTaskMem(ppAddResults); return opcDaItemResults; }, itemDefinitions.Length, itemDefinitions); errors = _errors; return result; }
private void IdentifyCallback(PVOID IdentifyCallbackContext, HRESULT OperationStatus, WINBIO_UNIT_ID UnitId, WINBIO_IDENTITY Identity, WINBIO_BIOMETRIC_SUBTYPE SubFactor, WINBIO_REJECT_DETAIL RejectDetail) { switch (OperationStatus) { case S_OK: { var accountSid = Identity.Value.AccountSid[0]; var sid = new SecurityIdentifier(accountSid.Data.ToArray(accountSid.Size), 0); IdentityReference user = sid.Translate(typeof(NTAccount)); if (user != null) IdentifySuccess(this, new AuthenticationSuccessEventArgs(user, (WinBioFinger)(int)SubFactor)); else IdentifyFailed(this, new AuthenticationFailedEventArgs(WinBioError.NoAccount, WinBioRejectDetail.None)); break; } case WINBIO_E_UNKNOWN_ID: { IdentifyFailed(this, new AuthenticationFailedEventArgs(WinBioError.UnknownId, (WinBioRejectDetail)(int)RejectDetail)); break; } case WINBIO_E_BAD_CAPTURE: { IdentifyFailed(this, new AuthenticationFailedEventArgs(WinBioError.BadCapture, (WinBioRejectDetail)(int)RejectDetail)); break; } case WINBIO_E_CANCELED: break; default: { IdentifyFailed(this, new AuthenticationFailedEventArgs(WinBioError.Failed, (WinBioRejectDetail)(int)RejectDetail)); break; } } }
public object[] ReadMaxAge(int[] serverHandles, IList<TimeSpan> maxAge, out OpcDaQuality[] qualities, out DateTimeOffset[] timestamps, out HRESULT[] errors) { int[] intMaxAge = ArrayHelpers.CreateMaxAgeArray(maxAge, maxAge.Count); object[] ppvValues = {}; short[] ppwQualities = {}; FILETIME[] ppftTimeStamps = {}; HRESULT[] _errors = {}; DoComCall(ComObject, "IOpcSyncIO2::ReadMaxAge", () => ComObject.ReadMaxAge(serverHandles.Length, serverHandles, intMaxAge, out ppvValues, out ppwQualities, out ppftTimeStamps, out _errors), serverHandles.Length, serverHandles, intMaxAge); timestamps = new DateTimeOffset[ppftTimeStamps.Length]; qualities = new OpcDaQuality[ppwQualities.Length]; for (int i = 0; i < timestamps.Length; i++) { timestamps[i] = FileTimeConverter.FromFileTime(ppftTimeStamps[i]); qualities[i] = new OpcDaQuality(ppwQualities[i]); } errors = _errors; return ppvValues; }
private void OnDataChange(int dwTransid, int hGroup, HRESULT hrMasterquality, HRESULT hrMastererror, int dwCount, int[] phClientItems, object[] pvValues, short[] pwQualities, FILETIME[] pftTimeStamps, HRESULT[] pErrors) { try { Log.TraceFormat( "On data change. Transaction id: {0}. Client group handle: {1}. Master quality: {2}. Error: {3}.", dwTransid, hGroup, hrMasterquality, hrMastererror); if (hGroup != _opcDaGroup.ClientHandle) throw new ArgumentException("Wrong group handle", "hGroup"); OpcDaItemValue[] values = OpcDaItemValue.Create(_opcDaGroup, dwCount, phClientItems, pvValues, pwQualities, pftTimeStamps, pErrors); if (dwTransid == 0) // Data from subscription { OnNewItemValues(values); return; } IAsyncRequest request = CompleteRequest(dwTransid); if (request == null) return; if (request.TransactionId != dwTransid) throw new ArgumentException("Wrong transaction id.", "dwTransid"); request.OnDataChange(dwTransid, hGroup, hrMasterquality, hrMastererror, values); OnNewItemValues(values); } catch (Exception ex) { Log.Error("Error on data change.", ex); } }
public void CanEnumerateDesktopFolders() { // Defines the type of items that we want to retieve below the desktop root item const SHCONTF flags = SHCONTF.NONFOLDERS | SHCONTF.FOLDERS | SHCONTF.INCLUDEHIDDEN; // Get the desktop root folder. IntPtr ptrDesktopFolder = default(IntPtr); IntPtr enumerator = default(IntPtr); IShellFolder2 iDesktopFolder = null; // Enumerate over children of given shell folder item using this interface // https://msdn.microsoft.com/en-us/library/windows/desktop/bb761983(v=vs.85).aspx IEnumIDList enumIDs = null; try { HRESULT hr = NativeMethods.SHGetDesktopFolder(out ptrDesktopFolder); Assert.IsTrue(hr == HRESULT.S_OK); if (ptrDesktopFolder != IntPtr.Zero) { iDesktopFolder = (IShellFolder2)Marshal.GetTypedObjectForIUnknown(ptrDesktopFolder, typeof(IShellFolder2)); } Assert.IsTrue(iDesktopFolder != null); // Create an enumerator and enumerate over each item. hr = iDesktopFolder.EnumObjects(IntPtr.Zero, flags, out enumerator); Assert.IsTrue(hr == HRESULT.S_OK); // Convert enum IntPtr to interface enumIDs = (IEnumIDList)Marshal.GetTypedObjectForIUnknown(enumerator, typeof(IEnumIDList)); Assert.IsTrue(enumIDs != null); uint fetched, count = 0; IntPtr apidl = default(IntPtr); // Get one item below desktop root at a time and process by getting its display name for (; enumIDs.Next(1, out apidl, out fetched) == HRESULT.S_OK; count++) { if (fetched <= 0) // End this loop if no more items are available { break; } IntPtr ptrStr = default(IntPtr); // get strings for this item try { string displayName = null, parseName = null; ptrStr = Marshal.AllocCoTaskMem(NativeMethods.MAX_PATH * 2 + 4); Marshal.WriteInt32(ptrStr, 0, 0); StringBuilder buf = new StringBuilder(NativeMethods.MAX_PATH); // The apidl ITEMIDLIST structures returned in the array are relative to // the IShellFolder being enumerated. if (iDesktopFolder.GetDisplayNameOf(apidl, SHGDNF.SHGDN_NORMAL, ptrStr) == HRESULT.S_OK) { NativeMethods.StrRetToBuf(ptrStr, ptrDesktopFolder, buf, NativeMethods.MAX_PATH); displayName = buf.ToString(); } if (iDesktopFolder.GetDisplayNameOf(apidl, SHGDNF.SHGDN_FORPARSING, ptrStr) == HRESULT.S_OK) { NativeMethods.StrRetToBuf(ptrStr, ptrDesktopFolder, buf, NativeMethods.MAX_PATH); parseName = buf.ToString(); } Assert.IsFalse(string.IsNullOrEmpty(displayName)); Assert.IsFalse(string.IsNullOrEmpty(parseName)); } finally { ptrStr = PidlManager.FreeCoTaskMem(ptrStr); apidl = PidlManager.FreeCoTaskMem(apidl); } } // There should be more than one item below the desktop root item // 'My PC', 'Recycle Bin', and 'Network' are already three Assert.IsTrue(count > 2); } finally { if (enumerator != default(IntPtr)) { Marshal.Release(enumerator); } if (iDesktopFolder != null) { Marshal.ReleaseComObject(iDesktopFolder); } if (ptrDesktopFolder != default(IntPtr)) { Marshal.Release(ptrDesktopFolder); } } }
/// <summary> /// Create a ColorContext from an unmanaged color context /// </summary> private ColorContext(SafeMILHandle colorContextHandle) { _colorContextHandle = colorContextHandle; // // For 3.* backwards compat, we aren't going to HRESULT.Check() anywhere because // that could introduce new exceptions. If anything fails, _colorContextHelper // will be invalid and we'll emulate the old failure behavior later in // OpenProfileStream() // IWICCC.WICColorContextType type; if (HRESULT.Failed(IWICCC.GetType(_colorContextHandle, out type))) { return; } switch (type) { case IWICCC.WICColorContextType.WICColorContextProfile: uint cbProfileActual; int hr = IWICCC.GetProfileBytes(_colorContextHandle, 0, null, out cbProfileActual); if (HRESULT.Succeeded(hr) && cbProfileActual != 0) { byte[] profileData = new byte[cbProfileActual]; if (HRESULT.Failed(IWICCC.GetProfileBytes( _colorContextHandle, cbProfileActual, profileData, out cbProfileActual)) ) { return; } FromRawBytes(profileData, (int)cbProfileActual, /* dontThrowException = */ true); } break; case IWICCC.WICColorContextType.WICColorContextExifColorSpace: uint colorSpace; if (HRESULT.Failed(IWICCC.GetExifColorSpace(_colorContextHandle, out colorSpace))) { return; } // // From MSDN: // "1" is sRGB. We will use our built-in sRGB profile. // "2" is Adobe RGB. WIC says we should never see this because they are nonstandard and instead a // real profile will be returned. // "3-65534" is unused. // // From the Exif spec: // B. Tag Relating to Color Space // ColorSpace // // The color space information tag (ColorSpace) is always recorded as the color space specifier. // Normally sRGB (=1) is used to define the color space based on the PC monitor conditions and environment. If a // color space other than sRGB is used, Uncalibrated (=FFFF.H) is set. Image data recorded as Uncalibrated can be // treated as sRGB when it is converted to Flashpix. On sRGB see Annex E. // Tag = 40961 (A001.H) // Type = SHORT // Count = 1 // 1 = sRGB // FFFF.H = Uncalibrated // // So for 65535 we will return sRGB since it is acceptible rather than having an invalid ColorContext. The Exif // CC should always be the second one so the real one is given priority. Alternatively, we could ignore the // uncalibrated CC but that would be a breaking change with 3.* (returning 1 instead of 2). // // If anything other than 1 or 65535 happens, _colorContextHelper will remain invalid and we will emulate // the old crash behavior in OpenProfileStream(). // if (colorSpace == 1 || colorSpace == 65535) { ResourceManager resourceManager = new ResourceManager( _colorProfileResources, Assembly.GetAssembly(typeof(ColorContext)) ); byte[] sRGBProfile = (byte[])resourceManager.GetObject(_sRGBProfileName); // The existing ColorContext has already been initialized as Exif so we can't initialize it again // and instead must create a new one. using (FactoryMaker factoryMaker = new FactoryMaker()) { _colorContextHandle.Dispose(); _colorContextHandle = null; if (HRESULT.Failed(UnsafeNativeMethodsMilCoreApi.WICCodec.CreateColorContext( factoryMaker.ImagingFactoryPtr, out _colorContextHandle)) ) { return; } if (HRESULT.Failed(IWICCC.InitializeFromMemory( _colorContextHandle, sRGBProfile, (uint)sRGBProfile.Length)) ) { return; } } // Finally, fill in _colorContextHelper FromRawBytes(sRGBProfile, sRGBProfile.Length, /* dontThrowException = */ true); } else if (Invariant.Strict) { Invariant.Assert(false, String.Format(CultureInfo.InvariantCulture, "IWICColorContext::GetExifColorSpace returned {0}.", colorSpace)); } break; default: if (Invariant.Strict) { Invariant.Assert(false, "IWICColorContext::GetType() returned WICColorContextUninitialized."); } break; } // SECURITY NOTE: This constructor does not set a Uri because the profile comes from raw file // data. Thus, we don't set _isProfileUriNotFromUser to true because we // don't want get_ProfileUri to demand permission to return null. Debug.Assert(_profileUri.Value == null); }
private void OnWriteComplete(int dwTransid, int hGroup, HRESULT hrMastererr, int dwCount, int[] pClienthandles, HRESULT[] pErrors) { try { Log.TraceFormat("On write complete. Transaction id: {0}. Client group handle: {1}. Error: {2}.", dwTransid, hGroup, hrMastererr); IAsyncRequest request = CompleteRequest(dwTransid); if (request == null) return; if (request.TransactionId != dwTransid) throw new ArgumentException("Wrong transaction id.", "dwTransid"); request.OnWriteComplete(dwTransid, hGroup, hrMastererr, dwCount, pClienthandles, pErrors); } catch (Exception ex) { Log.Error("Error on write complete.", ex); } }
public unsafe override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent) { IntPtr handle = (parent == null ? IntPtr.Zero : parent.Handle); // try to get the page guid if (obj is Ole32.IPerPropertyBrowsing) { // check for a property page Guid guid = Guid.Empty; HRESULT hr = ((Ole32.IPerPropertyBrowsing)obj).MapPropertyToPage(Ole32.DispatchID.MEMBERID_NIL, &guid); if (hr == HRESULT.S_OK & !guid.Equals(Guid.Empty)) { object o = obj; SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, 1, new Guid[] { guid }, Application.CurrentCulture.LCID, 0, IntPtr.Zero); return(true); } } if (obj is Ole32.ISpecifyPropertyPages ispp) { bool failed = false; Exception failureException; try { var uuids = new Ole32.CAUUID(); HRESULT hr = ispp.GetPages(&uuids); if (!hr.Succeeded() || uuids.cElems == 0) { return(false); } try { object o = obj; SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, uuids.cElems, (IntPtr)uuids.pElems, Application.CurrentCulture.LCID, 0, IntPtr.Zero); return(true); } finally { if (uuids.pElems != null) { Marshal.FreeCoTaskMem((IntPtr)uuids.pElems); } } } catch (Exception ex1) { failed = true; failureException = ex1; } if (failed) { string errString = SR.ErrorPropertyPageFailed; IUIService uiSvc = (context != null) ? ((IUIService)context.GetService(typeof(IUIService))) : null; if (uiSvc == null) { RTLAwareMessageBox.Show(null, errString, SR.PropertyGridTitle, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); } else if (failureException != null) { uiSvc.ShowError(failureException, errString); } else { uiSvc.ShowError(errString); } } } return(false); }
//// public void LoadProperties() //// { //// if (_KnownFolderIsInitialized == false) //// { //// _KnownFolderIsInitialized = true; //// KnownFolder = LoadKnownFolder(); //// } //// //// if (_ItemTypeIsInitialized == false) //// { //// _ItemTypeIsInitialized = true; //// ItemType = LoadItemType(); //// } //// //// if (_IconResourceIdInitialized == false) //// { //// _IconResourceIdInitialized = true; //// _IconResourceId = LoadIconResourceId(); //// } //// } /// <summary> /// Initializes the items type flags and path properties. /// </summary> /// <param name="path">Is either a path reference a la 'C:' or a /// special folder path reference a la '::{...}' <seealso cref="KF_IID"/> /// for more details.</param> /// <returns>Returns a simple pojo type object to initialize /// the calling object members.</returns> internal static BrowseItemFromPath InitItem(string path) { if (string.IsNullOrEmpty(path) == true) // return unknown references { var ret = new BrowseItemFromPath(path, path); ret.Name = path; return(ret); } if (path.Length == 38) { try { Guid theGuid; if (Guid.TryParse(path, out theGuid) == true) { path = KF_IID.IID_Prefix + path; } } catch { // Catching errors just in case ... } } // Return item for root desktop item if (string.Compare(path, KF_IID.ID_ROOT_Desktop, true) == 0) { return(InitDesktopRootItem()); } ShellHelpers.SpecialPath isSpecialID = ShellHelpers.IsSpecialPath(path); string normPath = null, SpecialPathId = null; bool hasPIDL = false; IdList parentIdList, relativeChildIdList; if (isSpecialID == ShellHelpers.SpecialPath.IsSpecialPath) { SpecialPathId = path; hasPIDL = PidlManager.GetParentIdListFromPath(path, out parentIdList, out relativeChildIdList); } else { normPath = Browser.NormalizePath(path); hasPIDL = PidlManager.GetParentIdListFromPath(normPath, out parentIdList, out relativeChildIdList); } if (hasPIDL == false) // return references that cannot resolve with a PIDL { var ret = new BrowseItemFromPath(path, path); ret.Name = path; return(ret); } string parseName = normPath; string name = normPath; string labelName = null; IdList fullIdList = null; // Get the IShellFolder2 Interface for the original path item... IntPtr fullPidlPtr = default(IntPtr); IntPtr ptrShellFolder = default(IntPtr); IntPtr parentPIDLPtr = default(IntPtr); IntPtr relativeChildPIDLPtr = default(IntPtr); try { // We are asked to build the desktop root item here... if (parentIdList == null && relativeChildIdList == null) { using (var shellFolder = new ShellFolderDesktop()) { parseName = shellFolder.GetShellFolderName(fullPidlPtr, SHGDNF.SHGDN_FORPARSING); name = shellFolder.GetShellFolderName(fullPidlPtr, SHGDNF.SHGDN_INFOLDER | SHGDNF.SHGDN_FOREDITING); labelName = shellFolder.GetShellFolderName(fullPidlPtr, SHGDNF.SHGDN_NORMAL); } } else { fullIdList = PidlManager.CombineParentChild(parentIdList, relativeChildIdList); fullPidlPtr = PidlManager.IdListToPidl(fullIdList); if (fullPidlPtr == default(IntPtr)) { return(null); } HRESULT hr = HRESULT.False; if (fullIdList.Size == 1) // Is this item directly under the desktop root? { hr = NativeMethods.SHGetDesktopFolder(out ptrShellFolder); if (hr != HRESULT.S_OK) { return(null); } using (var shellFolder = new ShellFolder(ptrShellFolder)) { parseName = shellFolder.GetShellFolderName(fullPidlPtr, SHGDNF.SHGDN_FORPARSING); name = shellFolder.GetShellFolderName(fullPidlPtr, SHGDNF.SHGDN_INFOLDER | SHGDNF.SHGDN_FOREDITING); labelName = shellFolder.GetShellFolderName(fullPidlPtr, SHGDNF.SHGDN_NORMAL); } } else { parentPIDLPtr = PidlManager.IdListToPidl(parentIdList); relativeChildPIDLPtr = PidlManager.IdListToPidl(relativeChildIdList); using (var desktopFolder = new ShellFolderDesktop()) { hr = desktopFolder.Obj.BindToObject(parentPIDLPtr, IntPtr.Zero, typeof(IShellFolder2).GUID, out ptrShellFolder); } if (hr != HRESULT.S_OK) { return(null); } // This item is not directly under the Desktop root using (var shellFolder = new ShellFolder(ptrShellFolder)) { parseName = shellFolder.GetShellFolderName(relativeChildPIDLPtr, SHGDNF.SHGDN_FORPARSING); name = shellFolder.GetShellFolderName(relativeChildPIDLPtr, SHGDNF.SHGDN_INFOLDER | SHGDNF.SHGDN_FOREDITING); labelName = shellFolder.GetShellFolderName(relativeChildPIDLPtr, SHGDNF.SHGDN_NORMAL); } } } if (ShellHelpers.IsSpecialPath(parseName) == ShellHelpers.SpecialPath.None) { normPath = parseName; } return(new BrowseItemFromPath(path, parseName, name, labelName, SpecialPathId, normPath //// ,parentIdList, relativeChildIdList )); } finally { PidlManager.ILFree(parentPIDLPtr); PidlManager.ILFree(relativeChildPIDLPtr); if (fullPidlPtr != default(IntPtr)) { NativeMethods.ILFree(fullPidlPtr); } } }
private static void IUnknown(IUnknown *pUnk) { HRESULT hr = pUnk->QueryInterface(Guid.NewGuid(), out void *ppvObject); uint c = pUnk->AddRef(); uint r = pUnk->Release(); }
private void FinishFormat(HRESULT hResult) { this._device.EnumeratedEvent -= new FallibleEventHandler(this.EnumerationCompleted); this.Completed.Invoke(); }
public TimeSpan[] GetItemSamplingRate( int[] serverHandles, out HRESULT[] errors) { throw new NotImplementedException(); }
public HRESULT FinishOperations(HRESULT hrResult) { this.Progress.FinishOperations(hrResult); return(COMErrorCodes.S_OK); }
/// <summary> /// 표정의 재생을 시작합니다. /// </summary> public void StartExpression() { HRESULT.Check(NativeMethods.StartExpression(new IntPtr(Handle))); }
public virtual void ThrowExceptionForJitResult_wrapper(IntPtr _this, out IntPtr exception, HRESULT result) { exception = IntPtr.Zero; try { ThrowExceptionForJitResult(result); return; } catch (Exception ex) { exception = AllocException(ex); } }
/// <summary> /// 표정 객체를 생성합니다. /// </summary> public L2DExpression() { HRESULT.Check(NativeMethods.CreateExpression(out _Handle)); _IsLoaded = true; }
/// /// Create the unmanaged resources /// internal override void FinalizeCreation() { _bitmapInit.EnsureInitializedComplete(); BitmapSourceSafeMILHandle wicTransformer = null; double scaleX, scaleY; WICBitmapTransformOptions options; GetParamsFromTransform(Transform, out scaleX, out scaleY, out options); using (FactoryMaker factoryMaker = new FactoryMaker()) { try { IntPtr wicFactory = factoryMaker.ImagingFactoryPtr; wicTransformer = _source.WicSourceHandle; if (!DoubleUtil.IsOne(scaleX) || !DoubleUtil.IsOne(scaleY)) { uint width = Math.Max(1, (uint)(scaleX * _source.PixelWidth + 0.5)); uint height = Math.Max(1, (uint)(scaleY * _source.PixelHeight + 0.5)); HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapScaler( wicFactory, out wicTransformer)); lock (_syncObject) { HRESULT.Check(UnsafeNativeMethods.WICBitmapScaler.Initialize( wicTransformer, _source.WicSourceHandle, width, height, WICInterpolationMode.Fant)); } } if (options != WICBitmapTransformOptions.WICBitmapTransformRotate0) { // Rotations are extremely slow if we're pulling from a decoder because we end // up decoding multiple times. Caching the source lets us rotate faster at the cost // of increased memory usage. wicTransformer = CreateCachedBitmap( null, wicTransformer, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default, _source.Palette); // BitmapSource.CreateCachedBitmap already calculates memory pressure for // the new bitmap, so there's no need to do it before setting it to // WicSourceHandle. BitmapSourceSafeMILHandle rotator = null; HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFlipRotator( wicFactory, out rotator)); lock (_syncObject) { HRESULT.Check(UnsafeNativeMethods.WICBitmapFlipRotator.Initialize( rotator, wicTransformer, options)); } wicTransformer = rotator; } // If we haven't introduced either a scaler or rotator, add a null rotator // so that our WicSourceHandle isn't the same as our Source's. if (options == WICBitmapTransformOptions.WICBitmapTransformRotate0 && DoubleUtil.IsOne(scaleX) && DoubleUtil.IsOne(scaleY)) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFlipRotator( wicFactory, out wicTransformer)); lock (_syncObject) { HRESULT.Check(UnsafeNativeMethods.WICBitmapFlipRotator.Initialize( wicTransformer, _source.WicSourceHandle, WICBitmapTransformOptions.WICBitmapTransformRotate0)); } } WicSourceHandle = wicTransformer; _isSourceCached = _source.IsSourceCached; } catch { _bitmapInit.Reset(); throw; } } CreationCompleted = true; UpdateCachedSettings(); }
public void CanGetShellFolder2() { string specialPath = KF_IID.ID_FOLDERID_UsersFiles; IdList parentIdList = null, relativeChild = null; var retVal = PidlManager.GetParentIdListFromPath(specialPath, out parentIdList, out relativeChild); Assert.IsTrue(retVal); // Child item is the desktop -> cannot implement this for desktop since it has no parent if (parentIdList == null || relativeChild == null) { throw new NotImplementedException(); } IntPtr parentPtr = default(IntPtr); IntPtr relChildPtr = default(IntPtr); IntPtr relChildPtr1 = default(IntPtr); IntPtr ptrShellFolder = default(IntPtr); try { parentPtr = PidlManager.IdListToPidl(parentIdList); relChildPtr = PidlManager.IdListToPidl(relativeChild); Assert.IsTrue(parentPtr != default(IntPtr)); Assert.IsTrue(relChildPtr != default(IntPtr)); Guid guid = typeof(IShellFolder2).GUID; HRESULT hr = NativeMethods.SHBindToParent(relChildPtr, guid, out ptrShellFolder, ref relChildPtr1); Assert.IsTrue(hr == HRESULT.S_OK); using (var shellFolder = new ShellFolder(ptrShellFolder)) { Assert.IsTrue(shellFolder != null); var ParseName = shellFolder.GetShellFolderName(relChildPtr, SHGDNF.SHGDN_FORPARSING); Assert.IsFalse(string.IsNullOrEmpty(ParseName)); var Name = shellFolder.GetShellFolderName(relChildPtr, SHGDNF.SHGDN_NORMAL); Assert.IsFalse(string.IsNullOrEmpty(Name)); } } finally { if (parentPtr != default(IntPtr)) { NativeMethods.ILFree(parentPtr); } if (relChildPtr != default(IntPtr)) { NativeMethods.ILFree(relChildPtr); } // if (relChildPtr != default(IntPtr)) // NativeMethods.ILFree(relChildPtr1); } }
internal override void SetupFrame(SafeMILHandle frameEncodeHandle, SafeMILHandle encoderOptions) { PROPBAG2 propBag = new PROPBAG2(); PROPVARIANT propValue = new PROPVARIANT(); if (_imagequalitylevel != c_defaultImageQualityLevel) { try { propBag.Init("ImageQuality"); propValue.Init((float)_imagequalitylevel); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_transformation != c_defaultTransformation) { try { propBag.Init("BitmapTransform"); propValue.Init((byte)_transformation); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_lossless != c_defaultLossless) { try { propBag.Init("Lossless"); propValue.Init((bool)_lossless); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_usecodecoptions != c_defaultUseCodecOptions) { try { propBag.Init("UseCodecOptions"); propValue.Init((bool)_usecodecoptions); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_qualitylevel != c_defaultQualityLevel) { try { propBag.Init("Quality"); propValue.Init((byte)_qualitylevel); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_subsamplinglevel != c_defaultSubsamplingLevel) { try { propBag.Init("Subsampling"); propValue.Init((byte)_subsamplinglevel); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_overlaplevel != c_defaultOverlapLevel) { try { propBag.Init("Overlap"); propValue.Init((byte)_overlaplevel); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_horizontaltileslices != c_defaultHorizontalTileSlices) { try { propBag.Init("HorizontalTileSlices"); propValue.Init((ushort)_horizontaltileslices); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_verticaltileslices != c_defaultVerticalTileSlices) { try { propBag.Init("VerticalTileSlices"); propValue.Init((ushort)_verticaltileslices); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_frequencyorder != c_defaultFrequencyOrder) { try { propBag.Init("FrequencyOrder"); propValue.Init((bool)_frequencyorder); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_interleavedalpha != c_defaultInterleavedAlpha) { try { propBag.Init("InterleavedAlpha"); propValue.Init((bool)_interleavedalpha); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_alphaqualitylevel != c_defaultAlphaQualityLevel) { try { propBag.Init("AlphaQuality"); propValue.Init((byte)_alphaqualitylevel); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_compresseddomaintranscode != c_defaultCompressedDomainTranscode) { try { propBag.Init("CompressedDomainTranscode"); propValue.Init((bool)_compresseddomaintranscode); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_imagedatadiscardlevel != c_defaultImageDataDiscardLevel) { try { propBag.Init("ImageDataDiscard"); propValue.Init((byte)_imagedatadiscardlevel); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_alphadatadiscardlevel != c_defaultAlphaDataDiscardLevel) { try { propBag.Init("AlphaDataDiscard"); propValue.Init((byte)_alphadatadiscardlevel); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_ignoreoverlap != c_defaultIgnoreOverlap) { try { propBag.Init("IgnoreOverlap"); propValue.Init((bool)_ignoreoverlap); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.Initialize( frameEncodeHandle, encoderOptions )); }
public static bool Succeeded(HRESULT hr) { return ((int)hr >= 0); }
public FallibleEventArgs(HRESULT hr) => this.HR = hr;
private void ThrowExceptionForJitResult(IntPtr _this, HRESULT result) { throw new NotImplementedException("ThrowExceptionForJitResult"); }
internal static bool Failed(HRESULT hresult) { return ((int)hresult < 0); }
public HRESULT PostRenameItem(uint dwFlags, IShellItem psiItem, string pszNewName, HRESULT hrRename, IShellItem psiNewlyCreated) { this.Progress.PostRename((TransferSourceFlags)dwFlags, CreateShellObject(psiItem), pszNewName, hrRename, CreateShellObject(psiNewlyCreated)); return(COMErrorCodes.S_OK); }
internal void NativeShow() { // Applies config struct and other settings, then // calls main Win32 function. if (settings == null) { throw new InvalidOperationException( "An error has occurred in dialog configuration."); } // Do a last-minute parse of the various dialog control lists, // and only allocate the memory at the last minute. MarshalDialogControlStructs(); // Make the call and show the dialog. // NOTE: this call is BLOCKING, though the thread // WILL re-enter via the DialogProc. try { showState = NativeDialogShowState.Showing; // Here is the way we would use "vanilla" PInvoke to call TaskDialogIndirect; // but if we did so here, we'd be at the mercy of the CLR's native DLL cache - // see below for more details. // HRESULT hresult = NativeMethods.TaskDialogIndirect( // nativeDialogConfig, // out selectedButtonID, // out selectedRadioButtonID, // out checkBoxChecked); // Instead, we load comctl and bind to TaskDialogIndirect // We do it this way so we can rigidly control // which version of comctl32 is loaded, // The CLR's PInvoke mechanism maintains a DLL cache that is // NOT invalidated when the OS activation context is changed // such that different DLL versions are needed. IntPtr tdi = DllVersionManager.GetNativeFunctionPointer( ExternDll.ComCtl32, "TaskDialogIndirect"); NativeMethods.TDIDelegate taskDialogFunctionPointer = (NativeMethods.TDIDelegate) Marshal.GetDelegateForFunctionPointer( tdi, typeof(NativeMethods.TDIDelegate) ); // Invoke TaskDialogIndirect. HRESULT hresult = taskDialogFunctionPointer( nativeDialogConfig, out selectedButtonID, out selectedRadioButtonID, out checkBoxChecked); if (ErrorHelper.Failed(hresult)) { string msg; switch (hresult) { case HRESULT.E_INVALIDARG: msg = "Invalid arguments to Win32 call."; break; case HRESULT.E_OUTOFMEMORY: msg = "Dialog contents too complex."; break; default: msg = String.Format( "An unexpected internal error occurred in the Win32 call:{0:x}", hresult); break; } Exception e = Marshal.GetExceptionForHR((int)hresult); throw new Win32Exception(msg, e); } } finally { showState = NativeDialogShowState.Closed; } }
static void Main(string[] args) { string extractDir = @"F:\Takatano\Desktop\experiment\storages"; bool includeExtension = true; string msiFilePath = @"F:\Takatano\Projects\MsixEx\NDP45-KB3037581.msp"; VsInterop.IStorage rootStorage = null; HRESULT hr = NativeMethods.StgOpenStorage(msiFilePath, null, STGM.STGM_READ | STGM.STGM_SHARE_EXCLUSIVE, null, 0, out rootStorage); if (HResultHelper.IsSucceeded(hr) && rootStorage != null) { // // もしかすると、この辺関係ないかも // (構造を維持して展開できれば、話は違うかも) // //VsInterop.IEnumSTATSTG enumStatStg = null; //rootStorage.EnumElements(0, IntPtr.Zero, 0, out enumStatStg); //if (enumStatStg != null) //{ // while (true) // { // VsInterop.STATSTG[] stg = new VsInterop.STATSTG[1]; // uint fetched; // hr = (HRESULT)enumStatStg.Next(1, stg, out fetched); // if (hr == HRESULT.S_FALSE) // { // break; // } // if (hr != HRESULT.S_OK) // { // throw new Exception(@"Failed: IEnumSTATSTG.Next(): Failed to enumerate next storage status"); // } // Console.WriteLine(@"Name:{0}, Type:{1}", stg[0].pwcsName, stg[0].type); // if ((VsInterop.STGTY)stg[0].type == VsInterop.STGTY.STGTY_STORAGE) // { // saveStorage(rootStorage, extractDir, stg[0].pwcsName, includeExtension ? @".mst" : null); // } // //if (stg.pwcsName) // //{ // // CoTaskMemFree(stg.pwcsName); // これ必要なのかも, Marshal.FreeCoTaskMem(), string になっているし、不要かな。 // // stg.pwcsName = NULL; // //} // } // Marshal.ReleaseComObject(enumStatStg); //} // // A Database and Patch Example // https://msdn.microsoft.com/en-us/library/aa367813(v=vs.85).aspx // // http://www.pinvoke.net/default.aspx/msi.msirecordsetstring // http://blogs.msdn.com/b/heaths/archive/2006/03/31/566288.aspx // MsiDbOpenPersist msiDbOpenPersist = MsiDbOpenPersist.MSIDBOPEN_READONLY; if (isPatch(rootStorage)) { msiDbOpenPersist = MsiDbOpenPersist.MSIDBOPEN_READONLY | MsiDbOpenPersist.MSIDBOPEN_PATCHFILE; } // Release COM object of root storage. Marshal.ReleaseComObject(rootStorage); IntPtr msiDatabaseHandle = IntPtr.Zero; uint err = NativeMethods.MsiOpenDatabase(msiFilePath, new IntPtr((uint)msiDbOpenPersist), out msiDatabaseHandle); if (err == WinError.ERROR_SUCCESS) { IntPtr msiViewHandle = IntPtr.Zero; err = NativeMethods.MsiDatabaseOpenView(msiDatabaseHandle, @"SELECT Name, Data FROM _Streams", out msiViewHandle); if (err == WinError.ERROR_SUCCESS) { err = NativeMethods.MsiViewExecute(msiViewHandle, IntPtr.Zero); if (err == WinError.ERROR_SUCCESS) { while (true) { IntPtr msiRecordHandle = IntPtr.Zero; err = NativeMethods.MsiViewFetch(msiViewHandle, out msiRecordHandle); if (err != WinError.ERROR_SUCCESS) { break; } saveStream(msiRecordHandle, extractDir, includeExtension); NativeMethods.MsiCloseHandle(msiRecordHandle); } } } // Close MSI view handle. if (msiViewHandle != IntPtr.Zero) { NativeMethods.MsiCloseHandle(msiViewHandle); } } // Close MSI database handle. if (msiDatabaseHandle != IntPtr.Zero) { NativeMethods.MsiCloseHandle(msiDatabaseHandle); } } else { throw new Exception(string.Format(@"Failed: StgOpenStorage(): Failed to open root storage ""{0}""", msiFilePath)); } }
public void OnWriteComplete(int dwTransid, int hGroup, int hrMastererr, int dwCount, int[] pClienthandles, HRESULT[] pErrors) { throw new NotSupportedException(); }
private void AppendCustomCategories() { // Initialize our current index in the custom categories list int currentIndex = 0; // Keep track whether we add the Known Categories to our list bool knownCategoriesAdded = false; if (customCategoriesCollection != null) { // Append each category to list foreach (JumpListCustomCategory category in customCategoriesCollection) { // If our current index is same as the KnownCategory OrdinalPosition, // append the Known Categories if (!knownCategoriesAdded && currentIndex == KnownCategoryOrdinalPosition) { AppendKnownCategories(); knownCategoriesAdded = true; } // Don't process empty categories if (category.JumpListItems.Count == 0) { continue; } IObjectCollection categoryContent = (IObjectCollection) new CEnumerableObjectCollection(); // Add each link's shell representation to the object array foreach (IJumpListItem link in category.JumpListItems) { if (link is JumpListItem) { categoryContent.AddObject(((JumpListItem)link).NativeShellItem); } else if (link is JumpListLink) { categoryContent.AddObject(((JumpListLink)link).NativeShellLink); } } // Add current category to destination list HRESULT hr = customDestinationList.AppendCategory( category.Name, (IObjectArray)categoryContent); if (!CoreErrorHelper.Succeeded((int)hr)) { if ((uint)hr == 0x80040F03) { throw new InvalidOperationException("The file type is not registered with this application."); } else if ((uint)hr == 0x80070005 /*E_ACCESSDENIED*/) { // If the recent documents tracking is turned off by the user, // custom categories or items to an existing category cannot be added. // The recent documents tracking can be changed via: // 1. Group Policy “Do not keep history of recently opened documents”. // 2. Via the user setting “Store and display recently opened items in // the Start menu and the taskbar” in the Start menu property dialog. // throw new UnauthorizedAccessException("Custom categories cannot be added while recent documents tracking is turned off."); } else { Marshal.ThrowExceptionForHR((int)hr); } } // Increase our current index currentIndex++; } } // If the ordinal position was out of range, append the Known Categories // at the end if (!knownCategoriesAdded) { AppendKnownCategories(); } }
/// Note: often the data buffer is larger than the actual data in it. /// /// dontThrowException is for preserving the 3.* behavior of ColorContext(SafeMILHandle) /// private void FromRawBytes(byte[] data, int dataLength, bool dontThrowException) { Invariant.Assert(dataLength <= data.Length); Invariant.Assert(dataLength >= 0); UnsafeNativeMethods.PROFILEHEADER header; UnsafeNativeMethods.PROFILE profile; unsafe { fixed(void *dataPtr = data) { profile.dwType = NativeMethods.ProfileType.PROFILE_MEMBUFFER; profile.pProfileData = dataPtr; profile.cbDataSize = (uint)dataLength; _colorContextHelper.OpenColorProfile(ref profile); if (_colorContextHelper.IsInvalid) { if (dontThrowException) { return; } else { HRESULT.Check(Marshal.GetHRForLastWin32Error()); } } } } if (!_colorContextHelper.GetColorProfileHeader(out header)) { if (dontThrowException) { return; } else { HRESULT.Check(Marshal.GetHRForLastWin32Error()); } } // Copy the important stuff from the header into our smaller cache _profileHeader.phSize = header.phSize; _profileHeader.phCMMType = header.phCMMType; _profileHeader.phVersion = header.phVersion; _profileHeader.phClass = header.phClass; _profileHeader.phDataColorSpace = header.phDataColorSpace; _profileHeader.phConnectionSpace = header.phConnectionSpace; _profileHeader.phDateTime_0 = header.phDateTime_0; _profileHeader.phDateTime_1 = header.phDateTime_1; _profileHeader.phDateTime_2 = header.phDateTime_2; _profileHeader.phSignature = header.phSignature; _profileHeader.phPlatform = header.phPlatform; _profileHeader.phProfileFlags = header.phProfileFlags; _profileHeader.phManufacturer = header.phManufacturer; _profileHeader.phModel = header.phModel; _profileHeader.phAttributes_0 = header.phAttributes_0; _profileHeader.phAttributes_1 = header.phAttributes_1; _profileHeader.phRenderingIntent = header.phRenderingIntent; _profileHeader.phIlluminant_0 = header.phIlluminant_0; _profileHeader.phIlluminant_1 = header.phIlluminant_1; _profileHeader.phIlluminant_2 = header.phIlluminant_2; _profileHeader.phCreator = header.phCreator; switch (_profileHeader.phDataColorSpace) { case NativeMethods.ColorSpace.SPACE_XYZ: case NativeMethods.ColorSpace.SPACE_Lab: case NativeMethods.ColorSpace.SPACE_Luv: case NativeMethods.ColorSpace.SPACE_YCbCr: case NativeMethods.ColorSpace.SPACE_Yxy: case NativeMethods.ColorSpace.SPACE_HSV: case NativeMethods.ColorSpace.SPACE_HLS: case NativeMethods.ColorSpace.SPACE_CMY: _numChannels = 3; _colorSpaceFamily = StandardColorSpace.Unknown; break; case NativeMethods.ColorSpace.SPACE_RGB: _colorSpaceFamily = StandardColorSpace.Rgb; _numChannels = 3; break; case NativeMethods.ColorSpace.SPACE_GRAY: _colorSpaceFamily = StandardColorSpace.Gray; _numChannels = 1; break; case NativeMethods.ColorSpace.SPACE_CMYK: _colorSpaceFamily = StandardColorSpace.Cmyk; _numChannels = 4; break; case NativeMethods.ColorSpace.SPACE_2_CHANNEL: _colorSpaceFamily = StandardColorSpace.Multichannel; _numChannels = 2; break; case NativeMethods.ColorSpace.SPACE_3_CHANNEL: _colorSpaceFamily = StandardColorSpace.Multichannel; _numChannels = 3; break; case NativeMethods.ColorSpace.SPACE_4_CHANNEL: _colorSpaceFamily = StandardColorSpace.Multichannel; _numChannels = 4; break; case NativeMethods.ColorSpace.SPACE_5_CHANNEL: _numChannels = 5; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_6_CHANNEL: _numChannels = 6; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_7_CHANNEL: _numChannels = 7; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_8_CHANNEL: _numChannels = 8; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_9_CHANNEL: _numChannels = 9; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_A_CHANNEL: _numChannels = 10; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_B_CHANNEL: _numChannels = 11; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_C_CHANNEL: _numChannels = 12; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_D_CHANNEL: _numChannels = 13; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_E_CHANNEL: _numChannels = 14; _colorSpaceFamily = StandardColorSpace.Multichannel; break; case NativeMethods.ColorSpace.SPACE_F_CHANNEL: _numChannels = 15; _colorSpaceFamily = StandardColorSpace.Multichannel; break; default: _numChannels = 0; _colorSpaceFamily = StandardColorSpace.Unknown; break; } }
private unsafe void EnsureArrays() { if (arraysFetched) { return; } arraysFetched = true; try { // marshal the items. object[] nameItems = nameMarshaller.Items; object[] cookieItems = valueMarshaller.Items; Oleaut32.IPerPropertyBrowsing ppb = (Oleaut32.IPerPropertyBrowsing)target.TargetObject; int itemCount = 0; Debug.Assert(cookieItems != null && nameItems != null, "An item array is null"); if (nameItems.Length > 0) { object[] valueItems = new object[cookieItems.Length]; int cookie; Debug.Assert(cookieItems.Length == nameItems.Length, "Got uneven names and cookies"); // for each name item, we ask the object for it's corresponding value. // Type targetType = target.PropertyType; for (int i = nameItems.Length - 1; i >= 0; i--) { cookie = (int)cookieItems[i]; if (nameItems[i] is null || !(nameItems[i] is string)) { Debug.Fail("Bad IPerPropertyBrowsing item [" + i.ToString(CultureInfo.InvariantCulture) + "], name=" + (nameItems is null ? "(unknown)" : nameItems[i].ToString())); continue; } using var var = new Oleaut32.VARIANT(); HRESULT hr = ppb.GetPredefinedValue(target.DISPID, (uint)cookie, &var); if (hr == HRESULT.S_OK && var.vt != VARENUM.EMPTY) { valueItems[i] = var.ToObject(); if (valueItems[i].GetType() != targetType) { if (targetType.IsEnum) { valueItems[i] = Enum.ToObject(targetType, valueItems[i]); } else { try { valueItems[i] = Convert.ChangeType(valueItems[i], targetType, CultureInfo.InvariantCulture); } catch { // oh well... } } } } if (hr == HRESULT.S_OK) { itemCount++; continue; } if (itemCount > 0) { // shorten the arrays to ignore the failed ones. this isn't terribly // efficient but shouldn't happen very often. It's rare for these to fail. // Array.Copy(nameItems, i, nameItems, i + 1, itemCount); Array.Copy(valueItems, i, valueItems, i + 1, itemCount); } } // pass this data down to the base Com2Enum object... string[] strings = new string[itemCount]; Array.Copy(nameItems, 0, strings, 0, itemCount); base.PopulateArrays(strings, valueItems); } } catch (Exception ex) { base.PopulateArrays(Array.Empty <string>(), Array.Empty <object>()); Debug.Fail("Failed to build IPerPropertyBrowsing editor. " + ex.GetType().Name + ", " + ex.Message); } }
public void OnError(HRESULT hr) { ((delegate * unmanaged <IMFSourceBufferNotify *, HRESULT, void>)(lpVtbl[5]))((IMFSourceBufferNotify *)Unsafe.AsPointer(ref this), hr); }
private unsafe void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent gveevent) { if (sender.TargetObject is Oleaut32.IPerPropertyBrowsing ppb) { bool hasStrings = false; // check for enums var caStrings = new Ole32.CA(); var caCookies = new Ole32.CA(); HRESULT hr = HRESULT.S_OK; try { hr = ppb.GetPredefinedStrings(sender.DISPID, &caStrings, &caCookies); } catch (ExternalException ex) { hr = (HRESULT)ex.ErrorCode; Debug.Fail("An exception occurred inside IPerPropertyBrowsing::GetPredefinedStrings(dispid=" + sender.DISPID + "), object type=" + new ComNativeDescriptor().GetClassName(ppb) + ". This is caused by an exception (usually an AV) inside the object being browsed, and is not a problem in the properties window."); } // Terminate the existing editor if we created the current one // so if the items have disappeared, we don't hold onto the old // items. if (gveevent.TypeConverter is Com2IPerPropertyEnumConverter) { gveevent.TypeConverter = null; } if (hr != HRESULT.S_OK) { hasStrings = false; } else { hasStrings = true; } if (hasStrings) { OleStrCAMarshaler stringMarshaler = new OleStrCAMarshaler(caStrings); Int32CAMarshaler intMarshaler = new Int32CAMarshaler(caCookies); if (stringMarshaler.Count > 0 && intMarshaler.Count > 0) { gveevent.TypeConverter = new Com2IPerPropertyEnumConverter(new Com2IPerPropertyBrowsingEnum(sender, this, stringMarshaler, intMarshaler, true)); } else { //hasStrings = false; } } // if we didn't get any strings, try the proppage edtior // if (!hasStrings) { // this is a _bit_ of a backwards-compat work around... // many older ActiveX controls will show a property page // for all properties since the old grid would only put up the // [...] button for "(Custom)". If we have a conversion editor, // don't allow this to override it... // if (sender.ConvertingNativeType) { return; } Guid g = GetPropertyPageGuid(ppb, sender.DISPID); if (!Guid.Empty.Equals(g)) { gveevent.TypeEditor = new Com2PropertyPageUITypeEditor(sender, g, (UITypeEditor)gveevent.TypeEditor); } } } }
/// <summary> /// 표정에 구버전 형식의 매개변수를 추가합니다. /// </summary> /// <param name="paramID">매개변수의 고유값입니다.</param> /// <param name="value">매개변수의 값입니다.</param> /// <param name="defaultValue">매개변수의 기본값입니다.</param> public void AddParamV09(string paramID, string calc, float value, float defaultValue) { HRESULT.Check(NativeMethods.ExpressionAddParamV09(new IntPtr(Handle), Marshal.StringToHGlobalAnsi(paramID), value, defaultValue)); }
public RpcFailedEventArgs(object userData, HRESULT error) { UserData = userData; Error = error; }
/// <summary> /// 표정의 페이드 아웃 시간을 설정합니다. /// </summary> /// <param name="msec">애니메이션을 진행할 밀리초단위의 시간입니다.</param> public void SetFadeOut(int msec) { HRESULT.Check(NativeMethods.ExpressionSetFadeOut(new IntPtr(Handle), msec)); _FadeOut = msec; }
//******************************************************************************************** // Function: GetConnectionCostandDataPlanStatus // // Description: Enumerates the connections and displays the cost and data plan status for each connection // //******************************************************************************************** static void GetConnectionCostandDataPlanStatus() { HRESULT hr = HRESULT.S_OK; bool bDone = false; int numberOfConnections = 0; try { using var pCostManager = ComReleaserFactory.Create(new INetworkCostManager()); var pNLM = (INetworkListManager)pCostManager.Item; var pNetworkConnections = pNLM.GetNetworkConnections(); while (!bDone) { //Get cost and data plan status info for each of the connections on the machine hr = pNetworkConnections.Next(1, out var ppConnection, out var cFetched); if ((HRESULT.S_OK == hr) && (cFetched > 0)) { try { using var pConnection = ComReleaserFactory.Create(ppConnection); numberOfConnections++; var interfaceGUID = pConnection.Item.GetAdapterId(); Console.Write("--------------------------------------------------------------\n"); GetInterfaceType(interfaceGUID, hr); // get the connection interface var pConnectionCost = (INetworkConnectionCost)pConnection.Item; var cost = pConnectionCost.GetCost(); var dataPlanStatus = pConnectionCost.GetDataPlanStatus(); DisplayCostDescription(cost); DisplayDataPlanStatus(dataPlanStatus); //to give suggestions for data usage, depending on cost and data usage. CostBasedSuggestions(cost, dataPlanStatus); } catch (Exception ex) { hr = ex.HResult; } } else { bDone = true; } if (numberOfConnections == 0) { Console.Write("Machine has no network connection\n"); } } } catch (Exception ex) { hr = ex.HResult; } if (hr != HRESULT.S_FALSE) { DisplayError(hr); } }
public void ClearItemSamplingRate( int[] serverHandles, out HRESULT[] errors) { throw new NotImplementedException(); }
/// <summary> /// Method for Non-DC configuration: Create a group in domain DM /// </summary> /// <param name="groupName">Variable of type string which is used as the name of the group.</param> /// <param name="_serverHandle">Variable of type pointer HANDLE that Lockout the server handle.</param> /// <param name="_domainHandle">Variable of type pointer HANDLE that Lockout the domain handle.</param> /// <param name="_groupHandle">Out parameter of type pointer HANDLE representing the created group handle.</param> /// <param name="relativeId">Out parameter of type uint representing the relativeId of the created group object.</param> /// <param name="groupDesiredAccess">Variable of type uint that specifies the required access for GroupHandle.GrantedAccess.</param> public void CreateGroup_NonDC(string groupName, IntPtr _serverHandle, IntPtr _domainHandle, out IntPtr _groupHandle, out uint relativeId, uint groupDesiredAccess = (uint)Group_ACCESS_MASK.GROUP_ALL_ACCESS) { Site.Log.Add(LogEntryKind.TestStep, "Record the current DACL of domain DM."); _SAMPR_SR_SECURITY_DESCRIPTOR?sd; HRESULT hResult = _samrProtocolAdapter.SamrQuerySecurityObject(_domainHandle, SecurityInformation.DACL_SECURITY_INFORMATION, out sd); Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrQuerySecurityObject must return STATUS_SUCCESS."); Site.Assert.IsNotNull(sd, "The SecurityDescriptor returned by SamrQuerySecurityObject is not null."); CommonSecurityDescriptor ObtainedSecurityDescriptor = new CommonSecurityDescriptor(false, true, sd.Value.SecurityDescriptor, 0); string oldDACL = ObtainedSecurityDescriptor.GetSddlForm(AccessControlSections.Access); Site.Log.Add(LogEntryKind.TestStep, "Old DACL: {0}", oldDACL); try { Site.Log.Add(LogEntryKind.TestStep, "Modify the DACL value of domain DM to get the access to create group in this domain."); CommonSecurityDescriptor commonsd = new CommonSecurityDescriptor(false, true, "D:(A;;0xf07ff;;;WD)(A;;0xf07ff;;;BA)(A;;0xf07ff;;;AO)"); byte[] buffer = new byte[commonsd.BinaryLength]; commonsd.GetBinaryForm(buffer, 0); _SAMPR_SR_SECURITY_DESCRIPTOR securityDescriptor = new _SAMPR_SR_SECURITY_DESCRIPTOR() { SecurityDescriptor = buffer, Length = (uint)buffer.Length }; Site.Log.Add(LogEntryKind.TestStep, "SamrSetSecurityObject, SecurityInformation: OWNER_SECURITY_INFORMATION. "); hResult = _samrProtocolAdapter.SamrSetSecurityObject(_domainHandle, SecurityInformation.DACL_SECURITY_INFORMATION, securityDescriptor); Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrSetSecurityObject must return STATUS_SUCCESS."); hResult = _samrProtocolAdapter.SamrQuerySecurityObject(_domainHandle, SecurityInformation.DACL_SECURITY_INFORMATION, out sd); Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrQuerySecurityObject must return STATUS_SUCCESS."); ObtainedSecurityDescriptor = new CommonSecurityDescriptor(false, true, sd.Value.SecurityDescriptor, 0); Site.Log.Add(LogEntryKind.TestStep, "New DACL: {0}", ObtainedSecurityDescriptor.GetSddlForm(AccessControlSections.Access)); Site.Log.Add(LogEntryKind.TestStep, "Reopen the domain DM"); _RPC_SID domainSid; hResult = _samrProtocolAdapter.SamrLookupDomainInSamServer( _serverHandle, _samrProtocolAdapter.domainMemberFqdn, out domainSid); Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrLookupDomainInSamServer returns:{0}.", hResult); Site.Log.Add(LogEntryKind.TestStep, "SamrOpenDomain: obtain a handle to a domain object, given SID."); hResult = _samrProtocolAdapter.SamrOpenDomain( _serverHandle, Utilities.MAXIMUM_ALLOWED, domainSid, out _domainHandle); Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrOpenDomain returns:{0}.", hResult); Site.Assert.IsNotNull(hResult, "The returned domain handle is:{0}.", _domainHandle); Site.Log.Add(LogEntryKind.TestStep, "SamrCreateGroupInDomain: create a group with Name:{0}, AccountType:{1}, and DesiredAccess:{2}", testGroupName, GROUP_TYPE.GROUP_TYPE_SECURITY_ACCOUNT, groupDesiredAccess); HRESULT result = _samrProtocolAdapter.SamrCreateGroupInDomain( _domainHandle, groupName, (uint)groupDesiredAccess, out _groupHandle, out relativeId); Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, result, "SamrCreateGroupInDomain succeeded."); Site.Assert.AreNotEqual(IntPtr.Zero, _groupHandle, "The returned group handle is: {0}.", _groupHandle); Site.Assert.IsTrue(relativeId >= 1000, "The Rid value MUST be greater than or equal to 1000"); } finally { Site.Log.Add(LogEntryKind.TestStep, "Change back the DACL of domain DM."); CommonSecurityDescriptor commonsd = new CommonSecurityDescriptor(false, true, oldDACL); byte[] buffer = new byte[commonsd.BinaryLength]; commonsd.GetBinaryForm(buffer, 0); _SAMPR_SR_SECURITY_DESCRIPTOR securityDescriptor = new _SAMPR_SR_SECURITY_DESCRIPTOR() { SecurityDescriptor = buffer, Length = (uint)buffer.Length }; Site.Log.Add(LogEntryKind.TestStep, "SamrSetSecurityObject, SecurityInformation: OWNER_SECURITY_INFORMATION. "); hResult = _samrProtocolAdapter.SamrSetSecurityObject(_domainHandle, SecurityInformation.DACL_SECURITY_INFORMATION, securityDescriptor); Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrSetSecurityObject must return STATUS_SUCCESS."); hResult = _samrProtocolAdapter.SamrQuerySecurityObject(_domainHandle, SecurityInformation.DACL_SECURITY_INFORMATION, out sd); Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrQuerySecurityObject must return STATUS_SUCCESS."); ObtainedSecurityDescriptor = new CommonSecurityDescriptor(false, true, sd.Value.SecurityDescriptor, 0); Site.Assert.AreEqual(oldDACL, ObtainedSecurityDescriptor.GetSddlForm(AccessControlSections.Access), "The DACL of domain DM should be changed back"); } }
public static bool Failed(HRESULT hr) { return ((int)hr < 0); }
/// /// Create the unmanaged resources /// internal override void FinalizeCreation() { _bitmapInit.EnsureInitializedComplete(); BitmapSourceSafeMILHandle wicFormatter = null; using (FactoryMaker factoryMaker = new FactoryMaker()) { try { IntPtr wicFactory = factoryMaker.ImagingFactoryPtr; HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateFormatConverter( wicFactory, out wicFormatter)); SafeMILHandle internalPalette; if (DestinationPalette != null) { internalPalette = DestinationPalette.InternalPalette; } else { internalPalette = new SafeMILHandle(); } Guid format = DestinationFormat.Guid; lock (_syncObject) { HRESULT.Check(UnsafeNativeMethods.WICFormatConverter.Initialize( wicFormatter, Source.WicSourceHandle, ref format, DitherType.DitherTypeErrorDiffusion, internalPalette, AlphaThreshold, WICPaletteType.WICPaletteTypeOptimal )); } // // This is just a link in a BitmapSource chain. The memory is being used by // the BitmapSource at the end of the chain, so no memory pressure needs // to be added here. // WicSourceHandle = wicFormatter; // Even if our source is cached, format conversion is expensive and so we'll // always maintain our own cache for the purpose of rendering. _isSourceCached = false; } catch { _bitmapInit.Reset(); throw; } finally { if (wicFormatter != null) { wicFormatter.Close(); } } } CreationCompleted = true; UpdateCachedSettings(); }
/// <summary> /// Initializes a new instance of the <see cref="OpcDaItemResult"/> class. /// </summary> /// <param name="item">The item.</param> /// <param name="error">The HRESULT of the operation.</param> public OpcDaItemResult(OpcDaItem item, HRESULT error) { Item = item; Error = error; }
internal static bool Failed(HRESULT hresult) { return((int)hresult < 0); }
// Извлечение child'a public TMetaBase getChild(int _iIndex, ref HRESULT _iRes) { if ((_iIndex < 0) || (_iIndex > fpChilds.Count)) return null; return fpChilds.ElementAt(_iIndex); }
public int Connect(IPin pReceivePin, AMMediaType pmt) { unchecked { if (_ConnectedPin != null) { return((int)HRESULT.VFW_E_ALREADY_CONNECTED); } PinDirection pd; pReceivePin.QueryDirection(out pd); if (pd == _Direction) { return((int)HRESULT.VFW_E_INVALID_DIRECTION); } PinInfo pi; pReceivePin.QueryPinInfo(out pi); FilterInfo fi; pi.filter.QueryFilterInfo(out fi); Debug.WriteLine(fi.achName + "." + pi.name, _Name + " connect attempt from"); if (pi.name == "Subpicture Input") { } HRESULT hr = HRESULT.VFW_E_NO_ACCEPTABLE_TYPES; // // Try match our media types with the specific one requested // if any... // if (null != (pmt)) { for (int i = 0; i < MediaTypes.Count; i++) { if (MatchesPartial(MediaTypes[i], pmt)) { hr = OnReceiveConnection(pReceivePin, MediaTypes[i]); if (hr != HRESULT.S_OK) { // pReceivePin.Disconnect(); } else { break; } } } } // // Otherwise try force-connect all of the ones we like. // if (hr != HRESULT.S_OK) { for (int i = 0; i < MediaTypes.Count; i++) { AMMediaType newMT = new AMMediaType(); Copy(MediaTypes[i], newMT); hr = (HRESULT)pReceivePin.QueryAccept(newMT); if (hr == HRESULT.S_OK) { hr = OnReceiveConnection(pReceivePin, newMT); if (hr != HRESULT.S_OK) { //pReceivePin.Disconnect(); } else { break; } } } } // // Failing that, try connect with any of their numerous // supported types.. // if (hr != HRESULT.S_OK) { IEnumMediaTypes en; pReceivePin.EnumMediaTypes(out en); en.Reset(); /* * Unsafe pointer edition * ====================== * I was experminting AMMediaType as a value struct type * for better marshalling. * * AMMediaType* types = null; * int fetched = 0; * do * { * HRESULT r = en.Next(1, (AMMediaType**)&types, out fetched); * if (r != HRESULT.S_OK || fetched == 0) || break; || AMMediaType tmp = *types; || for (int x = 0; x < MediaTypes.Count; x++) || { || if ((MediaTypes[x].majorType == tmp.majorType || && MediaTypes[x].subType == tmp.subType) || AcceptsAnyMedia) || { || hr = OnReceiveConnection(pReceivePin, tmp); //MediaTypes[x] || || if (hr != HRESULT.S_OK) || { || pReceivePin.Disconnect(); || } || else || break; || } || } || AMMediaType.Free(tmp); ||} while (fetched > 0);*/ AMMediaType[] types = new AMMediaType[100]; IntPtr ptr = ToPtr(types); IntPtr fetched = IntPtr.Zero; en.Next(10, types, fetched); types = FromIntPtr(ptr, fetched.ToInt32()); if (fetched.ToInt32() > 0 && types != null) { for (int x = 0; x < MediaTypes.Count; x++) { for (int i = 0; i < fetched.ToInt32(); i++) { if ((MediaTypes[x].majorType == types[i].majorType && MediaTypes[x].subType == types[i].subType) || AcceptsAnyMedia) { hr = OnReceiveConnection(pReceivePin, types[i]); if (hr != HRESULT.S_OK) { //pReceivePin.Disconnect(); } else { break; } } } if (hr == HRESULT.S_OK) { break; } } } for (int i = 0; i < fetched.ToInt32(); i++) { Free(types[i]); } if (Marshal.IsComObject(en)) { Marshal.ReleaseComObject(en); } } if (hr != HRESULT.S_OK) { // Final clean up this.Disconnect(); if (Marshal.IsComObject(pReceivePin)) { Marshal.ReleaseComObject(pReceivePin); } // Connect failed, but may have returned S_FALSE // so this ensures a better return code. hr = HRESULT.VFW_E_NO_ACCEPTABLE_TYPES; } if (hr == HRESULT.S_OK) { ResolveConnectedFilter(); } return((int)hr); } }
public static bool Failed(HRESULT hResult) { return ((int)hResult < 0); }
internal static MilRectD GetPathBoundsAsRB( PathGeometryData pathData, Pen pen, Matrix worldMatrix, double tolerance, ToleranceType type, bool skipHollows) { // This method can't handle the empty geometry case, as it's impossible for us to // return Rect.Empty. Callers should do their own check. Debug.Assert(!pathData.IsEmpty()); unsafe { MIL_PEN_DATA penData; double[] dashArray = null; // If we have a pen, populate the CMD struct if (pen != null) { pen.GetBasicPenData(&penData, out dashArray); } MilMatrix3x2D worldMatrix3X2 = CompositionResourceManager.MatrixToMilMatrix3x2D(ref worldMatrix); fixed(byte *pbPathData = pathData.SerializedData) { MilRectD bounds; Debug.Assert(pbPathData != (byte *)0); fixed(double *pDashArray = dashArray) { int hr = UnsafeNativeMethods.MilCoreApi.MilUtility_PathGeometryBounds( (pen == null) ? null : &penData, pDashArray, &worldMatrix3X2, pathData.FillRule, pbPathData, pathData.Size, &pathData.Matrix, tolerance, type == ToleranceType.Relative, skipHollows, &bounds ); if (hr == (int)MILErrors.WGXERR_BADNUMBER) { // When we encounter NaNs in the renderer, we absorb the error and draw // nothing. To be consistent, we report that the geometry has empty bounds // (NaN will get transformed into Rect.Empty higher up). bounds = MilRectD.NaN; } else { HRESULT.Check(hr); } } return(bounds); } } }