protected VLFile ExecuteAndGetFile(DbCommand cmd) { VLFile _retObject = null; bool _closeTheConnection = false; try { if (cmd.Connection.State == ConnectionState.Closed) { cmd.Connection.Open(); _closeTheConnection = true; } using (DbDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows == false) { return(null); } reader.Read(); _retObject = new VLFile(reader); } } finally { if (_closeTheConnection) { cmd.Connection.Close(); } } return(_retObject); }
void UploadFile(VLSurveyManager surveyManager, VLSurvey survey, StringBuilder sb) { try { HttpPostedFile oFile = Request.Files[0]; if (oFile == null) { throw new VLException("Κανένα αρχείο δεν έγινε upload!"); } int fileLength = oFile.ContentLength; if (fileLength <= 0) { throw new VLException("To αρχείο είχε μηδενικό μέγεθος!"); } string postedFileName = Path.GetFileName(oFile.FileName); //Πρέπει να μεταφέρουμε το αρχείο στον EcmsFileManager. //Για να το κάνουμε αυτό το μεταφέρουμε στην μνήμη System.Byte[] mem = new byte[fileLength]; Stream postedStream = oFile.InputStream; postedStream.Read(mem, 0, fileLength); VLFile file = surveyManager.AssignFile(survey.SurveyId, mem, postedFileName); sb.Append("{\"res\":\"ok\", \"msg\":\"\"}"); } catch (Exception ex) { sb.AppendFormat("{{\"res\":\"error\", \"msg\":\"{0}\"}}", ex.Message); Logger.Error(HttpContext.Current.Request.RawUrl, ex); } }
internal static Collection <VLFile> ExecuteAndGetFiles(DbCommand cmd) { var collection = new Collection <VLFile>(); bool _closeTheConnection = false; try { if (cmd.Connection.State == ConnectionState.Closed) { cmd.Connection.Open(); _closeTheConnection = true; } using (DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { var _object = new VLFile(reader); collection.Add(_object); } } } finally { if (_closeTheConnection) { cmd.Connection.Close(); } } return(collection); }
public VLFile UpdateFile(Int32 accessToken, VLFile file) { if (file == null) { throw new ArgumentNullException("file"); } try { return(UpdateFileImpl(accessToken, file, Utility.UtcNow())); } catch (Exception ex) { throw new VLDataException("Exception occured at FilesDaoBase::UpdateFile().", ex); } }
/// <summary> /// /// </summary> /// <param name="file"></param> /// <returns></returns> public System.Byte[] GetFileStream(VLFile file) { if (file == null) { throw new ArgumentNullException("file"); } //Αναλόγως που βρίσκεται το binary περιεχόμενο του αρχείου μας, το διαβάζουμε μέσα στον πίνακα _binaryContent: System.Byte[] _binaryContent = null; if (file.IsPhysicalFile) { #region read file content from filesystem string filePath = this.GetFilePath(file); FileInfo fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { using (FileStream fs = fileInfo.OpenRead()) { //το _binaryContent το θέτουμε στο μέγεθος του φυσικού αρχείου που θα διαβάσουμε _binaryContent = new byte[fileInfo.Length]; //Διαβάζουμε μονομιάς το binary περιεχόμενο int totalNumberOfBytes = fs.Read(_binaryContent, 0, _binaryContent.Length); } } else { throw new VLException(string.Format("Physical file {0} with path: '{1}' and fileId={2} does not exists!", file.OriginalFileName, filePath, file.FileId)); } #endregion } else { #region read file content from database _binaryContent = FilesDal.GetFileStreamInternal(file.FileId); #endregion } //θα πρέπει το κατεγεγραμμένο μέγεθος του αρχείου στην βάση (file.FileBytes) να είναι ίδιο //με αυτό που διαβάσαμε απο το φυσικό αρχείο if (_binaryContent.Length != file.Size) { throw new VLException(string.Format("The readed physical size of {0} file is {1} bytes which is different from the recorded value of {2} bytes!", file.OriginalFileName, _binaryContent.Length, file.Size)); } return(_binaryContent); }
internal static string GetFilePath(string rootDirectory, VLFile file) { if (file == null) { throw new ArgumentNullException("file"); } if (!file.IsPhysicalFile) { throw new VLException("The file is not a physical file!"); } if (string.IsNullOrWhiteSpace(rootDirectory)) { throw new VLException("The rootDirectory is invalid!"); } return(Path.Combine(Path.Combine(rootDirectory, file.InventoryPath), file.ManagedFileName)); }
public void DeletePhysicalFile(VLFile fileToBeDeleted, string rootDirectory) { if (fileToBeDeleted.IsPhysicalFile == false) { return; } try { FileInfo finfo = new FileInfo(GetFilePath(rootDirectory, fileToBeDeleted)); //Εάν το αρχείο υπάρχει θα προσπαθήσουμε να το διαγράψουμε. Εάν δεν υπάρχει, προς το παρόν αδιαφορούμε! if (finfo.Exists) { finfo.Delete(); } } catch (Exception ex) { throw new VLException(string.Format(CultureInfo.InvariantCulture, "Failure to delete '{0}'. (FileId='{1}')", GetFilePath(rootDirectory, fileToBeDeleted), fileToBeDeleted.FileId), ex); } }
protected override VLFile UpdateFileImpl(Int32 accessToken, VLFile file, DateTime currentTimeUtc) { try { DbCommand command = CreateCommand("valis_files_Update"); AddParameter(command, "@accessToken", accessToken, DbType.Int32); AddParameter(command, "@client", file.Client, DbType.Int32); AddParameter(command, "@fileId", file.FileId, DbType.Guid); AddParameter(command, "@survey", file.Survey, DbType.Int32); AddParameter(command, "@originalFileName", file.OriginalFileName, DbType.String); AddParameter(command, "@managedFileName", file.ManagedFileName, DbType.String); AddParameter(command, "@extension", file.Extension, DbType.String); AddParameter(command, "@size", file.Size, DbType.Int32); AddParameter(command, "@status", file.Status, DbType.Byte); AddParameter(command, "@attributeFlags", file.AttributeFlags, DbType.Int32); AddParameter(command, "@inventoryPath", file.InventoryPath, DbType.String); AddParameter(command, "@width", file.Width, DbType.Int16); AddParameter(command, "@height", file.Height, DbType.Int16); AddParameter(command, "@currentTimeUtc", currentTimeUtc, DbType.DateTime); return(ExecuteAndGetFile(command)); } catch (SqlException ex) { if (ex.Class == 14 && ex.State == 10) { throw new VLInvalidAccessTokenException(SR.GetString(SR.Invalid_accessToken_while_calling_FilesDao, "UpdateFileImpl"), ex); } else { throw new VLDataException(SR.GetString(SR.Exception_occured_at_FilesDao, "UpdateFileImpl"), ex); } } catch (Exception ex) { throw new VLDataException(SR.GetString(SR.Exception_occured_at_FilesDao, "UpdateFileImpl"), ex); } }
protected abstract VLFile CreateFileImpl(Int32 accessToken, VLFile file, DateTime currentTimeUtc);
/// <summary> /// /// </summary> /// <param name="fileId"></param> /// <returns></returns> public System.Byte[] GetFileStream(Guid fileId) { VLFile file = FilesDal.GetFileByIdInternal(fileId); return(GetFileStream(file)); }
/// <summary> /// Gets the full path of the specified managed file. /// <para>GetFilePath returns the entire path for the file (including the filename and the extension).</para> /// </summary> /// <param name="file"></param> /// <returns></returns> public string GetFilePath(VLFile file) { return(FilesDaoBase.GetFilePath(ValisSystem.Core.FileInventory.Path, file)); }
void SendFileFromFS(HttpRequest request, HttpResponse response, InternalFileManager fileManager, VLFile file) { string acceptEncoding = request.Headers["Accept-Encoding"]; bool isGzipOutput = (!string.IsNullOrWhiteSpace(acceptEncoding) && acceptEncoding.Contains("gzip")); bool isDeflateOutput = (!string.IsNullOrWhiteSpace(acceptEncoding) && acceptEncoding.Contains("deflate")); Stream outputStream = null; bool disposeStream = false; try { string filepath = fileManager.GetFilePath(file); string filename = file.ManagedFileName; FileInfo fileInfo = new FileInfo(filepath); if (fileInfo.Exists) { int len = (int)fileInfo.Length; if (len <= TransmitFileUpperLimit) { response.TransmitFile(filepath); } else { StreamContent(request, response, len, System.IO.File.OpenRead(filepath)); } } } catch (Exception ex) { Logger.Error(HttpContext.Current.Request.RawUrl, ex); throw; } finally { if (outputStream != null && disposeStream) { ((IDisposable)outputStream).Dispose(); } } }
void SendFileFromCMS(HttpRequest request, HttpResponse response, InternalFileManager fileManager, VLFile file) { Stream contentStream = null; try { var binaryContent = fileManager.GetFileStream(file); contentStream = new MemoryStream(binaryContent, 0, binaryContent.Length, false, false); StreamContent(request, response, binaryContent.Length, contentStream); } catch (Exception ex) { Logger.Error(HttpContext.Current.Request.RawUrl, ex); throw; } finally { if (contentStream != null) { ((IDisposable)contentStream).Dispose(); } } }
void SendFile(HttpRequest request, HttpResponse response, InternalFileManager fileManager, VLFile file) { try { response.ClearHeaders(); response.Clear(); response.Cookies.Clear(); response.Cache.SetCacheability(HttpCacheability.NoCache); response.Charset = System.Text.UTF8Encoding.UTF8.WebName; String userAgent = HttpContext.Current.Request.Headers.Get("User-Agent"); if (userAgent.Contains("MSIE")) { response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.OriginalFileName.Replace(" ", "_"), System.Text.Encoding.UTF8)); } else { response.AppendHeader("Content-Disposition", "attachment; filename=" + file.OriginalFileName.Replace(" ", "_")); } response.ContentType = GetMimeType(file.OriginalFileName); if (!file.IsPhysicalFile || file.IsCompressed || file.IsEncrypted) { SendFileFromCMS(request, response, fileManager, file); } else { SendFileFromFS(request, response, fileManager, file); } } catch (Exception ex) { Logger.Error(HttpContext.Current.Request.RawUrl, ex); throw; } }
public VLFile SaveFile(Int32 accessToken, VLSurvey survey, byte[] buffer, string fileName, string rootDirectory, Guid?fileId = null, string managedFileName = null, bool deleteFileIfExists = false) { if (fileId == null || fileId == default(Guid)) { fileId = Guid.NewGuid(); } if (string.IsNullOrWhiteSpace(managedFileName)) { managedFileName = fileName; } try { #region implementation VLFile file = new VLFile(); file.Client = survey.Client; file.FileId = fileId.Value; file.Survey = survey.SurveyId; file.OriginalFileName = fileName; file.ManagedFileName = managedFileName; file.Extension = Path.GetExtension(fileName); file.Size = buffer.Length; file.Status = VLFileStatus.Temporal; try { MemoryStream stream = new MemoryStream(buffer); Image img = Image.FromStream(stream); file.IsImage = true; file.Width = Convert.ToInt16(img.Width); file.Height = Convert.ToInt16(img.Height); } catch { file.IsImage = false; } if (survey.SaveFilesInDatabase) { file.IsPhysicalFile = false; #region implementation file = CreateFileImpl(accessToken, file, Utility.UtcNow()); SetFileStreamImpl(accessToken, file.FileId, buffer); #endregion } else { file.IsPhysicalFile = true; #region implementation string fileDirPath = Path.Combine(rootDirectory, survey.Client.ToString(CultureInfo.InvariantCulture), survey.SurveyId.ToString(CultureInfo.InvariantCulture)); //Εάν δεν υπάρχει το fileDirPath το δημιουργούμε if (!Directory.Exists(fileDirPath)) { Directory.CreateDirectory(fileDirPath); } file.InventoryPath = Path.Combine(survey.Client.ToString(CultureInfo.InvariantCulture), survey.SurveyId.ToString(CultureInfo.InvariantCulture)) + "\\"; //Εάν υπάρχει ήδη φυσικό αρχείο με το ίδιο όνομα το διαγράφουμε? if (deleteFileIfExists) { FileInfo fileInfo = new FileInfo(GetFilePath(rootDirectory, file)); if (fileInfo.Exists) { fileInfo.Delete(); } } //Πρέπει να σιγουρευτούμε ότι το ManagedFileName είναι μοναδικό μέσα στο fileDirPath Int32 loopCounter = 1; FileInfo fInfo = new FileInfo(GetFilePath(rootDirectory, file)); while (fInfo.Exists) { file.ManagedFileName = Path.GetFileNameWithoutExtension(managedFileName) + "_" + loopCounter.ToString(CultureInfo.InvariantCulture) + file.Extension; loopCounter++; fInfo = new FileInfo(GetFilePath(rootDirectory, file)); } /* * Ο τρόπος που ανοίγουμε την FileStream για γράψιμο, διαγράφει τυχόν προυπάρχον αρχείο με το ίδιο όνομα */ using (FileStream fstream = new FileStream(GetFilePath(rootDirectory, file), FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fstream)) { bw.Write(buffer); } } file = CreateFileImpl(accessToken, file, Utility.UtcNow()); #endregion } #endregion return(file); } catch (Exception ex) { throw new VLDataException("Exception occured at FilesDaoBase::SaveFile()", ex); } }
public void FileTests01_01() { var systemManager = VLSystemManager.GetAnInstance(admin); var surveyManager = VLSurveyManager.GetAnInstance(admin); try { //δημιουργούμε ένα client: var client1 = systemManager.CreateClient("Thomas Cookings S.A.", BuiltinCountries.Greece, "THMC", profile: BuiltinProfiles.UTESTFree.ProfileId); Assert.IsNotNull(client1); //Δημιουργούμε ένα νέο survey: var survey1 = surveyManager.CreateSurvey(client1.ClientId, "Questionnaire #1", "Risk assessment"); Assert.IsNotNull(survey1); //Στην αρχή δεν υπάρχει κανένα αρχείο για αυτό το survey: Assert.IsTrue(surveyManager.GetFiles(survey1).Count == 0); VLFile file1 = null; using (var fs = new FileStream(Path.Combine(_ImagesPath, "image1.jpg"), FileMode.Open)) { file1 = surveyManager.AssignFile(survey1, fs, "image1.jpg"); } Assert.IsNotNull(file1); Assert.IsTrue(file1.Client == survey1.Client); Assert.IsTrue(file1.Survey == survey1.SurveyId); Assert.AreEqual <string>("image1.jpg", file1.OriginalFileName); Assert.AreEqual <string>("image1.jpg", file1.ManagedFileName); Assert.AreEqual <string>(".jpg", file1.Extension); Assert.IsTrue(file1.Size == 52077); Assert.IsTrue(file1.IsPhysicalFile); Assert.IsTrue(file1.InventoryPath == Path.Combine(survey1.Client.ToString(CultureInfo.InvariantCulture), survey1.SurveyId.ToString(CultureInfo.InvariantCulture)) + "\\"); var svdFile1 = surveyManager.GetFileById(file1.FileId); Assert.AreEqual <VLFile>(file1, svdFile1); //τώρα έχουμε ένα αρχείο για αυτό το survey Assert.IsTrue(surveyManager.GetFiles(survey1).Count == 1); VLFile file2 = null; using (var fs = new FileStream(Path.Combine(_ImagesPath, "image2.jpg"), FileMode.Open)) { file2 = surveyManager.AssignFile(survey1, fs, "image2.jpg"); } Assert.IsNotNull(file2); Assert.IsTrue(file2.Client == survey1.Client); Assert.IsTrue(file2.Survey == survey1.SurveyId); Assert.AreEqual <string>("image2.jpg", file2.OriginalFileName); Assert.AreEqual <string>("image2.jpg", file2.ManagedFileName); Assert.AreEqual <string>(".jpg", file2.Extension); Assert.IsTrue(file2.Size == 33013); Assert.IsTrue(file2.IsPhysicalFile); Assert.IsTrue(file2.InventoryPath == Path.Combine(survey1.Client.ToString(CultureInfo.InvariantCulture), survey1.SurveyId.ToString(CultureInfo.InvariantCulture)) + "\\"); var svdfile2 = surveyManager.GetFileById(file2.FileId); Assert.AreEqual <VLFile>(file2, svdfile2); //τώρα έχουμε δύο αρχεία για αυτό το survey Assert.IsTrue(surveyManager.GetFiles(survey1).Count == 2); VLFile file3 = null; using (var fs = new FileStream(Path.Combine(_ImagesPath, "image2.jpg"), FileMode.Open)) { file3 = surveyManager.AssignFile(survey1, fs, "image2.jpg"); } Assert.IsNotNull(file3); Assert.IsTrue(file3.Client == survey1.Client); Assert.IsTrue(file3.Survey == survey1.SurveyId); Assert.AreEqual <string>("image2.jpg", file3.OriginalFileName); Assert.AreEqual <string>("image2_1.jpg", file3.ManagedFileName); Assert.AreEqual <string>(".jpg", file3.Extension); Assert.IsTrue(file3.Size == 33013); Assert.IsTrue(file3.IsPhysicalFile); Assert.IsTrue(file3.InventoryPath == Path.Combine(survey1.Client.ToString(CultureInfo.InvariantCulture), survey1.SurveyId.ToString(CultureInfo.InvariantCulture)) + "\\"); var svdfile3 = surveyManager.GetFileById(file3.FileId); Assert.AreEqual <VLFile>(file3, svdfile3); //τώρα έχουμε τρία αρχεία για αυτό το survey Assert.IsTrue(surveyManager.GetFiles(survey1).Count == 3); //διαγράφουμε το ένα surveyManager.Removefile(file3.FileId); Assert.IsNull(surveyManager.GetFileById(file3.FileId)); //τώρα έχουμε δύο αρχεία για αυτό το survey Assert.IsTrue(surveyManager.GetFiles(survey1).Count == 2); //διαγράφουμε το ένα surveyManager.Removefile(file2.FileId); Assert.IsNull(surveyManager.GetFileById(file2.FileId)); //τώρα έχουμε δύο αρχεία για αυτό το survey Assert.IsTrue(surveyManager.GetFiles(survey1).Count == 1); } finally { var clients = systemManager.GetClients(); foreach (var client in clients) { if (client.IsBuiltIn) { continue; } var surveys = surveyManager.GetSurveysForClient(client.ClientId); foreach (var survey in surveys) { surveyManager.DeleteSurvey(survey.SurveyId); } systemManager.DeleteClient(client); } } }
void SendFileFromCMS(HttpRequest request, HttpResponse response, VLSurveyManager surveyManager, VLFile file) { Stream contentStream = null; try { var binaryContent = surveyManager.GetFileStream(file); contentStream = new MemoryStream(binaryContent, 0, binaryContent.Length, false, false); StreamContent(request, response, binaryContent.Length, contentStream); } catch { } finally { if (contentStream != null) { ((IDisposable)contentStream).Dispose(); } } }