Ejemplo n.º 1
0
 public ModelProperty(IPortableDeviceValues deviceProperties)
     : base(deviceProperties)
 {
     FormatId = new Guid("26D4979A-E643-4626-9E2B-736DC0C92FDC");
     PositionId = 8;
     Value = GetStringPropertyValue(FormatId, PositionId);
 }
Ejemplo n.º 2
0
 public NameProperty(IPortableDeviceValues deviceProperties)
     : base(deviceProperties)
 {
     FormatId = new Guid("EF6B490D-5CD8-437A-AFFC-DA8B60EE4A3C");
     PositionId = 4;
     Value = GetStringPropertyValue(FormatId, PositionId);
 }
        /// <summary>
        /// Callback for event from device
        /// </summary>
        /// <param name="pEventParameters"></param>
        public void OnEvent(IPortableDeviceValues pEventParameters)
        {
            string pnpDeviceId;
              pEventParameters.GetStringValue(ref PortableDevicePKeys.WPD_EVENT_PARAMETER_PNP_DEVICE_ID, out pnpDeviceId);
              if (this.device.DeviceId != pnpDeviceId)
            return;

              Guid eventGuid;
              pEventParameters.GetGuidValue(ref PortableDevicePKeys.WPD_EVENT_PARAMETER_EVENT_ID, out eventGuid);

              PortableDeviceEventType deviceEventType = new PortableDeviceEventType() {EventGuid = eventGuid};

              if (eventGuid == PortableDeviceGuids.WPD_EVENT_OBJECT_ADDED)
              {
            string objectId;
            pEventParameters.GetStringValue(ref PortableDevicePKeys.WPD_OBJECT_ID, out objectId);
            string objectName;
            pEventParameters.GetStringValue(ref PortableDevicePKeys.WPD_OBJECT_NAME, out objectName);
            PortableDeviceObject deviceObject = new PortableDeviceObject(objectId) {Name = objectName};
            deviceEventType.DeviceObject = deviceObject;
              }

              // the original api isn't finise, i use a siple workaroud, but this need to be fixed using event factory
              //this.device.RaiseEvent(PortableDeviceEventTypeFactory.Instance.CreateEventType(eventGuid));
              this.device.RaiseEvent(deviceEventType);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// ポータブル デバイス上で変更が生じた時に発生します。
 /// </summary>
 /// <param name="pEventParameters">イベント データ。</param>
 public void OnEvent( IPortableDeviceValues pEventParameters )
 {
     if( this._handler != null )
     {
         this._handler( new WpdEventArgs( pEventParameters ) );
     }
 }
Ejemplo n.º 5
0
 public TypeProperty(IPortableDeviceValues deviceProperties)
     : base(deviceProperties)
 {
     FormatId = new Guid("26D4979A-E643-4626-9E2B-736DC0C92FDC");
     PositionId = 15;
     Value = GetUIntPropertyValue(FormatId, PositionId);
     ExtrapolateDeviceType(Value);
 }
 public ContentTypeProperty(IPortableDeviceValues deviceProperties)
     : base(deviceProperties)
 {
     FormatId = new Guid("EF6B490D-5CD8-437A-AFFC-DA8B60EE4A3C");
     PositionId = 7;
     Value = GetGUIDPropertyValue(FormatId, PositionId).ToString();
     ExtrapolateDeviceType(Value);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// インスタンスを初期化します。
        /// </summary>
        /// <param name="key">識別子。</param>
        /// <param name="info">プロパティ値の情報。</param>
        /// <param name="values">値。</param>
        internal WpdPropertyValue( _tagpropertykey key, tag_inner_PROPVARIANT info, IPortableDeviceValues values )
        {
            this.Key      = key;
            this.HasValue = true;

            switch( ( PropVariantTypes )info.vt )
            {
            case PropVariantTypes.VT_BOOL:
                this.Type      = WpdPropertyValueType.Bool;
                this.ValueBool = WpdPropertyValue.ReadBool( key, values );
                break;

            case PropVariantTypes.VT_DATE:
                this.Type          = WpdPropertyValueType.DateTime;
                this.ValueDateTime = WpdPropertyValue.ReadDateTime( key, values );
                break;

            case PropVariantTypes.VT_CLSID:
                this.Type      = WpdPropertyValueType.Guid;
                this.ValueGuid = WpdPropertyValue.ReadGuid( key, values );
                break;

            case PropVariantTypes.VT_I4:
                this.Type       = WpdPropertyValueType.Int32;
                this.ValueInt32 = WpdPropertyValue.ReadInt32( key, values );
                break;

            case PropVariantTypes.VT_I8:
                this.Type       = WpdPropertyValueType.Int64;
                this.ValueInt64 = WpdPropertyValue.ReadInt64( key, values );
                break;

            case PropVariantTypes.VT_BSTR:
            case PropVariantTypes.VT_LPSTR:
            case PropVariantTypes.VT_LPWSTR:
                this.Type        = WpdPropertyValueType.String;
                this.ValueString = WpdPropertyValue.ReadString( key, values );
                break;

            case PropVariantTypes.VT_UI4:
                this.Type        = WpdPropertyValueType.UInt32;
                this.ValueUInt32 = WpdPropertyValue.ReadUInt32( key, values );
                break;

            case PropVariantTypes.VT_UI8:
                this.Type        = WpdPropertyValueType.UInt64;
                this.ValueUInt64 = WpdPropertyValue.ReadUInt64( key, values );
                break;

            default:
                this.Type     = WpdPropertyValueType.Unknown;
                this.HasValue = false;
                break;
            }
        }
        /// <summary>
        ///     Callback for event from device
        /// </summary>
        /// <param name="pEventParameters"></param>
        public void OnEvent(IPortableDeviceValues pEventParameters)
        {
            string pnpDeviceId;
            pEventParameters.GetStringValue(ref PortableDevicePKeys.WPD_EVENT_PARAMETER_PNP_DEVICE_ID, out pnpDeviceId);
            if (device.DeviceId != pnpDeviceId)
                return;

            Guid eventGuid;
            pEventParameters.GetGuidValue(ref PortableDevicePKeys.WPD_EVENT_PARAMETER_EVENT_ID, out eventGuid);

            device.RaiseEvent(PortableDeviceEventTypeFactory.Instance.CreateEventType(eventGuid));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="portableDevice"></param>
        /// <param name="parentId"></param>
        private static void TransferContentToDevice(string sourceFile, PortableDeviceClass portableDevice, string parentId)
        {
            IPortableDeviceContent content;

            portableDevice.Content(out content);


            IPortableDeviceValues values = GetRequiredPropertiesForContentType(sourceFile, parentId);


            IStream tempStream;
            uint    optimalTransferSizeBytes = 0;

            content.CreateObjectWithPropertiesAndData(values, out tempStream, ref optimalTransferSizeBytes, null);


            System.Runtime.InteropServices.ComTypes.IStream targetStream = (System.Runtime.InteropServices.ComTypes.IStream)tempStream;


            try
            {
                using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
                {
                    int bytesRead = 0;
                    do
                    {
                        int    count  = 1024 * 1024;
                        byte[] buffer = new byte[count];
                        bytesRead = sourceStream.Read(buffer, 0, count);


                        IntPtr pcbWritten = IntPtr.Zero;
                        targetStream.Write(buffer, bytesRead, pcbWritten);
                    }while (bytesRead > 0);
                }
                targetStream.Commit(0);
            }
            finally
            {
                Marshal.ReleaseComObject(tempStream);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 获取访问时间属性
        /// </summary>
        /// <param name="deviceValues"></param>
        /// <returns></returns>
        private static string GetFileDateAuthoredProperty(IPortableDeviceValues deviceValues)
        {
            _tagpropertykey nameKey = new _tagpropertykey();

            nameKey.fmtid = new Guid(0xEF6B490D, 0x5CD8, 0x437A, 0xAF, 0xFC, 0xDA, 0x8B, 0x60, 0xEE, 0x4A, 0x3C); //guid唯一值
            nameKey.pid   = 20;                                                                                   //索引

            string sizeProperty = string.Empty;

            try
            {
                deviceValues.GetStringValue(ref nameKey, out sizeProperty);
            }
            catch
            {
                return("");
            }

            return(sizeProperty);
        }
Ejemplo n.º 11
0
        public static bool HasKeyValue(this IPortableDeviceValues values, PropertyKey findKey)
        {
            uint num = 0;

            values?.GetCount(ref num);
            for (uint i = 0; i < num; i++)
            {
                PropertyKey key = new PropertyKey();
                using (PropVariantFacade val = new PropVariantFacade())
                {
                    values.GetAt(i, ref key, ref val.Value);
                    if (key == findKey)
                    {
                        return(val.VariantType != PropVariantType.VT_ERROR);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// インスタンスを初期化します。
        /// </summary>
        /// <param name="values">イベント データのコレクション。</param>
        internal WpdEventArgs( IPortableDeviceValues values )
        {
            uint count = 0;
            values.GetCount( ref count );
            if( count < 1 )
            {
                this.Values = new List< WpdPropertyValue >( 0 );
                return;
            }

            this.Values = new List< WpdPropertyValue >( ( int )count );
            var key     = new _tagpropertykey();
            var info    = new tag_inner_PROPVARIANT();

            for( uint i = 0; i < count; ++i )
            {
                values.GetAt( i, ref key, ref info );

                var value = new WpdPropertyValue( key, info, values );
                if( value.Key.Equals( WpdProperties.WPD_EVENT_PARAMETER_PNP_DEVICE_ID ) )
                {
                    this.DeviceId = value.ValueString;
                }
                else if( value.Key.Equals( WpdProperties.WPD_OBJECT_ID ) )
                {
                    this.ObjectId = value.ValueString;
                }
                else if( value.Key.Equals( WpdProperties.WPD_OBJECT_PARENT_ID ) )
                {
                    this.ParentObjectId = value.ValueString;
                }
                else if( value.Key.Equals( WpdProperties.WPD_EVENT_PARAMETER_EVENT_ID ) )
                {
                    if( value.ValueGuid != null ) { this.Type = TypeConvertUtility.GuidToEventType( value.ValueGuid.Value ); }
                }
                else
                {
                    this.Values.Add( value );
                }
            }
        }
        private PortableDeviceObject CreateGenericObject(IPortableDeviceValues values)
        {
            string filename;
            int    size;

            try
            {
                values.GetStringValue(ref PortableDevicePKeys.WPD_OBJECT_ORIGINAL_FILE_NAME, out filename);
                values.GetSignedIntegerValue(ref PortableDevicePKeys.WPD_OBJECT_SIZE, out size);
            }
            catch
            {
                return(CreateObject <PortableDeviceObject>(values));
            }

            var obj = CreateObject <PortableDeviceFileObject>(values);

            obj.FileName = filename;
            obj.Size     = size;
            return(obj);
        }
Ejemplo n.º 14
0
        public static List <MTPDevice> GetDevices()
        {
            var devices = new List <MTPDevice>();

            string[]               deviceIds = EnumerateDevices();
            PortableDevice         portableDevice;
            IPortableDeviceContent deviceContent;

            MTPDevice tempDevice;

            if (deviceIds.IsInvalid())
            {
                return(devices);
            }
            foreach (var deviceId in deviceIds)
            {
                IPortableDeviceValues deviceValues = Connect(deviceId, out portableDevice, out deviceContent);
                MTPDeviceType         deviceType   = GetDeviceType(deviceValues);
                //if (deviceType == MTPDeviceType.MediaPlayer || deviceType == MTPDeviceType.Phone)
                {
                    tempDevice                 = new MTPDevice();
                    tempDevice.DeviceId        = deviceId;
                    tempDevice.DeviceType      = deviceType;
                    tempDevice.SerialNumber    = GetSerialNumber(deviceValues);
                    tempDevice.DeviceName      = GetDeviceName(deviceValues);
                    tempDevice.FirmwareVersion = GetFirmwareVersion(deviceValues);
                    tempDevice.Manufacturer    = GetManufacturer(deviceValues);
                    tempDevice.Model           = GetModel(deviceValues);

                    devices.Add(tempDevice);
                }

                Disconnect(portableDevice);
            }

            return(devices);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Connect to the portable device
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="majorVersionNumber"></param>
        /// <param name="minorVersionNumber"></param>
        public void ConnectToDevice(string appName, float majorVersionNumber, float minorVersionNumber)
        {
            if (string.IsNullOrEmpty(appName))
            {
                throw new ArgumentNullException("appName");
            }

            if (IsConnected)
            {
                return;
            }
            //Creating propValues for connection
            IPortableDeviceValues clientValues = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValuesClass();

            //Set the application name
            _tagpropertykey prop = PortableDevicePKeys.WPD_CLIENT_NAME;

            clientValues.SetStringValue(ref prop, appName);
            //Set the App version
            prop = PortableDevicePKeys.WPD_CLIENT_MAJOR_VERSION;
            clientValues.SetFloatValue(ref prop, majorVersionNumber);
            //Set the app minor version
            prop = PortableDevicePKeys.WPD_CLIENT_MINOR_VERSION;
            clientValues.SetFloatValue(ref prop, minorVersionNumber);

            //Open connection
            this.portableDeviceClass.Open(this.DeviceId, clientValues);

            //Extract device capabilities
            //this.ExtractDeviceCapabilities();

            this.eventCallback = new PortableDeviceEventCallback(this);
            // According to documentation pParameters should be null (see http://msdn.microsoft.com/en-us/library/dd375684%28v=VS.85%29.aspx )
            this.portableDeviceClass.Advise(0, this.eventCallback, null, out this.adviseCookie);

            IsConnected = true;
        }
Ejemplo n.º 16
0
        /**
         * Device must be connected!
         *
         * Returns the id of the new folder.
         */
        public PortableDeviceFolder CreateDir(PortableDevice device, string folderName)
        {
            PortableDeviceFolder result = null;

            try
            {
                String newFolderId = "";

                // Already got folderName?
                result = FindDir(folderName);
                if (null == result)
                {
                    IPortableDeviceContent content = device.getContents();

                    // Get the properties of the object
                    IPortableDeviceProperties properties;
                    content.Properties(out properties);

                    IPortableDeviceValues createFolderValues = GetRequiredCreateDirPropertiesForContentType(Id, folderName);

                    content.CreateObjectWithPropertiesOnly(createFolderValues, ref newFolderId);

                    // Last, add to list of files.
                    result = new PortableDeviceFolder(newFolderId, folderName);

                    this.Files.Add(result);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                result = null;
            }

            return(result);
        }
        /// <summary>
        /// Callback for event from device
        /// </summary>
        /// <param name="pEventParameters"></param>
        public void OnEvent(IPortableDeviceValues pEventParameters)
        {
            string pnpDeviceId;

            pEventParameters.GetStringValue(ref PortableDevicePKeys.WPD_EVENT_PARAMETER_PNP_DEVICE_ID, out pnpDeviceId);
            if (this.device.DeviceId != pnpDeviceId)
            {
                return;
            }

            Guid eventGuid;

            pEventParameters.GetGuidValue(ref PortableDevicePKeys.WPD_EVENT_PARAMETER_EVENT_ID, out eventGuid);

            PortableDeviceEventType deviceEventType = new PortableDeviceEventType()
            {
                EventGuid = eventGuid
            };

            if (eventGuid == PortableDeviceGuids.WPD_EVENT_OBJECT_ADDED)
            {
                string objectId;
                pEventParameters.GetStringValue(ref PortableDevicePKeys.WPD_OBJECT_ID, out objectId);
                string objectName;
                pEventParameters.GetStringValue(ref PortableDevicePKeys.WPD_OBJECT_NAME, out objectName);
                PortableDeviceObject deviceObject = new PortableDeviceObject(objectId)
                {
                    Name = objectName
                };
                deviceEventType.DeviceObject = deviceObject;
            }

            // the original api isn't finise, i use a siple workaroud, but this need to be fixed using event factory
            //this.device.RaiseEvent(PortableDeviceEventTypeFactory.Instance.CreateEventType(eventGuid));
            this.device.RaiseEvent(deviceEventType);
        }
Ejemplo n.º 18
0
 public virtual extern void SendCommand([In] uint dwFlags, [In, MarshalAs(UnmanagedType.Interface)] IPortableDeviceValues pParameters, [MarshalAs(UnmanagedType.Interface)] out IPortableDeviceValues ppResults);
Ejemplo n.º 19
0
 public virtual extern void Advise([In] uint dwFlags, [In, MarshalAs(UnmanagedType.Interface)] IPortableDeviceEventCallback pCallback, [In, MarshalAs(UnmanagedType.Interface)] IPortableDeviceValues pParameters, [MarshalAs(UnmanagedType.LPWStr)] out string ppszCookie);
        private PortableDeviceObject CreateFolderObject(IPortableDeviceValues values)
        {
            var obj = CreateObject <PortableDeviceFolderObject>(values);

            return(obj);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// プロパティ値から、真偽値を読み取ります。
 /// </summary>
 /// <param name="key">識別子。</param>
 /// <param name="values">プロパティ値。</param>
 /// <returns>成功時は読み取った値。それ以外は null。</returns>
 public static bool? ReadBool( _tagpropertykey key, IPortableDeviceValues values )
 {
     try
     {
         int value;
         values.GetBoolValue( key, out value );
         return ( value != 0 );
     }
     catch( Exception exp )
     {
         Debug.WriteLine( exp.Message );
         return null;
     }
 }
Ejemplo n.º 22
0
        /// <summary>
        /// データ受信を伴うMTPオペレーションを実行する
        /// </summary>
        /// <param name="device"></param>
        /// <param name="code"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        private static MtpResponse executeDataReadCommand(PortableDevice device, ushort code, uint[] param, bool noReadResponseParam)
        {
            IPortableDeviceValues spResults;
            int    ret;
            string context;
            uint   size;

            byte[] bufferIn;
            IntPtr dataAddress;
            uint   readedSize;
            IntPtr dataPtr;

            byte[] bufferOut = null;
            uint   responseCode;

            uint[] responseParam;

            // MTPコマンドとパラメータを構築する
            IPortableDeviceValues mtpCommand = createMtpCommand(code, WpdProperty.WPD_COMMAND_MTP_EXT_EXECUTE_COMMAND_WITH_DATA_TO_READ);
            IPortableDevicePropVariantCollection mtpCommandParam = null;

            if (param != null)
            {
                mtpCommandParam = createMtpCommandParameter(param);
                mtpCommand.SetIPortableDevicePropVariantCollectionValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_OPERATION_PARAMS, mtpCommandParam);
            }
            // リクエストを送信
            device.SendCommand(0, mtpCommand, out spResults);
            // コマンドとパラメータは以後不要なので解放
            if (mtpCommandParam != null)
            {
                Marshal.ReleaseComObject(mtpCommandParam);
            }
            Marshal.ReleaseComObject(mtpCommand);
            // リクエストの結果を取得する
            spResults.GetErrorValue(ref WpdProperty.WPD_PROPERTY_COMMON_HRESULT, out ret);
            if (ret != 0)
            {   // エラーなら終了
                Marshal.ReleaseComObject(spResults);
                return(new MtpResponse(0, null, null));
            }
            // コンテキストを取得する
            spResults.GetStringValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, out context);
            // データサイズを取得する
            spResults.GetUnsignedIntegerValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_TOTAL_DATA_SIZE, out size);
            Marshal.ReleaseComObject(spResults);

            if (size > 0)
            {
                // データ受信用のコマンドを構築する
                bufferIn   = new byte[size];
                mtpCommand = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValues();
                mtpCommand.SetGuidValue(ref WpdProperty.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, ref WpdProperty.WPD_COMMAND_MTP_EXT_READ_DATA.fmtid);
                mtpCommand.SetUnsignedIntegerValue(ref WpdProperty.WPD_PROPERTY_COMMON_COMMAND_ID, WpdProperty.WPD_COMMAND_MTP_EXT_READ_DATA.pid);
                mtpCommand.SetStringValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, context);
                mtpCommand.SetBufferValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ref bufferIn[0], size);
                mtpCommand.SetUnsignedIntegerValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_TO_READ, size);
                // データを受信する
                device.SendCommand(0, mtpCommand, out spResults);
                Marshal.ReleaseComObject(mtpCommand);
                spResults.GetErrorValue(ref WpdProperty.WPD_PROPERTY_COMMON_HRESULT, out ret);
                if (ret != 0)
                {   // エラーなら終了
                    Marshal.ReleaseComObject(spResults);
                    return(new MtpResponse(0, null, null));
                }
                // 受信データのアドレスを取得する
                dataAddress = Environment.Is64BitProcess ? Marshal.AllocCoTaskMem(8) : Marshal.AllocCoTaskMem(4);
                spResults.GetBufferValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, dataAddress, out readedSize);
                dataPtr = Environment.Is64BitProcess ? new IntPtr(Marshal.ReadInt64(dataAddress)) : new IntPtr(Marshal.ReadInt32(dataAddress));
                Marshal.FreeCoTaskMem(dataAddress);
                // 受信データを取得する
                bufferOut = new byte[size];
                Marshal.Copy(dataPtr, bufferOut, 0, bufferOut.Length);
                Marshal.ReleaseComObject(spResults);
                Marshal.FreeCoTaskMem(dataPtr);
            }

            // DataEndTransfer(レスポンス)を送信する
            sendEndDataTransfer(device, context, out responseCode, out responseParam, noReadResponseParam);

            return(new MtpResponse((ushort)responseCode, responseParam, bufferOut));
        }
Ejemplo n.º 23
0
 /// <summary>
 /// プロパティ値から、日時値を読み取ります。
 /// </summary>
 /// <param name="key">識別子。</param>
 /// <param name="values">プロパティ値。</param>
 /// <returns>成功時は読み取った値。それ以外は null。</returns>
 public static DateTime? ReadDateTime( _tagpropertykey key, IPortableDeviceValues values )
 {
     try
     {
         float value;
         values.GetFloatValue( ref key, out value );
         return DateTime.FromOADate( value );
     }
     catch( Exception exp )
     {
         Debug.WriteLine( exp.Message );
         return null;
     }
 }
Ejemplo n.º 24
0
        public uint ExecuteWriteData(uint code, byte[] data, params uint[] parameters)
        {
            // source: http://msdn.microsoft.com/en-us/library/windows/desktop/ff384843(v=vs.85).aspx
            // and view-source:http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_26860397.html
            // error codes http://msdn.microsoft.com/en-us/library/windows/desktop/dd319335(v=vs.85).aspx
            //byte[] imgdate = new byte[8];

            IPortableDeviceValues commandValues = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValuesClass();
            IPortableDeviceValues pParameters   = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValues();

            IPortableDevicePropVariantCollection propVariant =
                (IPortableDevicePropVariantCollection) new PortableDeviceTypesLib.PortableDevicePropVariantCollection();
            IPortableDeviceValues pResults;

            //commandValues.SetGuidValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, ref command.fmtid);
            commandValues.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY,
                                       PortableDevicePKeys.WPD_COMMAND_MTP_EXT_EXECUTE_COMMAND_WITH_DATA_TO_WRITE.fmtid);
            commandValues.SetUnsignedIntegerValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID,
                                                  PortableDevicePKeys.WPD_COMMAND_MTP_EXT_EXECUTE_COMMAND_WITH_DATA_TO_WRITE.pid);
            commandValues.SetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ref data[0], (uint)data.Length);

            foreach (uint parameter in parameters)
            {
                tag_inner_PROPVARIANT vparam = new tag_inner_PROPVARIANT();
                UintToPropVariant(parameter, out vparam);
                propVariant.Add(ref vparam);
            }

            commandValues.SetIPortableDevicePropVariantCollectionValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_PARAMS, propVariant);
            commandValues.SetUnsignedLargeIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_TOTAL_DATA_SIZE,
                                                       (ulong)data.Length);
            commandValues.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_CODE, (uint)code);

            // According to documentation, first parameter should be 0 (see http://msdn.microsoft.com/en-us/library/dd375691%28v=VS.85%29.aspx)
            this.portableDeviceClass.SendCommand(0, commandValues, out pResults);

            try
            {
                int pValue = 0;
                pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
                if (pValue != 0)
                {
                    return((uint)pValue);
                }
                //uint mtperror;
                //pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_RESPONSE_CODE, out mtperror);
                //if (mtperror != 0)
                //  return mtperror;
            }
            catch (Exception)
            {
            }
            string tmpTransferContext = string.Empty;

            pResults.GetStringValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, out tmpTransferContext);


            pParameters.Clear();
            pResults.Clear();

            pParameters.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_WRITE_DATA.fmtid);
            pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_WRITE_DATA.pid);
            pParameters.SetStringValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, tmpTransferContext);
            pParameters.SetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ref data[0], (uint)data.Length);
            pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_TO_WRITE, (uint)data.Length);
            pParameters.SetIPortableDevicePropVariantCollectionValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_PARAMS, propVariant);


            portableDeviceClass.SendCommand(0, pParameters, out pResults);


            try
            {
                int pValue = 0;
                pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
                if (pValue != 0)
                {
                    return((uint)pValue);
                }
                //uint mtperror;
                //pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_RESPONSE_CODE, out mtperror);
                //if (mtperror != 0)
                //  return mtperror;
            }
            catch (Exception)
            {
            }


            pParameters.Clear();
            pResults.Clear();
            {
                pParameters.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_END_DATA_TRANSFER.fmtid);
                pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_END_DATA_TRANSFER.pid);
                pParameters.SetStringValue(PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, tmpTransferContext);
            }

            portableDeviceClass.SendCommand(0, pParameters, out pResults);


            try
            {
                int tmpResult = 0;

                pResults.GetErrorValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out tmpResult);
                if (tmpResult != 0)
                {
                    return((uint)tmpResult);
                }
                uint mtperror;
                pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_RESPONSE_CODE, out mtperror);
                if (mtperror != 0)
                {
                    return(mtperror);
                }
            }
            catch
            {
            }
            return(0);
        }
 public BaseWPDProperties(IPortableDeviceValues deviceProperties)
 {
     DeviceProperties = deviceProperties;
 }
