Example #1
0
 public static void ClearProp(PROPVARIANT p)
 {
     if (p.pwszVal != IntPtr.Zero)
     {
         Marshal.FreeCoTaskMem(p.pwszVal);
     }
 }
Example #2
0
 /// <summary>
 /// Gets the specified property value.
 /// </summary>
 /// <param name="pKey">The key identifying requested property.</param>
 public void GetValue(ref PropertyKey pKey, out PROPVARIANT pValue)
 {
     pValue = new PROPVARIANT();
     if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_ADDRESS1))
     {
         pValue.SetValue(_address1);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_ADDRESS2))
     {
         pValue.SetValue(_address2);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_CITY))
     {
         pValue.SetValue(_city);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_STATE_PROVINCE))
     {
         pValue.SetValue(_StateProvince);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_POSTALCODE))
     {
         pValue.SetValue(_PostalCode);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_TIMESTAMP))
     {
         pValue.SetFileTime(_timestamp);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_COUNTRY_REGION))
     {
         pValue.SetValue(_CountryRegion);
     }
 }
Example #3
0
        public void PROPVARIANTOtherPropsTest(VARTYPE vt, string prop)
        {
            object value;

            Assert.That(() =>
            {
                if ((value = GetSampleData(vt)) == null)
                {
                    return;
                }
                using (var pv = new PROPVARIANT(value, (VarEnum)vt))
                {
                    var isa = value.GetType().IsArray;
                    Assert.That(pv.vt, Is.EqualTo(vt));
                    if (isa)
                    {
                        Assert.That(pv.Value, Is.EquivalentTo((IEnumerable)value));
                    }
                    else
                    {
                        Assert.That(pv.Value, Is.EqualTo(value));
                    }
                    var pi = pv.GetType().GetProperty(prop);
                    Assert.That(pi, Is.Not.Null);
                    if (isa)
                    {
                        Assert.That(pi.GetValue(pv), Is.EquivalentTo((IEnumerable)value));
                    }
                    else
                    {
                        Assert.That(pi.GetValue(pv), Is.EqualTo(value));
                    }
                }
            }, Throws.Nothing);
        }
Example #4
0
        /// <summary>
        /// Generate a unique string for the ShellLink that can be used for equality checks.
        /// </summary>
        private static string ShellLinkToString(IShellLinkW shellLink)
        {
            var pathBuilder = new StringBuilder(Win32Constant.MAX_PATH);

            shellLink.GetPath(pathBuilder, pathBuilder.Capacity, null, SLGP.RAWPATH);

            string title = null;

            // Need to use the property store to get the title for the link.
            using (PROPVARIANT pv = new PROPVARIANT())
            {
                var  propStore = (IPropertyStore)shellLink;
                PKEY pkeyTitle = PKEY.Title;

                propStore.GetValue(ref pkeyTitle, pv);

                // PKEY_Title should be an LPWSTR if it's not empty.
                title = pv.GetValue() ?? "";
            }

            var argsBuilder = new StringBuilder(Win32Constant.INFOTIPSIZE);

            shellLink.GetArguments(argsBuilder, argsBuilder.Capacity);

            // Path and title should be case insensitive.
            // Shell treats arguments as case sensitive because apps can handle those differently.
            return(pathBuilder.ToString().ToUpperInvariant() + title.ToUpperInvariant() + argsBuilder.ToString());
        }
Example #5
0
        public void Initialize()
        {
            string shortcut = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "Intelligent Naval Gun.lnk");

            if (!File.Exists(shortcut))
            {
                // Find the path to the current executable
                string exePath     = Process.GetCurrentProcess().MainModule.FileName;
                var    newShortcut = (IShellLinkW) new CShellLink();

                // Create a shortcut to the exe
                newShortcut.SetPath(exePath);
                newShortcut.SetArguments("");

                // Open the shortcut property store, set the AppUserModelId property
                var newShortcutProperties = (IPropertyStore)newShortcut;

                using (var appId = new PROPVARIANT(aumid))
                {
                    var AUMID_KEY = new PROPERTYKEY(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 5);

                    newShortcutProperties.SetValue(AUMID_KEY, appId);
                    newShortcutProperties.Commit();
                }

                // Commit the shortcut to disk
                var newShortcutSave = (IPersistFile)newShortcut;

                newShortcutSave.Save(shortcut, true);
            }

            ToastNotificationManager.History.Clear(aumid);
        }
