示例#1
0
        private Command(PropertyKey commandKey)
        {
            this.values = (IPortableDeviceValues) new PortableDeviceValues();

            this.values.SetGuidValue(WPD.PROPERTY_COMMON_COMMAND_CATEGORY, commandKey.fmtid);
            this.values.SetUnsignedIntegerValue(WPD.PROPERTY_COMMON_COMMAND_ID, commandKey.pid);
        }
示例#2
0
        /// <summary>
        /// Construct the device by obtainin the device properties and the sub data.
        ///
        /// NOTE:
        /// There is a difference with the device id and the id.
        /// The id indicates the object id within the windows portable device.
        /// The device id indicates the object id within the operating system.
        ///
        /// The initial id for all windows portable devices is hard coded to "DEVICE"
        /// </summary>
        /// <param name="deviceId"></param>
        public Device(string deviceId, bool withDeviceItems = true) : base("DEVICE")
        {
            DeviceId        = deviceId;
            ComDeviceObject = new PortableDeviceClass();
            Connect();
            IPortableDeviceValues deviceProperties = ExtractDeviceProperties(ComDeviceObject);

            ContentType     = new ContentTypeProperty(deviceProperties);
            DeviceType      = new TypeProperty(deviceProperties);
            FirmwareVersion = new FirmwareVersionProperty(deviceProperties);
            FriendlyName    = new FriendlyNameProperty(deviceProperties);
            Manufacturer    = new ManufacturerProperty(deviceProperties);
            Model           = new ModelProperty(deviceProperties);
            Name            = new NameProperty(deviceProperties);
            SerialNumber    = new SerialNumberProperty(deviceProperties);

            if (withDeviceItems == true)
            {
                LoadDeviceData(ComDeviceObject);

                do
                {
                    System.Threading.Thread.Sleep(100);
                } while (UtilityHelper.threadList.Count > 0);
            }
            Disconnect();
        }
        private static PortableDeviceFolder CreateOneFolder(PortableDevice portableDevice, PortableDeviceFolder parentFolder,
                                                            string folderName)
        {
            if (portableDevice == null || !portableDevice.IsConnected)
            {
                throw new ArgumentNullException(nameof(portableDevice));
            }
            if (parentFolder == null)
            {
                throw new ArgumentNullException(nameof(parentFolder));
            }
            if (string.IsNullOrEmpty(folderName))
            {
                throw new ArgumentNullException(nameof(folderName));
            }

            IPortableDeviceValues values =
                GetRequiredPropertiesForContentType(folderName, parentFolder.Id);

            if (values == null)
            {
                throw new Exception($"Could not set values for creation of folder:{folderName}");
            }
            var newFolderId = parentFolder.Id;

            portableDevice.Content.CreateObjectWithPropertiesOnly(
                values, ref newFolderId);
            return(new PortableDeviceFolder(newFolderId, folderName));
        }
示例#4
0
        /// <summary>
        /// 获取对象名
        /// </summary>
        public string GetObjectName(IPortableDeviceValues objectValues)
        {
            string objectName;

            objectValues.GetStringValue(ref pKey.WPD_OBJECT_NAME, out objectName);
            return(objectName);
        }