Ejemplo n.º 26
0
        internal MediaDeviceService(MediaDevice device, string serviceId)
        {
            this.device    = device;
            this.ServiceId = serviceId;

            //Match match = Regex.Match(serviceId, @".*#(?<service>\{.*\})\\(?<name>\{.*\})");
            //if (match.Success)
            //{
            //    string service = match.Groups["service"].Value;
            //    Guid serviceGuid = new Guid(service);
            //    this.Service = serviceGuid.GetEnum<Services>();
            //    string serviceName = match.Groups["name"].Value;
            //    this.ServiceName = $"{this.Service} : {service} : {serviceName}";
            //}
            //else
            //{
            //    this.ServiceName = "Unknown";
            //}
            //this.ServiceName = serviceId.Substring(serviceId.LastIndexOf(@"\") + 1);

            IPortableDeviceValues values = (IPortableDeviceValues) new PortableDeviceValues();

            this.service.Open(this.ServiceId, values);

            this.service.GetServiceObjectID(out string serviceObjectID);
            this.ServiceObjectID = serviceObjectID;

            this.service.GetPnPServiceID(out string pnPServiceID);
            this.PnPServiceID = pnPServiceID;

            this.service.Capabilities(out capabilities);

            this.service.Content(out content);

            content.Properties(out IPortableDeviceProperties properties);

            properties.GetSupportedProperties(this.ServiceObjectID, out IPortableDeviceKeyCollection keyCol);

            properties.GetValues(this.ServiceObjectID, keyCol, out IPortableDeviceValues deviceValues);

            ComTrace.WriteObject(deviceValues);

#pragma warning disable IDE0079 // Remove unnecessary suppression
#pragma warning disable IDE0090 // Use 'new(...)'

            using (PropVariantFacade value = new PropVariantFacade())
            {
                deviceValues.GetValue(ref WPD.OBJECT_NAME, out value.Value);
                this.Name = value;
            }

            using (PropVariantFacade value = new PropVariantFacade())
            {
                deviceValues.GetValue(ref WPD.FUNCTIONAL_OBJECT_CATEGORY, out value.Value);

                Guid serviceGuid = new Guid((string)value);
                this.Service     = serviceGuid.GetEnum <MediaDeviceServices>();
                this.ServiceName = this.Service != MediaDeviceServices.Unknown ? this.Service.ToString() : serviceGuid.ToString();
            }

            using (PropVariantFacade value = new PropVariantFacade())
            {
                deviceValues.GetValue(ref WPD.SERVICE_VERSION, out value.Value);
                this.ServiceVersion = value;
            }

#pragma warning restore IDE0090 // Use 'new(...)'
#pragma warning restore IDE0079 // Remove unnecessary suppression

            Update();

            //var x = GetContent().ToArray();
        }
