コード例 #1
0
ファイル: FileSize.cs プロジェクト: BeiMeng/GitApplication
 /// <summary>
 /// 获取文件大小
 /// </summary>
 private static long GetSize( long size, FileUnit unit ) {
     switch ( unit ) {
         case FileUnit.K:
             return size * 1024;
         case FileUnit.M:
             return size * 1024 * 1024;
         case FileUnit.G:
             return size * 1024 * 1024 * 1024;
         default :
             return size;
     }
 }
コード例 #2
0
        private void button_delete_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要删除的文件");
                return;
            }
            FileUnit     fileObject = this.dataGridView1.SelectedRows[0].DataBoundItem as FileUnit;
            DialogResult result     = MessageBox.Show(string.Format("确定要删除文件{0}?", fileObject.FileRelativePath), "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                this.fileConfig.FileList.Remove(fileObject);
                this.fileConfig.Save();
                this.changed = true;
                this.BindData();
            }
        }
コード例 #3
0
        /// <summary>
        /// Button delete clicked.
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">event</param>
        private void Button_Delete_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 0)
            {
                MessageBox.Show(Resources.NoFileSelected);
                return;
            }

            FileUnit fileUnit = dataGridView.SelectedRows[0].DataBoundItem as FileUnit;

            if (DialogResult.OK == MessageBox.Show(string.Format("{0}{1}?", Resources.DeleteConfirmation, fileUnit.FileRelativePath), Resources.MessageTip, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))
            {
                mUpdateConfiguration.FileList.Remove(fileUnit);
                mUpdateConfiguration.Save();
                mConfigurationChanged = true;
                GetUpdateInfo();
            }
        }
コード例 #4
0
        /// <summary>
        /// 与服务器的最新版本进行比较,获取要升级的所有文件信息。
        /// </summary>
        private void GetUpdateInfo(out IList <string> downLoadFileNameList, out IList <FileUnit> removeFileNameList)
        {
            byte[] lastUpdateTime = rapidPassiveEngine.CustomizeOutter.Query(InformationTypes.GetLastUpdateTime, null);
            LastUpdateTimeContract lastUpdateTimeContract = CompactPropertySerializer.Default.Deserialize <LastUpdateTimeContract>(lastUpdateTime, 0);

            downLoadFileNameList = new List <string>();
            removeFileNameList   = new List <FileUnit>();
            if (this.updateConfiguration.ClientVersion != lastUpdateTimeContract.ClientVersion)
            {
                //获取服务器文件版本信息列表
                byte[]            fileInfoBytes = rapidPassiveEngine.CustomizeOutter.Query(InformationTypes.GetAllFilesInfo, null);
                FilesInfoContract contract      = CompactPropertySerializer.Default.Deserialize <FilesInfoContract>(fileInfoBytes, 0);

                //更新现有文件
                foreach (FileUnit file in this.updateConfiguration.FileList)
                {
                    FileUnit fileAtServer = ContainsFile(file.FileRelativePath, contract.AllFileInfoList);
                    if (fileAtServer != null)
                    {
                        if (file.Version < fileAtServer.Version)
                        {
                            downLoadFileNameList.Add(file.FileRelativePath);
                        }
                    }
                    else
                    {
                        removeFileNameList.Add(file);
                    }
                }

                //下载新文件
                foreach (FileUnit file in contract.AllFileInfoList)
                {
                    FileUnit fileAtServer = ContainsFile(file.FileRelativePath, this.updateConfiguration.FileList);
                    if (fileAtServer == null)
                    {
                        downLoadFileNameList.Add(file.FileRelativePath);
                    }
                }
                this.updateConfiguration.FileList      = contract.AllFileInfoList;
                this.updateConfiguration.ClientVersion = lastUpdateTimeContract.ClientVersion;
            }
        }
コード例 #5
0
        /// <summary>
        /// Get update information.
        /// </summary>
        private void GetUpdateInfo(out IList <string> fileRelativePathListNeedDownloaded, out IList <FileUnit> fileListNeedRemoved)
        {
            byte[] latestUpdateTime = mRapidPassiveEngine.CustomizeOutter.Query(InformationTypes.GetLatestUpdateTime, null);
            LatestUpdateTimeContract latestUpdateTimeContract = CompactPropertySerializer.Default.Deserialize <LatestUpdateTimeContract>(latestUpdateTime, 0);

            fileRelativePathListNeedDownloaded = new List <string>();
            fileListNeedRemoved = new List <FileUnit>();

            if (mUpdateConfiguration.ClientVersion != latestUpdateTimeContract.ClientVersion)
            {
                byte[]            fileInfoBytes     = mRapidPassiveEngine.CustomizeOutter.Query(InformationTypes.GetAllFilesInfo, null);
                FilesInfoContract filesInfoContract = CompactPropertySerializer.Default.Deserialize <FilesInfoContract>(fileInfoBytes, 0);

                foreach (FileUnit file in mUpdateConfiguration.FileList)
                {
                    FileUnit fileAtServer = ContainsFile(file.FileRelativePath, filesInfoContract.AllFileInfoList);
                    if (fileAtServer != null)
                    {
                        if (file.Version < fileAtServer.Version)
                        {
                            fileRelativePathListNeedDownloaded.Add(file.FileRelativePath);
                        }
                    }
                    else
                    {
                        fileListNeedRemoved.Add(file);
                    }
                }

                foreach (FileUnit file in filesInfoContract.AllFileInfoList)
                {
                    FileUnit fileAtServer = ContainsFile(file.FileRelativePath, mUpdateConfiguration.FileList);
                    if (fileAtServer == null)
                    {
                        fileRelativePathListNeedDownloaded.Add(file.FileRelativePath);
                    }
                }
                mUpdateConfiguration.FileList      = filesInfoContract.AllFileInfoList;
                mUpdateConfiguration.ClientVersion = latestUpdateTimeContract.ClientVersion;
            }
        }
