コード例 #1
0
        public ActionResult Categories(Category c)
        {
            bool   success = false;
            string Message = "";

            try
            {
                HttpPostedFileBase file = c.ImageFile;
                byte[]             data;
                using (Stream inputStream = file.InputStream)
                {
                    MemoryStream memoryStream = inputStream as MemoryStream;
                    if (memoryStream == null)
                    {
                        memoryStream = new MemoryStream();
                        inputStream.CopyTo(memoryStream);
                    }
                    data = memoryStream.ToArray();
                }
                c.Image = FileUploader.UploadFile(Path.GetFileName(file.FileName), data);
            }
            catch
            {
                success = false;
                Message = "Image Uploading Failed";
                goto end;
            }
            if (c.UpdateImage())
            {
                success = true;
                Message = "Image Updated Successfully";
            }
            else
            {
                success = false;
                Message = "Image Updating Failed";
            }
end:
            return(Json(new { success = success, message = Message }));
        }
コード例 #2
0
        public async Task <IActionResult> Create(IFormFile image, Product product)
        {
            try
            {
                var filename = FileUploader.UploadFile(image);
                product.ImageUrl = filename;
            }
            catch (Exception)
            {
                return(BadRequest());
            }

            if (ModelState.IsValid)
            {
                _context.Add(product);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CategoryId"] = new SelectList(_context.Categories, "Id", "Id", product.CategoryId);
            return(View(product));
        }
コード例 #3
0
        public async Task <ActionResult> Add(NewPublicationViewModel model)
        {
            byte[] content = null; //array that will contain bytes of content
            if (model.ContentType == ContentType.Image)
            {
                //TODO: Bad code. Need holder for image types names
                if (Request.Files.Count > 0 && (Request.Files[0].ContentType == System.Net.Mime.MediaTypeNames.Image.Gif || Request.Files[0].ContentType == System.Net.Mime.MediaTypeNames.Image.Jpeg))
                {
                    content = FileUploader.UploadFile(Request.Files[0]); //Convert uploaded file to byte array
                }
                else //if file is empty or has unsupported type
                {
                    ModelState.AddModelError("ImageFile", "For image post you must upload image file"); //Add validation error to model
                    return(View(model));
                }
            }
            else //if puplication has text content
            {
                content = Encoding.Default.GetBytes(model.Text); //convert text content to byte array
            }

            var publication = new CreatePublicationData() //create new publication object that contains main data to add to source
            {
                Author      = User.Identity.Name,
                Content     = content,
                ContentType = model.ContentType,
                Title       = model.Title
            };
            var result = await ContentService.CreatePublication(publication); //trying to add publication data to source

            if (result.Succedeed)                                             //if data was successfully added
            {
                return(RedirectToRoute(new { controller = "Home", action = "Hot" }));
            }

            ModelState.AddModelError("", "Cant`create publication: " + result.Message); //add validation error to model
            return(View());
        }
コード例 #4
0
        public UploadFileViewModel POST(RouteUploadFile request)
        {
            var uploadVm = new UploadFileViewModel();
            var files    = Request.Files;

            if (files.Length == 1)
            {
                var file = files[0];

                #region   文件
                try
                {
                    if (null != file && file.ContentLength != 0L)
                    {
                        var info = ZZTXManager.GetADCDInfoByADCD(adcd);
                        if (info == null)
                        {
                            throw new Exception("用户信息为空请重新登陆!");
                        }
                        var fileFolde = "/Upload/33/" + info.adcd.Substring(2, 2) + "/" + info.adcd.Substring(4, 2) + "/" + info.adcd.Substring(6, 3) + "/" + request.adcd;
                        //var fileFolde = "/Upload/" + (info == null ? adcd : info.adnm) + (request.fileFolde != null && request.fileFolde.Trim() != "" ? "/" + request.fileFolde : "");// " / Upload/funds/DocumentBasis";

                        var allowedFileTypes = request.allowedFileTypes;                                       // "doc,docx,pdf";
                        var allowedFileSize  = request.allowedFileSize != 0 ? request.allowedFileSize : 20480; // 20480;

                        var fileName = file.FileName;
                        if (fileName.Contains(":"))
                        {
                            var lastIndex  = fileName.LastIndexOf("\\");
                            var leftLength = fileName.Length - lastIndex - 1;

                            fileName = fileName.Substring(lastIndex + 1, leftLength);
                        }

                        /*第一步上传文件*/
                        FileUploader uploader = new FileUploader(fileFolde, DateTime.Now.ToString("yyyyMMddHHmmssff-") + fileName.Trim(), allowedFileTypes, allowedFileSize);

                        var flag = uploader.UploadFile(file);
                        uploadVm.isSuccess = flag;
                        if (flag)
                        {
                            uploadVm.fileName = fileName.Substring(0, fileName.LastIndexOf("."));
                            uploadVm.fileSrc  = uploader.SaveFilePath;
                            uploadVm.flieSize = (file.ContentLength / 1024) + "kb";
                            uploadVm.fileType = fileName.Substring(fileName.LastIndexOf(".") + 1, fileName.Length - fileName.LastIndexOf(".") - 1);
                            uploadVm.message  = "上传成功";
                        }
                        else
                        {
                            uploadVm.message = "上传失败";
                        }
                    }
                }catch (Exception ex)
                {
                    uploadVm.isSuccess = false;
                    uploadVm.message   = "文件超出规定大小5MB";
                }
                #endregion   文件
            }
            return(uploadVm);
        }
コード例 #5
0
        public ActionResult Save(Menu m)
        {
            try
            {
                bool   success = false;
                string Message = "";
                if (m.ImageFile != null)
                {
                    HttpPostedFileBase file = m.ImageFile;
                    byte[]             data;
                    using (Stream inputStream = file.InputStream)
                    {
                        MemoryStream memoryStream = inputStream as MemoryStream;
                        if (memoryStream == null)
                        {
                            memoryStream = new MemoryStream();
                            inputStream.CopyTo(memoryStream);
                        }
                        data = memoryStream.ToArray();
                    }
                    m.Image = FileUploader.UploadFile(Path.GetFileName(file.FileName), data);
                }
                else
                {
                    m.Image = new Menu().GetMenuById(m.MenuId).Image;
                }
                if (m.MenuId == 0)
                {
                    m.ShopNumber = ((Shop)Session["Shop"]).ShopNumber;
                    if (m.AddMenu())
                    {
                        success = true;
                        Message = "Menu Created Successfully";
                    }
                    else
                    {
                        success = false;
                        Message = "Menu Creation Failed";
                    }
                }
                else
                {
                    m.ShopNumber = ((Shop)Session["Shop"]).ShopNumber;
                    if (m.Update(m.MenuId))
                    {
                        success = true;
                        Message = "Company Details Updated Successfully";
                    }
                    else
                    {
                        success = false;
                        Message = "Company Details Updation Failed";
                    }
                }

                return(Json(new { Success = success, Message = Message }));
            }
            catch
            {
                return(Json(new { Success = false, Message = "Something Unexpected Happened" }));
            }
        }
コード例 #6
0
 /// <summary>
 /// Check <see cref="IAssetBankManager"/> for more information
 /// </summary>
 /// <param name="query">Check <see cref="IAssetBankManager"/> for more information</param>
 /// <returns>Check <see cref="IAssetBankManager"/> for more information</returns>
 public Task UploadFileAsync(UploadQuery query)
 {
     return(_uploader.UploadFile(query));
 }
コード例 #7
0
    protected void OnPatchBuildingContext()
    {
        try
        {
            #region Create new version
            EditorGUILayout.LabelField("New version builder", EditorStyles.boldLabel);

            EditorGUILayout.Space();

            _newVersionWindowScrollPosition = EditorGUILayout.BeginScrollView(_newVersionWindowScrollPosition, GUILayout.MaxHeight(450), GUILayout.ExpandHeight(false));

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("Last version:", GUILayout.MaxWidth(100));
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField(_lastVersion, _lastVersionStyle);
            EditorGUILayout.EndVertical();

            /*EditorGUILayout.BeginVertical();
             * IsIntegrated = EditorGUILayout.ToggleLeft("Is integrated?", IsIntegrated);
             * EditorGUILayout.EndVertical();*/

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal(GUI.skin.box);

            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("New version", GUILayout.MaxWidth(100));
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            _majorVersionNumber = EditorGUILayout.IntField(_majorVersionNumber, GUILayout.MaxWidth(25));
            EditorGUILayout.EndVertical();
            EditorGUILayout.BeginVertical();
            _minorVersionNumber = EditorGUILayout.IntField(_minorVersionNumber, GUILayout.MaxWidth(25));
            EditorGUILayout.EndVertical();
            EditorGUILayout.BeginVertical();
            _maintenanceNumber = EditorGUILayout.IntField(_maintenanceNumber, GUILayout.MaxWidth(25));
            EditorGUILayout.EndVertical();
            EditorGUILayout.BeginVertical();
            _buildNumber = EditorGUILayout.IntField(_buildNumber, GUILayout.MaxWidth(25));
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            GUI.enabled = _patchBuilderStatus == PatchBuilderStatus.IDLE;
            if (GUILayout.Button("New version"))
            {
                string newVersion = _majorVersionNumber + "." + _minorVersionNumber + "."
                                    + _maintenanceNumber + "." + _buildNumber;
                m_patchManager.SetOnSetMainProgressBarAction(OnSetMainProgressBar);
                m_patchManager.SetOnSetDetailProgressBarAction(OnSetDetailProgressBar);
                m_patchManager.SetOnIncreaseMainProgressBarAction(OnIncreaseMainProgressBar);
                m_patchManager.SetOnIncreaseDetailProgressBarAction(OnIncreaseDetailProgressBar);
                m_patchManager.SetOnLogAction(OnLog);
                m_patchManager.SetOnErrorAction(OnError);
                m_patchManager.SetOnFatalErrorAction(OnFatalError);
                m_patchManager.SetOnTaskStartedAction(OnTaskStarted);
                m_patchManager.SetOnTaskCompletedAction(OnTaskCompleted);
                //m_patchManager.BuildNewVersion(newVersion);

                IEnumerable <string> files = FileManager.GetFiles(SettingsManager.PATCHER_FILES_PATH, "*", SearchOption.AllDirectories);
                foreach (string entry in files)
                {
                    string currentFile = entry.Replace(SettingsManager.PATCHER_FILES_PATH, SettingsManager.CURRENT_BUILD_PATH);
                    if (!FileManager.FileExists(currentFile))
                    {
                        if (!FileManager.DirectoryExists(Path.GetDirectoryName(currentFile)))
                        {
                            FileManager.CreateDirectory(Path.GetDirectoryName(currentFile));
                        }
                    }
                    FileManager.FileCopy(entry, currentFile, false);
                }

                _patchBuilderThread = new Thread(() => m_patchManager.BuildNewVersion(newVersion));
                _patchBuilderThread.Start();
            }
            GUI.enabled = true;
            EditorGUILayout.EndVertical();

            EditorGUILayout.EndHorizontal();


            /*EditorGUILayout.BeginHorizontal();
             *
             * EditorGUILayout.BeginVertical();
             * EditorGUI.ProgressBar(new Rect(3, 45, position.width - 6, 20), _detailProgress / _detailProgressBarMax, _detailLog);
             * EditorGUI.ProgressBar(new Rect(3, 70, position.width - 6, 20), _mainProgress / _mainProgressBarMax, _mainLog);
             * EditorGUILayout.Space();
             * EditorGUILayout.Space();
             * EditorGUILayout.Space();
             * EditorGUILayout.Space();
             * EditorGUILayout.Space();
             * EditorGUILayout.Space();
             * EditorGUILayout.Space();
             * EditorGUILayout.EndVertical();
             *
             * EditorGUILayout.EndHorizontal();
             *
             * EditorGUILayout.Separator();*/

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField(_endLog, _endLogStyle);
            EditorGUILayout.EndVertical();

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.EndScrollView();
            #endregion

            #region Create patch
            EditorGUILayout.LabelField("Patch builder", EditorStyles.boldLabel);

            EditorGUILayout.Space();

            _patchesBuilderWindowScrollPosition = EditorGUILayout.BeginScrollView(_patchesBuilderWindowScrollPosition, GUILayout.MaxHeight(450), GUILayout.ExpandHeight(false));

            if (_currentVersions != null && _currentVersions.Length > 1)
            {
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("Compression type:", GUILayout.MaxWidth(150));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                _compressionTypeDropdownIndex = EditorGUILayout.Popup(_compressionTypeDropdownIndex, _compressionTypes, GUILayout.MinWidth(60));
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("Version from:", GUILayout.MaxWidth(100));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                _versionFromDropdownIndex = EditorGUILayout.Popup(_versionFromDropdownIndex, _currentVersions, GUILayout.MinWidth(60));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("Version to:", GUILayout.MaxWidth(100));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                _versionToDropdownIndex = EditorGUILayout.Popup(_versionToDropdownIndex, _currentVersions, GUILayout.MinWidth(60));
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();

                GUI.enabled = _patchBuilderStatus == PatchBuilderStatus.IDLE;
                if (GUILayout.Button("Build patch"))
                {
                    m_patchManager.SetOnSetMainProgressBarAction(OnSetMainProgressBarPatchBuild);
                    m_patchManager.SetOnSetDetailProgressBarAction(OnSetDetailProgressBarPatchBuild);
                    m_patchManager.SetOnIncreaseMainProgressBarAction(OnIncreaseMainProgressBarPatchBuild);
                    m_patchManager.SetOnIncreaseDetailProgressBarAction(OnIncreaseDetailProgressBarPatchBuild);
                    m_patchManager.SetOnLogAction(OnLogPatchBuild);
                    m_patchManager.SetOnErrorAction(OnErrorPatchBuild);
                    m_patchManager.SetOnFatalErrorAction(OnFatalErrorPatchBuild);
                    m_patchManager.SetOnTaskStartedAction(OnTaskStartedPatchBuild);
                    m_patchManager.SetOnTaskCompletedAction(OnTaskCompletedPatchBuild);
                    //m_patchManager.BuildPatch(_currentVersions[_versionFromDropdownIndex], _currentVersions[_versionToDropdownIndex], (CompressionType)Enum.Parse(typeof(CompressionType), _compressionTypes[_compressionTypeDropdownIndex]));
                    _patchBuilderThread = new Thread(
                        () => m_patchManager.BuildPatch(_currentVersions[_versionFromDropdownIndex], _currentVersions[_versionToDropdownIndex], (MHLab.PATCH.Compression.CompressionType)Enum.Parse(typeof(MHLab.PATCH.Compression.CompressionType), _compressionTypes[_compressionTypeDropdownIndex]))
                        );
                    _patchBuilderThread.Start();
                }
                GUI.enabled = true;

                EditorGUILayout.EndHorizontal();

                /*EditorGUILayout.BeginHorizontal();
                 *
                 * EditorGUILayout.BeginVertical();
                 * EditorGUI.ProgressBar(new Rect(3, 60, position.width - 6, 20), _detailProgressPatchBuild / _detailProgressBarMaxPatchBuild, _detailLogPatchBuild);
                 * EditorGUI.ProgressBar(new Rect(3, 85, position.width - 6, 20), _mainProgressPatchBuild / _mainProgressBarMaxPatchBuild, _mainLogPatchBuild);
                 * EditorGUILayout.Space();
                 * EditorGUILayout.Space();
                 * EditorGUILayout.Space();
                 * EditorGUILayout.Space();
                 * EditorGUILayout.Space();
                 * EditorGUILayout.Space();
                 * EditorGUILayout.Space();
                 * EditorGUILayout.Space();
                 * EditorGUILayout.EndVertical();
                 *
                 * EditorGUILayout.EndHorizontal();*/

                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField(_endLogPatchBuild, _endLogStyle);
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();
            }
            else
            {
                EditorGUILayout.BeginHorizontal(GUI.skin.box);

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("There are not enough builds to create patches!");
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.EndScrollView();
            #endregion

            #region Deploy
            EditorGUILayout.LabelField("Deploy", EditorStyles.boldLabel);

            EditorGUILayout.Space();

            _deployWindowScrollPosition = EditorGUILayout.BeginScrollView(_deployWindowScrollPosition, GUILayout.MaxHeight(450), GUILayout.ExpandHeight(false));

            if (_currentVersions != null && _currentVersions.Length > 0)
            {
                if (_scenesInBuildSettings.Count > 0)
                {
                    EditorGUILayout.BeginHorizontal();

                    EditorGUILayout.BeginVertical();
                    EditorGUILayout.LabelField("Compression type:", GUILayout.MaxWidth(150));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.BeginVertical();
                    _deployCompressionTypeDropdownIndex = EditorGUILayout.Popup(_deployCompressionTypeDropdownIndex, _compressionTypes, GUILayout.MinWidth(60));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();

                    EditorGUILayout.BeginVertical();
                    EditorGUILayout.LabelField("Version to deploy:", GUILayout.MaxWidth(150));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.BeginVertical();
                    _versionToDeployDropdownIndex = EditorGUILayout.Popup(_versionToDeployDropdownIndex, _currentVersions, GUILayout.MinWidth(60));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();

                    EditorGUILayout.BeginVertical();
                    EditorGUILayout.LabelField("Platform to deploy:", GUILayout.MaxWidth(150));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.BeginVertical();
                    _platformToDeployDropdownIndex = EditorGUILayout.Popup(_platformToDeployDropdownIndex, _platformsAvailable, GUILayout.MinWidth(60));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();

                    EditorGUILayout.BeginVertical();
                    EditorGUILayout.LabelField("Launcher scene:", GUILayout.MaxWidth(150));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.BeginVertical();
                    _launcherSceneToDeployDropdownIndex = EditorGUILayout.Popup(_launcherSceneToDeployDropdownIndex, _scenesInBuildSettings.ToArray(), GUILayout.MinWidth(60));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();

                    EditorGUILayout.BeginVertical();
                    EditorGUILayout.LabelField("Launcher custom name:", GUILayout.MaxWidth(150));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.BeginVertical();
                    _launcherCustomName = EditorGUILayout.TextField(_launcherCustomName, GUILayout.MinWidth(60));
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal(GUI.skin.box);

                    GUI.enabled = _patchBuilderStatus == PatchBuilderStatus.IDLE;

                    EditorGUILayout.BeginVertical();
                    if (GUILayout.Button("Update scenes", GUILayout.MaxWidth(150)))
                    {
                        UpdateScenesToBuild();
                    }
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.BeginVertical();
                    if (GUILayout.Button("Deploy", GUILayout.MaxWidth(300)))
                    {
                        Deploy();
                    }
                    EditorGUILayout.EndVertical();
                    GUI.enabled = true;

                    EditorGUILayout.EndHorizontal();
                }
                else
                {
                    EditorGUILayout.BeginHorizontal(GUI.skin.box);

                    EditorGUILayout.BeginVertical();
                    EditorGUILayout.LabelField("There are no available scenes to build your Launcher!");
                    EditorGUILayout.EndVertical();

                    EditorGUILayout.EndHorizontal();
                }
            }
            else
            {
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("There are no available builds to deploy your game!");
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.EndScrollView();
            #endregion

            #region Upload to FTP/SFTP
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("Upload to FTP", EditorStyles.boldLabel, GUILayout.MaxWidth(280));
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            if (GUILayout.Button("Save prefs", GUILayout.MaxWidth(150)))
            {
                SaveEditorPrefs();
            }
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            if (GUILayout.Button("Delete prefs", GUILayout.MaxWidth(150)))
            {
                DeleteEditorPrefs();
            }
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space();

            _uploadWindowScrollPosition = EditorGUILayout.BeginScrollView(_uploadWindowScrollPosition, GUILayout.MaxHeight(450), GUILayout.ExpandHeight(false));

            /*EditorGUILayout.BeginHorizontal();
             *
             * EditorGUILayout.BeginVertical();
             * EditorGUILayout.LabelField("Use SFTP:", GUILayout.MaxWidth(150));
             * EditorGUILayout.EndVertical();
             *
             * EditorGUILayout.BeginVertical();
             * _isSFTP = EditorGUILayout.Toggle(_isSFTP, GUILayout.MaxWidth(60));
             * EditorGUILayout.EndVertical();
             *
             * EditorGUILayout.EndHorizontal();*/

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("Host:", GUILayout.MaxWidth(150));
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            _uploadHost = EditorGUILayout.TextField(_uploadHost, GUILayout.MinWidth(60));
            EditorGUILayout.EndVertical();

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("Port:", GUILayout.MaxWidth(150));
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            _uploadHostPort = EditorGUILayout.IntField(_uploadHostPort, GUILayout.MinWidth(60));
            EditorGUILayout.EndVertical();

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("Username:"******"Password:"******"Remote path:", GUILayout.MaxWidth(80));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                _buildsRemotePath = EditorGUILayout.TextField(_buildsRemotePath, GUILayout.MinWidth(60));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("Select build:", GUILayout.MaxWidth(80));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                _versionToUploadDropdownIndex = EditorGUILayout.Popup(_versionToUploadDropdownIndex, _currentVersions, GUILayout.MinWidth(60));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                if (GUILayout.Button("Upload", GUILayout.MaxWidth(150)))
                {
                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Instantiating uploader...", 0);
                    FileUploader uploader = new FileUploader(
                        Protocol.FTP,
                        _uploadHost, _uploadHostPort, _uploadUsername, _uploadPassword
                        );
                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Setting up credentials...", 0.1f);

                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Retrieving files to upload...", 0.2f);
                    string        version        = Path.Combine(SettingsManager.BUILDS_PATH, _currentVersions[_versionToUploadDropdownIndex]);
                    List <string> files          = FileManager.GetFiles(version).ToList();
                    float         singleProgress = 0.7f / files.Count;
                    float         progress       = 0.2f;
                    foreach (string file in files)
                    {
                        string relativeFile    = file.Replace(SettingsManager.BUILDS_PATH, "");
                        string remoteDirectory = Path.Combine(_buildsRemotePath, relativeFile.Replace(Path.GetFileName(file), "")).Replace("\\", "/");
                        uploader.UploadFile(file, remoteDirectory);
                        progress += singleProgress;
                        EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Uploaded " + relativeFile + "!", progress);
                    }

                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Uploading indexes...", 0.95f);
                    string index      = Path.Combine(SettingsManager.BUILDS_PATH, "index");
                    string patchIndex = Path.Combine(SettingsManager.BUILDS_PATH, "index_" + _currentVersions[_versionToUploadDropdownIndex] + ".bix");
                    uploader.UploadFile(index, _buildsRemotePath);
                    uploader.UploadFile(patchIndex, _buildsRemotePath);

                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Done!", 1f);

                    EditorUtility.ClearProgressBar();
                }
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();
                #endregion

                #region Patcher
                EditorGUILayout.BeginHorizontal(GUI.skin.box);

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("Remote path:", GUILayout.MaxWidth(80));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                _patcherRemotePath = EditorGUILayout.TextField(_patcherRemotePath, GUILayout.MinWidth(60));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("Remote path for your launcher", GUILayout.MaxWidth(290), GUILayout.MinWidth(140));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                if (GUILayout.Button("Upload", GUILayout.MaxWidth(150)))
                {
                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Instantiating uploader...", 0);
                    FileUploader uploader = new FileUploader(
                        Protocol.FTP,
                        _uploadHost, _uploadHostPort, _uploadUsername, _uploadPassword
                        );
                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Setting up credentials...", 0.1f);

                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Building launcher...", 0.2f);
                    DeployLauncher();

                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Uploading launcher...", 0.95f);
                    uploader.UploadFile(Path.Combine(SettingsManager.DEPLOY_PATH, "patcher.zip"), _patcherRemotePath);

                    EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Done!", 1f);

                    EditorUtility.ClearProgressBar();
                }
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();
                #endregion
            }
            else
            {
                EditorGUILayout.BeginHorizontal(GUI.skin.box);

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("There are no available builds to upload!");
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();
            }

            if (_currentPatches != null && _currentPatches.Length > 0)
            {
                EditorGUILayout.BeginHorizontal(GUI.skin.box);

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("Remote path:", GUILayout.MaxWidth(80));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                _patchesRemotePath = EditorGUILayout.TextField(_patchesRemotePath, GUILayout.MinWidth(60));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("Select patch:", GUILayout.MaxWidth(80));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                _patchToUploadDropdownIndex = EditorGUILayout.Popup(_patchToUploadDropdownIndex, _currentPatches, GUILayout.MinWidth(60));
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();
                if (GUILayout.Button("Upload", GUILayout.MaxWidth(150)))
                {
                    try
                    {
                        EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Instantiating uploader...", 0);

                        FileUploader uploader = new FileUploader(Protocol.FTP,
                                                                 _uploadHost, _uploadHostPort, _uploadUsername, _uploadPassword
                                                                 );

                        EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Setting up credentials...", 0.1f);

                        EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Retrieving files to upload...", 0.2f);
                        string archive  = Path.Combine(SettingsManager.FINAL_PATCHES_PATH, _currentPatches[_patchToUploadDropdownIndex]) + ".archive";
                        string pix      = Path.Combine(SettingsManager.FINAL_PATCHES_PATH, _currentPatches[_patchToUploadDropdownIndex]) + ".pix";
                        string versions = Path.Combine(SettingsManager.FINAL_PATCHES_PATH, "versions.txt");

                        EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Uploading patch index...", 0.3f);
                        uploader.UploadFile(pix, _patchesRemotePath);
                        EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Uploading patch archive...", 0.6f);
                        uploader.UploadFile(archive, _patchesRemotePath);
                        EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Uploading versions indexer...", 0.9f);
                        uploader.UploadFile(versions, _patchesRemotePath);
                        EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Done!", 1f);

                        EditorUtility.ClearProgressBar();
                    }
                    catch (Exception e)
                    {
                        Debug.Log(e.Message);
                        EditorUtility.ClearProgressBar();
                    }
                }
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();
            }
            else
            {
                EditorGUILayout.BeginHorizontal(GUI.skin.box);

                EditorGUILayout.BeginVertical();
                EditorGUILayout.LabelField("There are no available patches to upload!");
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.EndScrollView();
            #endregion
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
    }
コード例 #8
0
        /// <summary>
        /// Handles the bulk of the work for submitting the job to the cloud.
        /// Zips up ApsimX (if necessary), uploads tools and ApsimX,
        /// </summary>
        /// <param name="e">Event arg, containing the job parameters</param>
        private void SubmitJob_DoWork(object o, DoWorkEventArgs e)
        {
            JobParameters jp = (JobParameters)e.Argument;

            jp.JobId                       = Guid.NewGuid();
            jp.CoresPerProcess             = 1;
            jp.JobManagerShouldSubmitTasks = true;
            jp.AutoScale                   = true;
            jp.PoolMaxTasksPerVM           = 16;
            string tmpZip = "";

            SetAzureMetaData("job-" + jp.JobId, "Owner", Environment.UserName.ToLower());

            // if jp.ApplicationPackagePath is a directory it will need to be zipped up
            if (Directory.Exists(jp.ApplicationPackagePath))
            {
                view.Status = "Zipping APSIM";

                tmpZip = Path.Combine(Path.GetTempPath(), "Apsim-tmp-X-" + Environment.UserName.ToLower() + ".zip");
                if (File.Exists(tmpZip))
                {
                    File.Delete(tmpZip);
                }

                if (CreateApsimXZip(jp.ApplicationPackagePath, tmpZip) > 0)
                {
                    view.Status = "Cancelled";
                    return;
                }

                jp.ApplicationPackagePath    = tmpZip;
                jp.ApplicationPackageVersion = Path.GetFileName(tmpZip).Substring(Path.GetFileName(tmpZip).IndexOf('-') + 1);
            }

            // add current job to the list of jobs

            // TODO : do we actually need/use the APSIMJob class?
            APSIMJob job = new APSIMJob(jp.JobDisplayName, "", jp.ApplicationPackagePath, jp.ApplicationPackageVersion, jp.Recipient, batchAuth, storageAuth, PoolSettings.FromConfiguration());

            job.PoolInfo.MaxTasksPerVM = jp.PoolMaxTasksPerVM;
            job.PoolInfo.VMCount       = jp.PoolVMCount;


            // upload tools such as 7zip, AzCopy, CMail, etc.

            view.Status = "Checking tools";

            string executableDirectory = GetExecutableDirectory();
            string toolsDir            = Path.Combine(executableDirectory, "tools");

            if (!Directory.Exists(toolsDir))
            {
                ShowErrorMessage("Tools Directory not found: " + toolsDir);
            }

            foreach (string filePath in Directory.EnumerateFiles(toolsDir))
            {
                UploadFileIfNeeded("tools", filePath);
            }

            if (jp.Recipient.Length > 0)
            {
                try
                {
                    // Store a config file into the job directory that has the e-mail config

                    string tmpConfig = Path.Combine(Path.GetTempPath(), settingsFileName);
                    using (StreamWriter file = new StreamWriter(tmpConfig))
                    {
                        file.WriteLine("EmailRecipient=" + jp.Recipient);
                        file.WriteLine("EmailSender=" + AzureSettings.Default["EmailSender"]);
                        file.WriteLine("EmailPW=" + AzureSettings.Default["EmailPW"]);
                    }

                    UploadFileIfNeeded("job-" + jp.JobId, tmpConfig);
                    File.Delete(tmpConfig);
                }
                catch (Exception err)
                {
                    ShowError(new Exception("Error writing to settings file; you may not receive an email upon job completion: ", err));
                }
            }

            // upload job manager
            UploadFileIfNeeded("jobmanager", Path.Combine(executableDirectory, "azure-apsim.exe"));



            // upload apsim
            view.Status = "Uploading APSIM Next Generation";

            UploadFileIfNeeded("apsim", jp.ApplicationPackagePath);


            // generate model files

            view.Status = "Generating model files";
            if (!Directory.Exists(jp.ModelPath))
            {
                Directory.CreateDirectory(jp.ModelPath);
            }

            try
            {
                // copy weather files to models directory to be zipped up
                foreach (Models.Weather child in Apsim.ChildrenRecursively(model).OfType <Models.Weather>())
                {
                    if (Path.GetDirectoryName(child.FullFileName) != Path.GetDirectoryName(presenter.ApsimXFile.FileName))
                    {
                        presenter.MainPresenter.ShowError("Weather file must be in the same directory as .apsimx file: " + child.FullFileName);
                        view.Status = "Cancelled";
                        return;
                    }
                    string sourceFile = child.FullFileName;
                    string destFile   = Path.Combine(jp.ModelPath, child.FileName);
                    if (!File.Exists(destFile))
                    {
                        File.Copy(sourceFile, destFile);
                    }
                    ;
                }
                // Generate .apsimx files, and if any errors are encountered, abort the job submission process.
                if (!presenter.GenerateApsimXFiles(model, jp.ModelPath))
                {
                    view.Status = "Cancelled";
                    return;
                }
            }
            catch (Exception err)
            {
                presenter.MainPresenter.ShowError(err);
                return;
            }

            tmpZip = "";

            // zip up models directory
            if (Directory.Exists(jp.ModelPath)) // this test may be unnecessary
            {
                tmpZip = GetTempFileName("Model-", ".zip", true);
                ZipFile.CreateFromDirectory(jp.ModelPath, tmpZip, CompressionLevel.Fastest, false);
                jp.ModelPath = tmpZip;
            }

            // upload models

            view.Status         = "Uploading models";
            job.ModelZipFileSas = uploader.UploadFile(jp.ModelPath, jp.JobId.ToString(), Path.GetFileName(jp.ModelPath));

            // clean up temporary model files
            if (File.Exists(tmpZip))
            {
                File.Delete(tmpZip);
            }
            if (!jp.SaveModelFiles)
            {
                if (Directory.Exists(jp.ModelPath))
                {
                    Directory.Delete(jp.ModelPath);
                }
            }

            view.Status = "Submitting Job";



            // submit job
            try
            {
                CloudJob cloudJob = batchCli.JobOperations.CreateJob(jp.JobId.ToString(), GetPoolInfo(job.PoolInfo));
                cloudJob.DisplayName        = job.DisplayName;
                cloudJob.JobPreparationTask = job.ToJobPreparationTask(jp.JobId, Microsoft.Azure.Storage.Blob.BlobAccountExtensions.CreateCloudBlobClient(storageAccount));
                cloudJob.JobReleaseTask     = job.ToJobReleaseTask(jp.JobId, Microsoft.Azure.Storage.Blob.BlobAccountExtensions.CreateCloudBlobClient(storageAccount));
                cloudJob.JobManagerTask     = job.ToJobManagerTask(jp.JobId, Microsoft.Azure.Storage.Blob.BlobAccountExtensions.CreateCloudBlobClient(storageAccount), jp.JobManagerShouldSubmitTasks, jp.AutoScale);

                cloudJob.Commit();
            }
            catch (Exception err)
            {
                ShowError(err);
            }

            view.Status = "Job Successfully submitted";

            if (jp.AutoDownload)
            {
                AzureResultsDownloader dl = new AzureResultsDownloader(jp.JobId, jp.JobDisplayName, jp.OutputDir, null, true, jp.Summarise, true, true, true);
                dl.DownloadResults(true);
            }
        }
コード例 #9
0
        /// <summary>
        /// Handles the bulk of the work for submitting the job to the cloud.
        /// Zips up ApsimX (if necessary), uploads tools and ApsimX,
        /// </summary>
        /// <param name="e">Event arg, containing the job parameters</param>
        private void SubmitJob_DoWork(object o, DoWorkEventArgs e)
        {
            JobParameters jp = (JobParameters)e.Argument;

            jp.JobId                       = Guid.NewGuid();
            jp.CoresPerProcess             = 1;
            jp.JobManagerShouldSubmitTasks = true;
            jp.AutoScale                   = true;
            jp.PoolMaxTasksPerVM           = 16;
            string tmpZip = "";

            SetAzureMetaData("job-" + jp.JobId, "Owner", Environment.UserName.ToLower());

            // if jp.ApplicationPackagePath is a directory it will need to be zipped up
            if (Directory.Exists(jp.ApplicationPackagePath))
            {
                view.Status = "Zipping APSIM";

                tmpZip = Path.Combine(Path.GetTempPath(), "Apsim-tmp-X-" + Environment.UserName.ToLower() + ".zip");
                if (File.Exists(tmpZip))
                {
                    File.Delete(tmpZip);
                }

                if (createApsimXZip(jp.ApplicationPackagePath, tmpZip) > 0)
                {
                    ShowError("Error zipping up Apsim");
                }

                jp.ApplicationPackagePath    = tmpZip;
                jp.ApplicationPackageVersion = Path.GetFileName(tmpZip).Substring(Path.GetFileName(tmpZip).IndexOf('-') + 1);
            }

            // add current job to the list of jobs

            // TODO : do we actually need/use the APSIMJob class?
            APSIMJob job = new APSIMJob(jp.JobDisplayName, "", jp.ApplicationPackagePath, jp.ApplicationPackageVersion, jp.Recipient, batchCredentials, storageCredentials, PoolSettings.FromConfiguration());

            job.PoolInfo.MaxTasksPerVM = jp.PoolMaxTasksPerVM;
            job.PoolInfo.VMCount       = jp.PoolVMCount;


            // upload tools such as 7zip, AzCopy, CMail, etc.

            view.Status = "Checking tools";

            string executableDirectory = GetExecutableDirectory();
            string toolsDir            = Path.Combine(executableDirectory, "tools");

            if (!Directory.Exists(toolsDir))
            {
                ShowError("Tools Directory not found: " + toolsDir);
            }

            foreach (string filePath in Directory.EnumerateFiles(toolsDir))
            {
                UploadFileIfNeeded("tools", filePath);
            }

            if (jp.Recipient.Length > 0)
            {
                try
                {
                    // Store a config file into the job directory that has the e-mail config

                    string tmpConfig = Path.Combine(Path.GetTempPath(), SETTINGS_FILENAME);
                    using (StreamWriter file = new StreamWriter(tmpConfig))
                    {
                        file.WriteLine("EmailRecipient=" + jp.Recipient);
                        file.WriteLine("EmailSender=" + AzureSettings.Default["EmailSender"]);
                        file.WriteLine("EmailPW=" + AzureSettings.Default["EmailPW"]);
                    }

                    UploadFileIfNeeded("job-" + jp.JobId, tmpConfig);
                    File.Delete(tmpConfig);
                }
                catch (Exception ex)
                {
                    ShowError("Error writing to settings file; you may not receive an email upon job completion: " + ex.ToString());
                }
            }

            // upload job manager
            UploadFileIfNeeded("jobmanager", Path.Combine(executableDirectory, "azure-apsim.exe"));



            // upload apsim
            view.Status = "Uploading APSIM Next Generation";

            UploadFileIfNeeded("apsim", jp.ApplicationPackagePath);


            // create models

            // TODO : show error message if other files already exist in model output directory?
            //        may be necessary if using  a user-selected directory

            string path = "";



            // generate model files

            view.Status = "Generating model files";
            if (!Directory.Exists(jp.ModelPath))
            {
                Directory.CreateDirectory(jp.ModelPath);
            }

            // generate xml
            string xml = "";

            foreach (Simulation sim in Runner.AllSimulations(model))
            {
                path = Path.Combine(jp.ModelPath, sim.Name + ".apsimx");
                // if weather file is not in the same directory as the .apsimx file, display an error then abort
                foreach (var child in sim.Children)
                {
                    if (child is Models.Weather)
                    {
                        string childPath = sim.Children.OfType <Models.Weather>().ToList()[0].FileName;
                        if (Path.GetDirectoryName(childPath) != "")
                        {
                            ShowError(childPath + " must be in the same directory as the .apsimx file" + (sim.FileName != null ? " (" + Path.GetDirectoryName(sim.FileName) + ")" : ""));
                            view.Status = "Cancelled";
                            return;
                        }
                        string sourcePath = sim.Children.OfType <Models.Weather>().ToList()[0].FullFileName;
                        string destPath   = Path.Combine(jp.ModelPath, sim.Children.OfType <Models.Weather>().ToList()[0].FileName);
                        if (!File.Exists(destPath))
                        {
                            File.Copy(sourcePath, destPath);
                        }
                    }
                }
                xml = Apsim.Serialise(sim);
                // delete model file if it already exists
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                string pattern = @"<\?xml[^<>]+>";
                System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                var matches = rx.Matches(xml);
                xml = "<Simulations xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" Version=\"23\">\r\n<Name>" + sim.Name + "</Name>\r\n" + xml.Replace(matches[0].ToString(), "") + "<DataStore><Name>DataStore</Name><AutoExport>false</AutoExport><MaximumResultsPerPage>0</MaximumResultsPerPage></DataStore><ExplorerWidth>296</ExplorerWidth></Simulations>";
                // write xml to file
                using (FileStream fs = File.Create(path))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes(xml);
                    fs.Write(info, 0, info.Length);
                }
            }

            tmpZip = "";

            // zip up models directory
            if (Directory.Exists(jp.ModelPath)) // this test may be unnecessary
            {
                tmpZip = GetTempFileName("Model-", ".zip", true);
                ZipFile.CreateFromDirectory(jp.ModelPath, tmpZip, CompressionLevel.Fastest, false);
                jp.ModelPath = tmpZip;
            }

            // upload models

            view.Status         = "Uploading models";
            job.ModelZipFileSas = uploader.UploadFile(jp.ModelPath, jp.JobId.ToString(), Path.GetFileName(jp.ModelPath));

            // clean up temporary model files
            if (File.Exists(tmpZip))
            {
                File.Delete(tmpZip);
            }
            if (!jp.SaveModelFiles)
            {
                if (Directory.Exists(jp.ModelPath))
                {
                    Directory.Delete(jp.ModelPath);
                }
            }

            view.Status = "Submitting Job";



            // submit job
            try
            {
                CloudJob cloudJob = batchClient.JobOperations.CreateJob(jp.JobId.ToString(), GetPoolInfo(job.PoolInfo));
                cloudJob.DisplayName        = job.DisplayName;
                cloudJob.JobPreparationTask = job.ToJobPreparationTask(jp.JobId, storageAccount.CreateCloudBlobClient());
                cloudJob.JobReleaseTask     = job.ToJobReleaseTask(jp.JobId, storageAccount.CreateCloudBlobClient());
                cloudJob.JobManagerTask     = job.ToJobManagerTask(jp.JobId, storageAccount.CreateCloudBlobClient(), jp.JobManagerShouldSubmitTasks, jp.AutoScale);

                cloudJob.Commit();
            } catch (Exception ex)
            {
                ShowError(ex.ToString());
            }

            view.Status = "Job Successfully submitted";

            // in theory, instantiating an AzureResultsDownloader here and passing in this job's ID and name, then calling its DownloadResults() method would allow
            // for automatic job downloading as soon as the job is finished. The trouble is it needs an AzureJobDisplayPresenter (for progress bar updating, etc).

            // explorerPresenter.MainPresenter.ShowMessage("Job Successfully submitted", Simulation.ErrorLevel.Information);
            // AzureResultsDownloader dl = new AzureResultsDownloader(jp.JobId, jp.JobDisplayName, jp.OutputDir, this.explorerPresenter, true, false, false);
        }
コード例 #10
0
        public async Task WhenFileUploadedThenUploadSequenceIsCalled()
        {
            var mock     = new Mock <IOauthRequestSender>(MockBehavior.Strict);
            var awsmock  = new Mock <IAmazonApi>(MockBehavior.Strict);
            var sequence = new MockSequence();

            var filename         = Path.GetTempFileName();
            var uploadRequest    = GetUploadRequest();
            var finalizeResponse = GetFinalizeResponse();

            // Init upload
            mock.InSequence(sequence).Setup(reqSenderMock => reqSenderMock.SendRequestAsync(GetValidUploadRequest(filename)))
            .Returns(Task.FromResult(uploadRequest));

            // Get Closest s3 endpoint to upload parts
            mock.InSequence(sequence).Setup(reqSenderMock => reqSenderMock.SendRequestAsync(GetValidClosestS3EndpointRequest()))
            .Returns(Task.FromResult("\"http://test.amazon.com/\""));

            // Upload Part to Amazon
            awsmock.InSequence(sequence).Setup(amazonApiMock => amazonApiMock.UploadPartToAmazon(
                                                   It.IsAny <string>(),
                                                   It.IsAny <string>(),
                                                   It.IsAny <UploadRequest>(),
                                                   It.IsAny <uint>(),
                                                   It.IsAny <byte[]>(),
                                                   It.IsAny <int>(),
                                                   It.IsAny <uint>())).Returns(Task.FromResult(true));

            // Register chunk in bynder
            mock.InSequence(sequence).Setup(reqSenderMock => reqSenderMock.SendRequestAsync(GetValidRegisterChunkRequest(uploadRequest)))
            .Returns(Task.FromResult(string.Empty));

            // Finalizes the upload
            mock.InSequence(sequence).Setup(reqSenderMock => reqSenderMock.SendRequestAsync(GetValidFinalizeResponseRequest(uploadRequest)))
            .Returns(Task.FromResult(finalizeResponse));

            // Poll status
            mock.InSequence(sequence).Setup(reqSenderMock => reqSenderMock.SendRequestAsync(GetValidPollStatus(finalizeResponse)))
            .Returns(Task.FromResult(GetPollStatus()));

            // Saves media
            mock.InSequence(sequence).Setup(reqSenderMock => reqSenderMock.SendRequestAsync(GetSaveMediaRequest(filename, finalizeResponse)))
            .Returns(Task.FromResult(string.Empty));

            FileUploader uploader = new FileUploader(mock.Object, awsmock.Object);

            using (var fileStream = File.OpenWrite(filename))
            {
                var bytes = Encoding.UTF8.GetBytes("mockdata");
                await fileStream.WriteAsync(bytes, 0, bytes.Length);
            }

            try
            {
                await uploader.UploadFile(new UploadQuery
                {
                    Filepath = filename
                });
            }
            finally
            {
                File.Delete(filename);
            }
        }
コード例 #11
0
        static void Main(string[] args)
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            var serverUri       = new Uri("https://localhost");
            var testDataManager = new TestDataManager();
            var fileUploader    = new FileUploader();

            var lowLimit  = 0;
            var highLimit = 70;

            for (var resultIndex = 0; resultIndex < 10; resultIndex++)
            {
                var fileId     = fileUploader.UploadFile("C:\\Broadway.tdms");
                var resultData = new ResultData()
                {
                    Operator     = "mvaterla",
                    ProgramName  = "A C# App",
                    Status       = new Status(StatusType.Running),
                    SerialNumber = Guid.NewGuid().ToString(),
                    Product      = "Some Software",
                    FileIds      = new List <string> {
                        fileId
                    }
                };
                var testResult = testDataManager.CreateResult(resultData);
                testResult.AutoUpdateTotalTime = true;

                Random random      = new Random();
                var    stepDatas   = new List <StepData>();
                var    current     = 0;
                var    voltage     = 0;
                var    currentLoss = 1 - random.NextDouble();
                var    voltageLoss = 1 - random.NextDouble();
                var    power       = current * currentLoss * voltage * voltageLoss;
                for (current = 0; current < 10; current++)
                {
                    currentLoss = 1 - random.NextDouble() * 0.25;
                    power       = current * currentLoss * voltage * voltageLoss;
                    var currentStepData = GenerateStepData($"Current Sweep {current}A", "SequenceCall", current, voltage, power, lowLimit, highLimit);
                    var currentStep     = testResult.CreateStep(currentStepData);

                    for (voltage = 0; voltage < 10; voltage++)
                    {
                        voltageLoss = 1 - random.NextDouble() * 0.25;
                        power       = current * currentLoss * voltage * voltageLoss;
                        var voltageStepData = GenerateStepData($"Voltage Sweep {voltage}V", "NumericLimit", current, voltage, power, lowLimit, highLimit);
                        var voltageStep     = currentStep.CreateStep(voltageStepData);

                        if (voltageStep.Data.Status.StatusType.Equals(StatusType.Failed))
                        {
                            currentStepData.Status = new Status(StatusType.Failed);
                            currentStep.Update(currentStepData);
                        }
                    }

                    if (currentStepData.Status.StatusType.Equals(StatusType.Running))
                    {
                        currentStepData.Status = new Status(StatusType.Passed);
                        currentStep.Update(currentStepData);
                    }
                }
                testResult = testResult.DetermineStatusFromSteps();
            }
        }