Ejemplo n.º 27
0
        private void GetRequiredPropertiesForFolder(string parentObjectId, string folderName, ref  IPortableDeviceValues ppObjectProperties)
        {
            ppObjectProperties.SetStringValue(ref PortableDevicePropertyKeys.WPD_OBJECT_PARENT_ID, parentObjectId);
            ppObjectProperties.SetStringValue(ref PortableDevicePropertyKeys.WPD_OBJECT_NAME, folderName);
            ppObjectProperties.SetStringValue(ref PortableDevicePropertyKeys.WPD_OBJECT_ORIGINAL_FILE_NAME, folderName);

            ppObjectProperties.SetGuidValue(ref PortableDevicePropertyKeys.WPD_OBJECT_CONTENT_TYPE, ref PortableDeviceConstants.WPD_CONTENT_TYPE_FOLDER);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Sets the values of multiple properties.
        /// </summary>
        /// <param name="data">An array that contains the property keys and values.</param>
        /// <returns>A dictionary of the new values for the properties. Actual values may not match the requested values.</returns>
        public IDictionary <PropertyKey, object> SetProperties(DataFieldInfo[] data)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentException(LocalizedMessages.SensorEmptyData, "data");
            }

            IPortableDeviceValues pdv = new PortableDeviceValues();

            for (int i = 0; i < data.Length; i++)
            {
                PropertyKey propKey = data[i].Key;
                object      value   = data[i].Value;
                if (value == null)
                {
                    throw new ArgumentException(
                              string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                            LocalizedMessages.SensorNullValueAtIndex, i),
                              "data");
                }

                try
                {
                    // new PropVariant will throw an ArgumentException if the value can
                    // not be converted to an appropriate PropVariant.
                    using (PropVariant pv = PropVariant.FromObject(value))
                    {
                        pdv.SetValue(ref propKey, pv);
                    }
                }
                catch (ArgumentException)
                {
                    byte[] buffer;
                    if (value is Guid)
                    {
                        Guid guid = (Guid)value;
                        pdv.SetGuidValue(ref propKey, ref guid);
                    }
                    else if ((buffer = value as byte[]) != null)
                    {
                        pdv.SetBufferValue(ref propKey, buffer, (uint)buffer.Length);
                    }
                    else
                    {
                        pdv.SetIUnknownValue(ref propKey, value);
                    }
                }
            }

            Dictionary <PropertyKey, object> results = new Dictionary <PropertyKey, object>();
            IPortableDeviceValues            pdv2    = null;
            HResult hr = nativeISensor.SetProperties(pdv, out pdv2);

            if (hr == HResult.Ok)
            {
                try
                {
                    uint count = 0;
                    pdv2.GetCount(ref count);

                    for (uint i = 0; i < count; i++)
                    {
                        PropertyKey propKey = new PropertyKey();
                        using (PropVariant propVal = new PropVariant())
                        {
                            pdv2.GetAt(i, ref propKey, propVal);
                            results.Add(propKey, propVal.Value);
                        }
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(pdv2);
                    pdv2 = null;
                }
            }

            return(results);
        }
