BinaryContentService.cs :  » Content-Management-Systems-CMS » Kooboo » Everest » CmsServices » Services » C# / CSharp Open Source

Home
C# / CSharp Open Source
1.2.6.4 mono .net core
2.2.6.4 mono core
3.Aspect Oriented Frameworks
4.Bloggers
5.Build Systems
6.Business Application
7.Charting Reporting Tools
8.Chat Servers
9.Code Coverage Tools
10.Content Management Systems CMS
11.CRM ERP
12.Database
13.Development
14.Email
15.Forum
16.Game
17.GIS
18.GUI
19.IDEs
20.Installers Generators
21.Inversion of Control Dependency Injection
22.Issue Tracking
23.Logging Tools
24.Message
25.Mobile
26.Network Clients
27.Network Servers
28.Office
29.PDF
30.Persistence Frameworks
31.Portals
32.Profilers
33.Project Management
34.RSS RDF
35.Rule Engines
36.Script
37.Search Engines
38.Sound Audio
39.Source Control
40.SQL Clients
41.Template Engines
42.Testing
43.UML
44.Web Frameworks
45.Web Service
46.Web Testing
47.Wiki Engines
48.Windows Presentation Foundation
49.Workflows
50.XML Parsers
C# / C Sharp
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source » Content Management Systems CMS » Kooboo 
Kooboo » Everest » CmsServices » Services » BinaryContentService.cs
/*
Kooboo is a content management system based on ASP.NET MVC framework. Copyright 2009 Yardi Technology Limited.

This program is free software: you can redistribute it and/or modify it under the terms of the
GNU General Public License version 3 as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program.
If not, see http://www.kooboo.com/gpl3/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.IO;

using Everest.CmsServices.Providers;
using Everest.CmsServices.Models;
using Everest.Library;
using Everest.Library.ExtensionMethod;
using Everest.Library.Data;
using Everest.Library.Versioning;
using Everest.Library.Web;
using Microsoft.Data.Extensions;
using System.Text.RegularExpressions;

namespace Everest.CmsServices.Services{

    public class BinaryContentService : ContentServiceBase
    {
        #region Add & Update
        public Cms_Content AddBinaryContent(NameValueCollection values, string userName, string fileName, Stream stream)
        {
            var dataContext = EverestCmsEntities.GetDataContext();
            var folderUUID = new Guid(values["folderUUID"]);
            var folder = dataContext.QueryFolder(folderUUID).First();

            var content = new Cms_Content();

            var published = StringExtensions.IsTrue(values["Published"]);
            if (published)
            {
                content.ContentStatus = (int)ContentStatus.Published;
            }
            else
            {
                content.ContentStatus = (int)ContentStatus.Draft;
            }

            content.Title = values["Title"];
            if (string.IsNullOrEmpty(content.Title))
            {
                content.Title = fileName;
            }
            content.ModifiedDate = DateTime.Now;
            content.UserName = userName;
            content.Cms_Folder = folder;
            content.Cms_Folder.aspnet_ApplicationsReference.Load();
            content.aspnet_Applications = content.Cms_Folder.aspnet_Applications;
            content.Cms_Folder.Cms_SchemaReference.Load();
            content.Cms_Schema = content.Cms_Folder.Cms_Schema;
            content.PostDate = DateTime.Now;

            dataContext.AddToCms_Content(content);

            AddBinaryFile(content, folder, fileName, stream);

            dataContext.SaveChanges();
            content.Checkin(userName, "");

            WorkflowService workflowService = UnityManager.Resolve<WorkflowService>();
            workflowService.StartWorkflow(dataContext, content);

            try
            {
                if (content.Cms_Folder != null)
                {
                    var derives = CachedData.GetAllDerives(content.Cms_Folder.UUID);

                    foreach (var folderItem in derives)
                    {
                        if (folderItem.IncludeBase)
                        {
                            Include(content.UUID, folderItem.UUID, false);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Everest.Library.HealthMonitor.HealthMonitoringLogging.LogError(e);
            }

            return content;
        }

        private void AddBinaryFile(Cms_Content content, Cms_Folder folder, string fileName, Stream stream)
        {
            var schema = content.Cms_Schema;
            if (!string.IsNullOrEmpty(schema.Extensions))
            {
                var extension = Path.GetExtension(fileName).Replace(".", "");
                if (!Regex.IsMatch(extension, schema.Extensions, RegexOptions.IgnoreCase))
                {
                    throw new Exception(Resources.FileTypeNotAllowed);
                }
            }
            var fileSize = (int)stream.Length;
            if (schema.MaxSize != 0)
            {
                if (fileSize > schema.MaxSize)
                {
                    throw new Everest.CmsServices.Exceptions.FileLengthExceededException();
                }
            }
            if (!StringExtensions.IsNullOrEmptyTrim(fileName))
            {
                fileName = Path.GetFileNameWithoutExtension(fileName).ReplaceToValidUrl() + Path.GetExtension(fileName);

                //save the file
                string absoluteFolderPath = folder.GetAbsoluteFolderContentFilePath("");

                string contentFilePath = Path.Combine(content.UUID.ToString(), Path.GetFileName(fileName));
                var savedFile = stream.SaveAs(Path.Combine(absoluteFolderPath, contentFilePath), false);

                Cms_BinaryContent binaryContent = new Cms_BinaryContent();
                binaryContent.Cms_Content = content;
                binaryContent.FileSize = fileSize;
                binaryContent.FilePath = UrlConvertor.AbsolutePathToRelativeUrl(savedFile);

                content.Cms_BinaryContent = binaryContent;
            }
        }

        /// <summary>
        /// Updates the binary contents.
        /// </summary>
        /// <param name="values">The values.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="fileSize">Size of the file.</param>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public Cms_Content UpdateBinaryContent(Guid contentUUID, NameValueCollection values, string userName, string fileName, Stream stream)
        {
            var dataContext = EverestCmsEntities.GetDataContext();
            var content = dataContext.QueryContent(contentUUID).First();
            if (content.Cms_Folder == null)
            {
                content.Cms_FolderReference.Load();
            }
            var folder = content.Cms_Folder;
            content.Title = values["Title"];
            if (!StringExtensions.IsNullOrEmptyTrim(fileName) && stream.Length > 0)
            {
                content.Cms_BinaryContentReference.Load();
                if (content.Cms_BinaryContent != null)
                {
                    dataContext.DeleteObject(content.Cms_BinaryContent);
                }
                content.Cms_BinaryContent = null;

                AddBinaryFile(content, folder, fileName, stream);
            }
            if (StringExtensions.IsTrue(values["Published"]))
            {
                content.ContentStatus = (int)ContentStatus.Published;
            }
            else
            {
                content.ContentStatus = (int)ContentStatus.Draft;
            }
            dataContext.SaveChanges();
            content.Checkin(userName, "");
            return content;
        }
        #endregion

        #region Query
        public IEnumerable<IDictionary<string, object>> QueryBinaryContents(Guid folderUUID, string userName, string queryStatement, NameValueCollection queryValues,
            bool? isProcessed, string orderBy, out int count, int start, int limit)
        {
            var dataContext = EverestCmsEntities.GetDataContext();
            var folder = CachedData.GetFolder(folderUUID);
            IContentProvider contentProvider = UnityManager.Resolve<IContentProvider>();

            var queryData = contentProvider.BinaryContentManager.QueryContents(dataContext, folder, folder.GetBaseFoldersRecusive(), queryStatement, queryValues.ToDictionary(), userName,
                            isProcessed, orderBy, start, limit);

            count = contentProvider.BinaryContentManager.CountContents(dataContext, folder, folder.GetBaseFoldersRecusive(), queryStatement, queryValues.ToDictionary()
                , userName, isProcessed);

            return queryData;
        }
        /// <summary>
        /// Queries the content of the binary.
        /// </summary>
        /// <param name="contentUUID">The content UUID.</param>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        public QueriedBinaryContent QueryBinaryContent(Guid contentUUID, string userName)
        {
            var dataContext = EverestCmsEntities.GetDataContext();
            WorkflowService workflowService = UnityManager.Resolve<WorkflowService>();
            var contentData = dataContext.QueryContent(contentUUID)
                               .Select(c => new QueriedBinaryContent()
                               {
                                   Application = c.aspnet_Applications.ApplicationName,
                                   UUID = c.UUID,
                                   ContentId = c.ContentId,
                                   Title = c.Title,
                                   FilePath = c.Cms_BinaryContent.FilePath,
                                   ContentStatus = c.ContentStatus
                               }).First();
            contentData.Readonly = !workflowService.CanEditContentByStatus(contentData.UUID, contentData.ContentStatus, userName);
            contentData.CanUpdateContentStatus = workflowService.CanEditContentByStatus(contentData.UUID, (int)ContentStatus.Published, userName);
            return contentData;
        }
        #endregion

        #region Delete
        /// <summary>
        /// Deletes the specified UUID.
        /// </summary>
        /// <param name="uuid">The UUID.</param>
        /// <param name="userName">Name of the user.</param>
        public void Delete(Guid uuid, string userName)
        {
            var dataContext = EverestCmsEntities.GetDataContext();
            Cms_Content content = dataContext.QueryContent(uuid).First();
            if (BeReferenced(dataContext, uuid))
            {
                throw new Exception(string.Format(Resources.ItemCouldNotBeDeleted, content.Title));
            }
            else
            {

                WorkflowService workflowService = UnityManager.Resolve<WorkflowService>();
                var readOnly = !workflowService.CanEditContentByStatus(content.UUID, content.ContentStatus, userName);
                if (readOnly)
                {
                    throw new Exception(Resources.NotAllowToDelete);
                }

                content.Cms_FolderReference.Load();

                string fileDirectory = content.Cms_Folder.GetAbsoluteFolderContentFilePath(content.UUID.ToString());

                using (var conn = dataContext.ObjectContext.Connection.CreateConnectionScope())
                {
                    using (var dbTrans = dataContext.ObjectContext.Connection.BeginTransaction())
                    {
                        content.Cms_ContentInFolder.Load();
                        while (content.Cms_ContentInFolder.Count > 0)
                        {
                            dataContext.DeleteObject(content.Cms_ContentInFolder.First());
                        }

                        content.Cms_BinaryContentReference.Load();

                        dataContext.DeleteObject(content.Cms_BinaryContent);
                        dataContext.DeleteObject(content);
                        dataContext.SaveChanges();
                        dbTrans.Commit();
                    }
                }
                //delete the content file directory
                if (System.IO.Directory.Exists(fileDirectory))
                {
                    System.IO.Directory.Delete(fileDirectory, true);
                }
            }
        }

        /// <summary>
        /// Bes the referenced.
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        /// <param name="uuid">The UUID.</param>
        /// <returns></returns>
        private bool BeReferenced(IEverestCmsDataContext dataContext, Guid uuid)
        {
            if (dataContext.QueryIncludedByContents(uuid).Exists())
            {
                return true;
            }
            if (dataContext.QueryContentLocalizations(uuid).Exists())
            {
                return true;
            }
            return false;
        }
        #endregion

        #region Localize
        /// <summary>
        /// Localizes the specified content UUID.
        /// </summary>
        /// <param name="contentUUID">The content UUID.</param>
        /// <param name="folderUUID">The folder UUID.</param>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        public Cms_Content Localize(Guid contentUUID, Guid folderUUID, string userName)
        {
            var dataContext = EverestCmsEntities.GetDataContext();
            Cms_Folder folder = dataContext.QueryFolder(folderUUID).First();
            var originalContent = dataContext.QueryContent(contentUUID).First();

            if (!folder.aspnet_ApplicationsReference.IsLoaded)
            {
                folder.aspnet_ApplicationsReference.Load();
            }
            Cms_Content localizedContent = originalContent.CopyNewBinaryContent();
            localizedContent.Cms_Folder = folder;
            localizedContent.aspnet_Applications = folder.aspnet_Applications;
            localizedContent.UserName = userName;
            localizedContent.PostDate = DateTime.Now;
            localizedContent.ModifiedDate = DateTime.Now;
            localizedContent.OriginalUUID = originalContent.OriginalUUID;
            localizedContent.FolderLevel = localizedContent.Cms_Folder.FolderLevel;

            dataContext.SaveChanges();

            WorkflowService workflowService = UnityManager.Resolve<WorkflowService>();
            workflowService.StartWorkflow(dataContext, localizedContent);

            return localizedContent;

        }
        #endregion
    }
}

www.java2v.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.