// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Peek.Common.Models;
namespace Peek.Common.Extensions
{
public static class IPropertyStoreExtensions
{
///
/// Helper method that retrieves a uint value from the given property store.
/// Returns 0 if the value is not a VT_UI4 (4-byte unsigned integer in little-endian order).
///
/// The property store
/// The pkey
/// The uint value
public static uint? TryGetUInt(this IPropertyStore propertyStore, PropertyKey key)
{
if (propertyStore == null)
{
return null;
}
try
{
PropVariant propVar;
propertyStore.GetValue(ref key, out propVar);
// VT_UI4 Indicates a 4-byte unsigned integer formatted in little-endian byte order.
if ((VarEnum)propVar.Vt == VarEnum.VT_UI4)
{
return propVar.UlVal;
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
///
/// Helper method that retrieves a ulong value from the given property store.
/// Returns 0 if the value is not a VT_UI8 (8-byte unsigned integer in little-endian order).
///
/// The property store
/// the pkey
/// the ulong value
public static ulong? TryGetULong(this IPropertyStore propertyStore, PropertyKey key)
{
if (propertyStore == null)
{
return null;
}
try
{
PropVariant propVar;
propertyStore.GetValue(ref key, out propVar);
// VT_UI8 Indicates an 8-byte unsigned integer formatted in little-endian byte order.
if ((VarEnum)propVar.Vt == VarEnum.VT_UI8)
{
return propVar.UhVal;
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
///
/// Helper method that retrieves a string value from the given property store.
///
/// The property store
/// The pkey
/// The string value
public static string? TryGetString(this IPropertyStore propertyStore, PropertyKey key)
{
if (propertyStore == null)
{
return null;
}
try
{
PropVariant propVar;
propertyStore.GetValue(ref key, out propVar);
if ((VarEnum)propVar.Vt == VarEnum.VT_LPWSTR)
{
return Marshal.PtrToStringUni(propVar.P) ?? string.Empty;
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
///
/// Helper method that retrieves an array of string values from the given property store.
///
/// The property store
/// The pkey
/// The array of string values
public static string[]? TryGetStringArray(this IPropertyStore propertyStore, PropertyKey key)
{
if (propertyStore == null)
{
return null;
}
try
{
PropVariant propVar;
propertyStore.GetValue(ref key, out propVar);
List? values = null;
if ((VarEnum)propVar.Vt == (VarEnum.VT_LPWSTR | VarEnum.VT_VECTOR))
{
values = new List();
for (int elementIndex = 0; elementIndex < propVar.Calpwstr.CElems; elementIndex++)
{
var stringVal = Marshal.PtrToStringUni(Marshal.ReadIntPtr(propVar.Calpwstr.PElems, elementIndex));
if (stringVal != null)
{
values.Add(stringVal);
}
}
}
return values?.ToArray();
}
catch (Exception)
{
return null;
}
}
}
}