Ejemplo n.º 1
0
        /// <summary>
        /// ЗАГРУЖАЕМ файл в базу
        /// </summary>
        public static void Download(FileSystemStoreObject descriptor, Stream source)
        {
            Stream destination = null;
            try
            {
                destination = File.Open(descriptor.RealFileName, FileMode.Create);
                BinaryWriter writer = new BinaryWriter(destination);

                byte[] buffer = new byte[1024 * 1024];
                int count = 0;
                while ((count = source.Read(buffer, 0, buffer.Length)) > 0)
                {
                    writer.Write(buffer, 0, count);
                }

                descriptor.Save();
            }
            catch { }
            finally
            {
                if (destination != null)
                {
                    destination.Close();
                    destination = null;
                }
            }
        }
Ejemplo n.º 2
0
 private void SaveFileSystemStoreObject(FileSystemStoreObject fileObject, System.IO.Stream stream)
 {
     if (fileObject != null && stream != null)
     {
         System.IO.MemoryStream memory = new System.IO.MemoryStream();
         stream.CopyTo(memory);
         memory.Position = 0;
         (fileObject as IFileData).LoadFromStream(fileObject.FileName, memory);
         fileObject.Save();
         stream.Close();
     }
 }
Ejemplo n.º 3
0
 private static void SaveConclusionTemplate(FileSystemStoreObject fileObject, System.IO.Stream stream)
 {
     if (fileObject != null && stream != null)
     {
         var memory = new System.IO.MemoryStream();
         stream.CopyTo(memory);
         memory.Position = 0;
         (fileObject as IFileData).LoadFromStream("Сonclusion-template.rtf", memory);
         fileObject.Save();
         stream.Close();
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Метод принимает поток из модулей IDynamicModule 
        /// </summary>
        /// <param name="context">Идентификатор обследования связанного с файлом</param>
        /// <param name="fileName">Имя файла</param>
        /// <param name="dataStream">Файловый поток</param>
        /// <param name="initialSize">Размер файла</param>
        public void TransferFile(Guid context, String fileName, Stream dataStream, long initialSize)
        {
            // Получаем объект для работы с данными БД
            UnitOfWork uow = new UnitOfWork((this.Application.CreateObjectSpace() as XPObjectSpace).Session.DataLayer);
            if (uow == null)
                throw new Exception("Error occurred while creating UnitOfWork object.");

            // Находим обследование по ИД
            IExamination examination = uow.GetObjectByKey<IExamination>(context);
            if (examination == null)
            {
                DevExpress.Persistent.Base.Tracing.Tracer.LogError("TransferFile({0}, {1}, {2}, {3}) Examination [id={0}] is not found in the database",
                    context, fileName, "dataStream", initialSize);
                return;
                //throw new Exception("The examination is not found in the database.");
            }
            if (String.IsNullOrEmpty(fileName) == true || initialSize <= 0)
                throw new Exception("Invalid file transfer params.");

            //...
            //XtraMessageBox.Show(String.Format("TransferFile: {0}, {1}", context, fileName));

            Guid owner = (examination as DevExpress.ExpressApp.DC.DCBaseObject).Oid;
            CriteriaOperator criteria = uow.ParseCriteria(String.Format("[OwnerId]= '{0}'", owner));

            XPClassInfo info = uow.GetClassInfo(typeof(FileSystemStoreObject));

            // находим отображаемые имена файлов данного обследования
            var ownerFiles = uow.GetObjects(info, criteria, null, int.MaxValue, false, true).Cast<FileSystemStoreObject>().Select(x => x.FileName).ToList<String>();

            FileSystemStoreObject fileStoreObject = new FileSystemStoreObject(uow)
            {
                OwnerId = owner,//((DevExpress.ExpressApp.DC.DCBaseObject)examination).Oid, // ИД владелеца файла
                FileName = GetDatabaseFileName(fileName, ownerFiles),// Path.GetFileName(fileName),
            };

            uow.CommitChanges(); // создаем в базе новый объект FileSystemStoreObject

            // пытаемся записать полученный файл
            if (FileProcessor.TryToWriteTransferredFile(fileStoreObject.RealFileName, dataStream) == false)//|| new FileInfo(fileStoreObject.RealFileName).Length != initialSize)
            {
                //XtraMessageBox.Show(String.Format("File transfer error !!!\n {0}, {1}", context, fileName));
                uow.Delete(fileStoreObject); // если записать файл не удалось, то удаляем из базы ссылку на файл
            }

            uow.CommitChanges();

            // Обновляем главное окно
            //UpdateWindow(context);

            OnViewUpdate();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Медод передает в FileSystemStoreObject ссылку на поток с исходным файлом
        /// ФАЙЛ СОХРАНЯЕТСЯ НА ДИСК ПРИ ВЫЗОВЕ ObjectSpace.CommitChanges()
        /// </summary>
        private static void CopyToStoreObject(string sourceFileName, FileSystemStoreObject destinationStoreObject)
        {
            System.IO.Stream stream = System.IO.File.Open(sourceFileName, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            System.IO.MemoryStream memory = new System.IO.MemoryStream();
            stream.CopyTo(memory);
            memory.Position = 0;

            (destinationStoreObject as IFileData).LoadFromStream(destinationStoreObject.FileName, memory);

            destinationStoreObject.Save();

            if (stream != null)
                stream.Close();
        }
Ejemplo n.º 6
0
        private static void CreateFromTemplate( FileSystemStoreObject template, FileSystemStoreObject target)
        {
            if (File.Exists(template.RealFileName) == true)
            {
                Stream stream = null;
                try
                {
                    stream = File.Open(template.RealFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                    var memory = new MemoryStream();

                    stream.CopyTo(memory);
                    memory.Position = 0;

                    (target as IFileData).LoadFromStream(target.FileName, memory);

                    target.Save();
                }
                catch (Exception e)
                {
                    Tracing.Tracer.LogError(e);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }
            }
            else
            {
                Tracing.Tracer.LogWarning("Conclusion template file not found!");
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// ВЫГРУЖАЕМ файл из базы
        /// </summary>
        public static void Upload(FileSystemStoreObject descriptor, Stream target)
        {
            FileStream source = File.OpenRead(descriptor.RealFileName);

            CopyStream(source, target);
            target.Flush();
            target.Close();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Удаляем файл ассоциированный с объектом БД
        /// </summary>
        /// <param name="descriptor"></param>
        public static void Remove(FileSystemStoreObject descriptor)
        {
            if (descriptor != null)
            {
                try
                {
                    if (File.Exists(descriptor.RealFileName))
                    {
                        File.Delete(descriptor.RealFileName);
                    }
                }
                catch{ }

                descriptor.Delete();
            }
        }