Example #1
0
 public ActionResult DeleteConfirm(int id, int edition)
 {
     Model.File deleteFile = _fileServices.Get(id, edition);
     System.IO.File.Delete(deleteFile.Url);
     _fileServices.DeleteConfirm(id, edition);
     return RedirectToAction("Trash", "File");
 }
Example #2
0
        public Model.File Remove(string id)
        {
            if (id == null)
            {
                throw new Exception("Ivalid ID");
            }

            Model.File removedFile = null;
            try
            {
                var cn = new EntityConnection("name=FlowerEntities");
                cn.Open();

                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
                }))
                {
                    removedFile = removeFromDB(id, cn);
                    scope.Complete();
                }
                if (removedFile != null)
                {
                    removeFile(removedFile.ID);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
            }
            return(removedFile);
        }
Example #3
0
        public Model.FileInfo UploadFile(Model.File file)
        {
            var sourceStream = file.Stream;
            var buffer       = new Byte[FileHelper.DefaultBufferSize];

            using (var memoryStream = new MemoryStream())
            {
                int read;

                while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    memoryStream.Write(buffer, 0, read);
                }

                file.Data = memoryStream.ToArray();

                memoryStream.Close();
                sourceStream.Close();
            }

            _fileRepository.Add(file);
            _fileRepository.Save();

            return(file.Info);
        }
        public static IFileDefinition FileDefinitionMapper(Model.File fileDefinition)
        {
            IFileDefinition file = null;

            try
            {
                file = ConfigurationComponentFactory().ConfigurationFactory <IFileDefinition>(typeof(IFileDefinition));
            }
            catch (Exception e)
            {
                throw new DataAccessComponentException(null, -1, "Configuration proxy factory failure - unable to create an instance of " + typeof(IFileDefinition) + "?", e);
            }


            try
            {
                file.Enabled = fileDefinition.Enabled;
                file.Path    = fileDefinition.Path;
            }
            catch (Exception e)
            {
                throw new DataAccessComponentException(null, -1, "Mapping process failure?", e);
            }
            return(file);
        }
        private async Task <string> SaveFile(IFormFile file)
        {
            var    extension = Path.GetExtension(file.FileName);
            string fileName  = GetFileName(file.FileName);

            try
            {
                using FileStream fs = new FileStream(_config.FullPath + "/" + fileName, FileMode.CreateNew);
                await file.CopyToAsync(fs);
            }
            catch (IOException)
            {
                throw new IOException("文件上传失败,请稍候重试.");
            }
            var mod = new Model.File
            {
                AddTime     = DateTime.Now,
                Ext         = extension,
                FileName    = file.FileName,
                MapPath     = _config.FrontExt + "/" + fileName,
                Size        = file.Length.ToString(),
                Id          = Guid.NewGuid(),
                ContentType = file.ContentType
            };

            _context.Files.Add(mod);
            _context.SaveChanges();
            _log.LogInformation($"Save File {file.FileName} , size: {file.Length}; type: {extension};");
            return(mod.Id.ToString());
        }