示例#5
0
        private void StringToPropVariant(string objectId, out PortableDeviceApiLib.tag_inner_PROPVARIANT pv)
        {
            IPortableDeviceValues values = (PortableDeviceApiLib.IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValues();

            values.SetStringValue(ref pKey.WPD_OBJECT_ID, objectId);
            values.GetValue(ref pKey.WPD_OBJECT_ID, out pv);
        }
示例#6
0
        public void OnEvent(IPortableDeviceValues pEventParameters)
        {
            pEventParameters.GetStringValue(WpdHelper.pKey.WPD_EVENT_PARAMETER_PNP_DEVICE_ID, out deviceId);
            pEventParameters.GetStringValue(WpdHelper.pKey.WPD_EVENT_PARAMETER_EVENT_ID, out eventId);

            if (eventId.Contains(WpdHelper.pGuid.WPD_EVENT_DEVICE_RESET.ToString().ToUpper()) ||
                eventId.Contains(WpdHelper.pGuid.WPD_EVENT_DEVICE_REMOVED.ToString().ToUpper()))
            {
                if (WpdHelper.UnexpectedClosed != null)
                {
                    WpdHelper.UnexpectedClosed();
                }
            }
            else
            {
                /*
                 * if (eventId.Contains(WpdHelper.pGuid.WPD_EVENT_OBJECT_ADDED.ToString().ToUpper()))
                 * {
                 *  eventId = "1";
                 * }
                 * else if (eventId.Contains(WpdHelper.pGuid.WPD_EVENT_OBJECT_REMOVED.ToString().ToUpper()))
                 * {
                 *  eventId = "2";
                 * }
                 * else if (eventId.Contains(WpdHelper.pGuid.WPD_EVENT_OBJECT_UPDATED.ToString().ToUpper()))
                 * {
                 *  eventId = "3";
                 * }
                 * */
            }
        }
        /// <summary>
        ///     Inspired by http://cgeers.com/2012/04/17/wpd-transfer-content-to-a-device/
        /// </summary>
        /// <param name="parentObject"></param>
        /// <param name="sourceStream"></param>
        /// <param name="name"></param>
        /// <param name="originalFileName"></param>
        /// <param name="size"></param>
        public PortableDeviceObject Push(PortableDeviceContainerObject parentObject, Stream sourceStream, string name, string originalFileName, ulong size, PushProgressReport progressReport)
        {
            IPortableDeviceContent content;

            portableDeviceClass.Content(out content);
            IPortableDeviceValues values = GetRequiredPropertiesForPush(parentObject, name, originalFileName, size);

            IStream tempStream;
            uint    optimalTransferSizeBytes = 0;

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

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

            try
            {
                int totalBytesRead = 0;
                if (progressReport != null)
                {
                    progressReport(totalBytesRead);
                }

                var buffer = new byte[optimalTransferSizeBytes];

                int bytesRead;
                do
                {
                    bytesRead = sourceStream.Read(buffer, 0, (int)optimalTransferSizeBytes);
                    IntPtr pcbWritten = IntPtr.Zero;

                    if (bytesRead < (int)optimalTransferSizeBytes)
                    {
                        targetStream.Write(buffer, bytesRead, pcbWritten);
                    }
                    else
                    {
                        targetStream.Write(buffer, (int)optimalTransferSizeBytes, pcbWritten);
                    }

                    totalBytesRead += bytesRead;
                    if (progressReport != null)
                    {
                        progressReport(totalBytesRead);
                    }
                } while (bytesRead > 0);

                targetStream.Commit(0);

                device.Update(ref content, parentObject);

                // TODO There is no IPortableDeviceDataStream in C# port to get ID, so we will make a bicycle
                return(Find("^" + originalFileName + "$", parentObject).First());
            }
            finally
            {
                Marshal.ReleaseComObject(tempStream);
            }
        }
示例#8
0
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="portableDevice"></param>
        /// <param name="parentId"></param>
        public string CreateDirectoryOnDevice(string folderName, string parentId)
        {
            string newFolderId           = "";
            IPortableDeviceValues values = GetRequiredPropertiesForFolder(parentId, folderName);

            this.deviceContent.CreateObjectWithPropertiesOnly(values, ref newFolderId);

            return(newFolderId);
        }
示例#9
0
        public void Connect()
        {
            if (_isConnected)
            {
                return;
            }
            IPortableDeviceValues clientInfo = (IPortableDeviceValues) new PortableDeviceValuesClass();

            PortableDeviceClass.Open(DeviceId, clientInfo);
            _isConnected = true;
        }
示例#10
0
        public void Connect()
        {
            if (this._isConnected)
            {
                return;
            }

            IPortableDeviceValues clientInfo = (IPortableDeviceValues) new PortableDeviceValuesClass();

            this._device.Open(this.DeviceId, clientInfo);
            this._isConnected = true;
        }
示例#11
0
        public void CreateFolder(string fileName, string parentObjectId)
        {
            IPortableDeviceContent content;

            this._device.Content(out content);

            //folder info
            IPortableDeviceValues values = this.GetRequiredPropertiesForContentTypeFolder(fileName, parentObjectId);

            string objectId = "";

            content.CreateObjectWithPropertiesOnly(values, ref objectId);
        }
        /// <summary>
        /// Extract device capabilities
        /// </summary>
        /// <param name="portableDeviceClass"></param>
        internal void ExtractDeviceCapabilities(PortableDeviceClass portableDeviceClass)
        {
            if (portableDeviceClass == null)
            {
                throw new ArgumentNullException("portableDeviceClass");
            }

            try
            {
                PortableDeviceApiLib.IPortableDeviceCapabilities capabilities;
                portableDeviceClass.Capabilities(out capabilities);

                if (capabilities == null)
                {
                    Trace.WriteLine("Cannot extract capabilities from device");
                    throw new PortableDeviceException("Cannot extract capabilities from device");
                }

                IPortableDevicePropVariantCollection functionalCategories;
                capabilities.GetFunctionalCategories(out functionalCategories);

                if (functionalCategories == null)
                {
                    throw new PortableDeviceException("Failed to extract functionnal categories");
                }

                uint countCategories = 1;
                functionalCategories.GetCount(ref countCategories);
                tag_inner_PROPVARIANT values = new tag_inner_PROPVARIANT();

                PortableDeviceApiLib.IPortableDeviceValues pValues = (PortableDeviceApiLib.IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValuesClass();
                string categoryName;
                Guid   currentGuid;
                for (uint i = 0; i < countCategories; i++)
                {
                    functionalCategories.GetAt(i, ref values);

                    pValues.SetValue(ref PortableDevicePKeys.WPD_COMMAND_CAPABILITIES_GET_SUPPORTED_FUNCTIONAL_CATEGORIES, ref values);
                    pValues.GetStringValue(ref PortableDevicePKeys.WPD_COMMAND_CAPABILITIES_GET_SUPPORTED_FUNCTIONAL_CATEGORIES, out categoryName);
                    currentGuid = new Guid(categoryName);
                    this.functionalCategories.Add(currentGuid, new FunctionalCategory(
                                                      portableDeviceClass,
                                                      currentGuid,
                                                      PortableDeviceHelpers.GetKeyNameFromGuid(currentGuid)));
                }
            }
            catch (Exception ex)
            {
                throw new PortableDeviceException("Error on extract device capabilities", ex);
            }
        }
示例#13
0
        private void ExtractContentType(PortableDeviceClass portableDeviceClass, Guid functionalCategory)
        {
            if (portableDeviceClass == null)
            {
                throw new ArgumentNullException("portableDeviceClass");
            }

            try
            {
                PortableDeviceApiLib.IPortableDeviceCapabilities capabilities;
                portableDeviceClass.Capabilities(out capabilities);

                if (capabilities == null)
                {
                    System.Diagnostics.Trace.WriteLine("Cannot extract capabilities from device");
                    throw new PortableDeviceException("Cannot extract capabilities from device");
                }


                PortableDeviceApiLib.IPortableDeviceValues pValues = (PortableDeviceApiLib.IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValuesClass();


                //Functional objects variables
                IPortableDevicePropVariantCollection contentTypes;
                uint countObjects            = 1;
                tag_inner_PROPVARIANT values = new tag_inner_PROPVARIANT();
                string contentTypeName;
                Guid   currentContentTypeGuid;
                capabilities.GetSupportedContentTypes(ref functionalCategory, out contentTypes);

                contentTypes.GetCount(ref countObjects);
                for (uint i = 0; i < countObjects; i++)
                {
                    contentTypes.GetAt(i, ref values);

                    pValues.SetValue(ref PortableDevicePKeys.WPD_COMMAND_CAPABILITIES_GET_SUPPORTED_CONTENT_TYPES, ref values);
                    pValues.GetStringValue(ref PortableDevicePKeys.WPD_COMMAND_CAPABILITIES_GET_SUPPORTED_CONTENT_TYPES, out contentTypeName);
                    currentContentTypeGuid = new Guid(contentTypeName);
                    this.contentTypes.Add(currentContentTypeGuid, new ContentType(
                                              portableDeviceClass,
                                              currentContentTypeGuid,
                                              PortableDeviceHelpers.GetKeyNameFromGuid(currentContentTypeGuid)));
                }
            }
            catch (Exception ex)
            {
                throw new PortableDeviceException("Error on extract functional object", ex);
            }
        }
示例#14
0
        public void TransferContentToDevice(string fileName, string parentObjectId)
        {
            IPortableDeviceContent content;

            this._device.Content(out content);

            IPortableDeviceValues values =
                GetRequiredPropertiesForContentType(fileName, parentObjectId);

            PortableDeviceApiLib.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 (var sourceStream =
                           new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
                    var buffer = new byte[optimalTransferSizeBytes];
                    int bytesRead;
                    do
                    {
                        bytesRead = sourceStream.Read(
                            buffer, 0, (int)optimalTransferSizeBytes);
                        IntPtr pcbWritten = IntPtr.Zero;
                        if (bytesRead < (int)optimalTransferSizeBytes)
                        {
                            targetStream.Write(buffer, bytesRead, pcbWritten);
                        }
                        else
                        {
                            targetStream.Write(buffer, (int)optimalTransferSizeBytes, pcbWritten);
                        }

                        /*targetStream.Write(
                         *      buffer, (int)optimalTransferSizeBytes, pcbWritten);*/
                    } while (bytesRead > 0);
                }
                targetStream.Commit(0);
            } finally {
                Marshal.ReleaseComObject(tempStream);
            }
        }
        public void Connect()
        {
            if (this._isConnected)
            {
                return;
            }

            PortableDeviceApiLib.IPortableDeviceValues portableDeviceValuesClass = (PortableDeviceApiLib.IPortableDeviceValues)(new PortableDeviceValuesClass());

            //added by AA
            if (_device != null && DeviceId != null)
            {
                this._device.Open(this.DeviceId, portableDeviceValuesClass);
                this._isConnected = true;
            }
        }
示例#16
0
        private void uLongIntToPropVariant(ulong value, out PortableDeviceApiLib.tag_inner_PROPVARIANT propvarValue)
        {
            // We'll use an IPortableDeviceValues object to transform the
            // string into a PROPVARIANT
            PortableDeviceApiLib.IPortableDeviceValues pValues =
                (PortableDeviceApiLib.IPortableDeviceValues)
                new PortableDeviceTypesLib.PortableDeviceValuesClass();

            // We insert the string value into the IPortableDeviceValues object
            // using the SetStringValue method
            pValues.SetUnsignedLargeIntegerValue(ref PortableDevicePKeys.WPD_OBJECT_ID, (ulong)value);

            // We then extract the string into a PROPVARIANT by using the
            // GetValue method
            pValues.GetValue(ref PortableDevicePKeys.WPD_OBJECT_ID,
                             out propvarValue);
        }
示例#17
0
        /// <summary>
        /// Construct the device by obtainin the device properties and the sub data.
        ///
        /// NOTE:
        /// There is a difference with the device id and the id.
        /// The id indicates the object id within the windows portable device.
        /// The device id indicates the object id within the operating system.
        ///
        /// The initial id for all windows portable devices is hard coded to "DEVICE"
        /// </summary>
        /// <param name="deviceId"></param>
        public Device(string deviceId) : base("DEVICE")
        {
            DeviceId        = deviceId;
            ComDeviceObject = new PortableDeviceClass();
            Connect();
            IPortableDeviceValues deviceProperties = ExtractDeviceProperties(ComDeviceObject);

            ContentType     = new ContentTypeProperty(deviceProperties);
            DeviceType      = new TypeProperty(deviceProperties);
            FirmwareVersion = new FirmwareVersionProperty(deviceProperties);
            FriendlyName    = new FriendlyNameProperty(deviceProperties);
            Manufacturer    = new ManufacturerProperty(deviceProperties);
            Model           = new ModelProperty(deviceProperties);
            Name            = new NameProperty(deviceProperties);
            SerialNumber    = new SerialNumberProperty(deviceProperties);

            LoadDeviceData(ComDeviceObject);

            Disconnect();
        }
示例#18
0
        private void ExtractSupportedFormat(PortableDeviceClass portableDeviceClass, Guid contentType)
        {
            if (portableDeviceClass == null)
            {
                throw new PortableDeviceException("");
            }

            PortableDeviceApiLib.IPortableDeviceCapabilities capabilities;
            portableDeviceClass.Capabilities(out capabilities);

            if (capabilities == null)
            {
                System.Diagnostics.Trace.WriteLine("Cannot extract capabilities from device");
                throw new PortableDeviceException("Cannot extract capabilities from device");
            }


            PortableDeviceApiLib.IPortableDeviceValues pValues = (PortableDeviceApiLib.IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValuesClass();


            //Functional objects variables
            IPortableDevicePropVariantCollection formats;
            uint countObjects            = 1;
            tag_inner_PROPVARIANT values = new tag_inner_PROPVARIANT();
            string formatName;
            Guid   currentFormat;

            capabilities.GetSupportedFormats(ref contentType, out formats);

            formats.GetCount(ref countObjects);
            for (uint i = 0; i < countObjects; i++)
            {
                formats.GetAt(i, ref values);

                pValues.SetValue(ref PortableDevicePKeys.WPD_COMMAND_CAPABILITIES_GET_SUPPORTED_FORMATS, ref values);
                pValues.GetStringValue(ref PortableDevicePKeys.WPD_COMMAND_CAPABILITIES_GET_SUPPORTED_FORMATS, out formatName);
                currentFormat = new Guid(formatName);
                this.formats.Add(currentFormat, PortableDeviceHelpers.GetKeyNameFromGuid(currentFormat));
            }
        }
示例#19
0
        /// <summary>
        /// 连接设备
        /// </summary>
        public bool Connect(string DeviceId)
        {
            bool bRet = true;

            try
            {
                IPortableDeviceValues clientInfo = (IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValues();
                portableDevice = new PortableDevice();
                portableDevice.Open(DeviceId, clientInfo);
                portableDevice.Content(out deviceContent);
                deviceContent.Properties(out deviceProperties);
                deviceProperties.GetValues("DEVICE", null, out deviceValues);

                AdviceEvent();
            }
            catch (Exception)
            {
                bRet = false;
            }

            return(bRet);
        }
示例#20
0
        internal Item CreateSubdirectory(string path)
        {
            Item child   = null;
            Item parent  = this;
            var  folders = path.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var folder in folders)
            {
                child = parent.GetChildren().FirstOrDefault(i => device.EqualsName(i.Name, folder));
                if (child == null)
                {
                    // create a new directory
                    IPortableDeviceValues deviceValues = (IPortableDeviceValues) new PortableDeviceValues();
                    deviceValues.SetStringValue(ref WPD.OBJECT_PARENT_ID, parent.Id);
                    deviceValues.SetStringValue(ref WPD.OBJECT_NAME, folder);
                    deviceValues.SetStringValue(ref WPD.OBJECT_ORIGINAL_FILE_NAME, folder);
                    deviceValues.SetGuidValue(ref WPD.OBJECT_CONTENT_TYPE, ref WPD.CONTENT_TYPE_FOLDER);
                    string id = string.Empty;
                    this.device.deviceContent.CreateObjectWithPropertiesOnly(deviceValues, ref id);
                    child = Item.Create(this.device, id, parent.FullName);
                }
                else if (child.Type == ItemType.File)
                {
                    // folder is already a file
                    throw new Exception($"A path of the path {folder} is a file");
                }
                else
                {
                    // folder exists
                    //id = child.Id;
                    //new Item()

                    // TODO
                }
                parent = child;
            }
            return(child);
        }
示例#21
0
        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="parentId"></param>
        public bool TransferContentToDevice(string sourceFile, string parentId)
        {
            bool bRet = true;
            IPortableDeviceValues values = GetRequiredPropertiesForContentType(sourceFile, parentId);

            PortableDeviceApiLib.IStream tempStream = null;
            uint optimalTransferSize = 0;

            try
            {
                deviceContent.CreateObjectWithPropertiesAndData(values, out tempStream, ref optimalTransferSize, null);
                System.Runtime.InteropServices.ComTypes.IStream targetStream = (System.Runtime.InteropServices.ComTypes.IStream)tempStream;

                using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
                {
                    int    filesize   = (int)optimalTransferSize;
                    int    bytesRead  = 0;
                    IntPtr pcbWritten = IntPtr.Zero;
                    do
                    {
                        byte[] buffer = new byte[filesize];
                        bytesRead = sourceStream.Read(buffer, 0, filesize);
                        targetStream.Write(buffer, bytesRead, pcbWritten);
                    }while (bytesRead > 0);
                }
                targetStream.Commit(0);
            }
            catch (Exception)
            {
                bRet = false;
            }
            finally
            {
                Marshal.ReleaseComObject(tempStream);
            }

            return(bRet);
        }
示例#22
0
        public static void WriteObject(IPortableDeviceValues values)
        {
            uint num = 0;

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

                Type twpd   = typeof(WPD);
                var  fields = twpd.GetFields().Where(f => f.FieldType == typeof(PropertyKey)).ToList();
                foreach (var field in fields)
                {
                    PropertyKey pk = (PropertyKey)field.GetValue(null);
                    if (pk.pid == key.pid && pk.fmtid == key.fmtid)
                    {
                        Trace.WriteLine($"##### {field.Name} = {((PropVariant)val).ToString()}");
                    }
                }
            }
        }
示例#23
0
        // UPLOAD file
        public bool UploadFileToWPD(string fileName, string parentObjectId)
        {
            bool success = false;
            IPortableDeviceContent content;

            this._device.Content(out content);
            IPortableDeviceValues values = this.GetRequiredPropertiesForContentType(fileName, parentObjectId);

            PortableDeviceApiLib.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(fileName, FileMode.Open, FileAccess.Read)) {
                    byte[] buffer = new byte[optimalTransferSizeBytes];
                    int    bytesRead;
                    do
                    {
                        bytesRead = sourceStream.Read(buffer, 0, (int)optimalTransferSizeBytes);
                        IntPtr pcbWritten = IntPtr.Zero;
                        if (bytesRead > 0)
                        {
                            targetStream.Write(buffer, bytesRead, pcbWritten);
                        }
                    } while (bytesRead > 0);
                }
                targetStream.Commit(0);
                success = true;
            } catch {
                success = false;
            } finally {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(tempStream);
            }
            return(success);
        }
        internal void CopyToDevice(string source, string destination, bool overwrite)
        {
            IPortableDeviceContent content;

            ComDeviceObject.Content(out content);
            string parentObjectId = null;

            FindParentObjectId(Path.GetDirectoryName(destination), ref parentObjectId);
            if (string.IsNullOrEmpty(parentObjectId))
            {
                throw new Exception("destination folder has not been found.");
            }

            IPortableDeviceValues values =
                GetRequiredPropertiesForContentType(source, destination, parentObjectId);

            PortableDeviceApiLib.IStream wpdStream = null;
            uint optimalTransferSize = 0;

            content.CreateObjectWithPropertiesAndData(
                values,
                out wpdStream,
                ref optimalTransferSize,
                null);
            System.Runtime.InteropServices.ComTypes.IStream targetStream = null;
            try
            {
                targetStream = (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;
                FileStream sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read);
                unsafe
                {
                    try
                    {
                        var buffer = new byte[optimalTransferSize];
                        int bytesRead;
                        do
                        {
                            bytesRead = sourceStream.Read(buffer, 0, (int)optimalTransferSize);
                            IntPtr pcbWritten = IntPtr.Zero;
                            if (bytesRead < (int)optimalTransferSize)
                            {
                                targetStream.Write(buffer, bytesRead, pcbWritten);
                            }
                            else
                            {
                                targetStream.Write(buffer, (int)optimalTransferSize, pcbWritten);
                            }
                        } while (bytesRead > 0);
                        targetStream.Commit(0);
                    }
                    catch (ArgumentException e)
                    {
                        throw new Exception("Some argument has problem, remember this API can't overwrite" +
                                            "file on the device side! message: " + e.Message);
                    }
                    finally
                    {
                        sourceStream.Close();
                    }
                }
            }
            finally
            {
                Marshal.ReleaseComObject(wpdStream);
                Marshal.ReleaseComObject(targetStream);
            }
        }