Ejemplo n.º 29
0
        private void GetProperties()
        {
            IPortableDeviceValues values = null;

            try
            {
                // get all predefined values
                this.device.deviceProperties.GetValues(this.Id, keyCollection, out values);
            }
            catch (Exception ex)
            {
                Trace.TraceError($"{ex.Message} for {this.Id}");
                return;
            }

            // read all properties
            // use a loop to prevent exceptions during calling GetValue for non existing values
            uint num = 0;

            values.GetCount(ref num);
            for (uint i = 0; i < num; i++)
            {
                PropertyKey key = new PropertyKey();
                using (PropVariantFacade val = new PropVariantFacade())
                {
                    values.GetAt(i, ref key, ref val.Value);

                    if (key.fmtid == WPD.OBJECT_PROPERTIES_V1)
                    {
                        switch ((ObjectProperties)key.pid)
                        {
                        case ObjectProperties.ContentType:
                            this.ContentType = val;
                            break;

                        case ObjectProperties.Name:
                            this.name = val;
                            break;

                        case ObjectProperties.OriginalFileName:
                            this.OriginalFileName = val;
                            break;

                        case ObjectProperties.HintLocationDisplayName:
                            this.HintLocationName = val;
                            break;

                        case ObjectProperties.ContainerFunctionalObjectId:
                            this.ParentContainerId = val;
                            break;

                        case ObjectProperties.Size:
                            this.Size = val;
                            break;

                        case ObjectProperties.DateCreated:
                            this.DateCreated = val;
                            break;

                        case ObjectProperties.DateModified:
                            this.DateModified = val;
                            break;

                        case ObjectProperties.DateAuthored:
                            this.DateAuthored = val;
                            break;

                        case ObjectProperties.CanDelete:
                            this.CanDelete = val;
                            break;

                        case ObjectProperties.IsSystem:
                            this.IsSystem = val.ToBool();
                            break;

                        case ObjectProperties.IsHidden:
                            this.IsHidden = val;
                            break;

                        case ObjectProperties.IsDrmProtected:
                            this.IsDRMProtected = val;
                            break;

                        case ObjectProperties.ParentId:
                            this.ParentId = val;
                            break;

                        case ObjectProperties.PersistentUniqueId:
                            this.PersistentUniqueId = val;
                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 30
0
 /// <summary>
 /// プロパティ値から、文字列値を読み取ります。
 /// </summary>
 /// <param name="key">識別子。</param>
 /// <param name="values">プロパティ値。</param>
 /// <returns>成功時は読み取った値。それ以外は null。</returns>
 public static string ReadString( _tagpropertykey key, IPortableDeviceValues values )
 {
     try
     {
         string value;
         values.GetStringValue( key, out value );
         return String.IsNullOrEmpty( value ) ? String.Empty : value;
     }
     catch( Exception exp )
     {
         Debug.WriteLine( exp.Message );
         return String.Empty;
     }
 }
Ejemplo n.º 31
0
 /// <summary>
 /// プロパティ値から、符号なし 64 ビット整数値を読み取ります。
 /// </summary>
 /// <param name="key">識別子。</param>
 /// <param name="values">プロパティ値。</param>
 /// <returns>成功時は読み取った値。それ以外は null。</returns>
 public static ulong? ReadUInt64( _tagpropertykey key, IPortableDeviceValues values )
 {
     try
     {
         ulong value;
         values.GetUnsignedLargeIntegerValue( key, out value );
         return value;
     }
     catch( Exception exp )
     {
         Debug.WriteLine( exp.Message );
         return null;
     }
 }
Ejemplo n.º 32
0
        private MTPDataResponse ExecuteReadData(uint code, IPortableDevicePropVariantCollection propVariant)
        {
            MTPDataResponse resp = new MTPDataResponse();

            // source: http://msdn.microsoft.com/en-us/library/windows/desktop/ff384843(v=vs.85).aspx
            // and view-source:http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_26860397.html
            // error codes http://msdn.microsoft.com/en-us/library/windows/desktop/dd319335(v=vs.85).aspx
            byte[] imgdate = new byte[8];

            IPortableDeviceValues commandValues = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValuesClass();
            IPortableDeviceValues pParameters   = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValues();

            IPortableDeviceValues pResults;

            //commandValues.SetGuidValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, ref command.fmtid);
            commandValues.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY,
                                       PortableDevicePKeys.WPD_COMMAND_MTP_EXT_EXECUTE_COMMAND_WITH_DATA_TO_READ.fmtid);
            commandValues.SetUnsignedIntegerValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID,
                                                  PortableDevicePKeys.WPD_COMMAND_MTP_EXT_EXECUTE_COMMAND_WITH_DATA_TO_READ.pid);
            commandValues.SetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ref imgdate[0], (uint)imgdate.Length);



            commandValues.SetIPortableDevicePropVariantCollectionValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_PARAMS, propVariant);
            commandValues.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_CODE, (uint)code);

            // According to documentation, first parameter should be 0 (see http://msdn.microsoft.com/en-us/library/dd375691%28v=VS.85%29.aspx)
            this.portableDeviceClass.SendCommand(0, commandValues, out pResults);

            try
            {
                int pValue;
                pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
                if (pValue != 0)
                {
                    resp.ErrorCode = (uint)pValue;
                    return(resp);
                }
            }
            catch (Exception)
            {
            }

            uint   tmpBufferSize      = 0;
            uint   tmpTransferSize    = 0;
            string tmpTransferContext = string.Empty;

            {
                pResults.GetStringValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, out tmpTransferContext);
                pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_TOTAL_DATA_SIZE, out tmpBufferSize);
                pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPTIMAL_TRANSFER_BUFFER_SIZE, out tmpTransferSize);
            }

            pParameters.Clear();
            pResults.Clear();

            byte[] tmpData = new byte[(int)tmpTransferSize];
            pParameters.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_READ_DATA.fmtid);
            pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_READ_DATA.pid);
            pParameters.SetStringValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, tmpTransferContext);
            pParameters.SetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ref tmpData[0], (uint)tmpTransferSize);
            pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_TO_READ, (uint)tmpTransferSize);
            pParameters.SetIPortableDevicePropVariantCollectionValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_PARAMS, propVariant);


            portableDeviceClass.SendCommand(0, pParameters, out pResults);


            uint cbBytesRead = 0;

            try
            {
                int pValue;
                pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
                if (pValue != 0)
                {
                    resp.ErrorCode = (uint)pValue;
                    return(resp);
                }
            }
            catch (Exception)
            {
            }
            // 24,142,174,9
            // 18, 8E
            GCHandle pinnedArray = GCHandle.Alloc(imgdate, GCHandleType.Pinned);
            IntPtr   ptr         = pinnedArray.AddrOfPinnedObject();

            uint dataread = 0;

            pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_READ, out dataread);
            pResults.GetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ptr, out cbBytesRead);


            IntPtr tmpPtr = new IntPtr(Marshal.ReadInt64(ptr));

            resp.Data = new byte[(int)cbBytesRead];
            Marshal.Copy(tmpPtr, resp.Data, 0, (int)cbBytesRead);
            //for (int i = 0; i < cbBytesRead; i++)
            //{
            //    resp.Data[i] = Marshal.ReadByte(tmpPtr, i);
            //}

            Marshal.FreeHGlobal(tmpPtr);
            pinnedArray.Free();

            pParameters.Clear();
            pResults.Clear();
            {
                pParameters.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_END_DATA_TRANSFER.fmtid);
                pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_END_DATA_TRANSFER.pid);
                pParameters.SetStringValue(PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, tmpTransferContext);
            }

            portableDeviceClass.SendCommand(0, pParameters, out pResults);



            try
            {
                int pValue;
                pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
                if (pValue != 0)
                {
                    resp.ErrorCode = (uint)pValue;
                    return(resp);
                }

                uint iValue;
                pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_RESPONSE_CODE, out iValue);
                if (iValue != 0)
                {
                    resp.ErrorCode = iValue;
                    return(resp);
                }
            }
            catch
            {
            }
            return(resp);
        }