Example #6
0
        /// <summary>
        /// Returns the property IDs and values for all data contained in this data report.
        /// </summary>
        /// <returns>A dictionary mapping property IDs to values.</returns>
        public IDictionary <PropertyKey, object> GetDataFields()
        {
            Dictionary <PropertyKey, object> reportData = new Dictionary <PropertyKey, object>();
            IPortableDeviceValues            valuesCollection;

            _iSensorReport.GetSensorValues(null, out valuesCollection);

            uint nItems = 0;

            valuesCollection.GetCount(ref nItems);
            for (uint i = 0; i < nItems; i++)
            {
                PropertyKey propKey   = new PropertyKey();
                PROPVARIANT propValue = new PROPVARIANT();
                valuesCollection.GetAt(i, ref propKey, out propValue);

                try
                {
                    reportData.Add(propKey, propValue.Value);
                }
                finally
                {
                    propValue.Clear();
                }
            }

            return(reportData);
        }
Example #7
0
        /// <summary>
        /// Retrives the values of multiple properties.
        /// </summary>
        /// <param name="propKeys">Properties to retrieve.</param>
        /// <returns>A dictionary containing the property keys and values.</returns>
        public IDictionary <PropertyKey, object> GetAllProperties()
        {
            IPortableDeviceValues valuesCollection;

            _iSensor.GetProperties(null, out valuesCollection);

            Dictionary <PropertyKey, object> data = new Dictionary <PropertyKey, object>();

            if (valuesCollection == null)
            {
                return(data);
            }

            uint count = 0;

            valuesCollection.GetCount(ref count);

            for (uint i = 0; i < count; i++)
            {
                PropertyKey propKey = new PropertyKey();
                PROPVARIANT propVal = new PROPVARIANT();
                valuesCollection.GetAt(i, ref propKey, out propVal);

                try
                {
                    data.Add(propKey, propVal.Value);
                }
                finally
                {
                    propVal.Clear();
                }
            }

            return(data);
        }
Example #8
0
 public void GetCF()
 {
     foreach (var f in Directory.EnumerateFiles(@"C:\Temp", "*.*", SearchOption.AllDirectories))
     {
         try
         {
             SHGetPropertyStoreFromParsingName(f, null, GETPROPERTYSTOREFLAGS.GPS_READWRITE,
                                               Marshal.GenerateGuidForType(typeof(IPropertyStore)), out IPropertyStore ps);
             if (ps == null)
             {
                 continue;
             }
             using (var pv = new PROPVARIANT())
             {
                 ps.GetValue(ref PROPERTYKEY.System.Thumbnail, pv);
                 if (pv.IsNullOrEmpty)
                 {
                     continue;
                 }
                 if (pv.vt == VARTYPE.VT_CF)
                 {
                     TestContext.WriteLine(f);
                 }
             }
             ps = null;
         }
         catch
         {
         }
     }
 }
Example #9
0
 /// <summary>
 /// Gets the specified property value.
 /// </summary>
 /// <param name="pKey">The key of the requested property.</param>
 public void GetValue(ref PropertyKey pKey, out PROPVARIANT pValue)
 {
     pValue = new PROPVARIANT();
     if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_LATITUDE_DEGREES))
     {
         pValue.SetValue(_latitude);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_LONGITUDE_DEGREES))
     {
         pValue.SetValue(_longitude);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_ERROR_RADIUS_METERS))
     {
         pValue.SetValue(_errorRadius);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_ALTITUDE_ELLIPSOID_METERS))
     {
         pValue.SetValue(_altitude);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_ALTITUDE_ELLIPSOID_ERROR_METERS))
     {
         pValue.SetValue(_altitudeError);
     }
     else if (pKey.Equals(SensorPropertyKeys.SENSOR_DATA_TYPE_TIMESTAMP))
     {
         pValue.SetFileTime(_timeStamp);
     }
 }
