public MatsScenario CreateScenario()
        {
            var scenario = _scenarioStore.CreateScenario();

            _uploader.Upload(GetEventsForUpload());
            return(scenario);
        }
        public async Task <IActionResult> Create(int unitId, ContentViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (Request.Form.Files == null || Request.Form.Files.Count < 1)
            {
                return(BadRequest("No file included in form data."));
            }

            var unit = _repos.Units.Get(unitId);

            if (unit == null)
            {
                return(NotFound("No record of units exists with that Id."));
            }

            IFile file = new FormFile(Request.Form.Files[0]);

            string uploadResult = await _uploader.Upload(file);

            if (string.IsNullOrWhiteSpace(uploadResult))
            {
                return(this.Error("Uploading file failed. Please try again."));
            }

            var content = _mapper.Map <DAL.Models.Content>(model);

            content.FileName = file.FileName;
            content.Type     = file.Format;
            content.Url      = uploadResult;
            content.Unit     = unit;

            // get & attach lecturer (uploader)
            var user = await _userManager.GetUserAsync(User);

            var lecturer = _repos.Lecturers.Get(user.AccountId);

            if (lecturer == null)
            {
                return(this.UnAuthorized("Current user account used in uploading content does not have have a valid Lecturer record."));
            }

            content.UploadedBy = lecturer;

            // save content finally
            content = _repos.Contents.Create(content);
            _repos.Commit();

            await _notify.OnNewContent(content);

            return(Created($"api/contents/{content.Id}", content));
        }
Example #3
0
 /// <summary>
 /// Log debug information
 /// </summary>
 /// <param name="command">The command</param>
 /// <param name="cancellationToken">The cancellation token</param>
 /// <returns>Upload continues</returns>
 public Task <IUploadResult> Upload(
     TCommand command,
     CancellationToken cancellationToken)
 {
     if (_logger.IsDebugEnabled)
     {
         return(UploadWithDebug(command, cancellationToken));
     }
     else
     {
         return(_uploader.Upload(command, cancellationToken));
     }
 }
Example #4
0
        public void Send(string Message, params IAttachment[] Attachments)
        {
            List <string> messagesToSend = new List <string>();

            // split up multi-line messages
            messagesToSend.AddRange(Message.Split('\n'));

            // upload each attachment.
            if (Attachments != null)
            {
                foreach (IAttachment attachment in Attachments)
                {
                    if (attachment is ImageAttachment)
                    {
                        string image = _uploader.Upload(attachment as ImageAttachment).Result;
                        if (!string.IsNullOrEmpty(image))
                        {
                            messagesToSend.Add(image);
                        }
                    }
                }
            }

            foreach (string message in messagesToSend)
            {
                _inner.Client.LocalUser.SendMessage(_inner, message);
            }
        }
Example #5
0
        private async Task UploadLoop()
        {
            while (await processingQueue.OutputAvailableAsync())
            {
                try {
                    var file = await processingQueue.TakeAsync();

                    file.UploadStatus = UploadStatus.InProgress;

                    // test if replay is eligible for upload (not AI, PTR, Custom, etc)
                    var replay = _analyzer.Analyze(file);
                    if (file.UploadStatus == UploadStatus.InProgress)
                    {
                        // if it is, upload it
                        await _uploader.Upload(replay, file);
                    }
                    SaveReplayList();
                    if (ShouldDelete(file, replay))
                    {
                        DeleteReplay(file);
                    }
                }
                catch (Exception ex) {
                    _log.Error(ex, "Error in upload loop");
                }
            }
        }
Example #6
0
 private static void Upload(IUploader uploader, string filePath)
 {
     for (int iteration = 0; iteration < 100; iteration++)
     {
         Console.WriteLine(iteration);
         using (var stream = File.OpenRead(filePath))
         {
             uploader.Upload(stream, iteration);
         }
     }
 }