Ejemplo n.º 33
0
        private void GetRequiredPropertiesForAllType(string sourcePath, string parentFolderId, out IPortableDeviceValues values)
        {
            values = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValues();

            values.SetStringValue(ref GlobalVar.WPD_OBJECT_NAME, Path.GetFileNameWithoutExtension(sourcePath));           //File name without extension
            values.SetStringValue(ref GlobalVar.WPD_OBJECT_ORIGINAL_FILE_NAME, Path.GetFileName(sourcePath));             //Full file name
            values.SetStringValue(ref GlobalVar.WPD_OBJECT_PARENT_ID, parentFolderId);                                    //ParentID
            values.SetUnsignedLargeIntegerValue(ref GlobalVar.WPD_OBJECT_SIZE, (ulong)(new FileInfo(sourcePath).Length)); //File size
        }
Ejemplo n.º 34
0
        public MTPDataResponse ExecuteReadBigData(uint code, TransferCallback callback, params uint[] parameters)
        {
            MTPDataResponse res = new MTPDataResponse();

            // source: http://msdn.microsoft.com/en-us/library/windows/desktop/ff384843(v=vs.85).aspx
            // and view-source:http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_26860397.html
            // error codes http://msdn.microsoft.com/en-us/library/windows/desktop/dd319335(v=vs.85).aspx
            byte[] imgdate = new byte[8];

            IPortableDeviceValues commandValues = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValuesClass();
            IPortableDeviceValues pParameters   = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValues();

            IPortableDevicePropVariantCollection propVariant =
                (IPortableDevicePropVariantCollection) new PortableDeviceTypesLib.PortableDevicePropVariantCollection();
            IPortableDeviceValues pResults;

            //commandValues.SetGuidValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, ref command.fmtid);
            commandValues.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY,
                                       PortableDevicePKeys.WPD_COMMAND_MTP_EXT_EXECUTE_COMMAND_WITH_DATA_TO_READ.fmtid);
            commandValues.SetUnsignedIntegerValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID,
                                                  PortableDevicePKeys.WPD_COMMAND_MTP_EXT_EXECUTE_COMMAND_WITH_DATA_TO_READ.pid);
            commandValues.SetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ref imgdate[0], (uint)imgdate.Length);

            foreach (uint parameter in parameters)
            {
                tag_inner_PROPVARIANT vparam = new tag_inner_PROPVARIANT();
                UintToPropVariant(parameter, out vparam);
                propVariant.Add(ref vparam);
            }

            commandValues.SetIPortableDevicePropVariantCollectionValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_PARAMS, propVariant);
            commandValues.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_CODE, (uint)code);

            // According to documentation, first parameter should be 0 (see http://msdn.microsoft.com/en-us/library/dd375691%28v=VS.85%29.aspx)
            this.portableDeviceClass.SendCommand(0, commandValues, out pResults);

            try
            {
                int pValue = 0;
                pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
                if (pValue != 0)
                {
                    // check if the device is busy, and after 100 ms seconds try again
                    if (((uint)pValue) == PortableDeviceErrorCodes.ERROR_BUSY)
                    {
                        Thread.Sleep(50);
                        return(ExecuteReadBigData(code, callback, parameters));
                    }
                }
            }
            catch (Exception)
            {
            }
            //string pwszContext = string.Empty;
            //pResults.GetStringValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, out pwszContext);
            //uint cbReportedDataSize = 0;
            //pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_TOTAL_DATA_SIZE, out cbReportedDataSize);


            uint   tmpBufferSize      = 0;
            uint   tmpTransferSize    = 0;
            string tmpTransferContext = string.Empty;

            {
                pResults.GetStringValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, out tmpTransferContext);
                pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_TOTAL_DATA_SIZE, out tmpBufferSize);
                pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPTIMAL_TRANSFER_BUFFER_SIZE, out tmpTransferSize);

                try
                {
                    int pValue;
                    pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
                    if (pValue != 0)
                    {
                        return(null);
                    }
                }
                catch
                {
                }
            }


            pParameters.Clear();
            pResults.Clear();
            uint offset = 0;

            res.Data = new byte[(int)tmpBufferSize];
            bool cont = true;

            do
            {
                if (offset + tmpTransferSize >= tmpBufferSize)
                {
                    cont            = false;
                    tmpTransferSize = (uint)(tmpBufferSize - offset);
                }

                byte[] tmpData = new byte[(int)tmpTransferSize];
                pParameters.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY,
                                         PortableDevicePKeys.WPD_COMMAND_MTP_EXT_READ_DATA.fmtid);
                pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID,
                                                    PortableDevicePKeys.WPD_COMMAND_MTP_EXT_READ_DATA.pid);
                pParameters.SetStringValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, tmpTransferContext);
                pParameters.SetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ref tmpData[0],
                                           (uint)tmpTransferSize);
                pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_TO_READ,
                                                    (uint)tmpTransferSize);
                pParameters.SetIPortableDevicePropVariantCollectionValue(
                    ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_PARAMS, propVariant);


                portableDeviceClass.SendCommand(0, pParameters, out pResults);


                uint cbBytesRead = 0;

                try
                {
                    int pValue = 0;
                    pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
                    if (pValue != 0)
                    {
                        res.ErrorCode = (uint)pValue;
                        return(res);
                    }
                }
                catch (Exception)
                {
                }

                callback((int)tmpBufferSize, (int)offset);

                GCHandle pinnedArray = GCHandle.Alloc(imgdate, GCHandleType.Pinned);
                IntPtr   ptr         = pinnedArray.AddrOfPinnedObject();

                uint dataread = 0;
                pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_READ,
                                                 out dataread);
                pResults.GetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ptr, out cbBytesRead);

                IntPtr tmpPtr = new IntPtr(Marshal.ReadInt64(ptr));

                //Marshal.Copy(tmpPtr, res.Data, (int)offset, (int)cbBytesRead);

                for (int i = 0; i < cbBytesRead; i++)
                {
                    res.Data[offset + i] = Marshal.ReadByte(tmpPtr, i);
                }

                Marshal.FreeHGlobal(tmpPtr);
                pinnedArray.Free();

                offset += cbBytesRead;
            } while (cont);

            pParameters.Clear();
            pResults.Clear();
            {
                pParameters.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_END_DATA_TRANSFER.fmtid);
                pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_END_DATA_TRANSFER.pid);
                pParameters.SetStringValue(PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, tmpTransferContext);
            }

            portableDeviceClass.SendCommand(0, pParameters, out pResults);

            try
            {
                int tmpResult = 0;

                pResults.GetErrorValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out tmpResult);
                if (tmpResult != 0)
                {
                }
            }
            catch
            {
            }
            return(res);
        }
