public void StartTransfer(Transfer transfer, TransferOptions options, TransferCallback callback)
        {
            if (!_collection.contains(transfer))
            {
                if (_collection.size() > _preferences.getInteger("queue.size.warn"))
                {
                    CommandBox(LocaleFactory.localizedString("Clean Up"),
                               LocaleFactory.localizedString("Remove completed transfers from list."), null,
                               LocaleFactory.localizedString("Clean Up"), true,
                               LocaleFactory.localizedString("Don't ask again", "Configuration"), TaskDialogIcon.Question,
                               delegate(int option, bool verificationChecked)
                    {
                        if (verificationChecked)
                        {
                            // Never show again.
                            _preferences.setProperty("queue.size.warn", int.MaxValue);
                        }
                        switch (option)
                        {
                        case 0:         // Clean Up
                            View_CleanEvent();
                            break;
                        }
                    });
                }
                _collection.add(transfer);
            }
            ProgressController progressController;

            _transferMap.TryGetValue(transfer, out progressController);
            PathCache cache = new PathCache(_preferences.getInteger("transfer.cache.size"));

            background(new TransferBackgroundAction(this, transfer.withCache(cache), options, callback, cache, progressController));
        }
        private void InvokeBackofficeCallback(EthereumTransfer transfer, CancellationToken cancellationToken)
        {
            TransferResult transferResult = null;

            do
            {
                try
                {
                    var backofficeRequest = _backofficeTransferHelper.CreateBackofficeTransferRequest(transfer, _options.ConfirmationsRequired);

                    transferResult = TransferCallback.Invoke(backofficeRequest);

                    if (transferResult.HasException)
                    {
                        throw transferResult.Exception;
                    }

                    LogInfo("Withdrawal transfer {@TransferId} with assetId = {@AssetId} and amountEth = {@Amount} to {@ToAddress} failed to be sent",
                            backofficeRequest.TransferId,
                            backofficeRequest.AssetId, backofficeRequest.Amount, backofficeRequest.TargetAccount);
                }
                catch (Exception ex)
                {
                    LogError(ex, "TransferCallback.Invoke failed");
                }
            } while (transferResult == null && !cancellationToken.WaitHandle.WaitOne(InvokeTransferCallbackRetryIntervalMs));
        }
Example #3
0
        public void TestAudioUpload()
        {
            UploadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MediaPlayerClips, helper =>
            {
                helper.DisposeSdkClient = true;

                var pidCmd = helper.Server.GetParsedDataDump().OfType <ProductIdentifierCommand>().Single();

                IBMDSwitcherMediaPool pool = GetMediaPool(helper);

                for (int i = 0; i < 3; i++)
                {
                    AtemState stateBefore = helper.Helper.BuildLibState();
                    uint index            = Randomiser.RangeInt((uint)stateBefore.MediaPool.Clips.Count);
                    IBMDSwitcherClip clip = GetClip(helper, index);

                    uint sampleCount = 10000;

                    string name = Guid.NewGuid().ToString();
                    worker      = new UploadJobWorker(sampleCount * 4, _output,
                                                      index + 1, 0, DataTransferUploadRequestCommand.TransferMode.Write2, false);

                    var cb = new LockCallback();
                    helper.SendAndWaitForChange(stateBefore, () => { clip.Lock(cb); });
                    Assert.True(cb.Wait.WaitOne(2000));

                    byte[] bytes = MediaPoolUtil.RandomFrame(sampleCount);
                    pool.CreateAudio((uint)bytes.Length, out IBMDSwitcherAudio frame);
                    MediaPoolUtil.FillSdkAudio(frame, bytes);

                    var clipState          = stateBefore.MediaPool.Clips[(int)index];
                    clipState.Audio.IsUsed = true;
                    clipState.Audio.Name   = name;

                    var uploadCb = new TransferCallback();
                    clip.AddCallback(uploadCb);
                    clip.UploadAudio(name, frame);

                    helper.HandleUntil(uploadCb.Wait, 5000);
                    Assert.True(uploadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMediaPoolEventType.bmdSwitcherMediaPoolEventTypeTransferCompleted,
                                 uploadCb.Result);

                    // TODO - this needs a better rule that can be properly exposed via the lib
                    byte[] flippedBytes = pidCmd.Model >= ModelId.PS4K
                        ? MediaPoolUtil.FlipAudio(bytes)
                        : bytes;
                    Assert.Equal(BitConverter.ToString(flippedBytes), BitConverter.ToString(worker.Buffer));

                    helper.SendAndWaitForChange(stateBefore, () =>
                    {
                        clip.Unlock(cb);
                    });
                }
            });
        }
