Beispiel #1
0
    protected void uploadButton_Click(object sender, EventArgs e)
    {
        string actualFileName = Path.GetFileName(FileUpload1.FileName).Replace(" ", "_");
        string storedFileName = Tools.GetRandomString() + "_" + actualFileName; //Append actualName to storedName so that links are nicer to view.

        if (Uploading.goodSize(FileUpload1.FileBytes.Length) == false)          //check if file is too big 30mb limit
        {
            Label10.Text = "File is larger than 30MB";
        }
        else if (actualFileName.Contains("&"))
        {
            Label10.Text = "File contains illegal character '&'"; //Should really just replace the '&' to a blank space instead of throwing error message
        }
        else
        {
            if (FileUpload1.HasFile)
            {
                if (Uploading.UploadFTPfile(FileUpload1, storedFileName) == true) //successful upload
                {
                    Label10.Text = "";                                            //Clear any error from the link location
                    Uploading.logUpload(storedFileName, actualFileName);
                    LinkButton1.Visible     = true;
                    LinkButton1.Text        = Tools.GenerateLink(storedFileName);
                    LinkButton1.PostBackUrl = LinkButton1.Text;
                }
                else
                {
                    Label10.Text = "File upload fail!";
                }
            }
        }
    }
Beispiel #2
0
        protected virtual void DefaultUpload(string filePath)
        {
            Uploading?.Invoke(this, new ElementActionEventArgs(this));

            WrappedElement.SendKeys(filePath);

            Uploaded?.Invoke(this, new ElementActionEventArgs(this));
        }
        public void Upload(string source, string target, Func <string, string> renameCallback, bool deleteSourceFile = false)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrWhiteSpace(target))
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (!IsConnected)
            {
                throw new SftpProviderException("Connect to server before upload.");
            }

            var   random     = new Random();
            var   totalBytes = (ulong)random.Next(1024 * 10, 1024 * 1024);
            ulong bytes      = 0;

            while (bytes < totalBytes)
            {
                _log.Debug(m => m("Uploading {0} to {1}", source, target));
                var uploaded = (ulong)random.Next(1024, 2048);
                if (bytes + uploaded < totalBytes)
                {
                    bytes += uploaded;
                }
                else
                {
                    bytes = totalBytes;
                }

                if (bytes < totalBytes)
                {
                    _log.Debug(m => m("Uploading {0} to {1} {2}/{3}", source, target, bytes, totalBytes));
                }
                else
                {
                    _log.Info(m => m("Upload {0} to {1} completed.", source, target));
                }
                Uploading?.Invoke(target, bytes, totalBytes);
                renameCallback?.Invoke(target);
            }

            if (!deleteSourceFile)
            {
                return;
            }

            _log.Debug($"{source} deleted.");
        }
Beispiel #4
0
        /// <summary>
        /// upload file
        /// </summary>
        /// <param name="url"></param>
        /// <param name="uploadFileInfo"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        public async Task <bool> Upload(Uri url, FileInfo uploadFileInfo, CancellationToken ct = default(CancellationToken))
        {
            var headResult = await _tusCore.Head(url, ct);

            long offset = long.Parse(headResult["Upload-Offset"]);

            var tusUploadFileContext = new TusUploadContext(totalSize: uploadFileInfo.Length,
                                                            uploadedSize: offset, uploadFileInfo: uploadFileInfo, uploadFileUrl: url);

            using (var fileStream = new FileStream(uploadFileInfo.FullName, FileMode.Open, FileAccess.Read))
            {
                while (!ct.IsCancellationRequested)
                {
                    if (offset == uploadFileInfo.Length)
                    {
                        UploadFinish?.Invoke(tusUploadFileContext);
                        break;
                    }

                    //get buffer of file
                    fileStream.Seek(offset, SeekOrigin.Begin);

                    int uploadSize = GetUploadSize(tusUploadFileContext);

                    byte[] buffer    = new byte[uploadSize];
                    var    readCount = await fileStream.ReadAsync(buffer, 0, uploadSize);

                    if (readCount < uploadSize)
                    {
                        Array.Resize(ref buffer, readCount);
                    }

                    var uploadResult = await _tusCore.Patch(url, buffer, offset, ct);

                    offset = long.Parse(uploadResult["Upload-Offset"]);
                    tusUploadFileContext.UploadedSize = offset;
                    Uploading?.Invoke(tusUploadFileContext);
                }
            }

            return(true);
        }
