Пример #1
0
        private readonly char separator = Path.DirectorySeparatorChar; // Directory separator.

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="CompareForm"/> class. 
        /// </summary>
        public CompareForm()
        {
            InitializeComponent();

            dirHelper = new DirectoryHelper(this);
            maxPathLength = (int)Math.Floor(groupBoxOriginal.Width / 5.5);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["path"] != null && Request.Params["type"] != null)
            {
                string path = Request.QueryString["path"];
                string type = Request.QueryString["type"];
                string message = "";
                switch (type.ToLower())
                {
                    case "file":
                        FileHelper.DeleteFile(path, ref message);
                        Response.Write(message);
                        break;

                    case "folder":
                        DirectoryHelper direcHelper = new DirectoryHelper(path);
                        direcHelper.DeleteDirectory(ref message);
                        Response.Write(message);
                        break;
                }
            }
        }
Пример #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Handle export settings
        if (!RequestHelper.IsCallback() && !RequestHelper.IsPostBack())
        {
            ExportSettings = GetNewSettings();
        }

        if (!RequestHelper.IsCallback())
        {
            // Display BETA warning
            lblBeta.Visible = CMSVersion.IsBetaVersion();
            lblBeta.Text    = string.Format(GetString("export.BETAwarning"), CMSVersion.GetFriendlySystemVersion(false));

            bool notTargetPermissions = false;
            bool notTempPermissions   = false;

            ctrlAsync.OnFinished += ctrlAsync_OnFinished;
            ctrlAsync.OnError    += ctrlAsync_OnError;

            // Init steps
            if (wzdExport.ActiveStepIndex < 2)
            {
                configExport.Settings = ExportSettings;
                if (!RequestHelper.IsPostBack())
                {
                    configExport.SiteId = SiteId;
                }

                pnlExport.Settings = ExportSettings;

                // Ensure directories and check permissions
                try
                {
                    DirectoryHelper.EnsureDiskPath(ExportSettings.TargetPath + "\\temp.file", ExportSettings.WebsitePath);
                    notTargetPermissions = !DirectoryHelper.CheckPermissions(ExportSettings.TargetPath, true, true, false, false);
                }
                catch (UnauthorizedAccessException)
                {
                    notTargetPermissions = true;
                }
                catch (IOExceptions.IOException ex)
                {
                    pnlWrapper.Visible = false;
                    SetErrorLabel(ex.Message);
                    return;
                }
                try
                {
                    DirectoryHelper.EnsureDiskPath(ExportSettings.TemporaryFilesPath + "\\temp.file", ExportSettings.WebsitePath);
                    notTempPermissions = !DirectoryHelper.CheckPermissions(ExportSettings.TemporaryFilesPath, true, true, false, false);
                }
                catch (UnauthorizedAccessException)
                {
                    notTempPermissions = true;
                }
                catch (IOExceptions.IOException ex)
                {
                    pnlWrapper.Visible = false;
                    SetErrorLabel(ex.Message);
                    return;
                }
            }

            if (notTargetPermissions || notTempPermissions)
            {
                string folder = (notTargetPermissions) ? ExportSettings.TargetPath : ExportSettings.TemporaryFilesPath;
                pnlWrapper.Visible = false;
                SetErrorLabel(String.Format(GetString("ExportSite.ErrorPermissions"), folder, WindowsIdentity.GetCurrent().Name));
                pnlPermissions.Visible     = true;
                lnkPermissions.Target      = "_blank";
                lnkPermissions.Text        = GetString("Install.ErrorPermissions");
                lnkPermissions.NavigateUrl = UIContextHelper.GetDocumentationTopicUrl(HELP_TOPIC_DISKPERMISSIONS_LINK);
            }
            else
            {
                // Try to delete temporary files from previous export
                if (!RequestHelper.IsPostBack())
                {
                    try
                    {
                        ExportProvider.DeleteTemporaryFiles(ExportSettings, false);
                    }
                    catch (Exception ex)
                    {
                        pnlWrapper.Visible = false;
                        SetErrorLabel(GetString("ImportSite.ErrorDeletionTemporaryFiles") + ex.Message);
                        return;
                    }
                }

                PortalHelper.EnsureScriptManager(Page).EnablePageMethods = true;

                // Javascript functions
                string script =
                    @"var exMessageText = '';
var exErrorText = '';
var exWarningText = '';
var exMachineName = '" + SystemContext.MachineName.ToLowerCSafe() + @"';
var getBusy = false;

function GetExportState(cancel) { 
    if (window.Activity) { 
        window.Activity(); 
    } 
    if (getBusy) return; 
    getBusy = true; 
    setTimeout('getBusy = false;', 2000);
    var argument = cancel + ';' + exMessageText.length + ';' + exErrorText.length + ';' + exWarningText.length + ';' + exMachineName; 
    " + Page.ClientScript.GetCallbackEventReference(this, "argument", "SetExportStateMssg", "argument", false) + @";
}

function SetExportStateMssg(rValue, context) {
    getBusy = false;
    if (rValue!='') {
        var args = context.split(';');
        var values = rValue.split('" + SiteExportSettings.SEPARATOR + @"');
        var messageElement = document.getElementById('" + lblProgress.ClientID + @"');
        var errorElement = document.getElementById('" + lblError.ClientID + @"');
        var warningElement = document.getElementById('" + lblWarning.ClientID + @"');
        var messageText = exMessageText;
        messageText = values[1] + messageText.substring(messageText.length - args[1]);
        if (messageText.length > exMessageText.length) { 
            exMessageText = messageElement.innerHTML = messageText; 
        }
        var errorText = exErrorText;
        errorText = values[2] + errorText.substring(errorText.length - args[2]);
        if (errorText.length > exErrorText.length) { 
            exErrorText = errorElement.innerHTML = errorText;
            document.getElementById('" + pnlError.ClientID + @"').style.removeProperty('display');
        }
        var warningText = exWarningText;
        warningText = values[3] + warningText.substring(warningText.length - args[3]);
        if (warningText.length > exWarningText.length) { 
            exWarningText = warningElement.innerHTML = warningText;
            document.getElementById('" + pnlWarning.ClientID + @"').style.removeProperty('display');
        }
        if ((values=='') || (values[0]=='F')) {
            StopExportStateTimer();
            var actDiv = document.getElementById('actDiv');
            if (actDiv != null) { actDiv.style.display = 'none'; }
            BTN_Enable('" + FinishButton.ClientID + @"');
            try {
                BTN_Disable('" + CancelButton.ClientID + @"');
            }
            catch(err) {
            }
        }
    }
}";

                // Register the script to perform get flags for showing buttons retrieval callback
                ScriptHelper.RegisterClientScriptBlock(this, GetType(), "GetSetExportState", ScriptHelper.GetScript(script));

                // Add cancel button attribute
                CancelButton.Attributes.Add("onclick", "BTN_Disable('" + CancelButton.ClientID + "'); return CancelExport();");

                wzdExport.NextButtonClick     += wzdExport_NextButtonClick;
                wzdExport.PreviousButtonClick += wzdExport_PreviousButtonClick;
                wzdExport.FinishButtonClick   += wzdExport_FinishButtonClick;

                if (!RequestHelper.IsPostBack())
                {
                    configExport.InitControl();
                }
            }
        }
    }
    /// <summary>
    /// Handle storing single media file info into the DB.
    /// </summary>
    private void HandleSingleMediaFile()
    {
        string fileName = txtImportFileName.Text.Trim();

        // Check if the filename is in correct format
        if (!ValidationHelper.IsFileName(fileName))
        {
            SetupTexts();

            // Inform user on error
            RaiseOnAction("importerror", GetString("media.rename.wrongformat"));
            return;
        }

        // Get info on current file path
        string currFileName = GetNextFileName();

        if (!String.IsNullOrEmpty(currFileName))
        {
            string ext = Path.GetExtension(currFileName);
            if (!MediaLibraryHelper.IsExtensionAllowed(ext.TrimStart('.')))
            {
                RaiseOnAction("importerror", string.Format(GetString("attach.notallowedextension"), ext, MediaLibraryHelper.GetAllowedExtensions(SiteName).TrimEnd(';').Replace(";", ", ")));
                return;
            }
        }

        try
        {
            // Get info on current file path
            if (!String.IsNullOrEmpty(currFileName))
            {
                string filePath = (string.IsNullOrEmpty(FolderPath)) ? currFileName : DirectoryHelper.CombinePath(FolderPath, currFileName);

                // Get file and library info
                FileInfo currFile = FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(SiteName, LibraryInfo.LibraryFolder, filePath));
                if (currFile != null)
                {
                    // Save media file info on current file
                    RaiseOnSaveRequired(currFile, txtImportFileTitle.Text.Trim(), txtImportFileDescription.Text.Trim(), URLHelper.GetSafeFileName(fileName, SiteName, false), filePath);
                }
            }

            // Update file paths set and store updated version in the ViewState
            int indexOfDel = ImportFilePaths.IndexOf("|");
            ImportFilePaths = (indexOfDel > 0 ? ImportFilePaths.Remove(0, indexOfDel + 1) : String.Empty);

            bool wasLast = String.IsNullOrEmpty(ImportFilePaths);
            if (wasLast)
            {
                FinishImport();
            }
            else
            {
                RaiseOnAction("singlefileimported", null);

                // Increment current file index
                ImportCurrFileIndex++;
            }
        }
        catch (Exception ex)
        {
            SetupTexts();

            // Inform user on error
            RaiseOnAction("importerror", ex.Message);
        }
        finally
        {
            SetupImport();
        }
    }
Пример #5
0
        public static async Task <bool> DumpToFile(byte[] videoBuffer, byte[] audioBuffer, string fileName, string ffmpegPath, int cameraIndex)
        {
            await Task.Delay(0);

            var dh      = new DirectoryHelper(cameraIndex);
            var fullDir = dh.GetRootDirectory(fileName);
            var tempDir = dh.GetTempDirectory(fileName);

            // Compile the initial video file (without any audio).
            var startInfo = new ProcessStartInfo(ffmpegPath);

            startInfo.RedirectStandardInput  = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError  = true;
            startInfo.UseShellExecute        = false;

            var argumentBuilder = new List <string>();

            argumentBuilder.Add("-loglevel panic");
            argumentBuilder.Add("-f h264");
            argumentBuilder.Add("-i pipe:");
            argumentBuilder.Add("-vsync vfr");
            argumentBuilder.Add("-c:v libx264");
            argumentBuilder.Add("-bf 0");
            argumentBuilder.Add("-pix_fmt yuv420p");
            argumentBuilder.Add($@"-vf ""drawtext=fontfile=C\\:/Windows/fonts/consola.ttf:fontsize=24:fontcolor='white':text='{fileName}':boxcolor=0x000000AA:box=1:x=10:y=20""");
            argumentBuilder.Add("-an");
            argumentBuilder.Add(tempDir);

            startInfo.Arguments = string.Join(" ", argumentBuilder.ToArray());

            var _ffMpegProcess = new Process();

            _ffMpegProcess.EnableRaisingEvents = true;
            _ffMpegProcess.OutputDataReceived += (s, e) => { Debug.WriteLine(e.Data); };
            _ffMpegProcess.ErrorDataReceived  += (s, e) => { Debug.WriteLine(e.Data); };
            _ffMpegProcess.StartInfo           = startInfo;

            Console.WriteLine($"\n[log] Starting write to {tempDir}...");

            try
            {
                _ffMpegProcess.Start();
                _ffMpegProcess.BeginOutputReadLine();
                _ffMpegProcess.BeginErrorReadLine();

                Console.WriteLine("[log] Full video buffer: " + videoBuffer.Length);
                Console.WriteLine("[log] Full audio buffer: " + audioBuffer.Length);

                using (var memoryStream = new MemoryStream(videoBuffer))
                {
                    memoryStream.CopyTo(_ffMpegProcess.StandardInput.BaseStream);
                }

                _ffMpegProcess.StandardInput.BaseStream.Close();
                _ffMpegProcess.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("[error] An error occurred writing the video file.");
                Console.WriteLine($"[error] {ex.Message}");

                await FileHelper.SafeDelete(tempDir);

                await DumpToFile(videoBuffer, audioBuffer, fileName, ffmpegPath, cameraIndex);
            }

            argumentBuilder = new List <string>();
            argumentBuilder.Add($"-i {tempDir}");
            argumentBuilder.Add("-i pipe:");
            argumentBuilder.Add($"{fullDir}");

            startInfo.Arguments = string.Join(" ", argumentBuilder.ToArray());

            var _ffMpegAudioProcess = new Process();

            _ffMpegAudioProcess.EnableRaisingEvents = true;
            _ffMpegAudioProcess.OutputDataReceived += (s, e) => { Debug.WriteLine(e.Data); };
            _ffMpegAudioProcess.ErrorDataReceived  += (s, e) => { Debug.WriteLine(e.Data); };
            _ffMpegAudioProcess.StartInfo           = startInfo;

            Console.WriteLine($"[log] Starting mux audio to {tempDir}...");

            try
            {
                _ffMpegAudioProcess.Start();
                _ffMpegAudioProcess.BeginOutputReadLine();
                _ffMpegAudioProcess.BeginErrorReadLine();

                Console.WriteLine("[log] Got access to the process input stream.");
                using (var memoryStream = new MemoryStream(audioBuffer))
                {
                    memoryStream.CopyTo(_ffMpegAudioProcess.StandardInput.BaseStream);
                }
                Console.WriteLine("[log] Done writing input stream.");

                _ffMpegAudioProcess.StandardInput.BaseStream.Close();
                _ffMpegAudioProcess.WaitForExit();

                Console.WriteLine("[log] Deleting auxiliary video file...");

                await FileHelper.SafeDelete(tempDir);

                Console.WriteLine($"[log] Final file production completed.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[error] An error occurred writing the audio file.");
                Console.WriteLine($"[error] {ex.Message}");

                await FileHelper.SafeDelete(tempDir);

                await FileHelper.SafeDelete(fullDir);

                await DumpToFile(videoBuffer, audioBuffer, fileName, ffmpegPath, cameraIndex);
            }

            return(true);
        }