示例#25
0
        // COPY inside of the same WPD
        public bool CopyInsideWPD2(PortableDeviceFile file, string parentObjectId)
        {
            bool success = false;

            // WPD source
            IPortableDeviceContent contentSrc;

            this._device.Content(out contentSrc);
            IPortableDeviceResources resourcesSrc;

            contentSrc.Transfer(out resourcesSrc);
            PortableDeviceApiLib.IStream wpdStreamSrc;
            uint            optimalTransferSizeSrc = 0;
            _tagpropertykey propertySrc            = new _tagpropertykey();

            propertySrc.fmtid = new Guid(0xE81E79BE, 0x34F0, 0x41BF, 0xB5, 0x3F, 0xF1, 0xA0, 0x6A, 0xE8, 0x78, 0x42);
            propertySrc.pid   = 0;
            resourcesSrc.GetStream(file.Id, ref propertySrc, 0, ref optimalTransferSizeSrc, out wpdStreamSrc);
            System.Runtime.InteropServices.ComTypes.IStream streamSrc = (System.Runtime.InteropServices.ComTypes.IStream)wpdStreamSrc;

            // WPD destination
            IPortableDeviceContent contentDst;

            this._device.Content(out contentDst);
            IPortableDeviceValues values = this.GetRequiredPropertiesForCopyWPD(file, parentObjectId);

            PortableDeviceApiLib.IStream tempStream;
            uint optimalTransferSizeBytes = 0;

            contentDst.CreateObjectWithPropertiesAndData(values, out tempStream, ref optimalTransferSizeBytes, null);
            System.Runtime.InteropServices.ComTypes.IStream streamDst = (System.Runtime.InteropServices.ComTypes.IStream)tempStream;

            try {
                unsafe {
                    byte[] buffer = new byte[1024];
                    int    bytesRead;
                    do
                    {
                        // read from source
                        streamSrc.Read(buffer, 1024, new IntPtr(&bytesRead));

                        // write to destination
                        IntPtr pcbWritten = IntPtr.Zero;
                        if (bytesRead > 0)
                        {
                            streamDst.Write(buffer, bytesRead, pcbWritten);
                        }
                    } while (bytesRead > 0);
                }
                success = true;
                streamDst.Commit(0);
            } catch (Exception) {
                success = false;
            } finally {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(tempStream);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(streamSrc);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wpdStreamSrc);
            }

            return(success);
        }
        /// <summary>
        /// Extract event supported by device
        /// </summary>
        /// <param name="portableDeviceClass"></param>
        internal void ExtractEvents(PortableDeviceClass portableDeviceClass)
        {
            PortableDeviceApiLib.IPortableDeviceCapabilities capabilities;
            portableDeviceClass.Capabilities(out capabilities);

            PortableDeviceApiLib.IPortableDevicePropVariantCollection events;
            capabilities.GetSupportedEvents(out events);

            uint countEvents = 0;

            events.GetCount(ref countEvents);

            PortableDeviceApiLib.IPortableDeviceValues pValues = (PortableDeviceApiLib.IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValuesClass();
            tag_inner_PROPVARIANT evt = new tag_inner_PROPVARIANT();

            Guid eventName;
            IPortableDeviceValues          eventOptions;
            PortableDeviceEventDescription eventDescription;

            for (uint i = 0; i < countEvents; i++)
            {
                events.GetAt(i, ref evt);
                pValues.SetValue(ref PortableDevicePKeys.WPD_EVENT_PARAMETER_EVENT_ID, ref evt);
                pValues.GetGuidValue(ref PortableDevicePKeys.WPD_EVENT_PARAMETER_EVENT_ID, out eventName);

                eventDescription = new PortableDeviceEventDescription(eventName, PortableDeviceHelpers.GetKeyNameFromGuid(eventName));

                //Retrieve options
                try
                { // Event option isn't always present, so ...
                    eventOptions = (PortableDeviceApiLib.IPortableDeviceValues) new PortableDeviceTypesLib.PortableDeviceValuesClass();
                    capabilities.GetEventOptions(ref eventName, out eventOptions);



                    //eventOptions.GetBoolValue(ref PortableDevicePKeys.WPD_EVENT_OPTION_IS_AUTOPLAY_EVENT, out isAutoPlayEvent);
                    //eventOptions.GetBoolValue(ref PortableDevicePKeys.WPD_EVENT_OPTION_IS_BROADCAST_EVENT, out isBroadcastEvent);

                    //eventDescription.AddOptions(new PortableDeviceEventOption()
                    //{
                    //    Guid = PortableDevicePKeys.WPD_EVENT_OPTION_IS_BROADCAST_EVENT.fmtid,
                    //    Name = PortableDeviceHelpers.GetKeyNameFromGuid(PortableDevicePKeys.WPD_EVENT_OPTION_IS_BROADCAST_EVENT.fmtid),
                    //    Value = isBroadcastEvent,
                    //    ValueType = TypeCode.Boolean
                    //});

                    //eventDescription.AddOptions(new PortableDeviceEventOption()
                    //{
                    //    Guid = PortableDevicePKeys.WPD_EVENT_OPTION_IS_AUTOPLAY_EVENT.fmtid,
                    //    Name = PortableDeviceHelpers.GetKeyNameFromGuid(PortableDevicePKeys.WPD_EVENT_OPTION_IS_AUTOPLAY_EVENT.fmtid),
                    //    Value = isAutoPlayEvent,
                    //    ValueType = TypeCode.Boolean
                    //});
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    Debug.WriteLine(ex.StackTrace);
                }

                this.events.Add(eventDescription, PortableDevicePKeys.WPD_EVENT_PARAMETER_EVENT_ID);
            }
        }
示例#27
0
        /**
         * Copy To Phone
         */
        public void TransferContentToDevice(PortableDeviceFolder parentFolder, string filePath)
        {
            PortableDeviceApiLib.IStream tempStream = null;
            System.Runtime.InteropServices.ComTypes.IStream targetStream = null;
            try
            {
                string fileName = PortableDeviceFolder.last(filePath, "\\");

                // Remove existing remote file, if it exists.
                parentFolder.DeleteFile(this, fileName);

                // make sure that we are not holding on to a file.
                DisconnectConnect();

                string parentObjectId = parentFolder.Id;

                IPortableDeviceContent content = getContents();
                IPortableDeviceValues  values  = GetRequiredPropertiesForContentType(filePath, parentObjectId);

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

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

                long length  = new System.IO.FileInfo(filePath).Length;
                long written = 0;
                long lPCt    = 0;

                using (var sourceStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    var buffer = new byte[optimalTransferSizeBytes];
                    int bytesRead;
                    do
                    {
                        bytesRead = sourceStream.Read(buffer, 0, (int)optimalTransferSizeBytes);
                        IntPtr PCbWritten = IntPtr.Zero;
                        targetStream.Write(buffer, bytesRead, PCbWritten);

                        written += bytesRead;
                        long PCt = length > 0 ? (100 * written) / length : 100;
                        if (PCt != lPCt)
                        {
                            lPCt = PCt;
                            Console.WriteLine("Progress: " + lPCt);
                        }
                    } while (bytesRead > 0);
                }
                targetStream.Commit(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
            finally
            {
                if (null != targetStream)
                {
                    Marshal.ReleaseComObject(targetStream);
                }
                if (null != tempStream)
                {
                    Marshal.ReleaseComObject(tempStream);
                }
                Disconnect();
            }
        }