Beispiel #5
0
 public object Post(Uploading request)
 {
     //string[] segments = base.Request.QueryString.GetValues(0);
     //string strFileName = segments[0];
     //string strPath = HttpContext.Current.Request.PhysicalApplicationPath;
     //string resultFile = Path.Combine(@"C:\inetpub\wwwroot\WebAPI\attach", strFileName);
     //if (File.Exists(resultFile))
     //{
     //				File.Delete(resultFile);
     //}
     //using (FileStream file = File.Create(resultFile))
     //{
     //				byte[] buffer = new byte[request.RequestStream.Length];
     //				request.RequestStream.Read(buffer, 0, buffer.Length);
     //				file.Write(buffer, 0, buffer.Length);
     //				file.Flush();
     //				file.Close();
     //}
     return(new HttpResult(System.Net.HttpStatusCode.OK));
 }
        public ApplicationContent(
            IApp page = null,
            IApplicationWebServiceX service = null)
        {
            // need absolute path when docked..
            page.style1.href = page.style1.href;

            // first order of business.
            // enable drop zone.
            var dz = new DropZone();


            dz.Container.AttachToDocument();
            dz.Container.Hide();

            var StayAlertTimer = default(Timer);
            var DoRefresh = default(Action);

            #region StayAlert
            Action<string> StayAlert =
                transaction_id =>
                {
                    StayAlertTimer = new Timer(
                        delegate
                        {
                            service.GetTransactionKeyAsync(
                                id =>
                                {
                                    if (id == transaction_id)
                                        return;

                                    // shot down during flight?
                                    if (!StayAlertTimer.IsAlive)
                                        return;

                                    Console.WriteLine("StayAlert " + new { id, transaction_id });

                                    DoRefresh();
                                }
                            );
                        }
                    );

                    StayAlertTimer.StartInterval(5000);
                };
            #endregion


            DoRefresh =
                delegate
                {
                    if (StayAlertTimer != null)
                        StayAlertTimer.Stop();

                    page.output.Clear();

                    new FileLoading().Container.AttachTo(page.output);

                    service.EnumerateFilesAsync(
                        y:
                        (
                            long ContentKey,
                            string ContentValue,
                            string ContentType,
                            long ContentBytesLength
                        ) =>
                        {
                            var e = new FileEntry();

                            #region ContentValue
                            e.ContentValue.value = ContentValue.TakeUntilLastIfAny(".");
                            e.ContentValue.onchange +=
                                delegate
                                {
                                    var ext = ContentValue.SkipUntilLastOrEmpty(".");

                                    if (ext != "")
                                        ext = "." + ext;

                                    ContentValue = e.ContentValue.value + ext;


                                    Console.WriteLine("before update!");

                                    service.UpdateAsync(
                                        ContentKey,
                                        ContentValue,
                                        // null does not really work?
                                        delegate
                                        {
                                            Console.WriteLine("update done!");
                                        }
                                    );

                                    e.open.href = Native.Document.location.href.TakeUntilLastIfAny("/") + "/io/" + ContentKey + "/" + ContentValue;
                                };
                            e.open.href = Native.Document.location.href.TakeUntilLastIfAny("/") + "/io/" + ContentKey + "/" + ContentValue;
                            e.open.target = Target;

                            #endregion

                            e.ContentType.innerText = ContentBytesLength + " bytes " + ContentType;


                            #region Delete
                            e.Delete.WhenClicked(
                                delegate
                                {
                                    //e.ContentValue.style.textDecoration = ""

                                    if (StayAlertTimer != null)
                                        StayAlertTimer.Stop();

                                    e.Container.style.backgroundColor = "red";

                                    service.DeleteAsync(
                                        ContentKey,
                                        delegate
                                        {

                                            DoRefresh();
                                        }
                                    );
                                }
                            );
                            #endregion


                            e.Container.AttachTo(page.output);



                            Console.WriteLine(
                                new { ContentKey, ContentValue, ContentType, ContentBytesLength }
                            );

                        },

                        done: transaction_id =>
                        {
                            Console.WriteLine(new { transaction_id });
                            new FileLoadingDone().Container.AttachTo(page.output);

                            StayAlert(transaction_id);
                        }
                    );
                };

            #region ondrop

            var TimerHide = new Timer(
                delegate
                {
                    dz.Container.Hide();
                }
            );

            Action<DragEvent> ondragover =
                evt =>
                {
                    //Console.WriteLine("ondragover");


                    evt.stopPropagation();
                    evt.preventDefault();

                    // ondragover { type = Files }

                    //foreach (var type in evt.dataTransfer.types)
                    //{
                    //    Console.WriteLine("ondragover " + new { type });
                    //}


                    if (evt.dataTransfer.types.Contains("Files"))
                    {


                        evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.

                        dz.Container.Show();
                        TimerHide.Stop();
                    }

                    //}

                    //Console.WriteLine(" Native.Document.body.ondragover");
                };

            Native.Document.body.ondragover += ondragover;
            dz.Container.ondragover += ondragover;

            //dz.Container.ondragstart +=
            //    evt =>
            //    {
            //        Console.WriteLine("ondragstart");


            //        evt.stopPropagation();
            //        evt.preventDefault();
            //    };

            dz.Container.ondragleave +=
                 evt =>
                 {
                     //Console.WriteLine("ondragleave");

                     //Console.WriteLine(" dz.Container.ondragleave");

                     evt.stopPropagation();
                     evt.preventDefault();

                     TimerHide.StartTimeout(90);
                 };

            dz.Container.ondrop +=
                evt =>
                {
                    //Console.WriteLine("ondrop");

                    TimerHide.StartTimeout(90);

                    evt.stopPropagation();
                    evt.stopImmediatePropagation();

                    evt.preventDefault();

                    // can we use a webClient yet?
                    var xhr = new IXMLHttpRequest();

                    // does not work for chrome?
                    //xhr.setRequestHeader("WebServiceMethod", "FileStorageUpload");

                    // which server?
                    xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/FileStorageUpload");

                    // http://stackoverflow.com/questions/13870853/how-to-upload-files-in-web-workers-when-formdata-is-not-defined

                    //var c = new WebClient();

                    ////c.UploadData(
                    //c.UploadProgressChanged +=
                    //    (sender, args) =>
                    //    {

                    //    };

                    //c.UploadFileAsync(



                    #region send
                    var d = new FormData();

                    evt.dataTransfer.files.AsEnumerable().WithEachIndex(
                        (f, index) =>
                        {
                            d.append("file" + index, f, f.name);
                        }
                    );

                    xhr.InvokeOnComplete(
                        delegate
                        {
                            Console.WriteLine("upload complete!");

                            DoRefresh();
                        }
                    );

                    var upload = new Uploading();

                    upload.Container.AttachTo(page.output);
                    // http://www.matlus.com/html5-file-upload-with-progress/
                    xhr.upload.onprogress +=
                        e =>
                        {
                            var p = (int)(e.loaded * 100 / e.total) + "%";

                            upload.status = p;

                            Console.WriteLine("upload.onprogress " + new { e.total, e.loaded });
                        };

                    xhr.send(d);
                    #endregion


                    if (StayAlertTimer != null)
                        StayAlertTimer.Stop();



                };
            #endregion




            DoRefresh();
        }