Ejemplo n.º 35
0
        private void GetRequiredPropertiesForFolderType(string folderName, string parentFolderId, out IPortableDeviceValues values)
        {
            values = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValues();

            values.SetStringValue(ref GlobalVar.WPD_OBJECT_NAME, Path.GetFileNameWithoutExtension(folderName));     //Folder name
            values.SetStringValue(ref GlobalVar.WPD_OBJECT_PARENT_ID, parentFolderId);                              //ParentID
            values.SetGuidValue(ref GlobalVar.WPD_OBJECT_CONTENT_TYPE, ref GlobalVar.WPD_CONTENT_TYPE_FOLDER_GUID); //Folder type
        }
Ejemplo n.º 36
0
 private Command(PropertyKey commandKey)
 {
     this.values = (IPortableDeviceValues) new PortableDeviceValues();
     this.values.SetGuidValue(ref WPD.PROPERTY_COMMON_COMMAND_CATEGORY, ref commandKey.fmtid);
     this.values.SetUnsignedIntegerValue(ref WPD.PROPERTY_COMMON_COMMAND_ID, commandKey.pid);
 }
Ejemplo n.º 37
0
 /// <summary>
 /// プロパティ値から、符号付き 32 ビット整数値を読み取ります。
 /// </summary>
 /// <param name="key">識別子。</param>
 /// <param name="values">プロパティ値。</param>
 /// <returns>成功時は読み取った値。それ以外は null。</returns>
 public static int? ReadInt32( _tagpropertykey key, IPortableDeviceValues values )
 {
     try
     {
         int value;
         values.GetSignedIntegerValue( key, out value );
         return value;
     }
     catch( Exception exp )
     {
         Debug.WriteLine( exp.Message );
         return null;
     }
 }