Example #10
0
        private void GetBackgroundColor(IWICMetadataQueryReader wicMetadataQueryReader)
        {
            // 如果图片里面包含了 global palette 就需要获取 palette 和背景色
            var propertyVariant = new PROPVARIANT();

            wicMetadataQueryReader.GetMetadataByName("/logscrdesc/GlobalColorTableFlag", ref propertyVariant);

            byte backgroundIndex = 0;

            var globalPalette = (propertyVariant.Type & VARTYPE.VT_BOOL) == VARTYPE.VT_BOOL &&
                                propertyVariant.Value.UI1 > 0;

            if (globalPalette)
            {
                propertyVariant = new PROPVARIANT();
                wicMetadataQueryReader.GetMetadataByName("/logscrdesc/BackgroundColorIndex", ref propertyVariant);

                if ((propertyVariant.Type & VARTYPE.VT_UI1) == VARTYPE.VT_UI1)
                {
                    backgroundIndex = propertyVariant.Value.UI1;
                }

                var wicPalette = WicImagingFactory.CreatePalette();
                WicBitmapDecoder.CopyPalette(wicPalette);
            }
        }
Example #11
0
        public void PROPVARIANTTest1()
        {
            var arr = new[] { "A", "B", "C" };

            using (var pv = new PROPVARIANT(arr))
                using (var pv2 = new PROPVARIANT(pv))
                    Assert.That(pv2.Value, Is.EquivalentTo(arr).And.EquivalentTo(pv.Value as IEnumerable));
        }
Example #12
0
        private static JumpItem GetJumpItemForShellObject(object shellObject)
        {
            var shellItem = shellObject as IShellItem2;
            var shellLink = shellObject as IShellLinkW;

            if (shellItem != null)
            {
                JumpPath path = new JumpPath
                {
                    Path = shellItem.GetDisplayName(SIGDN.DESKTOPABSOLUTEPARSING),
                };
                return(path);
            }

            if (shellLink != null)
            {
                var pathBuilder = new StringBuilder(Win32Constant.MAX_PATH);
                shellLink.GetPath(pathBuilder, pathBuilder.Capacity, null, SLGP.RAWPATH);
                var argsBuilder = new StringBuilder(Win32Constant.INFOTIPSIZE);
                shellLink.GetArguments(argsBuilder, argsBuilder.Capacity);
                var descBuilder = new StringBuilder(Win32Constant.INFOTIPSIZE);
                shellLink.GetDescription(descBuilder, descBuilder.Capacity);
                var iconBuilder = new StringBuilder(Win32Constant.MAX_PATH);
                int iconIndex;
                shellLink.GetIconLocation(iconBuilder, iconBuilder.Capacity, out iconIndex);
                var dirBuilder = new StringBuilder(Win32Constant.MAX_PATH);
                shellLink.GetWorkingDirectory(dirBuilder, dirBuilder.Capacity);

                JumpTask task = new JumpTask
                {
                    // Set ApplicationPath and IconResources, even if they're from the current application.
                    // This means that equivalent JumpTasks won't necessarily compare property-for-property.
                    ApplicationPath   = pathBuilder.ToString(),
                    Arguments         = argsBuilder.ToString(),
                    Description       = descBuilder.ToString(),
                    IconResourceIndex = iconIndex,
                    IconResourcePath  = iconBuilder.ToString(),
                    WorkingDirectory  = dirBuilder.ToString(),
                };

                using (PROPVARIANT pv = new PROPVARIANT())
                {
                    var  propStore = (IPropertyStore)shellLink;
                    PKEY pkeyTitle = PKEY.Title;

                    propStore.GetValue(ref pkeyTitle, pv);

                    // PKEY_Title should be an LPWSTR if it's not empty.
                    task.Title = pv.GetValue() ?? "";
                }

                return(task);
            }

            // Unsupported type?
            Debug.Assert(false);
            return(null);
        }
Example #13
0
        public void InitPropVariantFromFileTimeVectorTest()
        {
            var pv = new PROPVARIANT();

            InitPropVariantFromFileTimeVector(new[] { DateTime.Now.ToFileTimeStruct(), DateTime.Today.ToFileTimeStruct() }, 2, pv);
            Assert.That(pv.VarType, Is.EqualTo(VarEnum.VT_VECTOR | VarEnum.VT_FILETIME));
            Assert.That(pv.Value as IEnumerable <FILETIME>, Is.Not.Null.And.Exactly(2).Items);
            pv.Dispose();
        }
Example #14
0
        public void InitPropVariantFromInt32VectorTest()
        {
            var pv = new PROPVARIANT();

            InitPropVariantFromInt32Vector(new int[] { 1, 2, 3, 4 }, 4, pv);
            Assert.That(pv.VarType, Is.EqualTo(VarEnum.VT_VECTOR | VarEnum.VT_I4));
            Assert.That(pv.Value as IEnumerable <int>, Is.Not.Null.And.Exactly(4).Items);
            pv.Dispose();
        }