Example #4
0
        public void TestUpload()
        {
            UploadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MacroTransfer, helper =>
            {
                helper.DisposeSdkClient = true;

                var pool = helper.SdkClient.SdkSwitcher as IBMDSwitcherMacroPool;
                Assert.NotNull(pool);

                for (int i = 0; i < 5; i++)
                {
                    AtemState stateBefore = helper.Helper.BuildLibState();

                    uint index  = Randomiser.RangeInt((uint)stateBefore.Macros.Pool.Count);
                    string name = Guid.NewGuid().ToString();

                    byte[] op = new CutTransitionMacroOp {
                        Index = MixEffectBlockId.One
                    }.ToByteArray();
                    byte[] fakeOp   = { 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
                    byte[] combined = op.Concat(fakeOp).ToArray();
                    worker          = new UploadJobWorker((uint)combined.Length, _output, 0xffff, index,
                                                          DataTransferUploadRequestCommand.TransferMode.Write2 |
                                                          DataTransferUploadRequestCommand.TransferMode.Clear2);

                    // var cb = new TestMediaPoolStills.LockCallback();
                    // helper.SendAndWaitForChange(stateBefore, () => { .Lock(cb); });
                    // Assert.True(cb.Wait.WaitOne(2000));

                    pool.CreateMacro((uint)combined.Length, out IBMDSwitcherMacro macro);
                    macro.GetBytes(out IntPtr buffer);
                    Marshal.Copy(combined, 0, buffer, combined.Length);

                    var uploadCb = new TransferCallback();
                    pool.AddCallback(uploadCb);
                    pool.Upload(index, name, "not now", macro, out IBMDSwitcherTransferMacro transfer);

                    MacroState.ItemState macroState = stateBefore.Macros.Pool[(int)index];
                    macroState.Name              = name;
                    macroState.Description       = "not now";
                    macroState.HasUnsupportedOps = true;
                    macroState.IsUsed            = true;

                    helper.HandleUntil(uploadCb.Wait, 1000);
                    Assert.True(uploadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMacroPoolEventType.bmdSwitcherMacroPoolEventTypeTransferCompleted,
                                 uploadCb.Result);
                    Assert.Equal(BitConverter.ToString(combined), BitConverter.ToString(worker.Buffer));

                    helper.Helper.CheckStateChanges(stateBefore);
                }
            });
        }
Example #5
0
        private void DoUpload(int iterations, int timeout, Func <uint, uint, byte[]> frameBytes)
        {
            UploadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MediaPlayer, helper =>
            {
                helper.DisposeSdkClient = true;

                IBMDSwitcherMediaPool pool = GetMediaPool(helper);
                IBMDSwitcherStills stills  = GetStillsPool(helper);

                for (int i = 0; i < iterations; i++)
                {
                    AtemState stateBefore         = helper.Helper.BuildLibState();
                    Tuple <uint, uint> resolution = stateBefore.Settings.VideoMode.GetResolution().GetSize();

                    uint index  = Randomiser.RangeInt((uint)stateBefore.MediaPool.Stills.Count);
                    string name = Guid.NewGuid().ToString();
                    worker      = new UploadJobWorker(resolution.Item1 * resolution.Item2 * 4, _output,
                                                      (uint)MediaPoolFileType.Still, index, DataTransferUploadRequestCommand.TransferMode.Write);

                    var cb = new LockCallback();
                    helper.SendAndWaitForChange(stateBefore, () => { stills.Lock(cb); });
                    Assert.True(cb.Wait.WaitOne(2000));

                    pool.CreateFrame(_BMDSwitcherPixelFormat.bmdSwitcherPixelFormat10BitYUVA, resolution.Item1,
                                     resolution.Item2, out IBMDSwitcherFrame frame);
                    byte[] bytes = frameBytes(resolution.Item1, resolution.Item2);
                    if (bytes.Length > 0)
                    {
                        MediaPoolUtil.FillSdkFrame(frame, bytes);
                    }

                    var stillState      = stateBefore.MediaPool.Stills[(int)index];
                    stillState.IsUsed   = true;
                    stillState.Filename = name;

                    var uploadCb = new TransferCallback();
                    stills.AddCallback(uploadCb);
                    stills.Upload(index, name, frame);

                    helper.HandleUntil(uploadCb.Wait, timeout);
                    Assert.True(uploadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMediaPoolEventType.bmdSwitcherMediaPoolEventTypeTransferCompleted,
                                 uploadCb.Result);
                    Assert.Equal(BitConverter.ToString(bytes), BitConverter.ToString(worker.Buffer));

                    helper.SendAndWaitForChange(stateBefore, () =>
                    {
                        stills.Unlock(cb);
                    });
                }
            });
        }