Beispiel #7
0
        private void UploadProcess(int count)
        {
            int val = count;

            switch (val)
            {
            case 1:
                Uploading.Items();
                break;

            case 3:
                Uploading.Customers();
                break;

            case 4:
                Uploading.User();
                break;

            case 5:
                Uploading.Schedules();
                break;

            case 6:
                Uploading.Companys();
                break;

            case 7:

                break;

            case 8:

                break;

            case 9:

                break;

            case 10:

                break;

            case 11:

                break;

            case 12:
                Uploading.Deliverys();
                break;

            case 13:

                break;

            case 14:
                Uploading.Invoices();
                break;

            case 15:

                break;

            case 16:
                Uploading.CaseTransactions();
                break;

            case 17:

                break;

            case 18:
                Uploading.Payments();
                break;

            case 19:

                break;

            case 20:
                Uploading.Order();
                break;

            case 21:

                break;

            case 22:
                Uploading.Instructions();
                break;

            case 23:

                break;

            case 24:
                Uploading.Follows();
                break;

            case 25:

                break;

            case 26:
                Uploading.ItemReviews();
                break;

            case 27:

                break;

            case 28:
                Uploading.Vendors();
                break;

            case 29:

                break;

            case 30:
                Uploading.ItemStatuses();
                break;

            case 31:

                break;

            case 32:
                Uploading.Rates();
                break;

            case 33:

                break;

            case 34:
                Uploading.Accounts();
                break;

            case 35:

                break;

            case 36:
                Uploading.Repsonsibles();
                break;

            case 37:

                break;

            case 38:
                Uploading.Insurances();
                break;

            case 39:

                break;

            case 40:

                break;

            case 41:

                if (DBConnect.CloseMySqlConn())
                {
                    FeedBack("Uploading of information complete");
                    backgroundWorker.Dispose();
                    return;
                }
                else
                {
                    FeedBack("No valid connection ");
                }
                break;

            case 42:

                break;

            default:
                FeedBack("Processing");
                break;
            }
        }
        public void Upload(string source, string target, Func <string, string> renameCallback, bool deleteSourceFile = false)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrWhiteSpace(target))
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (!File.Exists(source))
            {
                throw new SftpProviderException($"{source} does not exist.");
            }

            if (!IsConnected)
            {
                throw new SftpProviderException("Connect to server before upload.");
            }

            var targetPath = target;

            try
            {
                CreateDirectory(targetPath);

                var completed = new ManualResetEvent(false);

                using (var fileStream = File.Open(source, FileMode.Open))
                {
                    _log.Debug(m => m("Uploading {0} to {1}", source, _host));

                    var totalBytes = (ulong)fileStream.Length;

                    if (totalBytes == 0)
                    {
                        if (!_client.Exists(target))
                        {
                            _client.Create(target).Close();
                        }
                        Uploading?.Invoke(target, 0, 0);

                        _log.Info(m => m("Upload {0} to {1} completed.", source, _host));
                    }
                    else
                    {
                        _client.UploadFile(fileStream, target, bytes =>
                        {
                            Uploading?.Invoke(target, bytes, totalBytes);

                            if (bytes == totalBytes)
                            {
                                _log.Info(m => m("Upload {0} to {1} completed.", source, _host));
                                completed.Set();
                            }
                            else
                            {
                                _log.Debug(m => m("Uploading {0} to {1} {2}/{3}", source, _host, bytes, totalBytes));
                            }
                        });

                        completed.WaitOne();
                    }

                    fileStream.Close();

                    if (renameCallback != null)
                    {
                        var renamedFile = renameCallback(targetPath);
                        if (string.CompareOrdinal(targetPath, renamedFile) != 0)
                        {
                            _client.RenameFile(targetPath, renamedFile);
                        }
                    }

                    if (!deleteSourceFile)
                    {
                        return;
                    }

                    File.Delete(source);
                    _log.Debug($"{source} deleted.");
                }
            }
            catch (Exception e)
            {
                throw new SftpProviderException(e.Message, e);
            }
        }
 protected virtual void RaiseUploadingEvent(int count)
 {
     Uploading?.Invoke(this, new UploadingEventArgs(count));
 }
        public void Upload(string source, string target, Func <string, string> renameCallback, bool deleteSourceFile = false)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrWhiteSpace(target))
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (!File.Exists(source))
            {
                throw new SftpProviderException($"{source} does not exist.");
            }

            if (string.CompareOrdinal(source, target) == 0)
            {
                throw new SftpProviderException("Target cannot be same as source.");
            }

            if (!IsConnected)
            {
                throw new SftpProviderException("Connect to server before upload.");
            }

            try
            {
                if (target.IndexOf("\\", StringComparison.InvariantCulture) != -1)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(target));
                }

                _log.Debug(m => m("Uploading {0} to {1}", source, target));
                var   buffer = new byte[2048];
                ulong bytes  = 0;

                using (var fileStream = File.Open(source, FileMode.Open))
                {
                    var totalBytes = (ulong)fileStream.Length;

                    if (totalBytes == 0)
                    {
                        File.Create(target).Close();
                        Uploading?.Invoke(target, 0, 0);
                        _log.Info(m => m("Upload {0} to {1} completed.", source, target));
                    }
                    else
                    {
                        using (var targetFileStream = File.Create(target))
                        {
                            long bytesRead;
                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                bytes += (ulong)bytesRead;
                                targetFileStream.Write(buffer, 0, buffer.Length);

                                _log.Debug(m => m("Uploading {0} to {1} {2}/{3}", source, target, bytes, totalBytes));
                                Uploading?.Invoke(target, bytes, totalBytes);
                            }
                            _log.Info(m => m("Upload {0} to {1} completed.", source, target));
                            Uploading?.Invoke(target, bytes, totalBytes);

                            targetFileStream.Close();
                        }
                        fileStream.Close();

                        if (renameCallback != null)
                        {
                            File.Move(target, renameCallback(target));
                        }

                        if (!deleteSourceFile)
                        {
                            return;
                        }

                        File.Delete(source);
                        _log.Debug($"{source} deleted.");
                    }
                }
            }
            catch (Exception e)
            {
                throw new SftpProviderException(e.Message, e);
            }
        }