Example #7
0
        /// <summary>
        /// Logs upload has started and continues with uploading
        /// </summary>
        /// <param name="command">The command</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>Upload continues</returns>
        public Task <IUploadResult> Upload(TCommand command, CancellationToken cancellationToken)
        {
            Argument.NotNull(command, nameof(command));

            if (_logger.IsInfoEnabled == true)
            {
                _logger.InfoFormat("Uploading {0}", command.Path);
            }

            return(_uploader.Upload(command, cancellationToken));
        }
Example #8
0
        public void Run()
        {
            var logger = _loggerFactory.CreateLogger <TmetricLoadService>();

            var logs = _loadService.Load();
            var aggregatedTimeEntries = logs.ToList();

            logger.LogInformation($"Aggregated entries found: {aggregatedTimeEntries.Count}");

            var issueKeys = aggregatedTimeEntries.Select(e => e.IssueKey).Distinct();
            var pwd       = _security.Decrypt("JiraPassword");

            _uploader.Upload(pwd, issueKeys, aggregatedTimeEntries);
        }
Example #9
0
        void UploadFile(UploadFile file)
        {
            Invoke(new Action(() =>
            {
                lblUploadFile.Text = "上傳檔案 : " + file.File.Name;

                int count         = this.files.Length;
                lblFileCount.Text = "檔案數 : " + (count - ques.Count) + "/" + this.files.Length;
            }));

            //string ftp = Path.Combine(this.url, file.ServerPath);
            string ftp = PathHelper.CombineURL(this.url, file.ServerPath);

            ftp = ftp.Replace(@"\", "/");
            uploader.Upload(ftp, file.File.FullName, this.user, this.password);
        }
Example #10
0
        public async Task <HttpResponseMessage> Upload()
        {
            logger.Info("Started");
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new InvalidOperationException("Required MimeMultipartContent");
            }

            logger.Info("File meet the requirements, upload starting");
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            var num = 0;

            foreach (var file in provider.Contents)
            {
                var name     = file.Headers.ContentDisposition.FileName;
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');

                if (!filename.EndsWith(".txt"))
                {
                    throw new InvalidOperationException("Required '.txt' file only");
                }

                var text = Encoding.Default.GetString(await file.ReadAsByteArrayAsync());
                logger.Info("Perevedeno v stroku");

                try
                {
                    num += await uploader.Upload(text).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException(ex.InnerException.Message);
                }
            }

            if (num == 0)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "Выписок не найдено"));
            }

            return(Request.CreateResponse(HttpStatusCode.OK, $"Всего сохранено выписок {num}"));
        }
Example #11
0
        public IActionResult Upload(IFormFile file)
        {
            var result = _uploader.Upload(new AliyunOssInput()
            {
                Stream = file.OpenReadStream(),
                Ext    = Path.GetExtension(file.FileName).TrimStart('.')
            });

            if (result.IsSuccess)
            {
                return(Ok(OperateResult.Succeed("上传成功", new
                {
                    fiileName = result.FileName,
                    filePath = result.FilePath,
                    fileUrl = result.FileFullPath,
                })));
            }
            else
            {
                return(Ok(OperateResult.Error("上传失败,请稍后再试")));
            }
        }
Example #12
0
        /// <summary>
        /// Handles creating the create stream from path query and uploading the datasource file
        /// </summary>
        /// <param name="command">The command</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The response</returns>
        public async Task <UploadDataSourceFileCommandResult> Handle(
            UploadDataSourceFileCommand command,
            CancellationToken cancellationToken)
        {
            Argument.NotNull(command, nameof(command));

            var commandResult = new UploadDataSourceFileCommandResult();

            var query = new CreateStreamFromPathQuery
            {
                Path = command.Path
            };

            using (var queryResult = await _queryHandler
                                     .Handle(query, cancellationToken)
                                     .ConfigureAwait(Await.Default))
            {
                var uploadCommand = new DataSourceFileUploadCommand
                {
                    DataSourceId     = command.DataSourceId,
                    File             = queryResult.File,
                    FileName         = queryResult.FileName,
                    Path             = queryResult.Path,
                    Size             = queryResult.Size,
                    CreationTimeUtc  = queryResult.CreationTimeUtc,
                    LastWriteTimeUtc = queryResult.LastWriteTimeUtc,
                };

                _ = await _uploader
                    .Upload(uploadCommand, cancellationToken)
                    .ConfigureAwait(Await.Default);
            }

            commandResult.Result = UploadDataSourceFileCommandResultKind.Success;

            return(commandResult);
        }