Example #6
0
 public void Delete(string path,
                    object body       = null,
                    int timeout       = 10000,
                    int retry         = -1,
                    bool throwable    = true,
                    Encoding encoding = null,
                    TransferCallback uploadProgress      = null,
                    IDictionary <string, string> headers = null,
                    CookieCollection cookies             = null)
 {
     callNoReturn(path, "DELETE", body, timeout, retry, throwable, encoding, uploadProgress, headers, cookies);
 }
Example #7
0
 public Task <Task> GetAsync <T>(string path,
                                 int timeout       = 10000,
                                 int retry         = -1,
                                 bool throwable    = true,
                                 Encoding encoding = null,
                                 TransferCallback uploadProgress      = null,
                                 TransferCallback downloadProgress    = null,
                                 IDictionary <string, string> headers = null,
                                 CookieCollection cookies             = null)
 {
     throw new NotImplementedException();
 }
Example #8
0
 public T Get <T>(string path,
                  int timeout       = 10000,
                  int retry         = -1,
                  bool throwable    = true,
                  Encoding encoding = null,
                  TransferCallback uploadProgress      = null,
                  TransferCallback downloadProgress    = null,
                  IDictionary <string, string> headers = null,
                  CookieCollection cookies             = null)
 {
     return(callReturn <T>(path, "DELETE", null, timeout, retry, throwable, encoding, uploadProgress, downloadProgress, headers, cookies));
 }
Example #9
0
 public void Get(string path,
                 int timeout       = 10000,
                 int retry         = -1,
                 bool throwable    = true,
                 Encoding encoding = null,
                 TransferCallback uploadProgress      = null,
                 TransferCallback downloadProgress    = null,
                 IDictionary <string, string> headers = null,
                 CookieCollection cookies             = null)
 {
     callNoReturn(path, "GET", null, timeout, retry, throwable, encoding, uploadProgress, headers, cookies);
 }
 public TransferBackgroundAction(TransferController controller, Transfer transfer, TransferOptions options,
                                 TransferCallback callback, PathCache cache, ProgressListener listener)
     : base(controller,
            null == transfer.getSource() ? SessionPool.DISCONNECTED : SessionPoolFactory.create(controller, transfer.getSource(), listener),
            null == transfer.getDestination() ? SessionPool.DISCONNECTED : SessionPoolFactory.create(controller, transfer.getDestination(), listener),
            controller.GetController(transfer),
            controller.GetController(transfer),
            transfer, options)
 {
     _transfer   = transfer;
     _callback   = callback;
     _controller = controller;
 }
Example #11
0
        private T callReturn <T>(string path,
                                 string method,
                                 object body,
                                 int timeout,
                                 int retry,
                                 bool throwable,
                                 Encoding encoding,
                                 TransferCallback uploadProgress,
                                 TransferCallback downloadProgress,
                                 IDictionary <string, string> headers,
                                 CookieCollection cookies)
        {
            var t = 0;

            Exception error = null;

            while (t++ < retry)
            {
                try
                {
                    var request = createRequest(path, method, timeout, headers, cookies);

                    var stream = request.GetRequestStream();

                    if (body != null)
                    {
                        writeIntoStream(stream, body, encoding, uploadProgress);
                    }

                    var respose = request.GetResponse();

                    var contentLengh = respose.ContentLength;

                    return(readStream <T>(contentLengh, respose.GetResponseStream(), encoding, downloadProgress));
                }
                catch (Exception ex)
                {
                    ErrorInterceptor?.Invoke(ex);
                    error = ex;
                }
            }

            if (throwable && error != null)
            {
                throw error;
            }
            else
            {
                return(default(T));
            }
        }