Example #15
0
        public void InitPropVariantFromDoubleVectorTest()
        {
            var pv = new PROPVARIANT();

            InitPropVariantFromDoubleVector(new[] { 1f, 2.0, 255.3, 0.1 }, 4, pv);
            Assert.That(pv.VarType, Is.EqualTo(VarEnum.VT_VECTOR | VarEnum.VT_R8));
            Assert.That(pv.Value as IEnumerable <double>, Is.Not.Null.And.Exactly(4).Items.And.Contains(0.1));
            pv.Dispose();
        }
Example #16
0
        public void InitPropVariantFromBooleanVectorTest()
        {
            var pv = new PROPVARIANT();

            InitPropVariantFromBooleanVector(new[] { true, false, true, true }, 4, pv);
            Assert.That(pv.VarType, Is.EqualTo(VarEnum.VT_VECTOR | VarEnum.VT_BOOL));
            Assert.That(pv.Value as IEnumerable <bool>, Is.Not.Null.And.Exactly(4).Items);
            pv.Dispose();
        }
Example #17
0
        public void InitPropVariantFromStringVectorTest()
        {
            var pv = new PROPVARIANT();

            InitPropVariantFromStringVector(new [] { "1", "2", "3", "4" }, 4, pv);
            Assert.That(pv.VarType, Is.EqualTo(VarEnum.VT_VECTOR | VarEnum.VT_LPWSTR));
            Assert.That(pv.Value as IEnumerable <string>, Is.Not.Null.And.Exactly(4).Items);
            pv.Dispose();
        }
Example #18
0
        public void InitPropVariantFromBufferTest()
        {
            var pv = new PROPVARIANT();

            InitPropVariantFromBuffer(new byte[] { 1, 2, 3, 4 }, 4, pv);
            Assert.That(pv.VarType, Is.EqualTo(VarEnum.VT_VECTOR | VarEnum.VT_UI1));
            Assert.That(pv.Value as IEnumerable <byte>, Is.Not.Null.And.Exactly(4).Items);
            pv.Dispose();
        }
Example #19
0
        public void PropVariantToBufferTest()
        {
            var pv  = new PROPVARIANT(new byte[] { 2, 2, 2, 2 });
            var oba = new byte[4];
            var hr  = PropVariantToBuffer(pv, oba, (uint)oba.Length);

            Assert.That(hr.Succeeded);
            Assert.That(oba, Has.Exactly(4).Items.And.All.EqualTo(2));
        }
Example #20
0
        public void PropVariantClearTest()
        {
            var pv = new PROPVARIANT();

            InitPropVariantFromStringVector(new[] { "A", "B", "C", "D" }, 4, pv);
            Assert.That(pv.vt != VARTYPE.VT_EMPTY);
            Assert.That(PropVariantClear(pv).Succeeded);
            Assert.That(pv.vt == VARTYPE.VT_EMPTY && pv.uhVal == 0);
        }
Example #21
0
        /// <summary>
        /// Retrives the values of multiple properties by their indices.
        /// Assues that the GUID component of property keys is the sensor's type GUID.
        /// </summary>
        /// <param name="propIndices">Indices of properties to retrieve.</param>
        /// <returns>An array containing the property values.</returns>
        /// <remarks>
        /// If the values of some properties could not be retrieved, then the returned array will contain null values in the corresponding positions.
        /// </remarks>
        public object[] GetProperties(params int[] propIndices)
        {
            if (propIndices == null || propIndices.Length == 0)
            {
                throw new ArgumentNullException("propIndices", "Property keys array must not be null or empty.");
            }

            IPortableDeviceKeyCollection keyCollection = new PortableDeviceKeyCollection();

            try
            {
                IPortableDeviceValues         valuesCollection;
                Dictionary <PropertyKey, int> propKeyToIdx = new Dictionary <PropertyKey, int>();

                for (int i = 0; i < propIndices.Length; i++)
                {
                    PropertyKey propKey = PropertyKey.Create(this.TypeID, propIndices[i]);
                    keyCollection.Add(ref propKey);
                    propKeyToIdx.Add(propKey, i);
                }

                object[] data = new object[propIndices.Length];
                _iSensor.GetProperties(keyCollection, out valuesCollection);

                if (valuesCollection == null)
                {
                    return(data);
                }

                uint count = 0;
                valuesCollection.GetCount(ref count);

                for (uint i = 0; i < count; i++)
                {
                    PropertyKey propKey = new PropertyKey();
                    PROPVARIANT propVal = new PROPVARIANT();
                    valuesCollection.GetAt(i, ref propKey, out propVal);

                    try
                    {
                        int idx = propKeyToIdx[propKey];
                        data[idx] = propVal.Value;
                    }
                    finally
                    {
                        propVal.Clear();
                    }
                }

                return(data);
            }
            finally
            {
                Marshal.ReleaseComObject(keyCollection);
            }
        }