Ejemplo n.º 38
0
        /// <summary>
        /// データ送信を伴うMTPオペレーションを実行する
        /// </summary>
        /// <param name="device"></param>
        /// <param name="code"></param>
        /// <param name="param"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private static MtpResponse executeDataWriteCommand(PortableDevice device, ushort code, uint[] param, byte[] data, bool noReadResponseParam)
        {
            int    ret = 1;
            string context;
            uint   writtenSize;
            uint   responseCode;

            uint[] responseParam;
            IPortableDeviceValues spResults;

            // MTPコマンドとパラメータを構築する
            IPortableDeviceValues mtpCommand = createMtpCommand(code, WpdProperty.WPD_COMMAND_MTP_EXT_EXECUTE_COMMAND_WITH_DATA_TO_WRITE);
            IPortableDevicePropVariantCollection mtpCommandParam = null;

            if (param != null)
            {
                mtpCommandParam = createMtpCommandParameter(param);
                mtpCommand.SetIPortableDevicePropVariantCollectionValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_OPERATION_PARAMS, mtpCommandParam);
            }
            // 送信するデータのサイズを設定する
            mtpCommand.SetUnsignedLargeIntegerValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_TOTAL_DATA_SIZE, (ulong)data.Length);
            // リクエストを送信
            device.SendCommand(0, mtpCommand, out spResults);
            // コマンドとパラメータは以後不要なので解放
            if (mtpCommandParam != null)
            {
                Marshal.ReleaseComObject(mtpCommandParam);
            }
            Marshal.ReleaseComObject(mtpCommand);
            // リクエストの結果を取得する
            spResults.GetErrorValue(ref WpdProperty.WPD_PROPERTY_COMMON_HRESULT, out ret);
            if (ret != 0)
            {   // エラーなら終了
                Marshal.ReleaseComObject(spResults);
                return(new MtpResponse(0, null, null));
            }
            // contextを取得する
            spResults.GetStringValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, out context);
            Marshal.ReleaseComObject(spResults);

            // データ送信用のコマンドを構築する
            mtpCommand = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValues();
            mtpCommand.SetGuidValue(ref WpdProperty.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, ref WpdProperty.WPD_COMMAND_MTP_EXT_WRITE_DATA.fmtid);
            mtpCommand.SetUnsignedIntegerValue(ref WpdProperty.WPD_PROPERTY_COMMON_COMMAND_ID, WpdProperty.WPD_COMMAND_MTP_EXT_WRITE_DATA.pid);
            mtpCommand.SetStringValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, context);
            mtpCommand.SetUnsignedIntegerValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_TO_WRITE, (uint)data.Length);
            mtpCommand.SetBufferValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ref data[0], (uint)data.Length);
            // データを送信する
            device.SendCommand(0, mtpCommand, out spResults);
            Marshal.ReleaseComObject(mtpCommand);
            // データ送信の結果を取得する
            spResults.GetErrorValue(ref WpdProperty.WPD_PROPERTY_COMMON_HRESULT, out ret);
            if (ret != 0)
            {   // エラーなら終了
                Marshal.ReleaseComObject(spResults);
                if (mtpCommandParam != null)
                {
                    Marshal.ReleaseComObject(mtpCommandParam);
                }
                return(new MtpResponse(0, null, null));
            }
            // デバイスが受け取ったデータサイズを取得する
            spResults.GetUnsignedIntegerValue(ref WpdProperty.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_WRITTEN, out writtenSize);
            Marshal.ReleaseComObject(spResults);

            // DataEndTransfer(レスポンス)を送信する
            sendEndDataTransfer(device, context, out responseCode, out responseParam, noReadResponseParam);

            return(new MtpResponse((ushort)responseCode, responseParam, null));
        }
Ejemplo n.º 39
0
 /// <summary>
 /// プロパティ値から、GUID 値を読み取ります。
 /// </summary>
 /// <param name="key">識別子。</param>
 /// <param name="values">プロパティ値。</param>
 /// <returns>成功時は読み取った値。それ以外は null。</returns>
 public static Guid? ReadGuid( _tagpropertykey key, IPortableDeviceValues values )
 {
     try
     {
         Guid value;
         values.GetGuidValue( key, out value );
         return value;
     }
     catch( Exception exp )
     {
         Debug.WriteLine( exp.Message );
         return null;
     }
 }