Example #12
0
        public void TestClipFrameUpload()
        {
            UploadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MediaPlayerClips, helper =>
            {
                helper.DisposeSdkClient = true;

                IBMDSwitcherMediaPool pool = GetMediaPool(helper);

                for (int i = 0; i < 3; i++)
                {
                    AtemState stateBefore         = helper.Helper.BuildLibState();
                    Tuple <uint, uint> resolution = stateBefore.Settings.VideoMode.GetResolution().GetSize();
                    uint index            = Randomiser.RangeInt((uint)stateBefore.MediaPool.Clips.Count);
                    uint frameIndex       = Randomiser.RangeInt(stateBefore.MediaPool.Clips[(int)index].MaxFrames);
                    IBMDSwitcherClip clip = GetClip(helper, index);

                    worker = new UploadJobWorker(resolution.Item1 * resolution.Item2 * 4, _output,
                                                 index + 1, frameIndex, DataTransferUploadRequestCommand.TransferMode.Write);

                    var cb = new LockCallback();
                    helper.SendAndWaitForChange(stateBefore, () => { clip.Lock(cb); });
                    Assert.True(cb.Wait.WaitOne(2000));

                    pool.CreateFrame(_BMDSwitcherPixelFormat.bmdSwitcherPixelFormat10BitYUVA, resolution.Item1,
                                     resolution.Item2, out IBMDSwitcherFrame frame);
                    byte[] bytes = MediaPoolUtil.SolidColour(resolution.Item1 * resolution.Item2, 100, 0, 0, 255);
                    MediaPoolUtil.FillSdkFrame(frame, bytes);

                    var clipState = stateBefore.MediaPool.Clips[(int)index];
                    clipState.Frames[(int)frameIndex].IsUsed = true;
                    //clipState.Audio.Name = name;

                    var uploadCb = new TransferCallback();
                    clip.AddCallback(uploadCb);
                    clip.UploadFrame(frameIndex, frame);

                    helper.HandleUntil(uploadCb.Wait, 5000);
                    Assert.True(uploadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMediaPoolEventType.bmdSwitcherMediaPoolEventTypeTransferCompleted,
                                 uploadCb.Result);
                    Assert.Equal(BitConverter.ToString(bytes), BitConverter.ToString(worker.Buffer));

                    helper.SendAndWaitForChange(stateBefore, () =>
                    {
                        clip.Unlock(cb);
                    });
                }
            });
        }
Example #13
0
        public void TestAbortingAudioUpload()
        {
            AbortedUploadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MediaPlayerClips, helper =>
            {
                helper.DisposeSdkClient = true;

                IBMDSwitcherMediaPool pool = GetMediaPool(helper);

                for (int i = 0; i < 3; i++)
                {
                    AtemState stateBefore = helper.Helper.BuildLibState();
                    uint index            = Randomiser.RangeInt((uint)stateBefore.MediaPool.Clips.Count);
                    IBMDSwitcherClip clip = GetClip(helper, index);

                    uint sampleCount = 10000;

                    string name = Guid.NewGuid().ToString();
                    worker      = new AbortedUploadJobWorker(_output);

                    var cb = new LockCallback();
                    helper.SendAndWaitForChange(stateBefore, () => { clip.Lock(cb); });
                    Assert.True(cb.Wait.WaitOne(2000));

                    byte[] bytes = MediaPoolUtil.RandomFrame(sampleCount);
                    pool.CreateAudio((uint)bytes.Length, out IBMDSwitcherAudio frame);
                    MediaPoolUtil.FillSdkAudio(frame, bytes);

                    var uploadCb = new TransferCallback();
                    clip.AddCallback(uploadCb);
                    clip.UploadAudio(name, frame);

                    // Short bit of work before the abort
                    helper.HandleUntil(uploadCb.Wait, 1000);
                    clip.CancelTransfer();

                    helper.HandleUntil(uploadCb.Wait, 1000);
                    Assert.True(uploadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMediaPoolEventType.bmdSwitcherMediaPoolEventTypeTransferCancelled,
                                 uploadCb.Result);

                    helper.SendAndWaitForChange(stateBefore, () =>
                    {
                        clip.Unlock(cb);
                    });
                }
            });
        }
Example #14
0
        public void TestDownload()
        {
            DownloadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MacroTransfer, helper =>
            {
                helper.DisposeSdkClient = true;

                var pool = helper.SdkClient.SdkSwitcher as IBMDSwitcherMacroPool;
                Assert.NotNull(pool);

                for (int i = 0; i < 5; i++)
                {
                    AtemState stateBefore = helper.Helper.BuildLibState();

                    uint index  = Randomiser.RangeInt((uint)stateBefore.Macros.Pool.Count);
                    string name = Guid.NewGuid().ToString();

                    byte[] op = new CutTransitionMacroOp {
                        Index = MixEffectBlockId.One
                    }.ToByteArray();
                    byte[] fakeOp   = { 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
                    byte[] combined = op.Concat(fakeOp).ToArray();
                    worker          = new DownloadJobWorker(_output, 0xffff, index, combined);

                    // var cb = new TestMediaPoolStills.LockCallback();
                    // helper.SendAndWaitForChange(stateBefore, () => { .Lock(cb); });
                    // Assert.True(cb.Wait.WaitOne(2000));

                    var downloadCb = new TransferCallback();
                    pool.AddCallback(downloadCb);
                    pool.Download(index, out IBMDSwitcherTransferMacro transfer);

                    helper.HandleUntil(downloadCb.Wait, 1000);
                    Assert.True(downloadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMacroPoolEventType.bmdSwitcherMacroPoolEventTypeTransferCompleted,
                                 downloadCb.Result);

                    transfer.GetMacro(out IBMDSwitcherMacro macro);
                    macro.GetBytes(out IntPtr buffer);
                    byte[] bytes = new byte[macro.GetSize()];
                    Marshal.Copy(buffer, bytes, 0, bytes.Length);
                    Assert.Equal(BitConverter.ToString(combined), BitConverter.ToString(bytes));

                    helper.Helper.CheckStateChanges(stateBefore);
                }
            });
        }