Example #6
0
 private void btAddFile_Click(object sender, EventArgs e)
 {
     try
     {
         using (var dialog = new OpenFileDialog())
         {
             if (dialog.ShowDialog() == DialogResult.OK)
             {
                 var fileContent = System.IO.File.ReadAllBytes(dialog.FileName);
                 var file        = new Model.File
                 {
                     Name  = Path.GetFileName(dialog.FileName),
                     Owner = new User
                     {
                         Id = _userId
                     }
                 };
                 var fileId = _client.CreateFile(file);
                 _client.UploadFileContent(fileId, fileContent);
                 RefreshFileList();
                 MessageBox.Show($"Файл {file.Name} успешно загружен", "Загрузка файла", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show($"Не удалось загрузить файл, текст ошибки: {Environment.NewLine}{exception.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Example #7
0
        public FilesResponse Add(Model.File file, byte[] data)
        {
            var response = HandleFileResponse(Client
                                              .Client
                                              .PostMultipartForm("files.xro/1.0/Files/" + Inbox, file.Mimetype, file.Name, file.Name, data));

            return(response);
        }
Example #8
0
 public Model.File GetFile(string id)
 {
     Model.File file = null;
     using (var entities = new Model.FlowerEntities())
     {
         file = (Model.File)(from e in entities.Files.AsEnumerable() where e.ID == id select e).Single();
     }
     return(file);
 }
Example #9
0
        public void ID取得_レコードあり()
        {
            var domain = new FileDomain(@".\TestCase\FileStore\");

            Model.File file = null;
            file = domain.Regist2DB("Test_Text.txt", "1");
            file = domain.Regist2DB("Test_Text.txt", "2");
            Assert.True(domain.getId() == "3");
            return;
        }
Example #10
0
        // GET: api/PDF
        public ResponseBase UpdateUserPurchaseReport(Purchase p)
        {
            Model.File newPDF = new Model.File()
            {
                FileType = Model.FileType.PDF,
                UserId   = p.Customer.Id
            };

            return(_service.StoreFile(newPDF));
        }
Example #11
0
        private Model.File GetComposedLookFile(string asset)
        {
            int index = asset.LastIndexOf("/");

            Model.File file = new Model.File();
            file.Src       = FixFileName(asset.Substring(index + 1));
            file.Folder    = asset.Substring(0, index);
            file.Overwrite = true;

            return(file);
        }
Example #12
0
 public FileDTO(Model.File file)
 {
     Model.File tmp;
     using (Meseger ctx = new Meseger())
     {
         tmp    = ctx.Files.SingleOrDefault(a => a.Id == file.Id);
         ChatId = tmp.Message.Chat.Id;
     }
     FileInfo   = new FileInfo(tmp.Path);
     FileStream = new FileStream(tmp.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
     FileName   = FileInfo.Name;
 }
        public ActionResult TextFile(string name)
        {
            var files = Directory.GetFiles(Server.MapPath("~/TextFiles"), String.Format("*{0}.txt", name));
            var file  = files[0];
            var f     = new Model.File
            {
                Content  = System.IO.File.ReadAllText(file),
                FileName = Path.GetFileName(file)
            };

            return(View(f));
        }
        private Model.File GetComposedLookFile(string asset)
        {
            int index = asset.LastIndexOf("/");

            Model.File file = new Model.File
            {
                Src       = FixFileName(asset.Substring(index + 1)),
                Folder    = asset.Substring(0, index),
                Overwrite = true,
                Security  = null
            };
            return(file);
        }
Example #15
0
        public static void AddFile(string destinationFile)
        {
            var fileInfo = new FileInfo(destinationFile);

            var file = new Model.File();

            file.Name = fileInfo.Name;
            file.Path = destinationFile;

            var fileId = RepositoryFile.SaveFileInDb(file, GetFileExtensionId(fileInfo));

            MetadataService.AddMetadata(fileInfo, fileId);
        }
Example #16
0
        public void publicarArquivo(Model.File oFile)
        {
            FileDAO oFileDAO = new FileDAO();

            try
            {
                oFileDAO.publicarArquivo(oFile);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #17
0
        public Model.ListFile listaArquivoCircular(Model.File oFile)
        {
            ListFile oListFile = new ListFile();
            FileDAO  oFileDAO  = new FileDAO();

            try
            {
                return(oListFile = oFileDAO.listaArquivoCircular(oFile));
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #18
0
 public async Task <ActionResult> GetFile(string FileName)
 {
     FileName = FileName.Split(".")[0];
     Model.File FileInstance = this.FileBusinessInstance.GetFile(FileName);
     if (FileInstance == null)
     {
         return(NotFound());
     }
     else
     {
         var Folder = "";
         this.EnsureUploadFolder(out Folder);
         var FilePath = Path.Combine(Folder, FileInstance.Location);
         return(File(await System.IO.File.ReadAllBytesAsync(FilePath), "image/jpeg"));
     }
 }
Example #19
0
        /// <summary>
        /// DBからのファイル情報削除
        /// </summary>
        /// <param name="id"></param>
        /// <remarks>トランザクションは管理しない</remarks>
        private Model.File removeFromDB(string id, DbConnection conn)
        {
            Model.File removedFile = null;

            using (var entities = new Model.FlowerEntitiesEx(conn, false))
            {
                var target = (from e in entities.Files.AsEnumerable() where e.ID == id select e);

                if (target != null && target.Count() > 0)
                {
                    removedFile = entities.Files.Remove(target.ElementAt(0));
                    entities.SaveChanges();
                }
            }
            return(removedFile);
        }
Example #20
0
        public async Task InsertFile(Model.File file)
        {
            var param = new DynamicParameters();

            param.Add("@ID", file.ID);
            param.Add("@FileName", file.FileName);
            param.Add("@Directory", file.Directory);
            param.Add("@Extension", file.Extension);
            param.Add("@Size", file.Size);

            await SqlMapper.ExecuteAsync(_unitOfWork.Connection,
                                         "InsertFile",
                                         param,
                                         commandType : CommandType.StoredProcedure,
                                         transaction : _unitOfWork.Transaction);
        }
Example #21
0
 private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
 {
     try
     {
         int fileId = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
         if (fileId != 0)
         {
             Model.File file = FileService.GetFile(fileId);
             Process.Start(@Path.GetDirectoryName(file.Path.ToString()));
         }
     }
     catch (Exception)
     {
         MessageBox.Show("The file does not exist anymore in the destination folder");
     }
 }
Example #22
0
        public Dictionary <int, int> contaArquivoByMeses(Model.File oFile)
        {
            Dictionary <int, int> mesQtd;
            FileDAO oFileDAO = new FileDAO();

            try
            {
                mesQtd = oFileDAO.contaArquivoByMeses(oFile);
            }

            catch (Exception)
            {
                throw;
            }

            return(mesQtd);
        }
Example #23
0
        public int validaCircular(Model.File oFile)
        {
            int     quantidade = 0;
            FileDAO oFileDAO   = new FileDAO();

            try
            {
                quantidade = oFileDAO.validaCircular(oFile);
            }

            catch (Exception)
            {
                throw;
            }

            return(quantidade);
        }
Example #24
0
        private async void AddFolderButton_Click(object sender, RoutedEventArgs e)
        {
            if (_context.SelectedDirectoryVM == null)
            {
                MessageBox.Show("Нет выбраной директории", "Ошибка");
                return;
            }

            Model.Directory parentDirectory = _context.SelectedDirectoryVM.Directory;

            OpenFileDialog openFileDialog = new OpenFileDialog();

            if (openFileDialog.ShowDialog() == true)
            {
                string fileName     = openFileDialog.FileName;
                string safeFileName = openFileDialog.SafeFileName;
                using (FileStream fs = new FileStream(fileName, FileMode.Open))
                {
                    StreamContent       sc = new StreamContent(fs);
                    HttpResponseMessage uploadFileResponse = await client.PostAsync("/api/Cloud/UploadFile?fileName=" + safeFileName + "&parentDirectoryId=" + parentDirectory.Id, sc);

                    if (uploadFileResponse.IsSuccessStatusCode)
                    {
                        string responseJson = await uploadFileResponse.Content.ReadAsStringAsync();

                        Guid fileId = JsonConvert.DeserializeObject <Guid>(responseJson);
                        File.Copy(fileName, @"D:\Education 5 2018\ТРПЗ\Data\" + fileId + safeFileName);
                        Model.File file = new Model.File()
                        {
                            Id              = fileId,
                            Name            = safeFileName,
                            ParentDirectory = parentDirectory,
                        };
                        parentDirectory.Files.Add(file);
                        if (_context.SelectedDirectoryVM.Directory == parentDirectory)
                        {
                            _context.Files.Add(new FileBaseVM(file));
                        }
                    }
                    else
                    {
                        MessageBox.Show(uploadFileResponse.StatusCode.ToString() + uploadFileResponse.RequestMessage.ToString(), "Ошибка запроса");
                    }
                }
            }
        }
Example #25
0
        /// <summary>
        /// Persists the non video file. If data point unique=true, update existing
        /// entry; else, add provided file as a new entry
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="user">The user.</param>
        public void PersistNonVideoFile(Model.File file, string userName)
        {
            var collection = _database.GetCollection <Model.File>("File");

            if (file.Unique)
            {
                var filter = Query.And(
                    Query.EQ("TitleId", file.TitleId),
                    Query.Matches("Match", new BsonRegularExpression("^" + file.Match + "$", "i")));

                collection.Remove(filter, RemoveFlags.None);
            }

            // Set audit information and save
            file.ModifiedDatetime = DateTime.UtcNow;
            file.ModifiedBy       = userName;
            collection.Insert(file);
        }
Example #26
0
        private void DownLoadFile(SharePointConnector reader, SharePointConnector readerRoot, FileConnectorBase writer, string webUrl, string asset, PnPMonitoredScope scope)
        {
            // No file passed...leave
            if (String.IsNullOrEmpty(asset))
            {
                return;
            }

            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_DownLoadFile_Downloading_asset___0_, asset);

            SharePointConnector readerToUse;

            Model.File f = GetComposedLookFile(asset);

            // Strip the /sites/root part from /sites/root/lib/folder structure, special case for root site handling.
            Uri u = new Uri(webUrl);

            if (f.Folder.IndexOf(u.PathAndQuery, StringComparison.InvariantCultureIgnoreCase) > -1 && u.PathAndQuery.Length > 1)
            {
                f.Folder = f.Folder.Replace(u.PathAndQuery, "");
            }

            // in case of a theme catalog we need to use the root site reader as that list only exists on root site level
            if (f.Folder.IndexOf("/_catalogs/theme", StringComparison.InvariantCultureIgnoreCase) > -1)
            {
                readerToUse = readerRoot;
            }
            else
            {
                readerToUse = reader;
            }

            String container           = f.Folder.Trim('/').Replace("%20", " ").Replace("/", "\\");
            String persistenceFileName = f.Src.Replace("%20", " ");

            using (Stream s = readerToUse.GetFileStream(f.Src, f.Folder))
            {
                if (s != null)
                {
                    writer.SaveFileStream(
                        persistenceFileName, container, s);
                }
            }
        }
        public Model.File GetFile(string pageUrl, TokenParser parser, bool ignoreDefault)
        {
            Model.File file = null;
            if (pageUrl.StartsWith(Web.ServerRelativeUrl, StringComparison.OrdinalIgnoreCase))
            {
                var provider = new WebPartsModelProvider(Web);
                var webPartsModels = provider.Retrieve(pageUrl, parser);

                var needToOverride = this.NeedToOverrideFile(Web, pageUrl);

                if ( !ignoreDefault || needToOverride || (1 != webPartsModels.Count) || !WebPartsModelProvider.IsWebPartDefault(webPartsModels[0]))
                {
                    var folderPath = this.GetFolderPath(pageUrl);
                    var localFilePath = this.GetFilePath(pageUrl);
                    file = new Model.File(localFilePath, folderPath, needToOverride, webPartsModels, null);
                }
            }
            return file;
        }
        //TODO: Candidate for cleanup
        private Model.File GetTemplateFile(Web web, string serverRelativeUrl)
        {
            var webServerUrl = web.EnsureProperty(w => w.Url);
            var serverUri    = new Uri(webServerUrl);
            var serverUrl    = string.Format("{0}://{1}", serverUri.Scheme, serverUri.Authority);
            var fullUri      = new Uri(UrlUtility.Combine(serverUrl, serverRelativeUrl));

            var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/');
            var fileName   = fullUri.Segments[fullUri.Segments.Count() - 1];

            var templateFile = new Model.File()
            {
                Folder    = Tokenize(folderPath, web.Url),
                Src       = fileName,
                Overwrite = true,
            };

            return(templateFile);
        }
Example #29
0
        private void PersistWorkflowForm(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope, String formUrl)
        {
            var fullUri = new Uri(UrlUtility.Combine(web.Url, formUrl));

            var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/');
            var fileName   = fullUri.Segments[fullUri.Segments.Count() - 1];

            var formFile = new Model.File()
            {
                Folder    = Tokenize(folderPath, web.Url),
                Src       = formUrl,
                Overwrite = true,
            };

            // Add the file to the template
            template.Files.Add(formFile);

            // Persist file using connector
            PersistFile(web, creationInfo, scope, folderPath, fileName);
        }
Example #30
0
 private string Update(HttpContext context)
 {
     try
     {
         Model.File file = new Model.File();
         file.ID              = int.Parse(context.Request.Form["hdID"]);
         file.file_name       = context.Request.Form["txtfile_name"].Replace("'", "''");
         file.pwd             = context.Request.Form["txtpwd"].Replace("'", "''");
         file.Remark          = context.Request.Form["txtRemark"].Replace("'", "''");
         file.updata_person   = Convert.ToInt32((context.Session["login"] as Model.BaseUser).UserID);
         file.updata_datetiem = DateTime.Now;
         try { file.pwdflag = int.Parse(context.Request.Form["cbpwdflag"]); }
         catch { file.pwdflag = 0; }
         return(new BLL.File().Update(file) ? "success" : "");
     }
     catch (Exception exc)
     {
         return(exc.Message);
     }
 }
Example #31
0
        /// <summary>
        /// Registers the video file by media identifier. 'contents.name' is considered unique. If it
        ///     exist, update, else insert
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="user">The user.</param>
        void RegisterVideoFileByMediaId(Model.File file, string userName)
        {
            // Gather audit information
            file.ModifiedDatetime = DateTime.UtcNow;
            file.ModifiedBy       = userName;

            // Check if file exist for given media id. If not, insert new file document, else;
            // if it exist, verify if the sub document matches. If so, update
            // existing sub document, else insert new sub document
            MongoCollection <Model.File> fileCollection = _database.GetCollection <Model.File>("File");
            var query = Query.And(Query.EQ("MediaId", file.MediaId), Query.NotExists("AiringId"));

            Model.File dbFile = fileCollection.Find(query).FirstOrDefault();
            if (dbFile == null)
            {
                // Add new file document
                fileCollection.Save(file);
            }
            else
            {
                // This removes existing content if it exists and then inserts.
                foreach (var content in file.Contents)
                {
                    query = Query.And(
                        Query.EQ("MediaId", file.MediaId),
                        Query.NotExists("AiringId"),
                        Query.EQ("Contents.Name", content.Name));

                    // Remove, if it exist
                    var pull = Update <Model.File> .Pull(x => x.Contents, builder => builder.EQ(q => q.Name, content.Name));

                    fileCollection.Update(query, pull);

                    // Insert
                    query = Query.And(Query.EQ("MediaId", file.MediaId), Query.NotExists("AiringId"));
                    fileCollection.Update(query, Update <Model.File> .AddToSet(c => c.Contents, content)
                                          .Set(c => c.ModifiedBy, file.ModifiedBy)
                                          .Set(c => c.ModifiedDatetime, file.ModifiedDatetime));
                }
            }
        }
Example #32
0
        /// <summary>
        /// Находит файл в базе данных по ID
        /// </summary>
        /// <param name="id">ID файла на сайте 2safe</param>
        /// <returns>Возвращает объект файла</returns>
        public static File FindById(string id)
        {
            SQLiteConnection connection = new SQLiteConnection(dbName);
            connection.Open();
            SQLiteCommand command = new SQLiteCommand("SELECT * FROM files WHERE id='" + id + "'", connection);
            SQLiteDataReader reader = command.ExecuteReader();
            reader.Read();

            Model.File file = new Model.File(reader.GetInt64(0), reader.GetInt64(1), reader.GetString(2), reader.GetInt64(3), reader.GetString(4), reader.GetInt32(5), reader.GetInt64(6));

            reader.Close();
            connection.Close();

            return file;
        }
Example #33
0
        /// <summary>
        /// ファイル情報のDB登録
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <remarks>トランザクションは管理しない</remarks>
        private Model.File Regist2DB(string fileName, string id)
        {
            var fullpath = this.folder + fileName;
            var file = new Model.File();

            try
            {
                using (var entities = new Model.FlowerEntities())
                {
                    file.ID         = id;
                    file.Name       = fileName;
                    file.CreateUser = "******";
                    file.CreateDate = DateTime.Now;

                    entities.Files.Add(file);
                    entities.SaveChanges();
                }
            }
            catch
            {
                file = null;
            }
            return file ;
        }
        private void ExtractMasterPagesAndPageLayouts(Web web, ProvisioningTemplate template, PnPMonitoredScope scope, ProvisioningTemplateCreationInformation creationInfo)
        {
            web.EnsureProperty(w => w.Url);
            String webApplicationUrl = GetWebApplicationUrl(web.Url);

            if (!String.IsNullOrEmpty(webApplicationUrl))
            {
                // Get the Publishing Feature reference template
                ProvisioningTemplate publishingFeatureTemplate = GetPublishingFeatureBaseTemplate();

                // Get a reference to the root folder of the master page gallery
                var gallery = web.GetCatalog(116);
                web.Context.Load(gallery, g => g.RootFolder);
                web.Context.ExecuteQueryRetry();

                var masterPageGalleryFolder = gallery.RootFolder;

                // Load the files in the master page gallery
                web.Context.Load(masterPageGalleryFolder.Files);
                web.Context.ExecuteQueryRetry();

                var sourceFiles = masterPageGalleryFolder.Files.AsEnumerable().Where(
                    f => f.Name.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase) ||
                    f.Name.EndsWith(".html", StringComparison.InvariantCultureIgnoreCase) ||
                    f.Name.EndsWith(".master", StringComparison.InvariantCultureIgnoreCase));

                foreach (var file in sourceFiles)
                {
                    var listItem = file.EnsureProperty(f => f.ListItemAllFields);
                    listItem.ContentType.EnsureProperties(ct => ct.Id, ct => ct.StringId);

                    // Check if the content type is of type Master Page or Page Layout
                    if (listItem.ContentType.StringId.StartsWith(MASTER_PAGE_CONTENT_TYPE_ID) ||
                        listItem.ContentType.StringId.StartsWith(PAGE_LAYOUT_CONTENT_TYPE_ID) ||
                        listItem.ContentType.StringId.StartsWith(HTML_MASTER_PAGE_CONTENT_TYPE_ID) ||
                        listItem.ContentType.StringId.StartsWith(HTML_PAGE_LAYOUT_CONTENT_TYPE_ID))
                    {
                        // Skip any .ASPX or .MASTER file related to an .HTML designer file
                        if ((file.Name.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase)
                            && sourceFiles.Any(f => f.Name.Equals(file.Name.ToLower().Replace(".aspx", ".html"),
                                StringComparison.InvariantCultureIgnoreCase))) ||
                            (file.Name.EndsWith(".master", StringComparison.InvariantCultureIgnoreCase)
                            && sourceFiles.Any(f => f.Name.Equals(file.Name.ToLower().Replace(".master", ".html"),
                                StringComparison.InvariantCultureIgnoreCase))))
                        {
                            continue;
                        }

                        // If the file is a custom one, and not one native
                        // and coming out from the publishing feature
                        if (creationInfo.IncludeNativePublishingFiles ||
                            !IsPublishingFeatureNativeFile(publishingFeatureTemplate, file.Name))
                        {
                            var fullUri = new Uri(UrlUtility.Combine(webApplicationUrl, file.ServerRelativeUrl));

                            var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/');
                            var fileName = fullUri.Segments[fullUri.Segments.Count() - 1];

                            var publishingFile = new Model.File()
                            {
                                Folder = Tokenize(folderPath, web.Url),
                                Src = HttpUtility.UrlDecode(fileName),
                                Overwrite = true,
                            };

                            // Add field values to file
                            RetrieveFieldValues(web, file, publishingFile);

                            // Add the file to the template
                            template.Files.Add(publishingFile);

                            // Persist file using connector, if needed
                            if (creationInfo.PersistPublishingFiles)
                            {
                                PersistFile(web, creationInfo, scope, folderPath, fileName, true);
                            }

                            if (listItem.ContentType.StringId.StartsWith(MASTER_PAGE_CONTENT_TYPE_ID))
                            {
                                scope.LogWarning(String.Format("The file \"{0}\" is a custom MasterPage. Accordingly to the PnP Guidance (http://aka.ms/o365pnpguidancemasterpages) you should try to avoid using custom MasterPages.", file.Name));
                            }
                        }
                        else
                        {
                            scope.LogWarning(String.Format("Skipping file \"{0}\" because it is native in the publishing feature.", file.Name));
                        }
                    }
                }
            }
        }
Example #35
0
 /// <summary>
 /// Загружает файл на сервер и сохраняет его в БД
 /// </summary>
 /// <param name="fullPath">Полный путь файла</param>
 /// <param name="parent_id">ID папки, в которой лежит файл</param>
 public static void Upload(long parent_id, string fullPath)
 {
     Dictionary<string, dynamic> json = Controller.ApiTwoSafe.putFile(parent_id, fullPath, null)["response"]["file"];
     File file = new Model.File(long.Parse(json["id"]), parent_id, json["name"], long.Parse(json["version_id"]), json["chksum"], json["size"], json["mtime"]);
     file.Save();
 }
 private Model.File GetComposedLookFile(string asset)
 {
     int index = asset.LastIndexOf("/");
     Model.File file = new Model.File();
     file.Src = FixFileName(asset.Substring(index + 1));
     file.Folder = asset.Substring(0, index);
     file.Overwrite = true;
     file.Security = null;
     return file;
 }
        //TODO: Candidate for cleanup
        private Model.File GetTemplateFile(Web web, string serverRelativeUrl)
        {

            var webServerUrl = web.EnsureProperty(w => w.Url);
            var serverUri = new Uri(webServerUrl);
            var serverUrl = string.Format("{0}://{1}", serverUri.Scheme, serverUri.Authority);
            var fullUri = new Uri(System.UrlUtility.Combine(serverUrl, serverRelativeUrl));

            var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/');
            var fileName = fullUri.Segments[fullUri.Segments.Count() - 1];

            var templateFile = new Model.File()
            {
                Folder = Tokenize(folderPath, web.Url),
                Src = fileName,
                Overwrite = true,
            };

            return templateFile;
        }
        //TODO: Candidate for cleanup
        private Model.File GetTemplateFile(Web web, string serverRelativeUrl, FileConnectorBase connector, TokenParser parser)
        {
            var webServerUrl = web.EnsureProperty(w => w.Url);
            var serverUri = new Uri(webServerUrl);
            var serverUrl = string.Format("{0}://{1}", serverUri.Scheme, serverUri.Authority);
            var fullUri = new Uri(UrlUtility.Combine(serverUrl, serverRelativeUrl));

            var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/');
            var fileName = fullUri.Segments[fullUri.Segments.Count() - 1];

            var templateFile = new Model.File()
            {
                Folder = TokenizeUrl(folderPath, parser),
                Src = (null != connector) ? Path.Combine(connector.GetConnectionString(), fileName) : fileName,
                Overwrite = true,
            };

            return templateFile;
        }
        private void PersistWorkflowForm(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope, String formUrl)
        {
            var fullUri = new Uri(UrlUtility.Combine(web.Url, formUrl));

            var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/');
            var fileName = fullUri.Segments[fullUri.Segments.Count() - 1];

            var formFile = new Model.File()
            {
                Folder = Tokenize(folderPath, web.Url),
                Src = formUrl,
                Overwrite = true,
            };

            // Add the file to the template
            template.Files.Add(formFile);

            // Persist file using connector
            PersistFile(web, creationInfo, scope, folderPath, fileName);
        }
Example #40
0
 /// <summary>
 /// Находит файл в базе данных по названию и ID родительской папки
 /// </summary>
 /// <param name="name">Имя файла</param>
 /// <param name="parent_id">ID родительской папки</param>
 /// <returns>Возвращает объект файла</returns>
 public static File FindByNameAndParentId(string name, long parent_id)
 {
     File result = null;
     SQLiteConnection connection = new SQLiteConnection(dbName);
     connection.Open();
     SQLiteCommand command = new SQLiteCommand("SELECT * FROM files WHERE name='" + name + "' AND parent_id='" + parent_id.ToString() + "'", connection);
     SQLiteDataReader reader = command.ExecuteReader();
     try
     {
         reader.Read();
         result = new Model.File(reader.GetInt64(0), reader.GetInt64(1), reader.GetString(2), reader.GetInt64(3), reader.GetString(4), reader.GetInt32(5), reader.GetInt64(6));
     }
     catch { }
     reader.Close();
     connection.Close();
     return result;
 }
 private Model.File GetComposedLookFile(string asset, FileConnectorBase connector)
 {
     int index = asset.LastIndexOf("/");
     Model.File file = new Model.File();
     string fileSrc = FixFileName(asset.Substring(index + 1));
     file.Src = (null != connector)?Path.Combine(connector.GetConnectionString(), fileSrc): fileSrc;
     file.Folder = asset.Substring(0, index);
     file.Overwrite = true;
     file.Security = null;
     return file;
 }