Ejemplo n.º 40
0
        /// <summary>
        /// Sets the values of multiple properties.
        /// </summary>
        /// <param name="data">The keys and values of properties to set.</param>
        /// <returns>The new values of the properties. Actual values may not match requested values.</returns>
        public IDictionary <PropertyKey, object> SetProperties(DataFieldInfo[] data)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("data", "Data field array must not be null or empty.");
            }

            IPortableDeviceValues pdv = new PortableDeviceValues();

            for (int i = 0; i < data.Length; i++)
            {
                PropertyKey propKey = data[i].Key;
                object      value   = data[i].Value;
                if (value == null)
                {
                    throw new ArgumentNullException("data", String.Format("Data contains a null value at index {0}", i));
                }

                if (value is string)
                {
                    pdv.SetStringValue(ref propKey, (string)value);
                }
                else if (value is uint)
                {
                    pdv.SetUnsignedIntegerValue(ref propKey, (uint)value);
                }
                else if (value is int)
                {
                    pdv.SetSignedIntegerValue(ref propKey, (int)value);
                }
                else if (value is ulong)
                {
                    pdv.SetUnsignedLargeIntegerValue(ref propKey, (ulong)value);
                }
                else if (value is long)
                {
                    pdv.SetSignedLargeIntegerValue(ref propKey, (long)value);
                }
                else if (value is float || value is double)
                {
                    pdv.SetFloatValue(ref propKey, (float)value);
                }
                else if (value is bool)
                {
                    pdv.SetBoolValue(ref propKey, ((bool)value) ? 1 : 0);
                }
                else if (value is Guid)
                {
                    Guid guid = (Guid)value;
                    pdv.SetGuidValue(ref propKey, ref guid);
                }
                else if (value is byte[])
                {
                    byte[] buffer = (byte[])value;
                    pdv.SetBufferValue(ref propKey, buffer, (uint)buffer.Length);
                }
                else
                {
                    pdv.SetIUnknownValue(ref propKey, value);
                }
            }

            IPortableDeviceValues pdv2 = null;

            _iSensor.SetProperties(pdv, out pdv2);

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

            if (pdv2 == null)
            {
                return(results);
            }

            uint count = 0;

            pdv2.GetCount(ref count);

            for (uint i = 0; i < count; i++)
            {
                PropertyKey propKey = new PropertyKey();
                PROPVARIANT propVal = new PROPVARIANT();
                try
                {
                    pdv2.GetAt(i, ref propKey, out propVal);
                    results.Add(propKey, propVal.Value);
                }
                finally
                {
                    propVal.Clear();
                }
            }

            return(results);
        }
Ejemplo n.º 41
0
        public IDictionary <PropertyKey, object> SetProperties(DataFieldInfo[] data)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("data", "Data field array must not be null or empty.");
            }

            IPortableDeviceValues pdv = new PortableDeviceValues( );

            for (int i = 0; i < data.Length; i++)
            {
                PropertyKey propKey = data[i].Key;
                object      value   = data[i].Value;
                if (value == null)
                {
                    throw new ArgumentNullException("data", String.Format("Data contains a null value at index {0}", i));
                }

                PropVariant pv = new PropVariant();
                try
                {
                    // PropVariant.FromObject will throw an ArgumentException if the value can
                    // not be converted to an appropriate PropVariant.
                    pv = PropVariant.FromObject(value);
                    pdv.SetValue(ref propKey, ref pv);
                }
                catch (ArgumentException)
                {
                    if (value is Guid)
                    {
                        Guid guid = (Guid)value;
                        pdv.SetGuidValue(ref propKey, ref guid);
                    }
                    else if (value is byte[])
                    {
                        byte[] buffer = (byte[])value;
                        pdv.SetBufferValue(ref propKey, buffer, (uint)buffer.Length);
                    }
                    else
                    {
                        pdv.SetIUnknownValue(ref propKey, value);
                    }
                }
                finally
                {
                    pv.Clear();
                }
            }

            Dictionary <PropertyKey, object> results = new Dictionary <PropertyKey, object>( );
            IPortableDeviceValues            pdv2    = null;
            HRESULT hr = nativeISensor.SetProperties(pdv, out pdv2);

            if (hr == HRESULT.S_OK)
            {
                try
                {
                    uint count = 0;
                    pdv2.GetCount(ref count);

                    for (uint i = 0; i < count; i++)
                    {
                        PropertyKey propKey = new PropertyKey();
                        PropVariant propVal = new PropVariant();
                        try
                        {
                            pdv2.GetAt(i, ref propKey, ref propVal);
                            results.Add(propKey, propVal.Value);
                        }
                        finally
                        {
                            propVal.Clear( );
                        }
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(pdv2);
                    pdv2 = null;
                }
            }

            return(results);
        }
Ejemplo n.º 42
0
 public DeviceManager()
 {
     _hPortableDeviceManager = new PortableDeviceManager();
     _hClientDeviceValues    = ClientValues;
 }
Ejemplo n.º 43
0
 public static void WriteObject(IPortableDeviceValues values)
 {
     InternalWriteObject(values);
 }
Ejemplo n.º 44
0
 public virtual extern void Open([In, MarshalAs(UnmanagedType.LPWStr)] string pszPnPDeviceID, [In, MarshalAs(UnmanagedType.Interface)] IPortableDeviceValues pClientInfo);
Ejemplo n.º 45
0
        private static void InternalWriteObject(IPortableDeviceValues values)
        {
            string func = new StackTrace().GetFrame(2).GetMethod().Name;

            Trace.WriteLine($"############################### {func}");
            uint num = 0;

            values.GetCount(ref num);
            for (uint i = 0; i < num; i++)
            {
                PropertyKey       key = new PropertyKey();
                PropVariantFacade val = new PropVariantFacade();
                values.GetAt(i, ref key, ref val.Value);

                string    fieldName = string.Empty;
                FieldInfo propField = FindPropertyKeyField(key);
                if (propField != null)
                {
                    fieldName = propField.Name;
                }
                else
                {
                    FieldInfo guidField = FindGuidField(key.fmtid);
                    if (guidField != null)
                    {
                        fieldName = $"{guidField.Name}, {key.pid}";
                    }
                    else
                    {
                        fieldName = $"{key.fmtid}, {key.pid}";
                    }
                }


                //string fieldName = string.Empty; // field?.Name ?? $"{key.fmtid}, {key.pid}";
                //if (field?.Name == null)
                //{
                //    if (key.fmtid == WPD.PROPERTIES_MTP_VENDOR_EXTENDED_DEVICE_PROPS)
                //    {

                //    }
                //    else
                //    {
                //        fieldName = $"{key.fmtid}, {key.pid}";
                //    }
                //}
                //else
                //{
                //    fieldName = field.Name;
                //}
                switch (val.VariantType)
                {
                case PropVariantType.VT_CLSID:
                    Trace.WriteLine($"##### {fieldName} = {FindGuidField(val.ToGuid())?.Name ?? val.ToString()}");
                    break;

                default:
                    Trace.WriteLine($"##### {fieldName} = {val.ToString()}");
                    break;
                }
            }
        }
Ejemplo n.º 46
0
        private void GetRequiredPropertiesForFolder(string parentObjectId, string folderName, ref IPortableDeviceValues ppObjectProperties)
        {
            ppObjectProperties.SetStringValue(ref PortableDevicePropertyKeys.WPD_OBJECT_PARENT_ID, parentObjectId);
            ppObjectProperties.SetStringValue(ref PortableDevicePropertyKeys.WPD_OBJECT_NAME, folderName);
            ppObjectProperties.SetStringValue(ref PortableDevicePropertyKeys.WPD_OBJECT_ORIGINAL_FILE_NAME, folderName);

            ppObjectProperties.SetGuidValue(ref PortableDevicePropertyKeys.WPD_OBJECT_CONTENT_TYPE, ref PortableDeviceConstants.WPD_CONTENT_TYPE_FOLDER);
        }
Ejemplo n.º 47
0
 public virtual extern void GetnativeIPortableDeviceValuesValue([In] ref PropertyKey key, [MarshalAs(UnmanagedType.Interface)] out IPortableDeviceValues ppValue);