Example #15
0
        public void TestAbortingStillUpload()
        {
            AbortedUploadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MediaPlayerStillTransfer, helper =>
            {
                helper.DisposeSdkClient = true;

                IBMDSwitcherMediaPool pool = GetMediaPool(helper);
                IBMDSwitcherStills stills  = GetStillsPool(helper);

                for (int i = 0; i < 3; i++)
                {
                    AtemState stateBefore         = helper.Helper.BuildLibState();
                    Tuple <uint, uint> resolution = stateBefore.Settings.VideoMode.GetResolution().GetSize();

                    uint index  = Randomiser.RangeInt((uint)stateBefore.MediaPool.Stills.Count);
                    string name = Guid.NewGuid().ToString();
                    worker      = new AbortedUploadJobWorker(_output);

                    var cb = new LockCallback();
                    helper.SendAndWaitForChange(stateBefore, () => { stills.Lock(cb); });
                    Assert.True(cb.Wait.WaitOne(2000));

                    pool.CreateFrame(_BMDSwitcherPixelFormat.bmdSwitcherPixelFormat10BitYUVA, resolution.Item1,
                                     resolution.Item2, out IBMDSwitcherFrame frame);
                    MediaPoolUtil.FillSdkFrame(frame, MediaPoolUtil.RandomFrame(resolution.Item1 * resolution.Item2));

                    var uploadCb = new TransferCallback();
                    stills.AddCallback(uploadCb);
                    stills.Upload(index, name, frame);

                    // Short bit of work before the abort
                    helper.HandleUntil(uploadCb.Wait, 1000);
                    stills.CancelTransfer();

                    helper.HandleUntil(uploadCb.Wait, 1000);
                    Assert.True(uploadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMediaPoolEventType.bmdSwitcherMediaPoolEventTypeTransferCancelled,
                                 uploadCb.Result);

                    helper.SendAndWaitForChange(stateBefore, () =>
                    {
                        stills.Unlock(cb);
                    });
                }
            });
        }
Example #16
0
        public void TestAbortUpload()
        {
            AbortedUploadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MacroTransfer, helper =>
            {
                helper.DisposeSdkClient = true;

                var pool = helper.SdkClient.SdkSwitcher as IBMDSwitcherMacroPool;
                Assert.NotNull(pool);

                for (int i = 0; i < 3; i++)
                {
                    AtemState stateBefore = helper.Helper.BuildLibState();

                    uint index = Randomiser.RangeInt((uint)stateBefore.Macros.Pool.Count);

                    byte[] op = new CutTransitionMacroOp {
                        Index = MixEffectBlockId.One
                    }.ToByteArray();
                    byte[] fakeOp   = { 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
                    byte[] combined = op.Concat(fakeOp).ToArray();
                    worker          = new AbortedUploadJobWorker(_output);

                    pool.CreateMacro((uint)combined.Length, out IBMDSwitcherMacro macro);
                    macro.GetBytes(out IntPtr buffer);
                    Marshal.Copy(combined, 0, buffer, combined.Length);

                    var uploadCb = new TransferCallback();
                    pool.AddCallback(uploadCb);
                    pool.Upload(index, "some thing", "not now", macro, out IBMDSwitcherTransferMacro transfer);

                    // Short bit of work before the abort
                    helper.HandleUntil(uploadCb.Wait, 1000);
                    transfer.Cancel();

                    helper.HandleUntil(uploadCb.Wait, 1000);
                    Assert.True(uploadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMacroPoolEventType.bmdSwitcherMacroPoolEventTypeTransferCancelled,
                                 uploadCb.Result);

                    helper.Helper.CheckStateChanges(stateBefore);
                }
            });
        }
Example #17
0
        private async Task callNoReturnAsync(string path,
                                             string method,
                                             object body,
                                             int timeout,
                                             int retry,
                                             bool throwable,
                                             Encoding encoding,
                                             TransferCallback uploadProgress,
                                             IDictionary <string, string> headers,
                                             CookieCollection cookies)
        {
            var t = 0;

            Exception error = null;

            while (t++ < retry)
            {
                try
                {
                    var request = createRequest(path, method, timeout, headers, cookies);

                    var stream = await request.GetRequestStreamAsync().ConfigureAwait(false);

                    if (body != null)
                    {
                        await  writeIntoStreamAsync(stream, body, encoding, uploadProgress).ConfigureAwait(false);
                    }

                    await request.GetResponseAsync().ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    ErrorInterceptor?.Invoke(ex);
                    error = ex;
                }
            }

            if (throwable && error != null)
            {
                throw error;
            }
        }