コード例 #6
0
        //
        // To recompile all the xaml files ( including page and application file).
        // Transfer all the xaml files to the recompileMarkupPages.
        //
        private void UpdateFileListForCleanbuild()
        {
            if (ListIsNotEmpty(_mcPass1.PageMarkup))
            {
                int count = _mcPass1.PageMarkup.Length;
                _recompileMarkupPages = new FileUnit[count];

                for (int i = 0; i < count; i++)
                {
                    ITaskItem taskItem = _mcPass1.PageMarkup[i];
                    _recompileMarkupPages[i] = new FileUnit(
                        Path.GetFullPath(taskItem.ItemSpec),
                        taskItem.GetMetadata(SharedStrings.Link),
                        taskItem.GetMetadata(SharedStrings.LogicalName));
                }
            }

            RecompileContentFiles();

            ProcessApplicationFile(true);
        }
コード例 #7
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="updateConfiguration">update configuration</param>
        /// <param name="fileUnit">file unit</param>
        public ModifyFileVersionForm(UpdateConfiguration updateConfiguration, FileUnit fileUnit)
        {
            InitializeComponent();

            mUpdateConfiguration = updateConfiguration;
            List <string> files = FileHelper.GetOffspringFiles(AppDomain.CurrentDomain.BaseDirectory + "FileFolder\\");

            files.Sort();
            comboBox.DataSource = files;
            if (files.Count > 0)
            {
                comboBox.SelectedIndex = 0;
            }

            mIsNewFile = (fileUnit == null);
            if (!mIsNewFile)
            {
                comboBox.Text            = fileUnit.FileRelativePath;
                textBox_FileVersion.Text = fileUnit.Version.ToString();
                comboBox.Enabled         = false;
            }
        }
コード例 #8
0
        //
        // Handle Application definition xaml file and Application Class name.
        // recompile parameter indicates whether or not to recompile the appdef file.
        // If the appdef file is not recompiled, a specially handling is required to 
        // take application class name from previous build.
        //
        private void ProcessApplicationFile(bool recompile)
        {
            if (!_mcPass1.IsApplicationTarget)
            {
                return;
            }

            if (recompile)
            {
                //
                // Take whatever setting in _mcPass1 task.
                //
                if (_mcPass1.ApplicationMarkup != null && _mcPass1.ApplicationMarkup.Length > 0 && _mcPass1.ApplicationMarkup[0] != null)
                {
                    ITaskItem taskItem = _mcPass1.ApplicationMarkup[0];
                    _recompileApplicationFile = new FileUnit(
                                                    _mcPass1.ApplicationFile, 
                                                    taskItem.GetMetadata(SharedStrings.Link),
                                                    taskItem.GetMetadata(SharedStrings.LogicalName));
                }
                else
                {
                    _recompileApplicationFile = FileUnit.Empty;
                }
            }
            else
            {
                _recompileApplicationFile = FileUnit.Empty;

            }
        }