Example #22
0
        public void InitPropVariantFromFileTimeTest()
        {
            var pv = new PROPVARIANT();
            var ft = DateTime.Now.ToFileTimeStruct();

            InitPropVariantFromFileTime(ref ft, pv);
            Assert.That(pv.VarType, Is.EqualTo(VarEnum.VT_FILETIME));
            Assert.That(pv.Value, Is.EqualTo(ft));
            pv.Dispose();
        }
Example #23
0
 public void FromNativeVariantTest()
 {
     using (var pVar = new SafeHGlobalHandle(100))
     {
         Marshal.GetNativeVariantForObject(0xFFFFFFFF, (IntPtr)pVar);
         var pv = PROPVARIANT.FromNativeVariant((IntPtr)pVar);
         Assert.That(pv.vt, Is.EqualTo(VARTYPE.VT_UI4));
         VariantClear((IntPtr)pVar);
     }
 }
Example #24
0
        public void EqualsTest()
        {
            var pv1 = new PROPVARIANT(1);
            var pv2 = new PROPVARIANT(1);
            var pv3 = new PROPVARIANT(5f);

            Assert.That(pv1.Equals(pv2), Is.True);
            Assert.That(pv1.Equals(pv3), Is.False);
            Assert.That(pv3.Equals(pv1), Is.False);
        }
Example #25
0
        // The Tasks category of Jump Lists supports separator items. These are simply IShellLinkW instances that have the
        // PKEY_AppUserModel_IsDestListSeparator property set to TRUE. All other values are ignored when this property is set.
        private static IShellLinkW _CreateSeparatorLink()
        {
            var psl     = new IShellLinkW();
            var pps     = (IPropertyStore)psl;
            var propvar = new PROPVARIANT(true);

            pps.SetValue(PROPERTYKEY.System.AppUserModel.IsDestListSeparator, propvar);
            pps.Commit();
            return(psl);
        }
Example #26
0
        public void CompareToTest()
        {
            var pv1 = new PROPVARIANT(1);
            var pv2 = new PROPVARIANT(1);
            var pv3 = new PROPVARIANT(5f);

            Assert.That(pv1.CompareTo(pv2), Is.EqualTo(0));
            Assert.That(pv1.CompareTo(pv3), Is.LessThan(0));
            Assert.That(pv3.CompareTo(pv1), Is.GreaterThan(0));
        }
Example #27
0
        /// <summary>
        /// Sets the application user model id for the window.
        /// </summary>
        /// <param name="hwnd">The window.</param>
        /// <param name="appId">The application id to set.</param>
        public static void SetWindowAppId(IntPtr hwnd, string appId)
        {
            var iPropertyStoreGuid = new Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99");

            SHGetPropertyStoreForWindow(hwnd, ref iPropertyStoreGuid, out IPropertyStore propertyStore);
            var appid = new PROPVARIANT(appId);

            propertyStore.SetValue(ref PropertyKey.SystemAppUserModelIDPropertyKey, appid);
            PROPVARIANT.ClearProp(appid);
        }
Example #28
0
        public void PropVariantToBooleanVectorAllocTest()
        {
            var pv = new PROPVARIANT(new[] { true, false, true, false });
            var hr = PropVariantToBooleanVectorAlloc(pv, out SafeCoTaskMemHandle h, out uint cnt);

            Assert.That(hr.Succeeded);
            bool[] ba = null;
            Assert.That(() => ba = h.ToEnumerable <uint>((int)cnt).Select(i => i != 0).ToArray(), Throws.Nothing);
            Assert.That(ba, Is.Not.Null.And.Exactly(4).Items);
        }