Example #13
0
        /// <summary>
        /// Uploads the file if the check finds that upload is needed
        /// </summary>
        /// <param name="command">The command</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The response</returns>
        public async Task <IUploadResult> Upload(TCommand command, CancellationToken cancellationToken)
        {
            Argument.NotNull(command, nameof(command));

            var query = new FileNeedsUploadQuery
            {
                File             = command.File,
                FileName         = command.FileName,
                Path             = command.Path,
                Size             = command.Size,
                CreationTimeUtc  = command.CreationTimeUtc,
                LastWriteTimeUtc = command.LastWriteTimeUtc,
            };

            var queryResult = await _queryHandler
                              .Handle(query, cancellationToken)
                              .ConfigureAwait(Await.Default);

            bool upload = queryResult.FileNeedsUpload;

            if (upload == true)
            {
                return(await _uploader
                       .Upload(command, cancellationToken)
                       .ConfigureAwait(Await.Default));
            }
            else
            {
                var uploadResult = new UploadResult
                {
                    Success = true,
                };

                return(uploadResult);
            }
        }
        public async Task <IActionResult> Create(CourseViewModel model)
        {
            Course course = _mapper.Map <Course>(model);

            course.Code = Guid.NewGuid();

            // upload backdrop image
            if (Request.Form.Files.Count > 0)
            {
                var uploadedFile = Request.Form.Files[0];

                if (uploadedFile.Length > 0)
                {
                    IFile file = new FormFile(Request.Form.Files[0]);
                    course.BackdropUrl = await _uploader.Upload(file);
                }
                else
                {
                    course.BackdropUrl = "https://devtimmystorage.blob.core.windows.net/images/education_button2.jpg";
                }
            }

            // get school
            var school = _repos.Schools.Get(1);

            if (school == null)
            {
                return(NotFound("Adding course to a non-existant school. School with that Id not found."));
            }

            course.School = school;
            course        = _repos.Courses.Create(course);
            _repos.Commit();

            return(RedirectPermanent(Request.Headers["Referer"].ToString()));
        }
Example #15
0
        public async Task <ActionResult> Profile()
        {
            try
            {
                int type = int.Parse(Request.Form["Type"]);

                var user = await _userManager.GetUserAsync(User);

                var profile = new Profile
                {
                    FullNames  = Request.Form["FullNames"],
                    NationalID = int.Parse(Request.Form["ID"])
                };
                if (Request.Form.Files.Count > 0)
                {
                    IFile file = new FormFile(Request.Form.Files[0]);
                    profile.PhotoUrl = await _uploader.Upload(file);
                }
                if (type == 1)
                {
                    //lec
                    Lecturer lecturer = new Lecturer(Guid.Parse(user.Id))
                    {
                        Profile = profile
                    };
                    _lepadContext.Lecturers.Add(lecturer);
                    _lepadContext.SaveChanges();

                    user.AccountId   = lecturer.Id;
                    user.AccountType = AccountType.Lecturer;
                }
                else if (type == 2)
                {
                    //student
                    Student student = new Student(Guid.Parse(user.Id))
                    {
                        YearOfStudy  = int.Parse(Request.Form["YrOfStudy"]),
                        AcademicYear = Request.Form["AcademicYr"],
                        RegNo        = Request.Form["RegNo"],
                        Profile      = profile,
                    };
                    _lepadContext.Students.Add(student);
                    _lepadContext.SaveChanges();

                    user.AccountId   = student.Id;
                    user.AccountType = AccountType.Student;
                }
                else if (type == 0)
                {
                    // admin
                    Admin admin = new Admin(Guid.Parse(user.Id))
                    {
                        Profile = profile
                    };

                    _lepadContext.Administrators.Add(admin);
                    _lepadContext.SaveChanges();

                    user.AccountId   = admin.Id;
                    user.AccountType = AccountType.Administrator;
                }

                // add claims we need in the app (userId, accountType)

                var claims = new List <Claim> {
                    new Claim("UserId", user.Id),
                    new Claim("ProfileId", profile.Id.ToString())
                };

                if (!string.IsNullOrWhiteSpace(profile.FullNames))
                {
                    claims.Add(new Claim("FullNames", profile.FullNames));
                }

                if (!string.IsNullOrWhiteSpace(profile.PhotoUrl))
                {
                    claims.Add(new Claim("PhotoUrl", profile.PhotoUrl));
                }

                await _userManager.AddClaimsAsync(user, claims);

                //update user identity account
                var result = await _userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return(RedirectPermanent("/"));
                }
                else
                {
                    return(Content(result.Errors.First().Description));
                }
            }
            catch (Exception ex)
            {
                return(Content(ex.Message));
            }
        }