コード例 #9
0
        //
        // Generate new list of files that require to recompile for incremental build based on _analyzeResult
        //
        private void UpdateFileListForIncrementalBuild(List <FileUnit> modifiedXamlFiles)
        {
            List <FileUnit> recompiledXaml    = new List <FileUnit>();
            bool            recompileApp      = false;
            int             numLocalTypeXamls = 0;

            if ((_analyzeResult & RecompileCategory.ContentFiles) == RecompileCategory.ContentFiles)
            {
                RecompileContentFiles();
            }

            if ((_analyzeResult & RecompileCategory.ApplicationFile) == RecompileCategory.ApplicationFile)
            {
                recompileApp = true;
            }

            if ((_analyzeResult & RecompileCategory.PagesWithLocalType) == RecompileCategory.PagesWithLocalType && TaskFileService.IsRealBuild)
            {
                CompilerLocalReference.LoadCacheFile();

                if (CompilerLocalReference.LocalApplicationFile != null)
                {
                    // Application file contains local types, it will be recompiled.
                    recompileApp = true;
                }

                if (ListIsNotEmpty(CompilerLocalReference.LocalMarkupPages))
                {
                    numLocalTypeXamls = CompilerLocalReference.LocalMarkupPages.Length;

                    for (int i = 0; i < CompilerLocalReference.LocalMarkupPages.Length; i++)
                    {
                        LocalReferenceFile localRefFile = CompilerLocalReference.LocalMarkupPages[i];
                        recompiledXaml.Add(new FileUnit(
                                               localRefFile.FilePath,
                                               localRefFile.LinkAlias,
                                               localRefFile.LogicalName));
                    }
                }
            }

            if ((_analyzeResult & RecompileCategory.ModifiedPages) == RecompileCategory.ModifiedPages)
            {
                // If the xaml is already in the local-type-ref xaml file list, don't add a duplicate file path to recompiledXaml list.

                for (int i = 0; i < modifiedXamlFiles.Count; i++)
                {
                    FileUnit xamlfile = modifiedXamlFiles[i];
                    bool     addToList;

                    addToList = true;

                    if (numLocalTypeXamls > 0)
                    {
                        for (int j = 0; j < numLocalTypeXamls; j++)
                        {
                            if (String.Compare(xamlfile.Path, CompilerLocalReference.LocalMarkupPages[j].FilePath, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                addToList = false;
                                break;
                            }
                        }
                    }

                    if (addToList)
                    {
                        recompiledXaml.Add(xamlfile);
                    }
                }
            }

            if (recompiledXaml.Count > 0)
            {
                _recompileMarkupPages = recompiledXaml.ToArray();
            }

            // Set ApplicationFile appropriatelly for this incremental build.
            ProcessApplicationFile(recompileApp);
        }
コード例 #10
0
    /// <summary>
    /// 获取指定路径的文件信息,
    ///
    /// 假设有如下目录和文件
    /// C;/MyTest/Liange/MyTest.txt
    ///
    /// 现在获取C:/MyTest目录下的文件,
    /// 如果相对路径(relativePath)为空(""),则MyTest.txt获取出来的相对路径就是Liange/MyTest.txt
    /// 如果相对路径(relativePath)为"MyDir",则MyTest.txt获取出来的相对路径就是MyDir/Liange/MyTest.txt
    ///
    /// </summary>
    /// <param name="fullDirPath">需要获取文件列表的目录路径</param>
    /// <param name="relativePath">获取的文件相对路径</param>
    /// <param name="fileList"></param>
    /// <param name="mode"></param>
    /// <param name="fileType">需要处理的文件类别,Ignore:忽略这种文件类型,Special:只查找这种文件类型</param>
    public static void GetRelativeFileList(string fullDirPath, string relativePath, ref List <FileUnit> fileList, FileSearchMode mode, string fileType)
    {
        try
        {
            if (string.IsNullOrEmpty(fileType) == false)
            {
                if (fileType[0] != '.')
                {
                    fileType = '.' + fileType;
                }
            }

            DirectoryInfo currentDir  = new DirectoryInfo(fullDirPath);
            FileInfo[]    tmpFileList = currentDir.GetFiles();
            foreach (FileInfo fi in tmpFileList)
            {
                switch (mode)
                {
                case FileSearchMode.Ignore:
                {
                    if (fi.Extension == fileType)
                    {
                        continue;
                    }
                }
                break;

                case FileSearchMode.Special:
                {
                    if (fi.Extension != fileType)
                    {
                        continue;
                    }
                }
                break;
                }

                FileUnit unit = new FileUnit();
                unit.name     = fi.Name;
                unit.fullPath = fi.FullName.Replace('\\', '/');
                if (string.IsNullOrEmpty(relativePath))
                {
                    unit.relativePath = fi.Name;
                }
                else
                {
                    unit.relativePath = relativePath + "/" + fi.Name;
                }

                fileList.Add(unit);
            }

            DirectoryInfo[] dirList = currentDir.GetDirectories();
            foreach (DirectoryInfo di in dirList)
            {
                string newRelativePath = null;
                if (string.IsNullOrEmpty(relativePath))
                {
                    newRelativePath = di.Name;
                }
                else
                {
                    newRelativePath = relativePath + "/" + di.Name;
                }

                GetRelativeFileList(di.FullName, newRelativePath, ref fileList, mode, fileType);
            }
        }
        catch (System.Exception ex)
        {
            Debug.LogError("MyFileUtil.GetRelativeFileList:" + ex.Message);
        }
    }
コード例 #11
0
        //
        // To recompile all the xaml files ( including page and application file).
        // Transfer all the xaml files to the recompileMarkupPages.
        // 
        private void UpdateFileListForCleanbuild()
        {
            if (ListIsNotEmpty(_mcPass1.PageMarkup))
            {
                int count = _mcPass1.PageMarkup.Length;
                _recompileMarkupPages = new FileUnit[count];

                for (int i = 0; i < count; i++)
                {
                    ITaskItem taskItem = _mcPass1.PageMarkup[i];
                    _recompileMarkupPages[i] = new FileUnit( 
                        Path.GetFullPath(taskItem.ItemSpec), 
                        taskItem.GetMetadata(SharedStrings.Link),
                        taskItem.GetMetadata(SharedStrings.LogicalName));
                }
            }

            RecompileContentFiles();

            ProcessApplicationFile(true);
        }
コード例 #12
0
        public void AllFunctionallityPositiveTestWithUserConfig_ReturnTrue()
        {
            // Arrange
            unit.UseMyFolderForJournals(this.UserFolderForJournals);

            var    sqliteTransactionFirst = new SQLiteUnit(this.PathToDataBase);
            string firstSqlCommand        =
                $"INSERT INTO {this.DbTableName}({this.DbFieldId}, {this.DbFieldFirstName}, {this.DbFieldLastName}) "
                + $"VALUES ({this.DbRowId}, '{this.FirstName}', '{this.LastName}')";
            string firstSqlRollback = $"DELETE FROM {this.DbTableName} WHERE {this.DbFieldId} = {this.DbRowId}";

            sqliteTransactionFirst.AddSqliteCommand(
                firstSqlCommand,
                firstSqlRollback);

            var fileTransaction = new FileUnit();

            fileTransaction.CreateFile(this.CreateFilePath);
            fileTransaction.Copy(this.CopyFilePath, this.CopybleFilePath, true);
            fileTransaction.AppendAllText(this.AppendFilePath, this.AddedContent);
            fileTransaction.WriteAllText(this.WriteFilePath, this.AddedContent);
            fileTransaction.Delete(this.DeleteFilePath);
            fileTransaction.Move(this.MoveFilePath, this.MovebleFilePath);

            var    sqliteTransactionSecond = new SQLiteUnit(this.PathToDataBase);
            string secondSqlCommand        =
                $"UPDATE {this.DbTableName} set {this.DbFieldFirstName} = "
                + $"'{this.NewFirstName}' WHERE {this.DbFieldId} = {this.DbRowId}";
            string secondSqlRollback =
                $"UPDATE {this.DbTableName} set {this.DbFieldFirstName} = "
                + $"'{this.LastName}' WHERE {this.DbFieldId} = {this.DbRowId}";

            sqliteTransactionSecond.AddSqliteCommand(
                secondSqlCommand,
                secondSqlRollback);

            // Act
            var bussinesTransaction = this.unit.BeginTransaction();

            bussinesTransaction.ExecuteUnit(sqliteTransactionFirst);
            bussinesTransaction.ExecuteUnit(sqliteTransactionFirst);
            bussinesTransaction.ExecuteUnit(fileTransaction);
            bussinesTransaction.ExecuteUnit(sqliteTransactionSecond);

            string firstNameInDb = string.Empty;
            string lastNameInDb  = string.Empty;

            this.GetInfOfDataBase(out firstNameInDb, out lastNameInDb);

            // Assert
            Assert.IsTrue(File.Exists(this.CreateFilePath));
            Assert.IsTrue(File.Exists(this.CopybleFilePath) && File.Exists(this.CopyFilePath));
            string textInAppendFile = File.ReadAllText(this.AppendFilePath);

            Assert.AreEqual(textInAppendFile, this.Content + this.AddedContent);
            string textInWriteFile = File.ReadAllText(this.WriteFilePath);

            Assert.AreEqual(textInWriteFile, this.AddedContent);
            Assert.IsFalse(File.Exists(this.DeleteFilePath));
            Assert.IsTrue(File.Exists(this.MovebleFilePath) && !File.Exists(this.MoveFilePath));
            Assert.AreEqual(this.NewFirstName, firstNameInDb);
            Assert.AreEqual(this.LastName, lastNameInDb);
            Assert.IsTrue(Directory.EnumerateFiles(this.UserFolderForJournals).Any());

            bussinesTransaction.Commit();
            bussinesTransaction.Dispose();
            unit.UseDefaultFolderForJournals();
        }
コード例 #13
0
        private void button1_Click(object sender, EventArgs e)
        {
            int             changedCount = 0;
            int             addedCount   = 0;
            List <FileUnit> deleted      = new List <FileUnit>();
            List <string>   files        = ESBasic.Helpers.FileHelper.GetOffspringFiles(AppDomain.CurrentDomain.BaseDirectory + "FileFolder\\");

            foreach (string fileRelativePath in files)
            {
                FileInfo info = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "FileFolder\\" + fileRelativePath);
                FileUnit unit = this.GetFileUnit(fileRelativePath);
                if (unit == null)
                {
                    unit = new FileUnit(fileRelativePath, 1, (int)info.Length, info.LastWriteTime);
                    this.fileConfig.FileList.Add(unit);
                    ++addedCount;
                }
                else
                {
                    if (unit.FileSize != info.Length || unit.LastUpdateTime.ToString() != info.LastWriteTime.ToString())
                    {
                        unit.Version       += 1;
                        unit.FileSize       = (int)info.Length;
                        unit.LastUpdateTime = info.LastWriteTime;
                        ++changedCount;
                    }
                }
            }

            foreach (FileUnit unit in this.fileConfig.FileList)
            {
                bool found = false;
                foreach (string fileRelativePath in files)
                {
                    if (fileRelativePath == unit.FileRelativePath)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    deleted.Add(unit);
                }
            }

            foreach (FileUnit unit in deleted)
            {
                this.fileConfig.FileList.Remove(unit);
            }
            this.fileConfig.Save();

            if (changedCount > 0 || addedCount > 0 || deleted.Count > 0)
            {
                this.changed = true;
                this.dataGridView1.DataSource = null;
                this.dataGridView1.DataSource = this.fileConfig.FileList;
                string msg = string.Format("更新:{0},新增:{1},删除:{2}", changedCount, addedCount, deleted.Count);
                MessageBox.Show(msg);
            }
        }