Example #29
0
        public void InitPropVariantFromCLSIDTest()
        {
            var pv = new PROPVARIANT();
            var g  = Guid.NewGuid();

            InitPropVariantFromCLSID(g, pv);
            Assert.That(pv.VarType, Is.EqualTo(VarEnum.VT_CLSID));
            Assert.That(pv.Value, Is.EqualTo(g));
            pv.Dispose();
        }
Example #30
0
        private void InitializeAudioDevice()
        {
            // Get default audio device
            MMDeviceEnumerator  deviceEnumeratorClass = new MMDeviceEnumerator();
            IMMDeviceEnumerator deviceEnumerator      = (IMMDeviceEnumerator)deviceEnumeratorClass;

            IMMDevice defaultDevice;

            deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out defaultDevice);

            // Log device name
            IPropertyStore store;

            defaultDevice.OpenPropertyStore(STGM.STGM_READ, out store);

            PROPVARIANT pv   = new PROPVARIANT();
            PropertyKey pkey = PKEY.PKEY_DeviceInterface_FriendlyName;

            store.GetValue(ref pkey, out pv);

            Debug.WriteLine("Using audio device '{0}'", pv.Value);

            // Retrieve IAudioClient
            Guid   iid     = new Guid(Constants.IID_IAudioClient);
            IntPtr propVar = IntPtr.Zero;
            object obj;

            defaultDevice.Activate(ref iid, CLSCTX.CLSCTX_ALL, ref propVar, out obj);

            this.audioClient = (IAudioClient)obj;

            // Get default format
            IntPtr defaultFormat;

            this.audioClient.GetMixFormat(out defaultFormat);
            this.UpdateWaveFormatInfo(defaultFormat);

            // Initialize IAudioClient
            Guid g = Guid.Empty;

            this.audioClient.Initialize(AUDCLNT_SHAREMODE.AUDCLNT_SHAREMODE_SHARED, (uint)AUDCLNT_STREAMFLAGS.AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, defaultFormat, ref g);
            this.audioClient.GetBufferSize(out this.wasapiBufferSize);
            this.audioClient.SetEventHandle(this.bufferReadyEvent.SafeWaitHandle.DangerousGetHandle());

            // Retrieve IAudioRenderClient
            iid = new Guid(Constants.IID_IAudioRenderClient);
            object ppv;

            this.audioClient.GetService(ref iid, out ppv);

            this.audioRenderClient = (IAudioRenderClient)ppv;

            // Start processing samples
            this.audioClient.Start();
        }
        private static AudioDevice CreateDevice(IMMDevice dev)
        {
            if (dev == null)
                return null;

            string id;
            dev.GetId(out id);
            DEVICE_STATE state;
            dev.GetState(out state);
            Dictionary<string, object> properties = new Dictionary<string, object>();
            IPropertyStore store;
            dev.OpenPropertyStore(STGM.STGM_READ, out store);
            if (store != null)
            {
                int propCount;
                store.GetCount(out propCount);
                for (int j = 0; j < propCount; j++)
                {
                    PROPERTYKEY pk;
                    if (store.GetAt(j, out pk) == 0)
                    {
                        PROPVARIANT value = new PROPVARIANT();
                        int hr = store.GetValue(ref pk, ref value);
                        object v = value.GetValue();
                        try
                        {
                            if (value.vt != VARTYPE.VT_BLOB) // for some reason, this fails?
                            {
                                PropVariantClear(ref value);
                            }
                        }
                        catch
                        {
                        }
                        string name = pk.ToString();
                        properties[name] = v;
                    }
                }
            }
            return new AudioDevice(id, (AudioDeviceState)state, properties);
        }
 private static extern int PropVariantClear(ref PROPVARIANT pvar);