Пример #6
0
        private async void SynchFiles(object sender = null)
        {
            var files = DirectoryHelper.GetDirectoryFile(DirectoryHelper.SourcePath);

            await Sync(files, sender);
        }
Пример #7
0
        private void uxDeleteEmptyFolder_Click(object sender, EventArgs e)
        {
            var directoryHelper = new DirectoryHelper();

            directoryHelper.DeleteEmptyDirectories(_sourceFolder);
        }
Пример #8
0
        public async Task <IActionResult> Post(List <IFormFile> file)
        {
            List <CodeResponse> response         = new List <CodeResponse>();
            List <CodeResponse> existingCodeData = new List <CodeResponse>();
            long   size = file.Sum(f => f.Length);
            bool   IsFileExists = false;
            string type, dirFullpath, nbPath, _url = string.Empty;
            // full path to file in temp location
            var filePath = Path.GetTempFileName();

            foreach (var formFile in file)
            {
                dirFullpath = DirectoryHelper.GetCodeDirectoryPath();
                if (formFile.Length > 0)
                {
                    //check if the file with the same name exists
                    existingCodeData = CodePayload.Get();
                    if (existingCodeData.Count > 0)
                    {
                        //
                        foreach (var record in existingCodeData)
                        {
                            if (record.Name == formFile.FileName)
                            {
                                IsFileExists = true;
                            }
                        }
                    }
                    existingCodeData.Clear();
                    //
                    if (!IsFileExists)
                    {
                        var fileExt = System.IO.Path.GetExtension(formFile.FileName).Substring(1);
                        if (fileExt.ToLower() == "ipynb")
                        {
                            dirFullpath = dirFullpath + formFile.FileName.Replace(".ipynb", "/");
                            _url        = DirectoryHelper.GetCodeUrl(formFile.FileName.Replace(".ipynb", string.Empty) + "/" + formFile.FileName);
                        }
                        else
                        {
                            _url = DirectoryHelper.GetCodeUrl(formFile.FileName);
                        }
                        nbPath = dirFullpath + formFile.FileName;

                        //check if folder path exists...if not then create folder
                        if (!Directory.Exists(dirFullpath))
                        {
                            Directory.CreateDirectory(dirFullpath);
                        }
                        // upload file start
                        using (var fileStream = new FileStream(Path.Combine(dirFullpath, formFile.FileName), FileMode.Create))
                        {
                            //check file allowed extensions
                            if (!extensions.Contains(fileExt.ToString().ToLower()))
                            {
                                return(BadRequest("File type not allowed"));
                            }

                            //file copy
                            await formFile.CopyToAsync(fileStream);

                            // upload file edn and start creating payload
                            switch (fileExt.ToLower())
                            {
                            case "py":
                                type = "PYTHON";
                                break;

                            case "ipynb":
                                type = "JUPYTER_NOTEBOOK";
                                break;

                            default:
                                type = "UNRECOGNIZED";
                                break;
                            }

                            CodeResponse newRecord = new CodeResponse()
                            {
                                Id          = formFile.FileName.Replace("." + fileExt, ""),
                                Name        = formFile.FileName,
                                User        = "",
                                Created_on  = DateTime.Now.ToString(),
                                Edited_on   = DateTime.Now.ToString(),
                                Extension   = fileExt,
                                MimeType    = formFile.ContentType,
                                Size        = formFile.Length,
                                Type        = type,
                                Url         = _url,
                                FilePath    = nbPath,
                                DateCreated = DateTime.Now
                            };
                            CodePayload.Create(newRecord);
                            response.Add(newRecord);
                        }
                    }
                }
                IsFileExists = false;
            }

            if (response.Count > 0)
            {
                return(Ok(response));
            }
            else
            {
                return(BadRequest("File already exists."));
            }
        }