コード例 #14
0
 /// <summary>
 /// 初始化文件大小
 /// </summary>
 /// <param name="size">文件字节大小</param>
 /// <param name="unit">文件字节大小</param>
 public FileSize(long size, FileUnit unit = FileUnit.Byte)
 {
     _size = GetSize(size, unit);
 }
コード例 #15
0
        public void ForgottenToMakeCommit_ReturnTrue()
        {
            // Arrange
            var    sqliteTransactionFirst = new SQLiteUnit(this.PathToDataBase);
            string firstSqlCommand        =
                $"INSERT INTO {this.DbTableName}({this.DbFieldId}, {this.DbFieldFirstName}, {this.DbFieldLastName}) "
                + $"VALUES ({DbRowId}, '{FirstName}', '{LastName}')";
            string firstSqlRollback = $"DELETE FROM {this.DbTableName} WHERE {DbFieldId} = {DbRowId}";

            sqliteTransactionFirst.AddSqliteCommand(
                firstSqlCommand,
                firstSqlRollback);

            var fileTransaction = new FileUnit();

            fileTransaction.CreateFile(this.CreateFilePath);
            fileTransaction.Copy(this.CopyFilePath, this.CopybleFilePath, true);
            fileTransaction.AppendAllText(this.AppendFilePath, this.AddedContent);
            fileTransaction.WriteAllText(this.WriteFilePath, this.AddedContent);
            fileTransaction.Delete(this.DeleteFilePath);
            fileTransaction.Move(this.MoveFilePath, this.MovebleFilePath);

            var    sqliteTransactionSecond = new SQLiteUnit(this.PathToDataBase);
            string secondSqlCommand        =
                $"UPDATE {this.DbTableName} set {this.DbFieldFirstName} = "
                + $"'{this.NewFirstName}' WHERE {this.DbFieldId} = {this.DbRowId}";
            string secondSqlRollback =
                $"UPDATE {this.DbTableName} set {this.DbFieldFirstName} = "
                + $"'{LastName}' WHERE {this.DbFieldId} = {this.DbRowId}";

            sqliteTransactionSecond.AddSqliteCommand(
                secondSqlCommand,
                secondSqlRollback);

            // Act
            using (var bussinesTransaction = this.unit.BeginTransaction())
            {
                bussinesTransaction.ExecuteUnit(sqliteTransactionFirst);
                bussinesTransaction.ExecuteUnit(fileTransaction);
                bussinesTransaction.ExecuteUnit(sqliteTransactionSecond);
            }

            string firstNameInDb = string.Empty;
            string lastNameInDb  = string.Empty;

            this.GetInfOfDataBase(out firstNameInDb, out lastNameInDb);

            // Assert
            Assert.IsFalse(File.Exists(this.CreateFilePath));
            Assert.IsTrue(!File.Exists(this.CopybleFilePath) && File.Exists(this.CopyFilePath));
            string textInAppendFile = File.ReadAllText(this.AppendFilePath);

            Assert.AreEqual(textInAppendFile, this.Content);
            string textInWriteFile = File.ReadAllText(this.WriteFilePath);

            Assert.AreEqual(textInWriteFile, this.Content);
            Assert.IsTrue(File.Exists(this.DeleteFilePath));
            Assert.IsTrue(!File.Exists(this.MovebleFilePath) && File.Exists(this.MoveFilePath));
            Assert.AreEqual(string.Empty, firstNameInDb);
            Assert.AreEqual(string.Empty, lastNameInDb);
        }