Example #33
0
 public static extern int PropVariantClear(PROPVARIANT pvar);
        GetOleProperty(
            Guid fmtid,
            uint propId
            )
        {
            CheckDisposed();

            // fmtid is always either DocSum or Sum.
            IPropertyStorage ps =
                fmtid == FormatId.SummaryInformation ? _psSummInfo : _psDocSummInfo;
            if (ps == null)
            {
                // This file doesn't even contain the property storage that this
                // property belongs to, so it certainly doesn't contain the property.
                return null;
            }

            object obj = null;

            PROPSPEC[] propSpecs = new PROPSPEC[1];
            PROPVARIANT[] vals = new PROPVARIANT[1];

            propSpecs[0].propType = (uint)PropSpecType.Id;
            propSpecs[0].union.propId = propId;

            VARTYPE vtExpected = GetVtFromPropId(fmtid, propId);

            int hresult = ps.ReadMultiple(1, propSpecs, vals);

            if (hresult == SafeNativeCompoundFileConstants.S_OK)
            {
                try
                {
                    if (vals[0].vt != vtExpected)
                    {
                        throw new FileFormatException(
                                        SR.Get(
                                            SRID.WrongDocumentPropertyVariantType,
                                            propId,
                                            fmtid.ToString(),
                                            vals[0].vt,
                                            vtExpected
                                            )
                                        );
                    }

                    switch (vals[0].vt)
                    {
                        case VARTYPE.VT_LPSTR:
                            //
                            // We store string properties as CP_ACP or UTF-8. 
                            // But no matter which format the string was encoded, we always use the UTF-8
                            // encoder/decoder to decode the byte array, because the UTF-8 code of an ASCII
                            // string is the same as the ASCII string.
                            //
                            IntPtr pszVal = vals[0].union.pszVal;
                            //
                            // Because both the ASCII string and UTF-8 encoded string (byte array) are
                            // stored in a memory block (pszVal) terminated by null, we can use 
                            // Marshal.PtrToStringAnsi(pszVal) to convert the memory block pointed by
                            // pszVal to a string. Then from the string.Length, we can get the number of
                            // bytes in the memory block. Otherwise, we cannot easily tell how many bytes
                            // are stored in pszVal without an extra parameter.
                            //
                            string ansiString = Marshal.PtrToStringAnsi(pszVal);
                            int nLen = ansiString.Length;

                            byte[] byteArray = new byte[nLen];
                            Marshal.Copy(pszVal, byteArray, 0, nLen);

                            obj = UTF8Encoding.UTF8.GetString(byteArray);
                            break;

                        case VARTYPE.VT_FILETIME:
                            //
                            // DateTime doesn't have a conversion from FILETIME. It has a
                            // misleadingly named "FromFileTime" method that actually wants
                            // a long. So...
                            //
                            obj = new Nullable<DateTime>(DateTime.FromFileTime(vals[0].union.hVal));
                            break;

                        default:
                            throw new FileFormatException(
                                        SR.Get(SRID.InvalidDocumentPropertyVariantType, vals[0].vt));
                    }
                }
                finally
                {
#pragma warning suppress 6031 // suppressing a "by design" ignored return value
                    SafeNativeCompoundFileMethods.SafePropVariantClear(ref vals[0]);
                }
            }
            else if (hresult == SafeNativeCompoundFileConstants.S_FALSE)
            {
                // Do nothing -- return the null object reference.
            }
            else
            {
                SecurityHelper.ThrowExceptionForHR(hresult);
            }

            return obj;
        }
        SetOleProperty(
            Guid fmtid,
            uint propId,
            object propVal
            )
        {
            CheckDisposed();

            IPropertyStorage ps =
                fmtid == FormatId.SummaryInformation ? _psSummInfo : _psDocSummInfo;

            if (ps == null)
            {
                //
                // The property set does not exist, so create it.
                //
                if (propVal != null)
                {
                    _pss.Create(
                            ref fmtid,
                            ref fmtid,
                            SafeNativeCompoundFileConstants.PROPSETFLAG_ANSI,
                            (uint)_grfMode,
                            out ps
                            );
                    if (fmtid == FormatId.SummaryInformation)
                    {
                        _psSummInfo = ps;
                    }
                    else
                    {
                        _psDocSummInfo = ps;
                    }
                }
                else
                {
                    //
                    // But if we were going to delete the property anyway, there's
                    // nothing to do.
                    //
                    return;
                }
            }

            PROPSPEC[] propSpecs = new PROPSPEC[1];
            PROPVARIANT[] vals = new PROPVARIANT[1];

            propSpecs[0].propType = (uint)PropSpecType.Id;
            propSpecs[0].union.propId = propId;

            if (propVal == null)
            {
                //
                // New value is null => remove the property. Unlike in the case of ReadMultiple,
                // we can just let this one throw an exception on failure. There are no non-zero
                // success codes to worry about.
                //
                ps.DeleteMultiple(1, propSpecs);
                return;
            }

            //
            // New value is non-null => set a new value for the property.
            //
            IntPtr pszVal = IntPtr.Zero;
            try
            {
                if (propVal is string)
                {
                    //
                    // 1) We store string properties internally as UTF-16. 
                    //    During save, convert the string (UTF-16) to CP_ACP and back
                    // 2) If property value changed during that process, store it in CF OLE Storage as UTF-8
                    // 3) Otherwise store it as CP_ACP
                    //
                    string inputString = propVal as string;

                    pszVal = Marshal.StringToCoTaskMemAnsi(inputString);
                    string convertedString = Marshal.PtrToStringAnsi(pszVal);

                    if (String.CompareOrdinal(inputString, convertedString) != 0)
                    {
                        // The string is not an ASCII string. Use UTF-8 to encode it!
                        byte[] byteArray = UTF8Encoding.UTF8.GetBytes(inputString);
                        int nLen = byteArray.Length;

                        //
                        // Before memory allocation for holding UTF-8 codes, we need to first free the memory
                        // allocated by Marshal.StringToCoTaskMemAnsi().
                        // Note that if there is any exception in this try scope, the memory will still be released
                        // by the finally of this try scope.
                        //
                        if (pszVal != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(pszVal);
                            pszVal = IntPtr.Zero;
                        }

                        pszVal = Marshal.AllocCoTaskMem(checked(nLen + 1));  //The extra one byte is for the string terminator null.

                        Marshal.Copy(byteArray, 0, pszVal, nLen);
                        Marshal.WriteByte(pszVal, nLen, 0);     //Put the string terminator null at the end of the array.
                    }

                    vals[0].vt = VARTYPE.VT_LPSTR;
                    vals[0].union.pszVal = pszVal;
                }
                else if (propVal is DateTime)
                {
                    // set FileTime as an Int64 to avoid pointer operations
                    vals[0].vt = VARTYPE.VT_FILETIME;
                    vals[0].union.hVal = ((DateTime)propVal).ToFileTime();
                }
                else
                {
                    throw new ArgumentException(
                                SR.Get(SRID.InvalidDocumentPropertyType, propVal.GetType().ToString()),
                                "propVal");
                }

                //
                // Again, we can just let it throw on failure; no non-zero success codes. It won't throw
                // if the property doesn't exist.
                //
                ps.WriteMultiple(1, propSpecs, vals, 0);
            }
            finally
            {
                if (pszVal != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pszVal);
                }
            }
        }