Beispiel #11
0
        public async Task <UploadResult> UploadStart(DataChunkSize dataChunkSize = DataChunkSize.ChunkSize_10MB)
        {
            youtubeSession.TryGetTarget(out YouTubeSession session);

            if (UploadingStatus == UploadingStatus.UploadCanceled)
            {
                UploadingStatus = UploadingStatus.Queued;
                video.Id        = null;
                if (mediaStream != null)
                {
                    mediaStream.Dispose();
                }
                mediaStream        = null;
                Progress           = 0;
                TotalUploaded      = 0;
                TimeRemaining      = new TimeSpan();
                videoInsertRequest = null;
                IsManuallyPaused   = false;
            }

            if (video.Id != null && (
                    UploadingStatus == UploadingStatus.UploadFailed ||
                    UploadingStatus == UploadingStatus.UploadCompleted ||
                    UploadingStatus == UploadingStatus.UpdateFailed ||
                    UploadingStatus == UploadingStatus.UpdateComplete
                    ))
            {
                UploadingStatus = UploadingStatus.UpdateStart;

                await UploadThumbnail(video.Id);

                var videoUpdateRequest = session.YouTubeService.Videos.Update(video, "snippet,status");
                var result             = await videoUpdateRequest.ExecuteAsync();

                if (result != null)
                {
                    UploadingStatus = UploadingStatus.UpdateComplete;
                    PC(nameof(UploadingStatus));
                    Completed?.Invoke(this, EventArgs.Empty);
                    return(UploadResult.Succeed);
                }
                else
                {
                    UploadingStatus = UploadingStatus.UpdateFailed;
                    PC(nameof(UploadingStatus));
                    Failed?.Invoke(this, EventArgs.Empty);
                    return(UploadResult.Succeed);
                }
            }

            if (!(UploadingStatus == UploadingStatus.Queued || UploadingStatus == UploadingStatus.UploadFailed))
            {
                return(UploadResult.AlreadyUploading);
            }

            UploadingStatus = UploadingStatus.PrepareUpload;

            bool virIsNull = videoInsertRequest == null;

            if (virIsNull)
            {
                videoInsertRequest = session.YouTubeService.Videos.Insert(video, "snippet,status", mediaStream, "video/*");
                if (videoInsertRequest == null)
                {
                    UploadingStatus = UploadingStatus.UploadFailed;
                    return(UploadResult.FailedUploadRequest);
                }

                DataChunkSize = dataChunkSize;
                videoInsertRequest.ProgressChanged += (uploadProgress) =>
                {
                    TotalUploaded = uploadProgress.BytesSent;
                    Progress      = uploadProgress.BytesSent / ( double )mediaStream.Length;
                    double percentage = (uploadProgress.BytesSent - lastSentBytes) / ( double )mediaStream.Length;
                    lastSentBytes = uploadProgress.BytesSent;
                    double totalSeconds = (DateTime.Now.TimeOfDay - startTime).TotalSeconds;
                    TimeRemaining = Progress != 0 ? TimeSpan.FromSeconds((totalSeconds / Progress) * (1 - Progress)) : TimeSpan.FromDays(999);

                    switch (uploadProgress.Status)
                    {
                    case UploadStatus.Starting:
                        startTime       = DateTime.Now.TimeOfDay;
                        UploadingStatus = UploadingStatus.UploadStart;
                        Started?.Invoke(this, EventArgs.Empty);
                        break;

                    case UploadStatus.Uploading:
                        UploadingStatus = UploadingStatus.Uploading;
                        Uploading?.Invoke(this, EventArgs.Empty);
                        break;

                    case UploadStatus.Failed:
                        UploadingStatus = UploadingStatus.UploadFailed;
                        Failed?.Invoke(this, EventArgs.Empty);
                        break;

                    case UploadStatus.Completed:
                        UploadingStatus = UploadingStatus.UploadCompleted;
                        Uploading?.Invoke(this, EventArgs.Empty);
                        Completed?.Invoke(this, EventArgs.Empty);
                        mediaStream.Dispose();
                        mediaStream = null;
                        break;
                    }

                    PC(nameof(Progress));
                    PC(nameof(UploadingStatus));
                    PC(nameof(TotalUploaded));
                    PC(nameof(TimeRemaining));
                };
                videoInsertRequest.ResponseReceived += async(video) =>
                {
                    await UploadThumbnail(video.Id);

                    foreach (var playlist in Playlists)
                    {
                        playlist.AddVideo(video.Id);
                    }
                };
            }

            try
            {
                startTime = DateTime.Now.TimeOfDay;
                cancellationTokenSource = new CancellationTokenSource();
                var uploadStatus = virIsNull ?
                                   await videoInsertRequest.UploadAsync(cancellationTokenSource.Token) :
                                   await videoInsertRequest.ResumeAsync(cancellationTokenSource.Token);

                cancellationTokenSource.Dispose();
                video = videoInsertRequest.ResponseBody ?? video;
                if (uploadStatus.Status == UploadStatus.NotStarted)
                {
                    UploadingStatus = UploadingStatus.UploadFailed;
                    return(UploadResult.CannotStartUpload);
                }
            }
            catch
            {
                UploadingStatus = UploadingStatus.UploadFailed;
                return(UploadResult.UploadCanceled);
            }

            return(UploadResult.Succeed);
        }
Beispiel #12
0
 private void _adapter_Uploading(string file, ulong uploaded, ulong totalBytes)
 {
     Uploading?.Invoke(file, uploaded, totalBytes);
 }