Example #16
0
        private async Task UploadPackage()
        {
            Uploading      = true;
            SuccessMessage = "";
            ErrorMessage   = "";

            // アップロードするパッケージをクラスに格納
            var version = new AppVersion()
            {
                Version1 = StringToUint(version1),
                Version2 = StringToUint(version2),
                Version3 = StringToUint(version3),
                Version4 = StringToUint(version4),
            };

            var supportedArchitecture = SupportedArchitectureHelper.GetSupportedArchitectureFromAppPackage(appPackage);

            // アプリが対応するアーキテクチャ依存ファイルのみをアップロード
            var dependencies = new List <StorageFile>();

            foreach (var dep in dependenciesFiles)
            {
                var parent          = System.IO.Directory.GetParent(dep.Path);
                var depArchitecture = SupportedArchitectureHelper.StringToSupportedArchitectureType(parent.Name);

                if (supportedArchitecture.HasFlag(depArchitecture))
                {
                    dependencies.Add(dep);
                }
            }

            var uploadPackage = new Application()
            {
                DeveloperName         = developerName,
                Name                  = name,
                Version               = version,
                SupportedArchitecture = supportedArchitecture,
                AppPackage            = appPackage,
                Dependencies          = dependencies,
            };

            var r = ResourceLoader.GetForCurrentView();

            if (uploadPackage.IsValid)
            {
                var uploadingMessageTemplate = r.GetString("Upload_UploadingMessage");
                var uploadingMessage         = string.Format(uploadingMessageTemplate, uploadPackage.Name);

                var uploadedMessageTemplate = r.GetString("Upload_SuccessMessage");
                var uploadedMessage         = string.Format(uploadedMessageTemplate, uploadPackage.Name + " " + uploadPackage.Version.ToString());

                indicator?.Hide();
                indicator = new BusyIndicator()
                {
                    Message = uploadingMessage
                };
                indicator.Show();

                SuccessMessage = uploadingMessage;

                var(appInfo, result) = await uploader.Upload(uploadPackage);

                switch (result)
                {
                case UploadStatusType.NewlyUploaded:
                    var app = new AppInfoForInstall()
                    {
                        AppInfo = appInfo
                    };
                    app.SelectLatestVersion();
                    NavigationService.Navigate(typeof(EditApplicationPage), app);
                    break;

                case UploadStatusType.Updated:
                    // 入力項目をクリア
                    Version1   = "";
                    Version2   = "";
                    Version3   = "";
                    Version4   = "";
                    Name       = "";
                    AppPackage = null;
                    await ClearDependency();

                    SuccessMessage = uploadedMessage;
                    break;

                case UploadStatusType.NetworkError:
                case UploadStatusType.UnknownError:
                    SuccessMessage = "";
                    ErrorMessage   = r.GetString("Upload_FailureMessage");
                    break;
                }
                indicator?.Hide();
            }
            else
            {
                ErrorMessage = r.GetString("Upload_MissingMessage");
            }
            Uploading = false;
        }
        public async Task <IActionResult> Add(int unitId)
        {
            ContentViewModel model = new ContentViewModel
            {
                Title       = Request.Form["Title"],
                Description = Request.Form["Desc"]
            };

            if (unitId < 1)
            {
                return(BadRequest("Invalid unit id."));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // get unit
            var unit = _repos.Units.Get(unitId);

            if (unit == null)
            {
                return(NotFound("Unit record with that Id does not exist."));
            }

            // get current user account
            AppUser user = await _userManager.GetUserAsync(User);

            //int account = this.GetAccountId();

            // get lecturer account
            var lec = _repos.Lecturers.GetWith(user.AccountId, "Profile");

            if (lec == null)
            {
                return(NotFound("Current logged in user does not have a valid lecturer account."));
            }

            // get content data
            var content = new Content()
            {
                Title       = model.Title,
                Description = model.Description,
                Unit        = unit,
                UploadedBy  = lec
            };

            int contentType = int.Parse(Request.Form["ContentType"]);

            if (contentType == 1)
            {
                if (string.IsNullOrWhiteSpace(Request.Form["Url"]))
                {
                    return(Redirect(Request.Headers["Referer"]));
                }
                else
                {
                    content.FileName = "Uploaded via Url";
                    content.Type     = (FormatType)int.Parse(Request.Form["UrlFileType"]);
                    content.Url      = Request.Form["Url"];
                }
            }
            else if (contentType == 2)
            {
                // try upload attached file
                if (Request.Form.Files.Count < 1)
                {
                    return(BadRequest("No file attached to the upload request. Contents must point to valid uploaded files."));
                }

                IFile file = new FormFile(Request.Form.Files[0]);

                content.FileName = file.FileName;
                content.Type     = file.Format;

                try
                {
                    content.Url = await _uploader.Upload(file);
                }
                catch (Exception)
                {
                    return(this.Error(HttpStatusCode.InternalServerError, "Uploading file failed! Please try again."));
                }
            }

            try
            {
                content = _repos.Contents.Create(content);
                _repos.Commit();

                await _notify.OnNewContent(content);

                return(LocalRedirect($"/contents/{content.Id}/{Services.Extensions.GenerateSlug(content.Title)}"));
            }
            catch (Exception ex)
            {
                return(this.Error(ex));
            }
        }
        /// <summary>
        /// Saves the result of the upload
        /// </summary>
        /// <param name="command">The command</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The upload result</returns>
        public async Task <IUploadResult> Upload(TCommand command, CancellationToken cancellationToken)
        {
            Argument.NotNull(command, nameof(command));

            var uploadResult = await _uploader
                               .Upload(command, cancellationToken)
                               .ConfigureAwait(Await.Default);

            var now = _dateTimeProvider.UtcNow;

            var file = _dataContext.DataSources
                       .Where(x => string.Equals(command.Path, x.Path, StringComparison.OrdinalIgnoreCase) == true)
                       .FirstOrDefault();

            if (file == null)
            {
                file = new DataSource
                {
                    Path     = command.Path,
                    Attempts = 0,
                };

                _dataContext.DataSources.Add(file);
            }

            if (file.Attempts.HasValue == false)
            {
                file.Attempts = 0;
            }

            if (uploadResult.Success == true)
            {
                var query = new HashFileQuery
                {
                    File = command.File,
                };

                var queryResult = await _hashFileQueryHandler
                                  .Handle(query, cancellationToken)
                                  .ConfigureAwait(Await.Default);

                file.UploadNeeded      = false;
                file.LastUploadDate    = now;
                file.Size              = command.Size;
                file.Hash              = queryResult.Hash;
                file.CreationTimeUtc   = command.CreationTimeUtc;
                file.LastWriteTimeUtc  = command.LastWriteTimeUtc;
                file.LastHashCheckDate = now;
                file.Attempts          = 1;
            }
            else
            {
                file.UploadNeeded = true;
                file.Attempts++;
            }

            await _dataContext
            .SaveChanges(cancellationToken)
            .ConfigureAwait(Await.Default);

            return(uploadResult);
        }