Example #36
0
        internal static IntPtr MarshalPropVariant(Object obj)
        {
            IntPtr pszVal = IntPtr.Zero;
            IntPtr pNative = IntPtr.Zero;

            try
            {
                PROPVARIANT v;

                if (obj is string)
                {
                    pszVal = Marshal.StringToCoTaskMemAnsi((string)obj);
                    
                    v = new PROPVARIANT();
                    v.vt = VARTYPE.VT_LPSTR;
                    v.union.pszVal = pszVal;
                }
                else if (obj is DateTime)
                {
                    v = new PROPVARIANT();
                    v.vt = VARTYPE.VT_FILETIME;
                    long longFileTime = ((DateTime)obj).ToFileTime();
                    v.union.filetime.dwLowDateTime = (Int32)longFileTime;
                    v.union.filetime.dwHighDateTime = (Int32)((longFileTime >> 32) & 0xFFFFFFFF);
                }
                else
                {
                    throw new InvalidOperationException(
                        SR.Get(SRID.FilterGetValueMustBeStringOrDateTime));
                }

                // allocate an unmanaged PROPVARIANT to return
                pNative = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(PROPVARIANT)));
                // Per MSDN, AllocCoTaskMem never returns null. One can't be too careful, though.
                Invariant.Assert(pNative != null);

                // marshal the managed PROPVARIANT into the unmanaged block and return it
                Marshal.StructureToPtr(v, pNative, false);
            }
            catch
            {
                if (pszVal != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pszVal);
                }

                if (pNative != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pNative);
                }

                throw;
            }

            return pNative;
        }
Example #37
0
 public static extern HRESULT PropVariantClear(ref PROPVARIANT p);
 internal int GetPropertyValue(Guid fmtid, uint propid, out PROPVARIANT propvar)
 {
     IPropertySetStorage propertySetStorage = (IPropertySetStorage)_rootStorage;
     return propertySetStorage.GetPropertyValue(fmtid, propid, out propvar);
 }