コード例 #16
0
        public async Task <string> UploadFile(HttpPostedFile file, AdditionalData fileData, int spaceId, int parentId)
        {
            _logger.WriteInfo("Upload method started");
            var user = await _usersService.GetCurrentUser();

            var localUser = await _unitOfWork?.Users?.Query.FirstOrDefaultAsync(x => x.GlobalId == user.id);

            var space = await _unitOfWork?.Spaces?.GetByIdAsync(spaceId);

            var parentFolder = await _unitOfWork?.Folders.GetByIdAsync(parentId);

            List <User> ReadPermittedUsers = new List <User>();

            ReadPermittedUsers.Add(localUser);

            List <User> ModifyPermittedUsers = new List <User>();

            ModifyPermittedUsers.Add(localUser);
            _logger.WriteInfo("Getting file info");
            string filename = fileData.Name + fileData.Extension;
            string mimeType = GetMimeType(filename);
            var    isImage  = IsImageMime(mimeType);

            _logger.WriteInfo("File name: " + filename + ", Mime type: " + mimeType);

            // File's content.
            Stream filestream = file.InputStream;

            byte[]       byteArray = ReadFully(filestream);
            MemoryStream stream    = new MemoryStream(byteArray);

            _logger.WriteInfo("File content stream: " + stream.Length);
            DriveService service;

            try
            {
                _logger.WriteInfo("Authorization started");
                service = AuthorizationService.ServiceAccountAuthorization();
                _logger.WriteInfo("Authorization succeeded");
            }
            catch (Exception e)
            {
                throw new Exception("Failed to authorize Drive service " + e.Message);
            }

            Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
            body.Name     = filename;
            body.MimeType = mimeType;
            body.Parents  = null;
            _logger.WriteInfo("File body created: " + body.Name);

            if (isImage)
            {
                try
                {
                    var image_link = await UploadToDriveAsync(service, body, stream, mimeType);

                    var prev_filename = "prev_" + fileData.Name + ".jpeg";
                    body.Name     = prev_filename;
                    body.MimeType = "image/jpeg";
                    var img_stream = MakeThumbnail(stream);
                    var prev_link  = await UploadToDriveAsync(service, body, img_stream, "image/jpeg");

                    var imageDto = new ImageUnit()
                    {
                        Name                 = filename,
                        FileType             = FileType.Images,
                        Link                 = image_link,
                        Prev_Link            = prev_link,
                        Description          = fileData.Description,
                        CreatedAt            = DateTime.Now,
                        LastModified         = DateTime.Now,
                        IsDeleted            = false,
                        Space                = space,
                        FolderUnit           = parentFolder,
                        Owner                = await _unitOfWork?.Users?.Query.FirstOrDefaultAsync(u => u.GlobalId == user.id),
                        ReadPermittedUsers   = ReadPermittedUsers,
                        ModifyPermittedUsers = ModifyPermittedUsers
                    };
                    _unitOfWork?.Files?.Create(imageDto);
                    await _unitOfWork?.SaveChangesAsync();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                string link = "";
                try
                {
                    _logger.WriteInfo("Begin upload");
                    link = await UploadToDriveAsync(service, body, stream, mimeType);

                    _logger.WriteInfo("Upload completed");
                }
                catch (Exception e)
                {
                    throw new Exception("Failed to upload file to drive " + e.Message);
                }
                try
                {
                    var fileDto = new FileUnit()
                    {
                        Name                 = filename,
                        FileType             = FileType.Uploaded,
                        Link                 = link,
                        Description          = fileData.Description,
                        CreatedAt            = DateTime.Now,
                        LastModified         = DateTime.Now,
                        IsDeleted            = false,
                        Space                = space,
                        FolderUnit           = parentFolder,
                        Owner                = await _unitOfWork?.Users?.Query.FirstOrDefaultAsync(u => u.GlobalId == user.id),
                        ReadPermittedUsers   = ReadPermittedUsers,
                        ModifyPermittedUsers = ModifyPermittedUsers
                    };
                    _unitOfWork?.Files?.Create(fileDto);
                    await _unitOfWork?.SaveChangesAsync();

                    _logger.WriteInfo("File saved to database");
                }
                catch (Exception e)
                {
                    _logger.WriteError(e, e.Message);
                    throw new Exception("Failed to save file to data base " + e.Message);
                }
            }
            return("Files uploaded successfully");
        }
コード例 #17
0
        private async Task CopyFolder(int folderToCopyId, string folderName, User owner, Space space, FolderUnit destination)
        {
            var folder = await _unitOfWork?.Folders?.Query
                         .Include(f => f.DataUnits.Select(u => u.ReadPermittedUsers))
                         .Include(f => f.DataUnits.Select(u => u.ModifyPermittedUsers))
                         .Include(f => f.DataUnits.Select(u => u.ReadPermittedRoles))
                         .Include(f => f.DataUnits.Select(u => u.MorifyPermittedRoles))
                         .Include(f => f.ModifyPermittedUsers)
                         .Include(f => f.ReadPermittedUsers)
                         .Include(f => f.MorifyPermittedRoles)
                         .Include(f => f.ReadPermittedRoles)
                         .SingleOrDefaultAsync(f => f.Id == folderToCopyId);

            if (folder == null)
            {
                return;
            }

            var copy = new FolderUnit
            {
                Name                 = folderName,
                Description          = folder.Description,
                IsDeleted            = folder.IsDeleted,
                CreatedAt            = DateTime.Now,
                LastModified         = DateTime.Now,
                Space                = space,
                Owner                = owner,
                ModifyPermittedUsers = folder.ReadPermittedUsers,
                ReadPermittedUsers   = folder.ModifyPermittedUsers,
                MorifyPermittedRoles = folder.MorifyPermittedRoles,
                ReadPermittedRoles   = folder.ReadPermittedRoles,
                FolderUnit           = destination
            };

            _unitOfWork.Folders.Create(copy);

            foreach (var subfolder in folder.DataUnits.OfType <FolderUnit>())
            {
                await CopyFolder(subfolder.Id, subfolder.Name, owner, space, copy);
            }
            foreach (var file in folder.DataUnits.OfType <FileUnit>().Where(x => !x.IsDeleted))
            {
                var newFile = new FileUnit
                {
                    Name                 = file.Name,
                    Description          = file.Description,
                    IsDeleted            = file.IsDeleted,
                    CreatedAt            = DateTime.Now,
                    LastModified         = DateTime.Now,
                    FileType             = file.FileType,
                    Link                 = file.Link,
                    Owner                = owner,
                    Space                = space,
                    FolderUnit           = copy,
                    ModifyPermittedUsers = file.ReadPermittedUsers,
                    ReadPermittedUsers   = file.ModifyPermittedUsers,
                    MorifyPermittedRoles = file.MorifyPermittedRoles,
                    ReadPermittedRoles   = file.ReadPermittedRoles
                };

                _unitOfWork.Files.Create(newFile);
            }

            await _unitOfWork?.SaveChangesAsync();
        }
コード例 #18
0
        //
        // Generate the necessary file lists and other information required by MarkupCompiler.
        //
        // Output ArrayLists:  localApplicationFile,
        //                     localXamlPageFileList
        //                     referenceList
        //
        private void PrepareForMarkupCompilation(out FileUnit localApplicationFile, out FileUnit[] localXamlPageFileList, out ArrayList referenceList)
        {
            Log.LogMessageFromResources(MessageImportance.Low, SRID.PreparingCompile);
            Log.LogMessageFromResources(MessageImportance.Low, SRID.OutputType, OutputType);

            // Initialize the output parameters
            localXamlPageFileList = new FileUnit[0];
            localApplicationFile  = FileUnit.Empty;
            referenceList         = new ArrayList();

            if (_localApplicationFile != null)
            {
                // We don't want to support multiple application definition file per project.
                localApplicationFile = new FileUnit(_localApplicationFile.FilePath, _localApplicationFile.LinkAlias, _localApplicationFile.LogicalName);

                Log.LogMessageFromResources(MessageImportance.Low, SRID.LocalRefAppDefFile, localApplicationFile);
            }

            // Generate the Xaml Markup file list
            if (_localMarkupPages != null && _localMarkupPages.Length > 0)
            {
                int localFileNum = _localMarkupPages.Length;
                localXamlPageFileList = new FileUnit[localFileNum];

                for (int i = 0; i < localFileNum; i++)
                {
                    FileUnit localPageFile = new FileUnit(_localMarkupPages[i].FilePath, _localMarkupPages[i].LinkAlias, _localMarkupPages[i].LogicalName);

                    localXamlPageFileList[i] = localPageFile;
                    Log.LogMessageFromResources(MessageImportance.Low, SRID.LocalRefMarkupPage, localPageFile);
                }
            }

            //
            // Generate the asmmebly reference list.
            // The temporay target assembly should have been added into Reference list from target file.
            //
            if (References != null && References.Length > 0)
            {
                ReferenceAssembly asmReference;
                string            refpath, asmname;

                for (int i = 0; i < References.Length; i++)
                {
                    refpath = References[i].ItemSpec;
                    refpath = TaskHelper.CreateFullFilePath(refpath, SourceDir);

                    asmname = Path.GetFileNameWithoutExtension(refpath);

                    asmReference = new ReferenceAssembly(refpath, asmname);
                    referenceList.Add(asmReference);

                    //
                    // If always run the compilation in second appdomain, there is no need to specially
                    // handle the referenced assemblies.
                    // Unload the appdomain can unload all the referenced assemblies.
                    //
                    if (AlwaysCompileMarkupFilesInSeparateDomain == false)
                    {
                        bool bCouldbeChanged = TaskHelper.CouldReferenceAssemblyBeChanged(refpath, KnownReferencePaths, AssembliesGeneratedDuringBuild);

                        if (bCouldbeChanged)
                        {
                            MarkupCompiler.InitializeAssemblyState(asmname);
                        }
                    }
                }
            }
        }
コード例 #19
0
        //
        // Generate new list of files that require to recompile for incremental build based on _analyzeResult
        //
        private void UpdateFileListForIncrementalBuild(List <FileUnit> modifiedXamlFiles)
        {
            List <FileUnit> recompiledXaml    = new List <FileUnit>();
            bool            recompileApp      = false;
            int             numLocalTypeXamls = 0;

            if ((_analyzeResult & RecompileCategory.ContentFiles) == RecompileCategory.ContentFiles)
            {
                RecompileContentFiles();
            }

            if ((_analyzeResult & RecompileCategory.ApplicationFile) == RecompileCategory.ApplicationFile)
            {
                recompileApp = true;
            }

            if ((_analyzeResult & RecompileCategory.PagesWithLocalType) == RecompileCategory.PagesWithLocalType && TaskFileService.IsRealBuild)
            {
                CompilerLocalReference.LoadCacheFile();

                if (CompilerLocalReference.LocalApplicationFile != null)
                {
                    // Application file contains local types, it will be recompiled.
                    recompileApp = true;
                }

                if (ListIsNotEmpty(CompilerLocalReference.LocalMarkupPages))
                {
                    numLocalTypeXamls = CompilerLocalReference.LocalMarkupPages.Length;

                    // Under incremental builds of SDK projects, we can have a state where the cache contains some XAML files but the Page blob
                    // no longer contains them.  To avoid attempting to recompile a file that no longer exists, ensure that any cached XAML file
                    // still exists in the Page blob prior to queuing it up for recompilation.
                    HashSet <string> localMarkupPages = new HashSet <string>(_mcPass1.PageMarkup.Select(x => x.GetMetadata(SharedStrings.FullPath)), StringComparer.OrdinalIgnoreCase);

                    for (int i = 0; i < numLocalTypeXamls; i++)
                    {
                        LocalReferenceFile localRefFile = CompilerLocalReference.LocalMarkupPages[i];

                        if (localMarkupPages.Contains(localRefFile.FilePath))
                        {
                            recompiledXaml.Add(new FileUnit(
                                                   localRefFile.FilePath,
                                                   localRefFile.LinkAlias,
                                                   localRefFile.LogicalName));
                        }
                    }
                }
            }

            if ((_analyzeResult & RecompileCategory.ModifiedPages) == RecompileCategory.ModifiedPages)
            {
                // If the xaml is already in the local-type-ref xaml file list, don't add a duplicate file path to recompiledXaml list.

                for (int i = 0; i < modifiedXamlFiles.Count; i++)
                {
                    FileUnit xamlfile = modifiedXamlFiles[i];
                    bool     addToList;

                    addToList = true;

                    if (numLocalTypeXamls > 0)
                    {
                        for (int j = 0; j < numLocalTypeXamls; j++)
                        {
                            if (String.Compare(xamlfile.Path, CompilerLocalReference.LocalMarkupPages[j].FilePath, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                addToList = false;
                                break;
                            }
                        }
                    }

                    if (addToList)
                    {
                        recompiledXaml.Add(xamlfile);
                    }
                }
            }

            if (recompiledXaml.Count > 0)
            {
                _recompileMarkupPages = recompiledXaml.ToArray();
            }

            // Set ApplicationFile appropriatelly for this incremental build.
            ProcessApplicationFile(recompileApp);
        }
コード例 #20
0
ファイル: FileSize.cs プロジェクト: BeiMeng/GitApplication
 /// <summary>
 /// 初始化文件大小
 /// </summary>
 /// <param name="size">文件字节大小</param>
 /// <param name="unit">文件字节大小</param>
 public FileSize( long size,FileUnit unit = FileUnit.Byte ) {
     _size = GetSize( size, unit );
 }
コード例 #21
0
        //
        // Call MarkupCompiler to do the real compilation work.
        //
        private void DoLocalReferenceMarkupCompilation(FileUnit localApplicationFile, FileUnit[] localXamlPageFileList, ArrayList referenceList)
        {
            // When code goes here, the MarkupCompilation is really required, so don't need
            // to do more further validation inside this private method.

            Log.LogMessageFromResources(MessageImportance.Low, SRID.DoCompilation);

            AppDomain       appDomain       = null;
            CompilerWrapper compilerWrapper = null;

            try
            {
                compilerWrapper = TaskHelper.CreateCompilerWrapper(AlwaysCompileMarkupFilesInSeparateDomain, ref appDomain);

                if (compilerWrapper != null)
                {
                    compilerWrapper.OutputPath = OutputPath;

                    compilerWrapper.TaskLogger               = Log;
                    compilerWrapper.UnknownErrorID           = UnknownErrorID;
                    compilerWrapper.XamlDebuggingInformation = XamlDebuggingInformation;

                    compilerWrapper.TaskFileService = _taskFileService;

                    if (OutputType.Equals(SharedStrings.Exe) || OutputType.Equals(SharedStrings.WinExe))
                    {
                        compilerWrapper.ApplicationMarkup = localApplicationFile;
                    }

                    compilerWrapper.References = referenceList;

                    compilerWrapper.LocalizationDirectivesToLocFile = (int)_localizationDirectives;

                    // This is for Pass2 compilation
                    compilerWrapper.DoCompilation(AssemblyName, Language, RootNamespace, localXamlPageFileList, true);

                    //
                    // If no any xaml file with local-types wants to reference an internal type from
                    // current assembly and friend assembly, and InternalTypeHelperFile is set in the
                    // cache file, now it is the time to remove the content of InternalTypeHelper File.
                    //
                    // We still keep the empty file to make other parts of the build system happy.
                    //
                    if (!String.IsNullOrEmpty(_internalTypeHelperFile) && !compilerWrapper.HasInternals)
                    {
                        if (TaskFileService.Exists(_internalTypeHelperFile))
                        {
                            // Make empty content for this file.

                            MemoryStream memStream = new MemoryStream();

                            using (StreamWriter writer = new StreamWriter(memStream, new UTF8Encoding(false)))
                            {
                                writer.WriteLine(String.Empty);
                                writer.Flush();
                                TaskFileService.WriteFile(memStream.ToArray(), _internalTypeHelperFile);
                            }

                            Log.LogMessageFromResources(MessageImportance.Low, SRID.InternalTypeHelperNotRequired, _internalTypeHelperFile);
                        }
                    }
                }
            }
            finally
            {
                if (compilerWrapper != null && compilerWrapper.ErrorTimes > 0)
                {
                    _nErrors += compilerWrapper.ErrorTimes;
                }

                if (appDomain != null)
                {
                    AppDomain.Unload(appDomain);
                    compilerWrapper = null;
                }
            }
        }
コード例 #22
0
        public async Task CreateCopyAsync(int id, FileUnitDto dto)
        {
            var file = await _unitOfWork?.Files.Query
                       .Include(f => f.ModifyPermittedUsers)
                       .Include(f => f.ReadPermittedUsers)
                       .Include(f => f.MorifyPermittedRoles)
                       .Include(f => f.ReadPermittedRoles)
                       .SingleOrDefaultAsync(f => f.Id == id);;

            if (file == null)
            {
                return;
            }

            var space = await _unitOfWork.Spaces.GetByIdAsync(dto.SpaceId);

            var user = await _usersService?.GetCurrentUser();

            Regex regEx = new Regex(@"(.+?)(\.[^.]*$|$)");

            string name      = regEx.Match(file.Name)?.Groups[1].Value;
            string extention = regEx.Match(file.Name)?.Groups[2].Value;

            var copies = await _unitOfWork.Files.Query.Where(f => f.Name.StartsWith(name + "-copy") &&
                                                             (f.FolderUnit.Id == dto.ParentId || (dto.ParentId == 0 && f.Space.Id == dto.SpaceId))).ToListAsync();

            if (copies.Count > 0)
            {
                int index    = 0;
                int maxIndex = 1;
                foreach (var copyStr in copies.Select(c => c.Name.Substring(name.Length)))
                {
                    if (Int32.TryParse(copyStr, out index))
                    {
                        if (index > maxIndex)
                        {
                            maxIndex = index;
                        }
                    }
                }
                name = name + (maxIndex + 1).ToString();
            }
            else
            {
                name = name + "-copy";
            }

            var copy = new FileUnit
            {
                Name                 = name + extention,
                Description          = file.Description,
                FileType             = file.FileType,
                IsDeleted            = file.IsDeleted,
                LastModified         = DateTime.Now,
                CreatedAt            = DateTime.Now,
                Link                 = file.Link,
                Space                = space,
                Owner                = await _unitOfWork.Users.Query.FirstOrDefaultAsync(u => u.GlobalId == user.id),
                ModifyPermittedUsers = file.ModifyPermittedUsers,
                ReadPermittedUsers   = file.ReadPermittedUsers,
                MorifyPermittedRoles = file.MorifyPermittedRoles,
                ReadPermittedRoles   = file.ReadPermittedRoles
            };

            if (dto.ParentId != 0)
            {
                var parent = await _unitOfWork.Folders.GetByIdAsync(dto.ParentId);

                copy.FolderUnit = parent;
            }
            if (file.FileType == FileType.AcademyPro)
            {
                var course = await _unitOfWork.AcademyProCourses.Query
                             .Include(a => a.Author)
                             .Include(a => a.Tags)
                             .Include(a => a.Lectures.Select(l => l.CodeSamples))
                             .Include(a => a.Lectures.Select(l => l.ContentList))
                             .Include(a => a.Lectures.Select(l => l.HomeTasks))
                             .Include(a => a.Lectures.Select(l => l.Author))
                             .FirstOrDefaultAsync(a => a.FileUnit.Id == file.Id);

                var coursecopy = new AcademyProCourse
                {
                    StartDate = course.StartDate,
                    IsDeleted = false,
                    Tags      = new List <Tag>(),
                    FileUnit  = copy,
                    Author    = course.Author,
                    Lectures  = new List <Lecture>()
                };

                course.Tags?.ToList().ForEach(tag =>
                {
                    coursecopy.Tags.Add(_unitOfWork.Tags.Query.FirstOrDefault(x => x.Name == tag.Name) ?? new Tag {
                        Name = tag.Name, IsDeleted = false
                    });
                });

                course.Lectures?.ToList().ForEach(lecture =>
                {
                    coursecopy.Lectures.Add(new Lecture
                    {
                        Author      = lecture.Author,
                        Name        = lecture.Name,
                        Description = lecture.Description,
                        IsDeleted   = lecture.IsDeleted,
                        CreatedAt   = DateTime.Now,
                        StartDate   = lecture.StartDate,
                        ModifiedAt  = DateTime.Now,
                        CodeSamples = lecture.CodeSamples.Select(cs => new CodeSample
                        {
                            Code      = cs.Code,
                            IsDeleted = cs.IsDeleted,
                            Name      = cs.Name
                        }).ToList(),
                        ContentList = lecture.ContentList.Select(cl => new ContentLink
                        {
                            Name        = cl.Name,
                            IsDeleted   = cl.IsDeleted,
                            Description = cl.Description,
                            LinkType    = cl.LinkType,
                            Link        = cl.Link
                        }).ToList(),
                        HomeTasks = lecture.HomeTasks.Select(ht => new HomeTask
                        {
                            Description  = ht.Description,
                            IsDeleted    = ht.IsDeleted,
                            DeadlineDate = ht.DeadlineDate
                        }).ToList()
                    });
                });

                _unitOfWork.AcademyProCourses.Create(coursecopy);
            }

            if (file.FileType == FileType.Events)
            {
                var originalEvent = await _unitOfWork.Events.Query
                                    .Include(e => e.ContentList)
                                    .FirstOrDefaultAsync(e => e.FileUnit.Id == file.Id);

                Event eventCopy = new Event
                {
                    IsDeleted   = originalEvent.IsDeleted,
                    EventDate   = originalEvent.EventDate,
                    EventType   = originalEvent.EventType,
                    FileUnit    = copy,
                    ContentList = new List <EventContent>()
                };

                originalEvent.ContentList.ToList().ForEach(c =>
                                                           eventCopy.ContentList.Add(new EventContent
                {
                    Name         = c.Name,
                    Description  = c.Description,
                    IsDeleted    = c.IsDeleted,
                    ContentType  = c.ContentType,
                    Order        = c.Order,
                    CreatedAt    = DateTime.Now,
                    LastModified = DateTime.Now,
                    Content      = c.Content
                })
                                                           );
                _unitOfWork.Events.Create(eventCopy);
            }

            _unitOfWork.Files.Create(copy);

            await _unitOfWork?.SaveChangesAsync();
        }