Example #18
0
        /// <summary>
        /// Sends the HTTP request and writes the response into <paramref name="stream" />. Throws a <see cref="HttpException" />, if the request failed.
        /// </summary>
        /// <param name="stream">A <see cref="Stream" /> to write the response into.</param>
        /// <param name="callback">The method that is called periodically while binary data is transferred, or <see langword="null" />.</param>
        public void Read(Stream stream, TransferCallback callback)
        {
            Try(() =>
            {
                using WebResponse response  = GetWebRequest().GetResponse();
                using Stream responseStream = response.GetResponseStream();

                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalBytesRead    = 0;
                long callbackBytesRead = 0;
                Stopwatch stopwatch    = ThreadFactory.StartStopwatch();

                do
                {
                    bytesRead       = responseStream.Read(buffer);
                    totalBytesRead += bytesRead;
                    stream.Write(buffer, 0, bytesRead);

                    if (callback != null)
                    {
                        callbackBytesRead += bytesRead;
                        if (stopwatch.Elapsed > TimeSpan.FromMilliseconds(100))
                        {
                            stopwatch.Restart();
                            callback(callbackBytesRead, totalBytesRead);
                            callbackBytesRead = 0;
                        }
                    }
                }while (bytesRead > 0);

                if (callback != null && callbackBytesRead > 0)
                {
                    callback(callbackBytesRead, totalBytesRead);
                }

                return(new object());
            });
        }
        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;
        }
Example #20
0
 public static extern int Handler(IntPtr str, TransferCallback callback);
Example #21
0
        public void TestClipFrameDownload()
        {
            DownloadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MediaPlayerClips, helper =>
            {
                helper.DisposeSdkClient = true;

                IBMDSwitcherMediaPool pool = GetMediaPool(helper);

                for (int i = 0; i < 3; i++)
                {
                    AtemState stateBefore         = helper.Helper.BuildLibState();
                    Tuple <uint, uint> resolution = stateBefore.Settings.VideoMode.GetResolution().GetSize();
                    uint index            = Randomiser.RangeInt((uint)stateBefore.MediaPool.Clips.Count);
                    uint frameIndex       = Randomiser.RangeInt(stateBefore.MediaPool.Clips[(int)index].MaxFrames);
                    IBMDSwitcherClip clip = GetClip(helper, index);

                    {
                        var frameState    = stateBefore.MediaPool.Clips[(int)index].Frames[(int)frameIndex];
                        frameState.IsUsed = true;
                        frameState.Hash   = new byte[16];
                        helper.SendFromServerAndWaitForChange(stateBefore, new MediaPoolFrameDescriptionCommand
                        {
                            Bank     = (MediaPoolFileType)index + 1,
                            Filename = "",
                            Index    = frameIndex,
                            IsUsed   = true
                        });
                    }
                    stateBefore = helper.Helper.BuildLibState();

                    byte[] bytes = new byte[resolution.Item1 * resolution.Item2 * 4];
                    worker       = new DownloadJobWorker(_output, index + 1, frameIndex, FrameEncodingUtil.EncodeRLE(bytes));

                    var cb = new LockCallback();
                    helper.SendAndWaitForChange(stateBefore, () => { clip.Lock(cb); });
                    Assert.True(cb.Wait.WaitOne(2000));

                    var downloadCb = new TransferCallback();
                    clip.AddCallback(downloadCb);
                    clip.DownloadFrame(frameIndex);

                    helper.HandleUntil(downloadCb.Wait, 5000);
                    Assert.True(downloadCb.Wait.WaitOne(500));

                    Assert.Equal(_BMDSwitcherMediaPoolEventType.bmdSwitcherMediaPoolEventTypeTransferCompleted,
                                 downloadCb.Result);
                    Assert.NotNull(downloadCb.Frame);
                    Assert.Null(downloadCb.Audio);

                    byte[] sdkBytes = MediaPoolUtil.GetSdkFrameBytes(downloadCb.Frame);
                    Assert.Equal(BitConverter.ToString(bytes), BitConverter.ToString(sdkBytes));

                    helper.SendAndWaitForChange(stateBefore, () =>
                    {
                        clip.Unlock(cb);
                    });
                }
            });
        }