Пример #9
0
        void STOR(string CmdArguments)
        {
            if (!ConnectedUser.CanStoreFiles)
            {
                SendMessage("426 Access Denied.\r\n");
                return;
            }
            Stream FS = null;

            string Path = ConnectedUser.StartUpDirectory + DirectoryHelper.GetExactPath(CmdArguments, ConnectedUser);

            if (Path.EndsWith("/") || Path.EndsWith(@"\"))
            {
                Path = Path.Substring(0, Path.Length - 1);
            }

            try
            {
                FS = new FileStream(Path, FileMode.Create, FileAccess.Write, FileShare.None);
            }
            catch (Exception Ex)
            {
                SendMessage("550 " + Ex.Message + "\r\n");
                return;
            }

            Socket DataSocket = GetDataSocket();

            if (DataSocket == null)
            {
                return;
            }
            try
            {
                int    ReadBytes = 1;
                byte[] tmpBuffer = new byte[10000];

                do
                {
                    ReadBytes = DataSocket.Receive(tmpBuffer);
                    FS.Write(tmpBuffer, 0, ReadBytes);
                } while (ReadBytes > 0);

                tmpBuffer = null;

                SendMessage("226 Transfer Complete.\r\n");

                // TODO
                // Parse this File And Save to Datebase
                if (Path.EndsWith(".helloworld"))
                {
                    FS.Close();
                    Task.Factory.StartNew(() => {
                        Uploaded.Invoke(Path);
                    });
                }
            }
            catch (Exception ex)
            {
                SendMessage("426 Connection closed unexpectedly.\r\n");
            }
            finally
            {
                if (DataSocket != null)
                {
                    DataSocket.Shutdown(SocketShutdown.Both);
                    DataSocket.Close();
                    DataSocket = null;
                }
                FS.Close(); FS = null;
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Handle export settings
        if (!RequestHelper.IsCallback() && !RequestHelper.IsPostBack())
        {
            ExportSettings = GetNewSettings();
        }

        if (!RequestHelper.IsCallback())
        {
            // Display BETA warning
            lblBeta.Visible = CMSVersion.IsBetaVersion();
            lblBeta.Text    = string.Format(GetString("export.BETAwarning"), CMSVersion.GetFriendlySystemVersion(false));

            bool notTargetPermissions = false;
            bool notTempPermissions   = false;

            ctrlAsyncSelection.OnFinished += CtrlAsyncSelectionOnFinished;
            ctrlAsyncSelection.OnError    += CtrlAsyncSelectionOnError;

            ctlAsyncExport.OnCancel += ctlAsyncExport_OnCancel;

            // Init steps
            if (wzdExport.ActiveStepIndex < 2)
            {
                configExport.Settings = ExportSettings;
                if (!RequestHelper.IsPostBack())
                {
                    configExport.SiteId = SiteId;
                }

                pnlExport.Settings = ExportSettings;

                // Ensure directories and check permissions
                try
                {
                    DirectoryHelper.EnsureDiskPath(ExportSettings.TargetPath + "\\temp.file", ExportSettings.WebsitePath);
                    notTargetPermissions = !DirectoryHelper.CheckPermissions(ExportSettings.TargetPath, true, true, false, false);
                }
                catch (UnauthorizedAccessException)
                {
                    notTargetPermissions = true;
                }
                catch (IOExceptions.IOException ex)
                {
                    pnlWrapper.Visible = false;
                    SetAlertLabel(lblErrorBlank, ex.Message);
                    return;
                }
                try
                {
                    DirectoryHelper.EnsureDiskPath(ExportSettings.TemporaryFilesPath + "\\temp.file", ExportSettings.WebsitePath);
                    notTempPermissions = !DirectoryHelper.CheckPermissions(ExportSettings.TemporaryFilesPath, true, true, false, false);
                }
                catch (UnauthorizedAccessException)
                {
                    notTempPermissions = true;
                }
                catch (IOExceptions.IOException ex)
                {
                    pnlWrapper.Visible = false;
                    SetAlertLabel(lblErrorBlank, ex.Message);
                    return;
                }
            }

            if (notTargetPermissions || notTempPermissions)
            {
                string folder = (notTargetPermissions) ? ExportSettings.TargetPath : ExportSettings.TemporaryFilesPath;
                pnlWrapper.Visible     = false;
                pnlPermissions.Visible = true;
                SetAlertLabel(lblErrorBlank, String.Format(GetString("ExportSite.ErrorPermissions"), folder, WindowsIdentity.GetCurrent().Name));
                lnkPermissions.Target      = "_blank";
                lnkPermissions.Text        = GetString("Install.ErrorPermissions");
                lnkPermissions.NavigateUrl = DocumentationHelper.GetDocumentationTopicUrl(HELP_TOPIC_DISKPERMISSIONS_LINK);
            }
            else
            {
                // Try to delete temporary files from previous export
                if (!RequestHelper.IsPostBack())
                {
                    try
                    {
                        ExportProvider.DeleteTemporaryFiles(ExportSettings, false);
                    }
                    catch (Exception ex)
                    {
                        pnlWrapper.Visible = false;
                        SetAlertLabel(lblErrorBlank, GetString("ImportSite.ErrorDeletionTemporaryFiles") + " " + ex.Message);
                        return;
                    }
                }

                ControlsHelper.EnsureScriptManager(Page).EnablePageMethods = true;

                // Javascript functions
                string script = String.Format(
                    @"
function Finished(sender) {{
    var errorElement = document.getElementById('{2}');

    var errorText = sender.getErrors();
    if (errorText != '') {{ 
        errorElement.innerHTML = errorText;
        document.getElementById('{4}').style.removeProperty('display');
    }}

    var warningElement = document.getElementById('{3}');
    
    var warningText = sender.getWarnings();
    if (warningText != '') {{ 
        warningElement.innerHTML = warningText;
        document.getElementById('{5}').style.removeProperty('display');
    }}    

    var actDiv = document.getElementById('actDiv');
    if (actDiv != null) {{ 
        actDiv.style.display = 'none'; 
    }}

    BTN_Disable('{0}');
    BTN_Enable('{1}');
}}
",
                    CancelButton.ClientID,
                    FinishButton.ClientID,
                    lblError.LabelClientID,
                    lblWarning.LabelClientID,
                    pnlError.ClientID,
                    pnlWarning.ClientID
                    );

                // Register the script to perform get flags for showing buttons retrieval callback
                ScriptHelper.RegisterClientScriptBlock(this, GetType(), "Finished", ScriptHelper.GetScript(script));

                // Add cancel button attribute
                CancelButton.Attributes.Add("onclick", ctlAsyncExport.GetCancelScript(true) + "return false;");

                wzdExport.NextButtonClick     += wzdExport_NextButtonClick;
                wzdExport.PreviousButtonClick += wzdExport_PreviousButtonClick;
                wzdExport.FinishButtonClick   += wzdExport_FinishButtonClick;

                if (!RequestHelper.IsPostBack())
                {
                    configExport.InitControl();
                }
            }
        }
    }
Пример #11
0
        public virtual async Task CreateFileAsync([FromForm] FileUploadDto input)
        {
            // 检查文件大小
            var fileSizeLimited = await SettingProvider
                                  .GetAsync(
                AbpFileManagementSettingNames.FileLimitLength,
                AbpFileManagementSettingNames.DefaultFileLimitLength);

            if (fileSizeLimited * 1024 * 1024 < input.TotalSize)
            {
                throw new UserFriendlyException(L["UploadFileSizeBeyondLimit", fileSizeLimited]);
            }
            // 采用分块模式上传文件

            // 保存分块到临时目录
            var fileName = input.FileName;
            // 文件扩展名
            var fileExtensionName  = FileHelper.GetExtension(fileName);
            var fileAllowExtension = await SettingProvider
                                     .GetOrNullAsync(AbpFileManagementSettingNames.AllowFileExtensions);

            if (fileAllowExtension.IsNullOrWhiteSpace())
            {
                fileAllowExtension = AbpFileManagementSettingNames.DefaultAllowFileExtensions;
            }
            // 检查文件扩展名
            if (!fileAllowExtension.Split(',')
                .Any(fe => fe.Equals(fileExtensionName, StringComparison.CurrentCultureIgnoreCase)))
            {
                throw new UserFriendlyException(L["NotAllowedFileExtensionName", fileExtensionName]);
            }
            // 以上传的文件名创建一个临时目录
            var tempFilePath = Path.Combine(
                Path.GetTempPath(),
                "lingyun-abp-file-management",
                "upload",
                string.Concat(input.Path ?? "", input.FileName).ToMd5());

            DirectoryHelper.CreateIfNotExists(tempFilePath);
            // 以上传的分片索引创建临时文件
            var tempSavedFile = Path.Combine(tempFilePath, $"{input.ChunkNumber}.{fileExtensionName}");

            try
            {
                if (HttpContext.RequestAborted.IsCancellationRequested)
                {
                    // 如果取消请求,删除临时目录
                    Directory.Delete(tempFilePath, true);
                    return;
                }

                if (input.File != null)
                {
                    // 保存临时文件
                    using (var fs = new FileStream(tempSavedFile, FileMode.Create, FileAccess.Write))
                    {
                        // 写入当前分片文件
                        await input.File.CopyToAsync(fs);
                    }
                }

                if (input.ChunkNumber == input.TotalChunks)
                {
                    // 合并文件
                    var mergeSavedFile = Path.Combine(tempFilePath, $"{fileName}");
                    // 获取并排序所有分片文件
                    var mergeFiles = Directory.GetFiles(tempFilePath).OrderBy(f => f.Length).ThenBy(f => f);
                    // 创建临时合并文件
                    input.Data = new byte[0];
                    foreach (var mergeFile in mergeFiles)
                    {
                        // 读取当前文件字节
                        var mergeFileBytes = await FileHelper.ReadAllBytesAsync(mergeFile);

                        // 写入到合并文件流
                        input.Data = input.Data.Concat(mergeFileBytes).ToArray();
                        Array.Clear(mergeFileBytes, 0, mergeFileBytes.Length);
                        // 删除已参与合并的临时文件分片
                        FileHelper.DeleteIfExists(mergeFile);
                    }
                    await FileSystemAppService.CreateFileAsync(input);

                    // 文件保存之后删除临时文件目录
                    Directory.Delete(tempFilePath, true);
                }
            }
            catch
            {
                // 发生异常删除临时文件目录
                Directory.Delete(tempFilePath, true);
                throw;
            }
        }
Пример #12
0
        void RETR(string CmdArguments)
        {
            if (!ConnectedUser.CanCopyFiles)
            {
                SendMessage("426 Access Denied.\r\n");
                return;
            }

            string ReturnMessage = string.Empty;

            FileStream FS         = null;
            Socket     DataSocket = null;

            try
            {
                string Path = ConnectedUser.StartUpDirectory + DirectoryHelper.GetExactPath(CmdArguments, ConnectedUser);
                Path = Path.Substring(0, Path.Length - 1);

                if (!ConnectedUser.CanViewHiddenFiles && (File.GetAttributes(Path) & FileAttributes.Hidden) == FileAttributes.Hidden)
                {
                    SendMessage("550 Access Denied or invalid path.\r\n");
                    return;
                }

                FS = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch
            {
                ReturnMessage = "550 Access denied or invalid path!\r\n";
                goto FinaliseAll;
            }


            DataSocket = GetDataSocket();
            if (DataSocket == null)
            {
                goto FinaliseAll;
            }

            try
            {
                byte[] data = new byte[(FS.Length > 100000) ? 100000 : (int)FS.Length];
                while (DataSocket.Send(data, 0, FS.Read(data, 0, data.Length), SocketFlags.None) != 0)
                {
                    ;
                }
                ReturnMessage = "226 Transfer Complete.\r\n";
            }
            catch
            {
                ReturnMessage = "426 Transfer aborted.\r\n";
            }

FinaliseAll:
            if (FS != null)
            {
                FS.Close();
            }
            FS = null;
            if (DataSocket != null && DataSocket.Connected)
            {
                DataSocket.Shutdown(SocketShutdown.Both);
                DataSocket.Close();
            }
            DataSocket = null;
            SendMessage(ReturnMessage);
        }
Пример #13
0
        public virtual async Task <IActionResult> DownloadFileAsync(FileSystemDownloadDto input)
        {
            var tempFileName = string.Concat(input.Path ?? "", input.Name);

            tempFileName = tempFileName.ToMd5() + Path.GetExtension(input.Name);
            // 以上传的文件名创建一个临时目录
            var tempFilePath = Path.Combine(
                Path.GetTempPath(),
                "lingyun-abp-file-management",
                "download");

            DirectoryHelper.CreateIfNotExists(tempFilePath);
            tempFilePath = Path.Combine(tempFilePath, tempFileName);
            long contentLength = 0L;
            // 单个分块大小 2MB
            int bufferSize = 2 * 1024 * 1024;

            using (new DisposeAction(() =>
            {
                // 最终下载完毕后,删除临时文件
                if (bufferSize + input.CurrentByte > contentLength)
                {
                    FileHelper.DeleteIfExists(tempFilePath);
                }
            }))
            {
                if (!System.IO.File.Exists(tempFilePath))
                {
                    var blobStream = await FileSystemAppService.DownloadFileAsync(input);

                    using (var tempFileStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
                    {
                        blobStream.Position = 0;
                        await blobStream.CopyToAsync(tempFileStream);
                    }
                }
                // 读取缓存文件
                using var fileStream = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
                // 得到文件扩展名
                var fileExt  = Path.GetExtension(input.Name);
                var provider = new FileExtensionContentTypeProvider();
                // Http响应标头的文件类型
                string memi = provider.Mappings[fileExt];
                // 文件大小
                contentLength = fileStream.Length;
                if (bufferSize > contentLength)
                {
                    var currentTransferBytes = await fileStream.GetAllBytesAsync();

                    // 写入响应流
                    return(File(currentTransferBytes, memi, input.Name));
                }
                else
                {
                    // 当前分页传输字节
                    byte[] currentTransferBytes = new byte[bufferSize];
                    if (input.CurrentByte + bufferSize >= contentLength)
                    {
                        currentTransferBytes = new byte[contentLength - input.CurrentByte];
                    }
                    // 读取文件流中的当前分块区段
                    fileStream.Seek(input.CurrentByte, SeekOrigin.Begin);
                    await fileStream.ReadAsync(currentTransferBytes, 0, currentTransferBytes.Length);

                    // 写入响应流
                    return(File(currentTransferBytes, memi, input.Name));
                }
            }
        }
        public void GenerateAirportCsvList(AirportList airportList)
        {
            var csvFile = XP2AFSConverterManager.Settings.XP2AFSConverterFolder + @"airports.csv";
            var writer  = new StreamWriter(csvFile);
            var csv     = new CsvWriter(writer);

            csv.WriteHeader <AirportCsvListItem>();
            csv.NextRecord();

            int i = 0;

            foreach (var airport in airportList.Airports)
            {
                // Exclude sea runways, closed runways and helipads
                if (!airport.AirportName.StartsWith("[S]") &&
                    !airport.AirportName.StartsWith("[X]") &&
                    !airport.AirportName.StartsWith("[H]"))
                {
                    var airportXPFullDirectory = DirectoryHelper.GetAirportXPFullDirectory(airport.AirportCode, XP2AFSConverterManager.Settings);
                    var airportZipFilename     = airportXPFullDirectory + @"\" + airport.AirportCode + ".zip";
                    var airportFilename        = airportXPFullDirectory + @"\airport.xml";
                    var airportSceneryFilename = airportXPFullDirectory + @"\scenery.xml";

                    if (File.Exists(airportZipFilename))
                    {
                        //if (airport.AirportCode == "")

                        log.InfoFormat("Adding airport {0} of {1}", i + 1, airportList.Airports.Count);
                        // Parse the DST and DAT files
                        var datFileLoader = new DATFileLoader();
                        var datFile       = datFileLoader.GetDATFileFromXPZip(airport.AirportCode, airportZipFilename);
                        //var dsfFile = this.GetDSFFileFromXPZip(airport.AirportCode, airportZipFilename);
                        var sceneryFile = DeserializeSceneryFile(airportSceneryFilename);

                        // Create empty AFS files
                        var tscFile = new TSCFile();
                        var tocFile = new TOCFile();

                        var datConverter = new DATConverter();
                        // Convert the X-Plane files
                        datConverter.Convert(datFile, tscFile, tocFile);

                        if (datFile.AirportHeader.AirportType == AirportType.Airport && datFile.LandRunways != null)
                        {
                            TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;

                            AirportCsvListItem airportListItem = new AirportCsvListItem();
                            airportListItem.Code      = airport.AirportCode;
                            airportListItem.Name      = textInfo.ToTitleCase(airport.AirportName.ToLower());
                            airportListItem.IsHelipad = false;

                            if (datFile.MetadataLookup.ContainsKey("datum_lat"))
                            {
                                double lat;
                                if (Double.TryParse(datFile.MetadataLookup["datum_lat"], out lat))
                                {
                                    airportListItem.Latitude = lat;
                                }
                            }

                            if (datFile.MetadataLookup.ContainsKey("datum_lon"))
                            {
                                double lon;
                                if (Double.TryParse(datFile.MetadataLookup["datum_lon"], out lon))
                                {
                                    airportListItem.Longitude = lon;
                                }
                            }

                            if (datFile.MetadataLookup.ContainsKey("country"))
                            {
                                airportListItem.Country = datFile.MetadataLookup["country"];
                            }

                            if (datFile.MetadataLookup.ContainsKey("state"))
                            {
                                airportListItem.Region = datFile.MetadataLookup["state"];
                            }

                            if (datFile.MetadataLookup.ContainsKey("city"))
                            {
                                airportListItem.City = datFile.MetadataLookup["city"];
                            }

                            if (datFile.MetadataLookup.ContainsKey("region_code"))
                            {
                                airportListItem.RegionCode = datFile.MetadataLookup["region_code"];
                            }

                            if (datFile.MetadataLookup.ContainsKey("icao_code"))
                            {
                                airportListItem.ICAO = datFile.MetadataLookup["icao_code"];
                            }

                            if (datFile.MetadataLookup.ContainsKey("iata_code"))
                            {
                                airportListItem.IATA = datFile.MetadataLookup["iata_code"];
                            }

                            if (datFile.MetadataLookup.ContainsKey("faa_code"))
                            {
                                airportListItem.FAACode = datFile.MetadataLookup["faa_code"];
                            }

                            if (datFile.Pavements == null || datFile.Pavements.Count == 0)
                            {
                                airportListItem.HasPavements = false;
                            }
                            else
                            {
                                airportListItem.HasPavements = true;
                            }

                            if (sceneryFile.Type == "3D")
                            {
                                airportListItem.Is3D = true;
                            }
                            else
                            {
                                airportListItem.Is3D = false;
                            }

                            foreach (var runway in datFile.LandRunways)
                            {
                                airportListItem.RunwaySurfaceType = (int)runway.SurfaceType;
                            }

                            airportListItem.RunwayCount = datFile.LandRunways.Count;

                            // If we couldn't get a value from the metadata we need to get it elsewhere
                            if (!airportListItem.Latitude.HasValue || !airportListItem.Longitude.HasValue)
                            {
                                airportListItem.Latitude  = tscFile.Location.Latitude;
                                airportListItem.Longitude = tscFile.Location.Longitude;
                            }

                            csv.WriteRecord(airportListItem);
                            csv.NextRecord();
                        }
                    }
                    else
                    {
                        log.ErrorFormat("Could not find the data for airport {0} make sure it is downloaded", airport.AirportCode);
                    }
                }

                i++;
            }

            writer.Flush();
            writer.Close();
            writer = null;
        }
Пример #15
0
        private void BWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            this.OnProgressStateChanged(new ProgressBarStateChangedEventArgs(Forms.MyMainMenu.ProgressBarVisibleState.Infinite));

            WorkerParams wp       = e.Argument as WorkerParams;
            string       pso2Path = wp.PSO2Path;

            // Check if there is any prepatch files
            if (!wp.IgnorePrepatch)
            {
                string prepatchFolderData = Path.Combine(pso2Path, PrepatchManager.PrepatchManager.PrepatchFolderName, "data");
                if (!DirectoryHelper.IsFolderEmpty(prepatchFolderData))
                {
                    // Ignore prepatch files if it's older than the current client version
                    PSO2Version currentVersion  = PSO2Version.Parse(MySettings.PSO2Version);
                    PSO2Version prepatchVersion = PSO2Version.Parse(MySettings.PSO2PrecedeVersion.Version);
                    if (prepatchVersion.CompareTo(currentVersion) > 0)
                    {
                        this.CurrentStep = LanguageManager.GetMessageText("PSO2Updater_FoundValidPrepatch", "Found prepatch files which are ready to be used.");
                        ValidPrepatchPromptEventArgs myEventArgs = new ValidPrepatchPromptEventArgs();
                        this.OnValidPrepatchPrompt(myEventArgs);
                        if (myEventArgs.Use)
                        {
                            string[] filenames = Directory.GetFiles(prepatchFolderData, "*", SearchOption.AllDirectories);
                            this.CurrentStep   = LanguageManager.GetMessageText("PSO2Updater_MovingPrepatchFiles", "Applying prepatch files.");
                            this.ProgressTotal = filenames.Length;
                            this.OnProgressStateChanged(new ProgressBarStateChangedEventArgs(Forms.MyMainMenu.ProgressBarVisibleState.Percent));
                            string str = null, maindatafolder = Path.Combine(pso2Path, "data"), targetfile = null;
                            for (int i = 0; i < filenames.Length; i++)
                            {
                                str        = filenames[i];
                                targetfile = maindatafolder + str.Remove(0, prepatchFolderData.Length);
                                File.Delete(targetfile);
                                File.Move(str, targetfile);
                                this.ProgressCurrent = i + 1;
                            }

                            // Check if it's empty again to remove it
                            if (DirectoryHelper.IsFolderEmpty(prepatchFolderData))
                            {
                                string prepatchfolder = Path.Combine(pso2Path, PrepatchManager.PrepatchManager.PrepatchFolderName);
                                try
                                {
                                    Directory.Delete(prepatchfolder, true);
                                }
                                catch { }
                            }
                        }
                    }
                    else
                    {
                        this.CurrentStep = LanguageManager.GetMessageText("PSO2Updater_FoundInvalidPrepatch", "Found out-dated prepatch files which will be ignored. These files shouldn't be used and should be deleted.");
                        InvalidPrepatchPromptEventArgs myEventArgs = new InvalidPrepatchPromptEventArgs();
                        this.OnInvalidPrepatchPrompt(myEventArgs);
                        if (myEventArgs.Delete)
                        {
                            this.CurrentStep = LanguageManager.GetMessageText("PSO2Updater_DeletingInvalidPrepatch", "Deleting out-dated prepatch files.");
                            string prepatchfolder = Path.Combine(pso2Path, PrepatchManager.PrepatchManager.PrepatchFolderName);
                            try
                            {
                                Directory.Delete(prepatchfolder, true);
                            }
                            catch { }
                        }
                    }
                }
            }

            this.OnProgressStateChanged(new ProgressBarStateChangedEventArgs(Forms.MyMainMenu.ProgressBarVisibleState.Infinite));

            var patchinfo = this.CheckForUpdates();

            if (this.GetFilesList(patchinfo))
            {
                System.Collections.Concurrent.ConcurrentDictionary <string, PSO2File> myPSO2filesList = ParseFilelist(this.myFileList, patchinfo);
                if (!myPSO2filesList.IsEmpty)
                {
                    this.ProgressTotal = myPSO2filesList.Count;
                    this.OnProgressStateChanged(new ProgressBarStateChangedEventArgs(Forms.MyMainMenu.ProgressBarVisibleState.Percent, new Forms.MyMainMenuCode.CircleProgressBarProperties(true)));
                    string verstring = wp.NewVersionString;
                    if (string.IsNullOrWhiteSpace(verstring))
                    {
                        verstring = this.myWebClient.DownloadString(Leayal.UriHelper.URLConcat(patchinfo.PatchURL, "version.ver"));
                    }
                    if (!string.IsNullOrWhiteSpace(verstring))
                    {
                        verstring = verstring.Trim();
                    }
                    anothersmallthreadpool                  = new AnotherSmallThreadPool(pso2Path, myPSO2filesList);
                    anothersmallthreadpool.StepChanged     += Anothersmallthreadpool_StepChanged;
                    anothersmallthreadpool.ProgressChanged += Anothersmallthreadpool_ProgressChanged;
                    anothersmallthreadpool.KaboomFinished  += Anothersmallthreadpool_KaboomFinished;

                    this.CurrentStep = LanguageManager.GetMessageText("PSO2Updater_BeginFileCheckAndDownload", "Begin the file check and download...");

                    anothersmallthreadpool.StartWork(new WorkerParams(pso2Path, verstring, wp.Installation, wp.IgnorePrepatch));
                    e.Result = null;
                }
                else
                {
                    e.Result = new PSO2UpdateResult(UpdateResult.Failed);
                }
            }
            else
            {
                e.Result = new PSO2UpdateResult(UpdateResult.Unknown);
                throw new PSO2UpdateException(LanguageManager.GetMessageText("PSO2UpdateManager_GetPatchListFailed", "Failed to get PSO2's file list."));
            }
        }
        private void ensureLogDirectoryExists()
        {
            var directory = FileHelper.FolderFromFileFullPath(_logFileFullPath);

            DirectoryHelper.CreateDirectory(directory);
        }
Пример #17
0
        void LIST(string CmdArguments)
        {
            string Path = ConnectedUser.StartUpDirectory + DirectoryHelper.GetExactPath(CmdArguments, ConnectedUser);

            if (!ConnectedUser.CanViewHiddenFolders && (new DirectoryInfo(Path).Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
            {
                SendMessage("550 Invalid path specified.\r\n");
                return;
            }

            Socket DataSocket = GetDataSocket();

            if (DataSocket == null)
            {
                return;
            }

            try
            {
                string[] FilesList    = Directory.GetFiles(Path, "*.*", SearchOption.TopDirectoryOnly);
                string[] FoldersList  = Directory.GetDirectories(Path, "*.*", SearchOption.TopDirectoryOnly);
                string   strFilesList = "";

                if (ConnectedUser.CanViewHiddenFolders)
                {
                    foreach (string Folder in FoldersList)
                    {
                        string date = Directory.GetCreationTime(Folder).ToString("MM-dd-yy hh:mmtt");
                        strFilesList += date + " <DIR> " + Folder.Substring(Folder.Replace('\\', '/').LastIndexOf('/') + 1) + "\r\n";
                    }
                }
                else
                {
                    foreach (string Folder in FoldersList)
                    {
                        if ((new DirectoryInfo(Folder).Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                        {
                            continue;
                        }

                        string date = Directory.GetCreationTime(Folder).ToString("MM-dd-yy hh:mmtt");
                        strFilesList += date + " <DIR> " + Folder.Substring(Folder.Replace('\\', '/').LastIndexOf('/') + 1) + "\r\n";
                    }
                }

                if (ConnectedUser.CanViewHiddenFiles)
                {
                    foreach (string FileName in FilesList)
                    {
                        string date = File.GetCreationTime(FileName).ToString("MM-dd-yy hh:mmtt");
                        strFilesList += date + " " + new FileInfo(FileName).Length.ToString() + " " + FileName.Substring(FileName.Replace('\\', '/').LastIndexOf('/') + 1) + "\r\n";
                    }
                }
                else
                {
                    foreach (string FileName in FilesList)
                    {
                        if ((File.GetAttributes(FileName) & FileAttributes.Hidden) == FileAttributes.Hidden)
                        {
                            continue;
                        }

                        string date = File.GetCreationTime(FileName).ToString("MM-dd-yy hh:mmtt");
                        strFilesList += date + " " + new FileInfo(FileName).Length.ToString() + " " + FileName.Substring(FileName.Replace('\\', '/').LastIndexOf('/') + 1) + "\r\n";
                    }
                }
                DataSocket.Send(Constant.DefaultEncoding.GetBytes(strFilesList));
                SendMessage("226 Transfer Complete.\r\n");
            }
            catch (DirectoryNotFoundException)
            {
                SendMessage("550 Invalid path specified.\r\n");
            }
            catch (UnauthorizedAccessException ex)
            {
                SendMessage("426 权限不足.\r\n");
            }
            catch (Exception ex)
            {
                SendMessage("426 Connection closed; transfer aborted.\r\n");
            }
            finally
            {
                DataSocket.Shutdown(SocketShutdown.Both);
                DataSocket.Close(); DataSocket = null;
            }
        }
Пример #18
0
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData()
    {
        try
        {
            treeElem.Nodes.Clear();

            // Get root files
            string rootDir = RootFolderPath;
            rootDir = DirectoryHelper.CombinePath(rootDir, !String.IsNullOrEmpty(MediaLibraryPath) ? MediaLibraryPath : MediaLibraryFolder);

            // Get the file and directories count
            int dirCount  = 0;
            int fileCount = 0;

            string[] files       = null;
            string[] directories = null;
            if ((rootDir != null) && (Directory.Exists(rootDir)))
            {
                files       = Directory.GetFiles(rootDir);
                directories = Directory.GetDirectories(rootDir);
            }

            if (files != null)
            {
                fileCount = files.Length;
            }

            if (directories != null)
            {
                // Each directory contains directory for thumbnails
                dirCount = directories.Length - 1;
            }

            // Create root tree node
            TreeNode root;
            if (DisplayFilesCount)
            {
                root = CreateNode("<span class=\"Name\">" + MediaLibraryFolder + " (" + fileCount + ")</span>", MediaLibraryFolder, null, dirCount, 0);
            }
            else
            {
                root = CreateNode("<span class=\"Name\">" + MediaLibraryFolder + "</span>", MediaLibraryFolder, null, dirCount, 0);
            }

            // Keep root expanded
            root.Expand();
            // Add root node
            treeElem.Nodes.Add(root);

            // Bind tree nodes
            if (String.IsNullOrEmpty(MediaLibraryPath))
            {
                BindTreeView(RootFolderPath + MediaLibraryFolder, root, true);
            }
            else
            {
                BindTreeView(DirectoryHelper.CombinePath(RootFolderPath, MediaLibraryPath), root, true);
            }
        }
        catch (Exception ex)
        {
            if (!IgnoreAccessDenied)
            {
                lblError.Text    = GetString("FolderTree.FailedLoad") + ": " + ex.Message;
                lblError.ToolTip = EventLogProvider.GetExceptionLogMessage(ex);
            }
        }
    }
Пример #19
0
        void CommandReceived(IAsyncResult arg)
        {
            #region Read and Parse commands
            int CommandSize = 0;
            try
            {
                CommandSize = ClientSocket.EndReceive(arg);
            }
            catch { }
            if (CommandSize == 0)
            {
                Disconnect(); return;
            }


            // Wait for the next command to be sent by the client
            try
            {
                ClientSocket.BeginReceive(BufferData, 0, BufferData.Length, SocketFlags.None, new AsyncCallback(CommandReceived), null);
            }
            catch { Disconnect(); }

            LastInteraction = DateTime.Now;
            string CommandText = Constant.DefaultEncoding.GetString(BufferData, 0, CommandSize).TrimStart(' ');
            string CmdArguments = null, Command = null;
            int    End = 0;
            if ((End = CommandText.IndexOf(' ')) == -1)
            {
                End = (CommandText = CommandText.Trim()).Length;
            }
            else
            {
                CmdArguments = CommandText.Substring(End).TrimStart(' ');
            }
            Command = CommandText.Substring(0, End).ToUpper();

            #endregion

            #region Execute Commands
            if (CmdArguments != null && CmdArguments.EndsWith("\r\n"))
            {
                CmdArguments = CmdArguments.Substring(0, CmdArguments.Length - 2);
            }
            bool CommandExecued = false;
            switch (Command)
            {
            case "USER":
                if (CmdArguments != null && CmdArguments.Length > 0)
                {
                    // WHY ??? 为什么在这里发送
                    string userName = CmdArguments;
                    ConnectedUser.LoadProfile(userName);
                    // 向客户端发送这句命令后客户端会马上发送密码信息过来
                    SendMessage("331 Password required!\r\n");
                }
                CommandExecued = true;
                break;

            case "PASS":
                if (ConnectedUser.UserName == "")
                {
                    SendMessage("503 Invalid User Name\r\n");
                    return;
                }

                if (ConnectedUser.Authenticate(CmdArguments))
                {
                    SendMessage("230 Authentication Successful\r\n");
                }
                else
                {
                    SendMessage("530 Authentication Failed!\r\n");
                }
                CommandExecued = true;
                break;
            }
            if (!CommandExecued)
            {
                // ConnectedUser.IsAuthenticated
                if (ConnectedUser.IsAuthenticated)
                {
                    Console.WriteLine("命令内容 " + Command + "  参数内容 " + CmdArguments);
                    switch (Command)
                    {
                    case "CWD":
                        // 确定目录是否存在
                        string dir = DirectoryHelper.GetExactPath(CmdArguments, ConnectedUser);
                        //string dir = CmdArguments;

                        if (ConnectedUser.ChangeDirectory(dir))
                        {
                            SendMessage("250 CWD command successful.\r\n");
                        }
                        else
                        {
                            SendMessage("550 System can't find directory '" + dir + "'.\r\n");
                        }
                        break;

                    case "PWD":
                        // 确定成功后返回当前工作路径
                        string msg = "257 \"" + ConnectedUser.CurrentWorkingDirectory.Replace('\\', '/') + "\"\r\n";
                        SendMessage(msg);
                        break;

                    case "LIST":
                        // 返回当前工作路径中所有的内容
                        LIST(CmdArguments);
                        break;

                    case "CDUP":
                        // 获取上级目录地址设置到currentWorkdDirectory
                        string curpath = DirectoryHelper.CDUP(ConnectedUser.CurrentWorkingDirectory);
                        ConnectedUser.CurrentWorkingDirectory = curpath;
                        SendMessage("250 CDUP command successful.\r\n");
                        break;

                    case "QUIT":
                        SendMessage("221 FTP server signing off\r\n");
                        Disconnect();
                        break;

                    case "PORT":
                        PORT(CmdArguments);
                        break;

                    case "PASV":
                        PASV(CmdArguments);
                        break;

                    case "TYPE":
                        TYPE(CmdArguments);
                        break;

                    case "RETR":
                        // 下载文件
                        RETR(CmdArguments);
                        break;

                    case "STOR":
                        // 上传文件
                        STOR(CmdArguments);
                        break;

                    case "APPE":
                        APPE(CmdArguments);
                        break;

                    case "RNFR":
                        // 重命名
                        RNFR(CmdArguments);
                        break;

                    case "RNTO":
                        RNTO(CmdArguments);
                        break;

                    case "DELE":
                        // 删除文件
                        DELE(CmdArguments);
                        break;

                    case "RMD":
                        // 重命名文件夹
                        RMD(CmdArguments);
                        break;

                    case "MKD":
                        // 创建文件夹
                        MKD(CmdArguments);
                        break;


                    case "NLST":
                        NLST(CmdArguments);
                        break;

                    case "SYST":
                        SendMessage("215 Windows_NT\r\n");
                        break;

                    case "NOOP":
                        SendMessage("200 OK\r\n");
                        break;

                    default:
                        SendMessage($"500 Unknown Command.\r\n");
                        break;

                        //	case "STAT":
                        //		break;

                        //	case "HELP":
                        //		break;

                        //	case "REIN":
                        //		break;

                        //	case "STOU":
                        //		break;

                        //	case "REST":
                        //		break;

                        //	case "ABOR":
                        //		break;
                    }
                }
                else
                {
                    SendMessage("530 Access Denied! Authenticate first\r\n");
                }
            }
            #endregion
        }
Пример #20
0
    // Use this for initialization
    void Start()
    {
        Application.runInBackground = true;
        assetPacker = GetComponent <AssetPacker>();

        currentState = UpdateWaitingForResourcesLoaded;

#if UNITY_EDITOR
        skinDirectory = Path.Combine(Directory.GetParent(Application.dataPath).ToString(), skinDirectory);
#else
        skinDirectory = Path.Combine(DirectoryHelper.GetMainDirectory(), skinDirectory);
#endif

        Debug.Log("Loading skin from directory " + skinDirectory);

        if (Directory.Exists(skinDirectory))
        {
            SetupResourcesToLoad();

            // Collect all the files
            string[] filepaths = GetAllFiles(skinDirectory).ToArray();
            Dictionary <string, string> filepathsDictionary = new Dictionary <string, string>();

            int bgCount = 0;

            foreach (string path in filepaths)
            {
                string assetKey = Path.GetFileNameWithoutExtension(path);
                if (!filepathsDictionary.ContainsKey(assetKey))
                {
                    filepathsDictionary.Add(assetKey, path);
                }
                else
                {
                    Debug.LogWarning("Found a duplicate custom asset with under a different file extenstion. Ignoring asset " + path);
                    continue;
                }

                // Checking if the file provided is a background. We have no limit on the amount of backgrounds we can load, so we can't pre-define them like we do above.
                if (System.Text.RegularExpressions.Regex.Match(assetKey, @"background-[0-9]+").Success)
                {
                    resources.Add(new CustomTexture(assetKey, 1920, 1080));
                    ++bgCount;
                }
            }

            Debug.Log("Total backgrounds: " + bgCount);

            foreach (CustomResource resource in resources)
            {
                if (resource.InitWWW(filepathsDictionary))
                {
                    resourcesLoading.Add(resource);
                    resourcesDictionary.Add(resource.name, resource);
                }
            }
        }
        else
        {
            Debug.LogError("Custom Resources not found");
        }
    }
Пример #21
0
        // ReSharper disable InconsistentNaming
        public void Resources_UnitTest_PluginPathsAndNames_WorkflowServicesAreIncluded()
        // ReSharper restore InconsistentNaming
        {
            //Isolate PathsAndNames for workflows as a functional unit
            var workspaceID   = Guid.NewGuid();
            var workspacePath = EnvironmentVariables.GetWorkspacePath(workspaceID);

            try
            {
                const int Modulo             = 4;
                const int TotalResourceCount = 9;
                for (var i = 0; i < TotalResourceCount; i++)
                {
                    var resource = new Resource
                    {
                        ResourceID   = Guid.NewGuid(),
                        ResourceName = string.Format("My Name {0}", i),
                        ResourcePath = string.Format("My Path {0}\\{1}", i, string.Format("My Name {0}", i))
                    };

                    switch (i % Modulo)
                    {
                    case 0:
                        resource.ResourcePath = ResourceType.WorkflowService + "\\" + resource.ResourceName;
                        resource.ResourceType = ResourceType.WorkflowService;
                        break;

                    case 1:
                        resource.ResourcePath = ResourceType.DbService + "\\" + resource.ResourceName;
                        resource.ResourceType = ResourceType.DbService;
                        break;

                    case 2:
                        resource.ResourcePath = ResourceType.PluginService + "\\" + resource.ResourceName;
                        resource.ResourceType = ResourceType.PluginService;
                        break;

                    case 3:
                        resource.ResourcePath = ResourceType.ServerSource + "\\" + resource.ResourceName;
                        resource.ResourceType = ResourceType.ServerSource;
                        break;
                    }
                    ResourceCatalog.Instance.SaveResource(workspaceID, resource);
                }
                var          resources    = new Resources();
                const string ExpectedJson = "{\"Names\":[\"My Name 3\",\"My Name 7\"],\"Paths\":[\"ServerSource\"]}";

                //Run PathsAndNames
                var actualJson = resources.PathsAndNames("ServerSource", workspaceID, Guid.Empty);

                //Assert CorrectListReturned
                Assert.AreEqual(ExpectedJson, actualJson, "Incorrect list of names and paths for workflow services");
            }
            finally
            {
                if (Directory.Exists(workspacePath))
                {
                    DirectoryHelper.CleanUp(workspacePath);
                }
            }
        }
Пример #22
0
        public async Task <IActionResult> ModifyFilenameAsync(string id)
        {
            string newFileName    = "";
            string newDirFullPath = "";
            string dirFullpath    = DirectoryHelper.GetCodeDirectoryPath();
            string reqBody        = "";
            await System.Threading.Tasks.Task.FromResult(0);

            //
            try
            {
                //read request body
                using (var reader = new StreamReader(Request.Body))
                {
                    var body = reader.ReadToEnd();
                    reqBody = body.ToString();
                }
                //get new filename
                if (!string.IsNullOrEmpty(reqBody))
                {
                    var content = JObject.Parse(reqBody);
                    newFileName = (string)content["newName"];
                    newFileName = Regex.Replace(newFileName, "[\n\r\t]", string.Empty);
                    newFileName = Regex.Replace(newFileName, @"\s", string.Empty);
                }
                //if same name exist - BadRequest
                foreach (var record in codeResponse)
                {
                    if (record.Id.ToLower() == newFileName.ToLower())
                    {
                        return(BadRequest(new { message = "File with same name already exists." }));
                    }
                }

                if (!string.IsNullOrEmpty(newFileName))
                {
                    //rename the file and/or folder
                    foreach (var record in codeResponse)
                    {
                        if (record.Id.ToString() == id)
                        {
                            if (record.Type == "JUPYTER_NOTEBOOK")
                            {
                                //check if folder path exists...if not then move folder
                                newDirFullPath = $"{dirFullpath}{newFileName}";
                                if (!Directory.Exists(newDirFullPath))
                                {
                                    Directory.Move($"{dirFullpath}{id}", newDirFullPath);
                                    FileFolderHelper.RenameFile($"{newDirFullPath}/{id}.{record.Extension}", $"{newDirFullPath}/{newFileName}.{record.Extension}");
                                    newDirFullPath = $"{newDirFullPath}/{newFileName}.{record.Extension}";
                                }
                                else
                                {
                                    return(BadRequest(new { message = "Folder with same name already exists. Please choose different file/folder name." }));
                                }
                            }
                            else
                            {
                                newDirFullPath = record.FilePath.Replace($"{id}.{record.Extension}", $"{newFileName}.{record.Extension}");
                                FileFolderHelper.RenameFile(record.FilePath, newDirFullPath);
                            }
                            //update GlobalStorage dictionary
                            CodeResponse newRecord = new CodeResponse()
                            {
                                Id          = newFileName,
                                Name        = $"{newFileName}.{record.Extension}",
                                User        = "",
                                Created_on  = record.Created_on,
                                Edited_on   = record.Edited_on,
                                Extension   = record.Extension,
                                MimeType    = record.MimeType,
                                Size        = record.Size,
                                Type        = record.Type,
                                Url         = record.Url.Replace(id, newFileName),
                                FilePath    = newDirFullPath,
                                DateCreated = record.DateCreated
                            };
                            CodePayload.Create(newRecord);
                            CodePayload.RemoveOnlyFromCodePayload(id);
                            return(Json(newRecord));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(new { message = "Renaming file failed.", exception = ex.StackTrace }));
            }
            return(BadRequest(new { message = "Renaming file failed." }));
        }
Пример #23
0
        public DirectoryM Get(string id)
        {
            var dirM = DirectoryHelper.GetDirectoryModelByPath(id);

            return(dirM);
        }
        public void BuildContent()
        {
            try
            {
                Assets assets       = new Assets(SourceFile);
                string relativePath = SourceFile.Replace(Program.Arguments.WorkingDirectory, "").Trim('/', '\\');
                string relativePathWithoutExtension = relativePath.Contains(".") ? relativePath.Remove(relativePath.LastIndexOf('.')) : relativePath;
                string relativeDirWithoutExtension  = relativePath.Contains("/") || relativePath.Contains("\\") ? relativePath.Remove(relativePath.LastIndexOfAny(new char[] { '/', '\\' })) : "";
                string tempImporter  = null;
                string tempProcessor = null;
                Dictionary <string, string> tempProcessorParam = new Dictionary <string, string>();

                if (!FirstBuild)
                {
                    tempImporter  = Importer;
                    tempProcessor = Processor;
                    tempProcessorParam.Union(ProcessorParam);
                    ProcessorParam.Clear();

                    if (!File.Exists(SourceFile))
                    {
                        DeleteFlag = true;
                    }
                    else if (!BuildTool.Equals(Program.Arguments.BuildTool.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        BuildTool   = Program.Arguments.BuildTool.ToString();
                        RebuildFlag = true;
                    }
                    else
                    {
                        string newHash;

                        using (FileStream fileStream = new FileStream(SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            newHash = fileStream.ToMD5();

                        if (!MetaHash.Equals(newHash, StringComparison.OrdinalIgnoreCase))
                        {
                            MetaHash    = newHash;
                            RebuildFlag = true;
                        }
                        else
                        {
                            List <string> fileToCheck = new List <string>();

                            if (DestinationFile != null)
                            {
                                fileToCheck.Add(DestinationFile.GetFullPath());
                            }

                            fileToCheck = fileToCheck.Union(BuildOutput).Union(BuildAsset).ToList();

                            foreach (string file in fileToCheck)
                            {
                                if (!File.Exists(file))
                                {
                                    RebuildFlag = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    using (FileStream fileStream = new FileStream(SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        MetaHash = fileStream.ToMD5();
                }

#if MonoGame
                if (assets.IsEffectAssets())
                {
                    // Effect Importer - MonoGame
                    string temp;

                    using (StreamReader reader = new StreamReader(new FileStream(SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8))
                        temp = reader.ReadToEnd();

                    temp = temp.Replace("vs_1_1", Program.Arguments.Platform.Equals("DesktopGL", StringComparison.OrdinalIgnoreCase) ? "vs_2_0" : "vs_4_0");
                    temp = temp.Replace("vs_2_0", Program.Arguments.Platform.Equals("DesktopGL", StringComparison.OrdinalIgnoreCase) ? "vs_2_0" : "vs_4_0");
                    temp = temp.Replace("vs_4_0", Program.Arguments.Platform.Equals("DesktopGL", StringComparison.OrdinalIgnoreCase) ? "vs_2_0" : "vs_4_0");
                    temp = temp.Replace("ps_1_1", Program.Arguments.Platform.Equals("DesktopGL", StringComparison.OrdinalIgnoreCase) ? "ps_2_0" : "ps_4_0");
                    temp = temp.Replace("ps_2_0", Program.Arguments.Platform.Equals("DesktopGL", StringComparison.OrdinalIgnoreCase) ? "ps_2_0" : "ps_4_0");
                    temp = temp.Replace("ps_4_0", Program.Arguments.Platform.Equals("DesktopGL", StringComparison.OrdinalIgnoreCase) ? "ps_2_0" : "ps_4_0");

                    using (StreamWriter Writer = new StreamWriter(new FileStream(SourceFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite), Encoding.UTF8)
                    {
                        AutoFlush = true
                    })
                        Writer.Write(temp);

                    temp = null;

                    Importer  = "EffectImporter";
                    Processor = "EffectProcessor";
                    ProcessorParam.Add("DebugMode", "Auto");
                }
                else if (assets.IsFbxModelAssets())
                {
                    // Fbx Importer - MonoGame
                    Importer  = "FbxImporter";
                    Processor = "ModelProcessor";
                    ProcessorParam.Add("ColorKeyColor", "0,0,0,0");
                    ProcessorParam.Add("ColorKeyEnabled", "True");
                    ProcessorParam.Add("DefaultEffect", "BasicEffect");
                    ProcessorParam.Add("GenerateMipmaps", "True");
                    ProcessorParam.Add("GenerateTangentFrames", "False");
                    ProcessorParam.Add("PremultiplyTextureAlpha", "True");
                    ProcessorParam.Add("PremultiplyVertexColors", "True");
                    ProcessorParam.Add("ResizeTexturesToPowerOfTwo", "False");
                    ProcessorParam.Add("RotationX", "0");
                    ProcessorParam.Add("RotationY", "0");
                    ProcessorParam.Add("RotationZ", "0");
                    ProcessorParam.Add("Scale", "1");
                    ProcessorParam.Add("SwapWindingOrder", "False");
                    ProcessorParam.Add("TextureFormat", "Color");
                }
                else if (assets.IsXModelAssets())
                {
                    // X Importer - MonoGame
                    Importer  = "XImporter";
                    Processor = "ModelProcessor";
                    ProcessorParam.Add("ColorKeyColor", "0,0,0,0");
                    ProcessorParam.Add("ColorKeyEnabled", "True");
                    ProcessorParam.Add("DefaultEffect", "BasicEffect");
                    ProcessorParam.Add("GenerateMipmaps", "True");
                    ProcessorParam.Add("GenerateTangentFrames", "False");
                    ProcessorParam.Add("PremultiplyTextureAlpha", "True");
                    ProcessorParam.Add("PremultiplyVertexColors", "True");
                    ProcessorParam.Add("ResizeTexturesToPowerOfTwo", "False");
                    ProcessorParam.Add("RotationX", "0");
                    ProcessorParam.Add("RotationY", "0");
                    ProcessorParam.Add("RotationZ", "0");
                    ProcessorParam.Add("Scale", "1");
                    ProcessorParam.Add("SwapWindingOrder", "False");
                    ProcessorParam.Add("TextureFormat", "Color");
                }
                else if (assets.IsOpenModelAssets())
                {
                    // Open Asset Import Library - MonoGame
                    Importer  = "OpenAssetImporter";
                    Processor = "ModelProcessor";
                    ProcessorParam.Add("ColorKeyColor", "0,0,0,0");
                    ProcessorParam.Add("ColorKeyEnabled", "True");
                    ProcessorParam.Add("DefaultEffect", "BasicEffect");
                    ProcessorParam.Add("GenerateMipmaps", "True");
                    ProcessorParam.Add("GenerateTangentFrames", "False");
                    ProcessorParam.Add("PremultiplyTextureAlpha", "True");
                    ProcessorParam.Add("PremultiplyVertexColors", "True");
                    ProcessorParam.Add("ResizeTexturesToPowerOfTwo", "False");
                    ProcessorParam.Add("RotationX", "0");
                    ProcessorParam.Add("RotationY", "0");
                    ProcessorParam.Add("RotationZ", "0");
                    ProcessorParam.Add("Scale", "1");
                    ProcessorParam.Add("SwapWindingOrder", "False");
                    ProcessorParam.Add("TextureFormat", "Color");
                }
                else if (assets.IsSpriteFontAssets())
                {
                    // Sprite Font Importer - MonoGame
                    Importer  = "FontDescriptionImporter";
                    Processor = "FontDescriptionProcessor";
                    ProcessorParam.Add("TextureFormat", "Color");
                }
                else if (assets.IsTextureAssets())
                {
                    // Texture Importer - MonoGame
                    if (assets.IsFontAssets())
                    {
                        Importer  = "TextureImporter";
                        Processor = "FontTextureProcessor";
                        ProcessorParam.Add("FirstCharacter", " ");
                        ProcessorParam.Add("PremultiplyAlpha", "True");
                        ProcessorParam.Add("TextureFormat", "Color");
                    }
                    else
                    {
                        Importer  = "TextureImporter";
                        Processor = "TextureProcessor";
                        ProcessorParam.Add("ColorKeyColor", "255,0,255,255");
                        ProcessorParam.Add("ColorKeyEnabled", "True");
                        ProcessorParam.Add("GenerateMipmaps", "False");
                        ProcessorParam.Add("PremultiplyAlpha", "True");
                        ProcessorParam.Add("ResizeToPowerOfTwo", "False");
                        ProcessorParam.Add("MakeSquare", "False");
                        ProcessorParam.Add("TextureFormat", "Color");
                    }
                }
                else if (assets.IsMp3Assets())
                {
                    // Mp3 Importer - MonoGame
                    if (assets.IsMusicAssets())
                    {
                        Importer  = "Mp3Importer";
                        Processor = "SongProcessor";
                        ProcessorParam.Add("Quality", "Low");
                    }
                    else if (assets.IsSoundAssets())
                    {
                        Importer  = "Mp3Importer";
                        Processor = "SoundEffectProcessor";
                        ProcessorParam.Add("Quality", "Low");
                    }
                }
                else if (assets.IsOggAssets())
                {
                    // Ogg Importer - MonoGame
                    if (assets.IsMusicAssets())
                    {
                        Importer  = "OggImporter";
                        Processor = "SongProcessor";
                        ProcessorParam.Add("Quality", "Low");
                    }
                    else if (assets.IsSoundAssets())
                    {
                        Importer  = "OggImporter";
                        Processor = "SoundEffectProcessor";
                        ProcessorParam.Add("Quality", "Low");
                    }
                }
                else if (assets.IsWavAssets())
                {
                    // Wav Importer - MonoGame
                    if (assets.IsMusicAssets())
                    {
                        Importer  = "WavImporter";
                        Processor = "SongProcessor";
                        ProcessorParam.Add("Quality", "Low");
                    }
                    else if (assets.IsSoundAssets())
                    {
                        Importer  = "WavImporter";
                        Processor = "SoundEffectProcessor";
                        ProcessorParam.Add("Quality", "Low");
                    }
                }
                else if (assets.IsWmaAssets())
                {
                    // Wma Importer - MonoGame
                    if (assets.IsMusicAssets())
                    {
                        Importer  = "WmaImporter";
                        Processor = "SongProcessor";
                        ProcessorParam.Add("Quality", "Low");
                    }
                    else if (assets.IsSoundAssets())
                    {
                        Importer  = "WmaImporter";
                        Processor = "SoundEffectProcessor";
                        ProcessorParam.Add("Quality", "Low");
                    }
                }
                else if (assets.IsMp4Assets())
                {
                    // H.264 Video - MonoGame
                    Importer  = "H264Importer";
                    Processor = "VideoProcessor";
                }
                else if (assets.IsWmvAssets())
                {
                    // Wmv Importer - MonoGame
                    Importer  = "WmvImporter";
                    Processor = "VideoProcessor";
                }
                else if (assets.IsXMLAssets())
                {
                    // Xml Importer - MonoGame
                    Importer  = "XmlImporter";
                    Processor = "PassThroughProcessor";
                }

                if (!FirstBuild)
                {
                    if (Importer != null && Processor != null)
                    {
                        if (!tempImporter.Equals(Importer, StringComparison.OrdinalIgnoreCase) ||
                            !tempProcessor.Equals(Processor, StringComparison.OrdinalIgnoreCase) ||
                            tempProcessorParam.Select(a => a.Key + "=" + a.Value).Join(";").Equals(ProcessorParam.Select(a => a.Key + "=" + a.Value).Join(";"), StringComparison.OrdinalIgnoreCase))
                        {
                            RebuildFlag = true;
                        }
                    }

                    tempImporter       = null;
                    tempProcessor      = null;
                    tempProcessorParam = null;
                }
#endif

                if (RebuildFlag || DeleteFlag)
                {
                    CleanFile();
                }

                if (Importer.IsNullOrEmpty() || Processor.IsNullOrEmpty())
                {
                    DestinationFile = (Program.Arguments.OutputDirectory + "/" + relativePath).GetFullPath();
                }
                else
                {
                    DestinationFile = (Program.Arguments.OutputDirectory + "/" + relativePathWithoutExtension + ".xnb").GetFullPath();
                }

                if (RebuildFlag || Program.Arguments.Rebuild)
                {
                    if (Importer.IsNullOrEmpty() || Processor.IsNullOrEmpty())
                    {
                        DirectoryHelper.CreateDirectoryIfNotExists((Program.Arguments.OutputDirectory + "/" + relativeDirWithoutExtension).GetFullPath());

                        if (!Program.Arguments.Quiet)
                        {
                            Console.WriteLine("Copying: " + relativePath);
                        }

                        using (FileStream fileStream = new FileStream(SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            using (FileStream fileStream2 = new FileStream((Program.Arguments.OutputDirectory + "/" + relativePath).GetFullPath(), FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
                                fileStream.CopyTo(fileStream2);
                        }

                        BuildSuccess = true;
                    }
                    else
                    {
#if MonoGame
                        PipelineManager manager = new PipelineManager(Program.Arguments.WorkingDirectory, Program.Arguments.OutputDirectory, Program.Arguments.IntermediateDirectory)
                        {
                            CompressContent = Program.Arguments.Compress
                        };

                        if (Program.Arguments.Platform.Equals("DesktopGL", StringComparison.OrdinalIgnoreCase))
                        {
                            manager.Platform = TargetPlatform.DesktopGL;
                        }
                        else if (Program.Arguments.Platform.Equals("Windows", StringComparison.OrdinalIgnoreCase))
                        {
                            manager.Platform = TargetPlatform.Windows;
                        }

                        if (Program.Arguments.Profile.Equals("Reach", StringComparison.OrdinalIgnoreCase))
                        {
                            manager.Profile = GraphicsProfile.Reach;
                        }
                        else if (Program.Arguments.Profile.Equals("HiDef", StringComparison.OrdinalIgnoreCase))
                        {
                            manager.Profile = GraphicsProfile.HiDef;
                        }

                        OpaqueDataDictionary Param = new OpaqueDataDictionary();

                        foreach (KeyValuePair <string, string> item in ProcessorParam)
                        {
                            Param.Add(item.Key, item.Value);
                        }

                        try
                        {
                            if (!Program.Arguments.Quiet)
                            {
                                Console.WriteLine("Building: " + relativePath);
                            }

                            PipelineBuildEvent buildResult = manager.BuildContent(SourceFile, null, Importer, Processor, Param);

                            BuildAsset  = buildResult.BuildAsset;
                            BuildOutput = buildResult.BuildOutput;

                            BuildSuccess = true;
                        }
                        catch (Exception ex)
                        {
                            if (!Program.Arguments.Quiet)
                            {
                                Console.Error.WriteLine("Content Error (" + relativePath + "): " + ex.Message);
                            }

                            BuildSuccess = false;
                        }
#endif
                    }
                }
                else if (DeleteFlag)
                {
                    BuildSuccess = true;
                }
                else
                {
                    if (!Program.Arguments.Quiet)
                    {
                        Console.WriteLine("Skip: " + relativePath);
                    }

                    BuildSuccess = true;
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Console.Error.WriteLine();
                Console.Error.WriteLine(ex.StackTrace);
            }
        }
Пример #25
0
        /// <summary>
        /// Gets invoked after the execution of the entire pex process
        /// </summary>
        public void AfterExecution()
        {
            try
            {
                //this.host.Log.LogMessage(PexMeLogCategories.MethodBegin, "Begin of PexMePostProcessor.AfterExecution() method");

                DirectoryHelper.CheckExistsOrCreate(PexMeConstants.PexMeStorageDirectory);

                //Filter covered locations from uncovered locations
                this.pmd.FilterOutCoveredCodeLocations();
                var currPUTSignature = MethodOrFieldAnalyzer.GetMethodSignature(this.pmd.CurrentPUTMethod);

                //Suggest factory methods
                SafeSet <Method> allSuggestedNewPUTs;
                bool             bHasSomeCoveredLocation, bAllAreNewLocations, bNoneAreNewLocations;
                this.GuessFactorymethods(out allSuggestedNewPUTs, currPUTSignature, out bHasSomeCoveredLocation, out bAllAreNewLocations, out bNoneAreNewLocations);

                var filename = Path.Combine(PexMeConstants.PexMeStorageDirectory, PexMeConstants.ReExecutionStatusFile);
                using (StreamWriter sw = new StreamWriter(filename))
                {
                    //nestingdepth == null represents that this is not run from the Perl
                    //script. So, ignoring the generation of alternative PUTs.
                    if (allSuggestedNewPUTs.Count == 0 || this.ndepth == -1 ||
                        this.ndepth >= PexMeConstants.MAX_ALLOWED_NESTED_DEPTH)
                    {
                        this.pmd.PendingExplorationMethods.Remove(currPUTSignature);

                        //Decide to re-execute or stop. So update all sequences
                        //within uncovered locations with new suggestions and prepare for re-execute
                        this.UpdateUncoveredLocationsWithNewSuggestions(currPUTSignature);

                        //Check whether there is a need to further continue based on requirement
                        //in uncovered locations in factory suggestion store. Used to communicate to outside
                        //process for re-execution
                        if (this.pmd.NeedReExecute(bHasSomeCoveredLocation, bAllAreNewLocations, bNoneAreNewLocations))
                        {
                            sw.WriteLine("REEXECUTE");
                        }
                        else
                        {
                            sw.WriteLine("STOP");

                            //Marks a successful exploration of this PUT
                            this.pmd.AllExploredMethods.Add(currPUTSignature);

                            //Remove all PUT specific sequences from the permanent store
                            this.EndOfPUTCleanUp(currPUTSignature);
                        }
                    }
                    else
                    {
                        //Set up new targets for additional explorations which are required for achieving
                        //the current target.
                        var newCommandFile = "PexMe." + System.Environment.TickCount + ".txt";
                        this.GenerateNestedCommandFile(allSuggestedNewPUTs, newCommandFile);
                        sw.WriteLine("NESTEDEXECUTE");
                        sw.WriteLine(newCommandFile);

                        //Putting all current information on uncovered locations to dormant
                        //stage. Will be re-activated when required and when this PUT is again
                        //brought to action.
                        var currPUT = MethodOrFieldAnalyzer.GetMethodSignature(this.pmd.CurrentPUTMethod);
                        this.SendToDormant(currPUT);
                    }
                }

                this.pdw.DumpDynamicDatabase(this.pmd as PexMeDynamicDatabase);
                this.pdw.DumpStaticDatabase(this.psd as PexMeStaticDatabase);
            }
            catch (Exception ex)
            {
                this.host.Log.LogCriticalFromException(ex, WikiTopics.MissingWikiTopic,
                                                       "postprocessor", ex.StackTrace);
            }
        }
Пример #26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Handle Import settings
        if (!Page.IsCallback && !RequestHelper.IsPostBack())
        {
            // Initialize virtual path provider
            VirtualPathHelper.Init(Page);

            // Initialize import settings
            ImportSettings = GetNewSettings();
        }

        if (!Page.IsCallback)
        {
            if (!CMS.SettingsProvider.SettingsKeyProvider.UsingVirtualPathProvider)
            {
                lblWarning.Visible = true;
                lblWarning.Text    = GetString("ImportSite.VirtualPathProviderNotRunning");
            }

            ctrlAsync.OnFinished += ctrlAsync_OnFinished;
            ctrlAsync.OnError    += ctrlAsync_OnError;

            bool notTempPermissions = false;

            if (wzdImport.ActiveStepIndex < 3)
            {
                stpConfigImport.Settings = ImportSettings;
                stpSiteDetails.Settings  = ImportSettings;
                stpImport.Settings       = ImportSettings;

                // Ensure directory
                DirectoryHelper.EnsureDiskPath(ImportSettings.TemporaryFilesPath + "\\temp.file", ImportSettings.WebsitePath);
                // Check permissions
                notTempPermissions = !DirectoryHelper.CheckPermissions(ImportSettings.TemporaryFilesPath, true, true, false, false);
            }

            if (notTempPermissions)
            {
                pnlWrapper.Visible         = false;
                lblError.Text              = string.Format(GetString("ImportSite.ErrorPermissions"), ImportSettings.TemporaryFilesPath, WindowsIdentity.GetCurrent().Name);
                pnlPermissions.Visible     = true;
                lnkPermissions.Target      = "_blank";
                lnkPermissions.Text        = GetString("Install.ErrorPermissions");
                lnkPermissions.NavigateUrl = ResolveUrl("~/CMSMessages/ConfigurePermissions.aspx");
            }
            else
            {
                if (!RequestHelper.IsPostBack())
                {
                    // Delete temporary files
                    try
                    {
                        // Delete only folder structure if there is not special folder
                        bool onlyFolderStructure = !Directory.Exists(DirectoryHelper.CombinePath(ImportSettings.TemporaryFilesPath, ImportExportHelper.FILES_FOLDER));
                        ImportProvider.DeleteTemporaryFiles(ImportSettings, onlyFolderStructure);
                    }
                    catch (Exception ex)
                    {
                        pnlWrapper.Visible = false;
                        lblError.Text      = GetString("ImportSite.ErrorDeletionTemporaryFiles") + ex.Message;
                        return;
                    }
                }

                // Javascript functions
                string script =
                    "var imMessageText = '';\n" +
                    "var imErrorText = '';\n" +
                    "var imWarningText = '';\n" +
                    "var imMachineName = '" + SqlHelperClass.MachineName.ToLower() + "';\n" +
                    "var getBusy = false;\n" +
                    "function GetImportState(cancel)\n" +
                    "{ if(window.Activity){window.Activity();} if (getBusy && !cancel) return; getBusy = true; setTimeout(\"getBusy = false;\", 2000); var argument = cancel + ';' + imMessageText.length + ';' + imErrorText.length + ';' + imWarningText.length + ';' + imMachineName; return " + Page.ClientScript.GetCallbackEventReference(this, "argument", "SetImportStateMssg", "argument", true) + " }\n";

                script +=
                    "function SetImportStateMssg(rValue, context)\n" +
                    "{\n" +
                    "   getBusy = false;\n" +
                    "   if(rValue != '')\n" +
                    "   {\n" +
                    "       var args = context.split(';');\n" +
                    "       var values = rValue.split('" + SiteExportSettings.SEPARATOR + "');\n" +
                    "       var messageElement = document.getElementById('" + lblProgress.ClientID + "');\n" +
                    "       var errorElement = document.getElementById('" + lblError.ClientID + "');\n" +
                    "       var warningElement = document.getElementById('" + lblWarning.ClientID + "');\n" +
                    "       var messageText = imMessageText;\n" +
                    "       messageText = values[1] + messageText.substring(messageText.length - args[1]);\n" +
                    "       if(messageText.length > imMessageText.length){ imMessageText = messageElement.innerHTML = messageText; }\n" +
                    "       var errorText = imErrorText;\n" +
                    "       errorText = values[2] + errorText.substring(errorText.length - args[2]);\n" +
                    "       if(errorText.length > imErrorText.length){ imErrorText = errorElement.innerHTML = errorText; }\n" +
                    "       var warningText = imWarningText;\n" +
                    "       warningText = values[3] + warningText.substring(warningText.length - args[3]);\n" +
                    "       if(warningText.length > imWarningText.length){ imWarningText = warningElement.innerHTML = warningText; }\n" +
                    "       if((values=='') || (values[0]=='F'))\n" +
                    "       {\n" +
                    "           StopImportStateTimer();\n" +
                    "           BTN_Disable('" + CancelButton.ClientID + "');\n" +
                    "           BTN_Enable('" + FinishButton.ClientID + "');\n" +
                    "       }\n" +
                    "   }\n" +
                    "}\n";

                // Register the script to perform get flags for showing buttons retrieval callback
                ScriptHelper.RegisterClientScriptBlock(this, GetType(), "GetSetImportState", ScriptHelper.GetScript(script));

                // Add cancel button attribute
                CancelButton.Attributes.Add("onclick", "BTN_Disable('" + CancelButton.ClientID + "');" + "return CancelImport();");

                wzdImport.NextButtonClick     += wzdImport_NextButtonClick;
                wzdImport.PreviousButtonClick += wzdImport_PreviousButtonClick;
                wzdImport.FinishButtonClick   += wzdImport_FinishButtonClick;

                if (!RequestHelper.IsPostBack())
                {
                    stpConfigImport.InitControl();
                }
            }
        }
    }
Пример #27
0
        private void btnFindDBPath_Click(object sender, EventArgs e)
        {
            if (IsServiceClass.IsService)
            {
                string path = AppConfigHelper.NormalizePathToWindows(txtDBPath.Text + "\\");
                Cursor.Current       = Cursors.WaitCursor;
                Explorer.frmExplorer = new Explorer(AppConfigHelper.LoggedOnUser, AppConfigHelper.JsonConfig(), "Archive database path",
                                                    DirectoryHelper.IsServerPath(txtDBPath.Text), DirectoryHelper.CleanPath(path),
                                                    string.Empty, null, AppConfigHelper.UbuntuPrefix());
                Cursor.Current = Cursors.Default;
                Explorer.frmExplorer.ShowDialog();
                if (Explorer.frmExplorer.DialogResult == DialogResult.OK)
                {
                    txtDBPath.Text = Explorer.PresentServerPath + Explorer.PresentLocalPath; // One of these is empty.
                }
                Explorer.frmExplorer = null;
            }
            else
            {
                VistaFolderBrowserDialog ofn = new VistaFolderBrowserDialog();
                ofn.Description            = "Archive database path";
                ofn.SelectedPath           = AppConfigHelper.NormalizePathToWindows(txtDBPath.Text);
                ofn.ShowNewFolderButton    = true;
                ofn.UseDescriptionForTitle = true;

                if (ofn.ShowDialog() != DialogResult.Cancel)
                {
                    //if (!ofn.SelectedPath.Trim().StartsWith(AppConfigHelper.UbuntuPrefix()))
                    //{
                    //  MessageBox.Show("The backup database path must be in the Linux file system.", "Wrong file system", MessageBoxButtons.OK);
                    //  return;
                    //}
                    txtDBPath.Text = ofn.SelectedPath.Trim();
                }
            }
        }
Пример #28
0
        public async Task <TemplateFile> GetAsync(
            string name,
            string type,
            string version        = null,
            string templateSource = null)
        {
            DirectoryHelper.CreateIfNotExists(CliPaths.TemplateCache);

            string latestVersion;

#if DEBUG
            latestVersion = await GetLatestSourceCodeVersionAsync(name, type, $"{CliUrls.WwwRocketIoProduction}api/download/{type}/get-version/");
#else
            latestVersion = await GetLatestSourceCodeVersionAsync(name, type);
#endif
            if (version == null)
            {
                if (latestVersion == null)
                {
                    Logger.LogWarning("The remote service is currently unavailable, please specify the version.");
                    Logger.LogWarning(string.Empty);
                    Logger.LogWarning("Find the following template in your cache directory: ");
                    Logger.LogWarning("\t Template Name\tVersion");

                    var templateList = GetLocalTemplates();
                    foreach (var cacheFile in templateList)
                    {
                        Logger.LogWarning($"\t {cacheFile.TemplateName}\t\t{cacheFile.Version}");
                    }

                    Logger.LogWarning(string.Empty);
                    throw new CliUsageException("Use command: rocket new Acme.BookStore -v version");
                }

                version = latestVersion;
            }

            string nugetVersion;

#if DEBUG
            nugetVersion = version;
#else
            nugetVersion = (await GetTemplateNugetVersionAsync(name, type, version)) ?? version;
#endif

            if (!string.IsNullOrWhiteSpace(templateSource) && !IsNetworkSource(templateSource))
            {
                Logger.LogInformation("Using local " + type + ": " + name + ", version: " + version);
                return(new TemplateFile(File.ReadAllBytes(Path.Combine(templateSource, name + "-" + version + ".zip")), version, latestVersion, nugetVersion));
            }

            var localCacheFile = Path.Combine(CliPaths.TemplateCache, name + "-" + version + ".zip");

#if DEBUG
            if (File.Exists(localCacheFile))
            {
                return(new TemplateFile(File.ReadAllBytes(localCacheFile), version, latestVersion, nugetVersion));
            }
#endif

            if (Options.CacheTemplates && File.Exists(localCacheFile) && templateSource.IsNullOrWhiteSpace())
            {
                Logger.LogInformation("Using cached " + type + ": " + name + ", version: " + version);
                return(new TemplateFile(File.ReadAllBytes(localCacheFile), version, latestVersion, nugetVersion));
            }

            Logger.LogInformation("Downloading " + type + ": " + name + ", version: " + version);

            var fileContent = await DownloadSourceCodeContentAsync(
                new SourceCodeDownloadInputDto {
                Name           = name,
                Type           = type,
                TemplateSource = templateSource,
                Version        = version
            }
                );

            if (Options.CacheTemplates && templateSource.IsNullOrWhiteSpace())
            {
                File.WriteAllBytes(localCacheFile, fileContent);
            }

            return(new TemplateFile(fileContent, version, latestVersion, nugetVersion));
        }
Пример #29
0
        static void FindPatchFiles(IList <string> patchFiles, string sourcePath, string inputPath, string outputPath, DateTime beginDate, DateTime endDate, string ignoreDirectories, string ignoreFiles, string ignoreBinaries)
        {
            if (inputPath.LastIndexOf("\\") == inputPath.Length - 1)
            {
                inputPath = inputPath.Substring(0, inputPath.Length - 1);
            }

            if (outputPath.LastIndexOf("\\") == outputPath.Length - 1)
            {
                outputPath = outputPath.Substring(0, outputPath.Length - 1);
            }

            string[] files = Directory.GetFiles(inputPath);

            string[] directories = Directory.GetDirectories(inputPath);

            foreach (string file in files)
            {
                FileInfo fileInfo = new FileInfo(file);

                if (ignoreFiles.IndexOf(fileInfo.Extension.ToLower() + ";") > -1 || ignoreFiles.IndexOf(fileInfo.Name.ToLower() + ";") > -1)
                {
                    continue;
                }

                if (fileInfo.Directory.Name == "bin" && ignoreBinaries.IndexOf(fileInfo.Name.ToLower() + ";") > -1)
                {
                    continue;
                }

                // 判断更新时间
                if (File.GetLastWriteTime(file) >= beginDate && File.GetLastWriteTime(file) <= endDate)
                {
                    patchFiles.Add(file);

                    string sourceFileName = file;

                    string destFileName = file.Replace(inputPath, outputPath);

                    string destPath = Path.GetDirectoryName(destFileName);

                    if (!Directory.Exists(destPath))
                    {
                        DirectoryHelper.Create(destPath);
                    }

                    if (File.Exists(destFileName))
                    {
                        File.SetAttributes(destFileName, System.IO.FileAttributes.Normal);
                    }

                    File.Copy(sourceFileName, destFileName, true);

                    Console.WriteLine(file.Replace(sourcePath, string.Empty));
                }
            }

            foreach (string directory in directories)
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(directory);

                string relativePath = directoryInfo.FullName.Replace(sourcePath, string.Empty).ToLower() + "\\";

                if (ignoreDirectories.IndexOf(relativePath + ";") > -1 || ignoreDirectories.IndexOf(directoryInfo.Name.ToLower() + ";") > -1)
                {
                    continue;
                }

                FindPatchFiles(patchFiles, sourcePath, directory, string.Format("{0}\\{1}", outputPath, directoryInfo.Name), beginDate, endDate, ignoreDirectories, ignoreFiles, ignoreBinaries);
            }
        }
    /// <summary>
    /// Handles storing of multiple media files at once.
    /// </summary>
    private void HandleMultipleMediaFiles()
    {
        try
        {
            string[] filePaths = ImportFilePaths.Split('|');
            if (filePaths.Length > 0)
            {
                bool   first       = true;
                string description = txtImportFileDescription.Text.Trim();
                string title       = txtImportFileTitle.Text.Trim();
                string name        = txtImportFileName.Text.Trim();

                // Check if the filename is in correct format
                if (!ValidationHelper.IsFileName(name))
                {
                    SetupTexts();

                    // Inform user on error
                    RaiseOnAction("importerror", GetString("media.rename.wrongformat"));
                    return;
                }

                // Go through the files and save one by one
                foreach (string path in filePaths)
                {
                    if (path.Trim() != "")
                    {
                        string filePath = DirectoryHelper.CombinePath(FolderPath, path);
                        string ext      = Path.GetExtension(filePath);
                        if (!MediaLibraryHelper.IsExtensionAllowed(ext.TrimStart('.')))
                        {
                            RaiseOnAction("importerror", string.Format(GetString("attach.notallowedextension"), ext, MediaLibraryHelper.GetAllowedExtensions(SiteName).TrimEnd(';').Replace(";", ", ")));
                            return;
                        }

                        // Get file and library info
                        FileInfo currFile = FileInfo.New(RootFolderPath + DirectoryHelper.CombinePath(LibraryInfo.LibraryFolder, filePath));
                        if (currFile != null)
                        {
                            if (first)
                            {
                                // Save media file info on current file
                                RaiseOnSaveRequired(currFile, title, description, URLHelper.GetSafeFileName(name, SiteName, false), filePath);

                                first = false;
                            }
                            else
                            {
                                string fileName = Path.GetFileNameWithoutExtension(currFile.Name);

                                // Save media file info on current file where title = file name
                                RaiseOnSaveRequired(currFile, fileName, description, URLHelper.GetSafeFileName(fileName, SiteName, false), filePath);
                            }
                        }
                    }
                }

                FinishImport();
            }
            else
            {
                // Inform user on error
                RaiseOnAction("importnofiles", null);
            }
        }
        catch (Exception ex)
        {
            SetupTexts();

            // Inform user on error
            RaiseOnAction("importerror", ex.Message);
        }
        finally
        {
            SetupImport();
        }
    }
Пример #31
0
        public void AppDataFolderTest()
        {
            var folder = DirectoryHelper.AppDataFolder();

            Assert.IsTrue(string.IsNullOrEmpty(folder) == false);
        }
Пример #32
0
        /// <summary>
        ///     生成服务方法
        ///     生成服务接口,与服务方法
        /// </summary>
        /// <param name="type"></param>
        public static void CreateApiController(Type type, string idType, string entityPath)
        {
            //  type = typeof(WidgetHistory);
            //if (type.BaseType.FullName != typeof(MongoEntity).FullName) throw new ValidException("非Mongodb实体方法,不支持服务方法生成");

            if (!type.BaseType.FullName.Contains("Entities"))
            {
                throw new ValidException("命名空间必须包含Entities");
            }

            var testBuilder = new StringBuilder();
            var filePath    = BaseTemplate.GetFilePath(type, "Controllers", entityPath);

            DirectoryHelper.CreateIfNotExists(filePath);
            var fileName = filePath + $"\\Api{type.Name}Controller.cs";

            if (!File.Exists(fileName))
            {
                testBuilder.AppendLine(
                    "using System;using Alabo.Domains.Repositories.EFCore;using Alabo.Domains.Repositories.Model;");
                testBuilder.AppendLine("using System.Linq;");

                testBuilder.AppendLine("using Alabo.Domains.Entities;");
                testBuilder.AppendLine("using Microsoft.AspNetCore.Mvc;");
                testBuilder.AppendLine("using Alabo.Framework.Core.WebApis.Filter;");
                testBuilder.AppendLine("");
                testBuilder.AppendLine("using MongoDB.Bson;");
                testBuilder.AppendLine("using Alabo.Framework.Core.WebApis.Controller;");
                testBuilder.AppendLine("using Alabo.RestfulApi;using ZKCloud.Open.ApiBase.Configuration;");
                testBuilder.AppendLine("using Alabo.Domains.Services;");
                testBuilder.AppendLine("using Alabo.Web.Mvc.Attributes;");
                testBuilder.AppendLine("using Alabo.Web.Mvc.Controllers;");
                testBuilder.AppendLine($"using {type.Namespace};");
                testBuilder.AppendLine($"using {type.Namespace.Replace("Entities", "Services")};");

                if (testBuilder.ToString().IndexOf(type.Namespace, StringComparison.OrdinalIgnoreCase) == -1)
                {
                    testBuilder.AppendLine($"using {type.Namespace};");
                }

                testBuilder.AppendLine();
                testBuilder.AppendLine(
                    $"namespace {type.Namespace.Replace("Entities", "Controllers").Replace("Domain.", "")} {{");

                testBuilder.AppendLine("\t\t[ApiExceptionFilter]");
                testBuilder.AppendLine($"\t\t[Route(\"Api/{type.Name}/[action]\")]");
                testBuilder.AppendLine(
                    $"\t\tpublic class Api{type.Name}Controller : ApiBaseController<{type.Name},{idType}>  {{");

                testBuilder.AppendLine(
                    $" public Api{type.Name}Controller() : base() ");
                testBuilder.AppendLine("\t{ ");
                testBuilder.AppendLine($"\t\tBaseService = Resolve<I{type.Name}Service>();");
                testBuilder.AppendLine("\t}");
                testBuilder.AppendLine();

                testBuilder.AppendLine("\t}");
                testBuilder.AppendLine("}");
                //创建文件

                using (var stream = File.Create(fileName))
                {
                    using (var writer = new StreamWriter(stream))
                    {
                        writer.Write(testBuilder);
                    }
                }
            }
        }
Пример #33
0
    /// <summary>
    /// Saves modified image data.
    /// </summary>
    /// <param name="name">Image name</param>
    /// <param name="extension">Image extension</param>
    /// <param name="mimetype">Image mimetype</param>
    /// <param name="title">Image title</param>
    /// <param name="description">Image description</param>
    /// <param name="binary">Image binary data</param>
    /// <param name="width">Image width</param>
    /// <param name="height">Image height</param>
    private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height)
    {
        // Process media file
        if (mfi == null)
        {
            mfi = MediaFileInfoProvider.GetMediaFileInfo(mediafileGuid, CurrentSiteName);
        }

        if (mfi != null)
        {
            MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(mfi.FileLibraryID);
            if (mli != null)
            {
                string path          = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(mli.LibraryID), mfi.FilePath));
                bool   permissionsOK = DirectoryHelper.CheckPermissions(path, false, true, true, true);

                // Check file write permissions
                FileInfo file = FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath));
                if (file != null)
                {
                    permissionsOK = permissionsOK && !file.IsReadOnly;
                }

                if (permissionsOK)
                {
                    MediaFileInfo originalMfi = mfi.Clone(true);

                    try
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mfi);

                        if (isPreview && !String.IsNullOrEmpty(PreviewPath))
                        {
                            SiteInfo si = SiteInfoProvider.GetSiteInfo(mfi.FileSiteID);
                            if (si != null)
                            {
                                string previewExt    = (!String.IsNullOrEmpty(extension) && (extension != OldPreviewExt)) ? extension : OldPreviewExt;
                                string previewName   = Path.GetFileNameWithoutExtension(PreviewPath);
                                string previewFolder = MediaLibraryHelper.EnsurePath(DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath).TrimEnd('/'), MediaLibraryHelper.GetMediaFileHiddenFolder(si.SiteName)));

                                // Delete old preview files with thumbnails
                                MediaFileInfoProvider.DeleteMediaFilePreview(CMSContext.CurrentSiteName, mli.LibraryID, mfi.FilePath, false);
                                MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                                // Save preview file
                                MediaFileInfoProvider.SaveFileToDisk(si.SiteName, mli.LibraryFolder, previewFolder, previewName, previewExt, mfi.FileGUID, binary, false, false);

                                // Log synchronization task
                                SynchronizationHelper.LogObjectChange(mfi, TaskTypeEnum.UpdateObject);
                            }
                        }
                        else
                        {
                            string newExt  = null;
                            string newName = null;

                            if (!String.IsNullOrEmpty(extension))
                            {
                                newExt = extension;
                            }
                            if (!String.IsNullOrEmpty(mimetype))
                            {
                                mfi.FileMimeType = mimetype;
                            }

                            mfi.FileTitle       = title;
                            mfi.FileDescription = description;

                            if (width > 0)
                            {
                                mfi.FileImageWidth = width;
                            }
                            if (height > 0)
                            {
                                mfi.FileImageHeight = height;
                            }
                            if (binary != null)
                            {
                                mfi.FileBinary = binary;
                                mfi.FileSize   = binary.Length;
                            }
                            // Test all parameters to empty values and update new value if available
                            if (!String.IsNullOrEmpty(name))
                            {
                                newName = name;
                            }
                            // If filename changed move preview file and remove all ald thumbnails
                            if ((!String.IsNullOrEmpty(newName) && (mfi.FileName != newName)) || (!String.IsNullOrEmpty(newExt) && (mfi.FileExtension.ToLowerCSafe() != newExt.ToLowerCSafe())))
                            {
                                SiteInfo si = SiteInfoProvider.GetSiteInfo(mfi.FileSiteID);
                                if (si != null)
                                {
                                    string fileName = (newName != null ? newName : mfi.FileName);
                                    string fileExt  = (newExt != null ? newExt : mfi.FileExtension);

                                    string newPath  = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt);
                                    string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath);

                                    // Rename file only if file with same name does not exsists
                                    if (!File.Exists(newPath))
                                    {
                                        // Ensure max length of file path
                                        if (newPath.Length < 260)
                                        {
                                            // Remove old thumbnails
                                            MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);
                                            MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                                            // Move media file
                                            MediaFileInfoProvider.MoveMediaFile(si.SiteName, mli.LibraryID, mfi.FilePath, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt, false);

                                            // Set new file name or extension
                                            mfi.FileName      = fileName;
                                            mfi.FileExtension = fileExt;

                                            // Ensure new binary
                                            if (binary != null)
                                            {
                                                mfi.FileBinary = binary;
                                                mfi.FileSize   = binary.Length;
                                            }
                                        }
                                        else
                                        {
                                            throw new IOExceptions.PathTooLongException();
                                        }
                                    }
                                    else
                                    {
                                        baseImageEditor.LblLoadFailed.Visible        = true;
                                        baseImageEditor.LblLoadFailed.ResourceString = "img.errors.fileexists";
                                        SavingFailed = true;
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                // Remove old thumbnails
                                MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);

                                // Remove original media file before save
                                string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath);
                                if (File.Exists(filePath))
                                {
                                    File.Delete(filePath);
                                }
                            }

                            // Save new data
                            MediaFileInfoProvider.SetMediaFileInfo(mfi, false);
                        }
                    }
                    catch (Exception e)
                    {
                        // Log exception
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("ImageEditor", "Save file", e);

                        baseImageEditor.LblLoadFailed.Visible        = true;
                        baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing";
                        ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, e.Message, "help");
                        SavingFailed = true;
                        // Save original media file info
                        MediaFileInfoProvider.SetMediaFileInfo(originalMfi, false);
                    }
                }
                else // User hasn't permissions for save file
                {
                    baseImageEditor.LblLoadFailed.Visible        = true;
                    baseImageEditor.LblLoadFailed.ResourceString = "img.errors.filesystempermissions";
                    SavingFailed = true;
                }
            }
        }
    }