Example #22
0
        private void DoDownload(int iterations, int timeout, Func <uint, uint, Tuple <byte[], byte[]> > rawBytesGen)
        {
            DownloadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MediaPlayerStillTransfer, helper =>
            {
                helper.DisposeSdkClient = true;

                IBMDSwitcherStills stills = GetStillsPool(helper);

                for (int i = 0; i < iterations; i++)
                {
                    AtemState stateBefore         = helper.Helper.BuildLibState();
                    Tuple <uint, uint> resolution = stateBefore.Settings.VideoMode.GetResolution().GetSize();

                    uint index = Randomiser.RangeInt((uint)stateBefore.MediaPool.Stills.Count);

                    {
                        var stillState      = stateBefore.MediaPool.Stills[(int)index];
                        stillState.Filename = "Some file";
                        stillState.IsUsed   = true;
                        stillState.Hash     = new byte[16];
                        helper.SendFromServerAndWaitForChange(stateBefore, new MediaPoolFrameDescriptionCommand
                        {
                            Bank     = MediaPoolFileType.Still,
                            Filename = "Some file",
                            Index    = index,
                            IsUsed   = true
                        });
                    }
                    stateBefore = helper.Helper.BuildLibState();

                    Tuple <byte[], byte[]> rawBytes = rawBytesGen(resolution.Item1, resolution.Item2);
                    worker = new DownloadJobWorker(_output, (uint)MediaPoolFileType.Still, index,
                                                   rawBytes.Item2);

                    var cb = new LockCallback();
                    helper.SendAndWaitForChange(stateBefore, () => { stills.Lock(cb); });
                    Assert.True(cb.Wait.WaitOne(2000));

                    var downloadCb = new TransferCallback();
                    stills.AddCallback(downloadCb);
                    stills.Download(index);

                    helper.HandleUntil(downloadCb.Wait, timeout);
                    Assert.True(downloadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMediaPoolEventType.bmdSwitcherMediaPoolEventTypeTransferCompleted,
                                 downloadCb.Result);

                    Assert.NotNull(downloadCb.Frame);
                    Assert.Equal(_BMDSwitcherPixelFormat.bmdSwitcherPixelFormat10BitYUVA,
                                 downloadCb.Frame.GetPixelFormat());
                    Assert.Equal(resolution.Item1, (uint)downloadCb.Frame.GetWidth());
                    Assert.Equal(resolution.Item2, (uint)downloadCb.Frame.GetHeight());
                    byte[] sdkBytes = MediaPoolUtil.GetSdkFrameBytes(downloadCb.Frame);
                    Assert.Equal(BitConverter.ToString(rawBytes.Item1), BitConverter.ToString(sdkBytes));

                    helper.SendAndWaitForChange(stateBefore, () =>
                    {
                        stills.Unlock(cb);
                    });
                }
            });
        }
Example #23
0
        public void TestAudioDownload()
        {
            DownloadJobWorker worker = null;

            AtemMockServerWrapper.Each(_output, _pool, (a, b) => worker?.HandleCommand(a, b), DeviceTestCases.MediaPlayerClips, helper =>
            {
                helper.DisposeSdkClient = true;

                var pidCmd = helper.Server.GetParsedDataDump().OfType <ProductIdentifierCommand>().Single();

                for (int i = 0; i < 3; i++)
                {
                    AtemState stateBefore = helper.Helper.BuildLibState();
                    uint index            = Randomiser.RangeInt((uint)stateBefore.MediaPool.Clips.Count);
                    IBMDSwitcherClip clip = GetClip(helper, index);

                    uint sampleCount = 10000;

                    {
                        var clipState          = stateBefore.MediaPool.Clips[(int)index];
                        clipState.Audio.Name   = "Some file";
                        clipState.Audio.IsUsed = true;
                        clipState.Audio.Hash   = new byte[16];
                        helper.SendFromServerAndWaitForChange(stateBefore, new MediaPoolAudioDescriptionCommand
                        {
                            Name   = "Some file",
                            Index  = index + 1,
                            IsUsed = true
                        });
                    }
                    stateBefore = helper.Helper.BuildLibState();

                    var bytes = MediaPoolUtil.RandomFrame(sampleCount);
                    worker    = new DownloadJobWorker(_output, index + 1, 0, bytes);

                    var cb = new LockCallback();
                    helper.SendAndWaitForChange(stateBefore, () => { clip.Lock(cb); });
                    Assert.True(cb.Wait.WaitOne(2000));

                    var downloadCb = new TransferCallback();
                    clip.AddCallback(downloadCb);
                    clip.DownloadAudio();

                    helper.HandleUntil(downloadCb.Wait, 5000);
                    Assert.True(downloadCb.Wait.WaitOne(500));
                    Assert.Equal(_BMDSwitcherMediaPoolEventType.bmdSwitcherMediaPoolEventTypeTransferCompleted,
                                 downloadCb.Result);

                    Assert.Null(downloadCb.Frame);
                    Assert.NotNull(downloadCb.Audio);
                    Assert.Equal((int)(sampleCount * 4), downloadCb.Audio.GetSize());
                    byte[] sdkBytes = MediaPoolUtil.GetSdkAudioBytes(downloadCb.Audio);

                    // TODO - this needs a better rule that can be properly exposed via the lib
                    byte[] flippedBytes = pidCmd.Model >= ModelId.PS4K
                        ? MediaPoolUtil.FlipAudio(bytes)
                        : bytes;
                    Assert.Equal(BitConverter.ToString(flippedBytes), BitConverter.ToString(sdkBytes));

                    helper.SendAndWaitForChange(stateBefore, () =>
                    {
                        clip.Unlock(cb);
                    });
                }
            });
        }
Example #24
0
        private T readStream <T>(long contentLengh, Stream stream, Encoding encoding, TransferCallback downloadProgress)
        {
            long transferd = 0;

            var buffer = new byte[contentLengh];//10kb

            while (stream.Read(buffer, (int)transferd, TranferCallbackSize) > TranferCallbackSize)
            {
                transferd += TranferCallbackSize;

                downloadProgress?.Invoke(contentLengh, transferd);
            }

            downloadProgress?.Invoke(contentLengh, contentLengh);

            return(JsonSerializer.Instance.Deserialize <T>(buffer, encoding));
        }
Example #25
0
 /// <summary>
 /// Sends the HTTP request and writes the response into a file. Throws a <see cref="HttpException" />, if the request failed.
 /// </summary>
 /// <param name="path">A <see cref="string" /> specifying the path of a file to which the response is written to.</param>
 /// <param name="callback">The method that is called periodically while binary data is transferred, or <see langword="null" />.</param>
 public void ReadFile(string path, TransferCallback callback)
 {
     using FileStream stream = File.Create(path);
     Read(stream, callback);
 }
Example #26
0
 /// <summary>
 /// Sends the HTTP request, reads the response and returns a <see cref="byte" />[] with the content. Throws a <see cref="HttpException" />, if the request failed.
 /// </summary>
 /// <param name="callback">The method that is called periodically while binary data is transferred, or <see langword="null" />.</param>
 /// <returns>
 /// A <see cref="byte" />[] with the content of the HTTP request.
 /// </returns>
 public byte[] ReadBytes(TransferCallback callback)
 {
     using MemoryStream memoryStream = new MemoryStream();
     Read(memoryStream, callback);
     return(memoryStream.ToArray());
 }
Example #27
0
 private void writeIntoStream(Stream stream, object body, Encoding encoding, TransferCallback uploadCallback)
 {
 }
Example #28
0
 private Task writeIntoStreamAsync(Stream stream, object body, Encoding encoding, TransferCallback uploadCallback)
 {
 }
        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);
        }
        public byte[] ExecuteReadBigDataWriteToFile(int code, int param1, int param2, TransferCallback callback, string fileName)
        {
            // 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);

            tag_inner_PROPVARIANT vparam1 = new tag_inner_PROPVARIANT();
            tag_inner_PROPVARIANT vparam2 = new tag_inner_PROPVARIANT();
            if (param1 > -1)
            {
                UintToPropVariant((uint)param1, out vparam1);
                propVariant.Add(ref vparam1);
            }
            if (param2 > -1)
            {
                UintToPropVariant((uint)param2, out vparam2);
                propVariant.Add(ref vparam2);
            }
            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 ExecuteReadBigDataWriteToFile(code, param1, param2, callback, fileName);
                    }
                }
            }
            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;
            byte[] res = new byte[(int)tmpBufferSize];
            bool cont = true;

            var hFile = WinApi.CreateFile(fileName, (uint)WinApi.DesiredAccess.GENERIC_WRITE,
                                         (uint)WinApi.ShareMode.FILE_SHARE_WRITE, IntPtr.Zero, (uint)WinApi.CreationDisposition.CREATE_ALWAYS,
                                         (uint)WinApi.FlagsAndAttributes.FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);

            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)
                        return null;
                }
                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));

                var natOverlap = new NativeOverlapped() { OffsetLow = (int)offset };

                IntPtr written = new IntPtr();
                WinApi.WriteFile(hFile, tmpPtr, (int)cbBytesRead, written, ref natOverlap);

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

                offset += cbBytesRead;
            } while (cont);

            WinApi.CloseHandle(hFile);

            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;
        }