/*
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.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Everest.CmsServices.Models;
using Everest.CmsServices.Search;
using Everest.Library.Versioning;
using Everest.CmsServices.Providers;
using Everest.Library.ExtensionMethod;
using Everest.Library;
using Everest.Library.Data.Entity;
using Everest.Library.Extjs;
using Microsoft.Data.Extensions;
using Everest.Library.Data;
using Everest.Library.Extjs.Tree;
using Everest.Library.Providers.Caching;
namespace Everest.CmsServices.Services{
public abstract class ContentServiceBase
{
protected static IEnumerable<IContentTrigger> contentTriggers = UnityManager.ResolveAll<IContentTrigger>();
#region Inclusion
public virtual void Include(Guid contentUUID, Guid folderUUID)
{
Include(contentUUID, folderUUID, true);
}
protected virtual void Include(Guid contentUUID, Guid folderUUID, bool fireTrigger)
{
var dataContext = EverestCmsEntities.GetDataContext();
Cms_ContentInFolder contentInFolder = new Cms_ContentInFolder();
contentInFolder.Cms_Content = dataContext.QueryContent(contentUUID).First();
contentInFolder.Cms_Folder = dataContext.QueryFolder(folderUUID).First();
//clear the schema cache data group
var schema = CachedData.GetSchemaByFolder(folderUUID);
CacheManager.RemoveCacheGroup(schema.UUID.ToString());
dataContext.AddToCms_ContentInFolder(contentInFolder);
dataContext.SaveChanges();
#region ContentTrigger
if (fireTrigger == true)
{
try
{
foreach (var trigger in contentTriggers)
{
trigger.OnIncluded(contentInFolder.Cms_Content, contentInFolder.Cms_Folder);
}
}
catch (Exception e)
{
Everest.Library.HealthMonitor.HealthMonitoringLogging.LogError(e);
}
}
#endregion
}
public virtual void Exclude(Guid contentUUID, Guid folderUUID)
{
Exclude(contentUUID, folderUUID, true);
}
protected virtual void Exclude(Guid contentUUID, Guid folderUUID, bool fireTrigger)
{
var dataContext = EverestCmsEntities.GetDataContext();
var contentInFolder = dataContext.QueryContentInFolder(contentUUID, folderUUID).FirstOrDefault();
if (contentInFolder != null)
{
contentInFolder.Cms_ContentReference.Load();
contentInFolder.Cms_FolderReference.Load();
var content = contentInFolder.Cms_Content;
var folder = contentInFolder.Cms_Folder;
dataContext.DeleteObject(contentInFolder);
//TriggerIndex(contentUUID, IndexType.Update);
dataContext.SaveChanges();
#region ContentTrigger
if (fireTrigger == true)
{
try
{
foreach (var trigger in contentTriggers)
{
trigger.OnExcluded(content, folder);
}
}
catch (Exception e)
{
Everest.Library.HealthMonitor.HealthMonitoringLogging.LogError(e);
}
}
#endregion
//clear the schema cache data group
var schema = CachedData.GetSchemaByFolder(folderUUID);
CacheManager.RemoveCacheGroup(schema.UUID.ToString());
}
}
#endregion
}
/// <summary>
///
/// </summary>
public class TextContentService : ContentServiceBase
{
public const string DeleteAllFileTag = "ALL";
IContentProvider contentProvider = UnityManager.Resolve<IContentProvider>();
#region AddContent
public Cms_Content AddContent(NameValueCollection values, string userName, HttpFileCollectionBase files)
{
return AddContent(values, userName, files, false, false);
}
/// <summary>
/// Adds the content.
/// </summary>
/// <param name="values">The values.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="files">The files.</param>
/// <param name="remoteSync">if set to <c>true</c> [remote sync].</param>
/// <param name="renewId">if set to <c>true</c> [renew id].</param>
/// <returns></returns>
public virtual Cms_Content AddContent(NameValueCollection values, string userName, HttpFileCollectionBase files, bool remoteSync, bool renewId)
{
var valuesWrapper = new NameValueCollection(values);
var dataContext = EverestCmsEntities.GetDataContext();
var content = new Cms_Content();
if (remoteSync && !renewId)
{
var contentUUID = new Guid(values["UUID"]);
content.UUID = contentUUID;
if (!string.IsNullOrEmpty(values["OriginalUUID"]))
{
var originalUUID = new Guid(values["OriginalUUID"]);
content.OriginalUUID = originalUUID;
}
if (!string.IsNullOrEmpty(values["BaseUUID"]))
{
var baseUUID = new Guid(values["BaseUUID"]);
content.Base = dataContext.QueryContent(baseUUID).FirstOrDefault();
}
}
var published = StringExtensions.IsTrue(valuesWrapper["Published"]);
if (published)
{
content.ContentStatus = (int)ContentStatus.Published;
}
else
{
content.ContentStatus = (int)ContentStatus.Draft;
}
content.Title = valuesWrapper["Title"];
content.UserKey = valuesWrapper["UserKey"];
//content.ModifiedDate = DateTime.Now;
content.PostDate = DateTime.Now;
content.UserName = userName;
Guid? parentUUID = valuesWrapper["ParentUUID"].GetNullableGuid();
Guid? schemaUUID = valuesWrapper["schemaUUID"].GetNullableGuid();
if (parentUUID == null)
{
var folderUUID = new Guid(valuesWrapper["folderUUID"]);
content.Cms_Folder = dataContext.QueryFolder(folderUUID).First();
content.FolderLevel = content.Cms_Folder.FolderLevel;
//string appName = valuesWrapper["application"];
content.Cms_Folder.aspnet_ApplicationsReference.Load();
content.aspnet_Applications = content.Cms_Folder.aspnet_Applications;
schemaUUID = CachedData.GetSchemaByFolder(folderUUID).UUID;
}
else
{
content.ParentContent = dataContext.QueryContent(parentUUID.Value).First();
//sub content application = parent content application
content.ParentContent.aspnet_ApplicationsReference.Load();
content.aspnet_Applications = content.ParentContent.aspnet_Applications;
}
content.ApplicationLevel = content.aspnet_Applications.ApplicationLevel;
content.Cms_Schema = dataContext.QuerySchema(schemaUUID.Value).First();
dataContext.AddToCms_Content(content);
AddBinarycontents(content, dataContext, valuesWrapper);
AddReferencingContents(content, dataContext, valuesWrapper);
UploadFiles(content, files, valuesWrapper);
try
{
var trans = dataContext.BeginTransaction();
{
dataContext.SaveChanges();
content.ContentFieldValues = contentProvider.TextContentManager.CreateContent(dataContext, content, valuesWrapper.ToDictionary());
//start workflow
WorkflowService workflowService = UnityManager.Resolve<WorkflowService>();
workflowService.StartWorkflow(dataContext, content);
var indexContent = content.UUID;
if (parentUUID != null)
{
indexContent = parentUUID.Value;
}
dataContext.Commit();
}
}
catch
{
dataContext.Rollback();
throw;
}
try
{
//
content.Checkin(userName, "");
foreach (var trigger in contentTriggers)
{
trigger.OnAdded(content);
}
}
catch (Exception e)
{
Everest.Library.HealthMonitor.HealthMonitoringLogging.LogError(e);
}
try
{
if (content.Cms_Folder != null)
{
var derives = CachedData.GetAllDerives(content.Cms_Folder.UUID);
foreach (var folder in derives)
{
if (folder.IncludeBase)
{
Include(content.UUID, folder.UUID, false);
}
}
}
}
catch (Exception e)
{
Everest.Library.HealthMonitor.HealthMonitoringLogging.LogError(e);
}
CacheManager.RemoveCacheGroup(schemaUUID.ToString());
var functions = CachedData.GetFunctionBySchema(schemaUUID.Value, FunctionType.AfterAdd);
if (functions.Count() > 0)
{
var contentValues = contentProvider.TextContentManager.QueryContent(dataContext, content).ToNameValueCollection();
//
// Added trigger script prototype
//
// void Execute(IEverestCmsDataContext dataContext, IContentProvider contentProvider, Cms_Content content,NameValueCollection contentValues,Cms_Schema schema)
//
ExecuteContentEvent(schemaUUID.Value, functions, dataContext, contentProvider, content, contentValues, content.Cms_Schema);
}
return content;
}
#endregion
#region UpdateContent
/// <summary>
/// Updates the content.
/// </summary>
/// <param name="contentId">The content id.</param>
/// <param name="values">The values.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="files">The files.</param>
/// <returns></returns>
public virtual Cms_Content UpdateContent(int contentId, NameValueCollection values, string userName, HttpFileCollectionBase files, bool updateAllField)
{
var dataContext = EverestCmsEntities.GetDataContext();
var content = dataContext.QueryContent(contentId).First();
return this.UpdateContent(dataContext, content, values, userName, files, updateAllField);
}
/// <summary>
/// Updates the content.
/// </summary>
/// <param name="contentUUID">The content uuid.</param>
/// <param name="values">The values.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="files">The files.</param>
/// <returns></returns>
public virtual Cms_Content UpdateContent(Guid contentUUID, NameValueCollection values, string userName, HttpFileCollectionBase files, bool updateAllField)
{
var dataContext = EverestCmsEntities.GetDataContext();
var content = dataContext.QueryContent(contentUUID).First();
return this.UpdateContent(dataContext, content, values, userName, files, updateAllField);
}
/// <summary>
/// Updates the content.
/// </summary>
/// <param name="dataContext">The data context.</param>
/// <param name="content">content instance.</param>
/// <param name="values">The values.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="files">The files.</param>
/// <param name="updateAllField">if set to <c>true</c> [update all field].</param>
/// <returns></returns>
protected virtual Cms_Content UpdateContent(IEverestCmsDataContext dataContext, Cms_Content content, NameValueCollection values, string userName, HttpFileCollectionBase files, bool updateAllField)
{
var valuesWrapper = new NameValueCollection(values);
var workflowService = UnityManager.Resolve<WorkflowService>();
if (!StringExtensions.IsNullOrEmptyTrim(valuesWrapper["Title"]))
{
content.Title = valuesWrapper["Title"].TryTrim();
}
content.UserKey = valuesWrapper["UserKey"].TryTrim();
//content.ParentId = values["ParentId"].GetNullableInt();
content.ModifiedDate = DateTime.Now;
content.UserName = userName;
//use in the AddBinarycontents
content.Cms_FolderReference.Load();
AddBinarycontents(content, dataContext, valuesWrapper);
AddReferencingContents(content, dataContext, valuesWrapper);
string deletedFiles = valuesWrapper["deletedFiles"];
DeleteFiles(dataContext, content.UUID, deletedFiles);
UploadFiles(content, files, valuesWrapper);
if (workflowService.CanEditContentByStatus(content.UUID, (int)ContentStatus.Published, userName))
{
if (StringExtensions.IsTrue(valuesWrapper["Published"]))
{
content.ContentStatus = (int)ContentStatus.Published;
}
else
{
content.ContentStatus = (int)ContentStatus.Draft;
}
}
try
{
var trans = dataContext.BeginTransaction();
{
dataContext.SaveChanges();
content.ContentFieldValues = contentProvider.TextContentManager.UpdateContent(dataContext, content, valuesWrapper.ToDictionary(), updateAllField);
dataContext.Commit();
}
}
catch
{
dataContext.Rollback();
throw;
}
try
{
content.Checkin(userName, "");
foreach (var trigger in contentTriggers)
{
trigger.OnUpdated(content);
}
}
catch (Exception e)
{
Everest.Library.HealthMonitor.HealthMonitoringLogging.LogError(e);
}
CacheManager.RemoveCacheGroup(content.SchemaUUIDFromReference.ToString());
content.Cms_SchemaReference.Load(content.Cms_Schema, content.EntityState);
var functions = CachedData.GetFunctionBySchema(content.Cms_Schema.UUID, FunctionType.AfterUpdate);
if (functions.Count() > 0)
{
var contentValues = contentProvider.TextContentManager.QueryContent(dataContext, content).ToNameValueCollection();
//
// Updated trigger script prototype
//
// void Execute(IEverestCmsDataContext dataContext, IContentProvider contentProvider, Cms_Content content,NameValueCollection contentValues,Cms_Schema schema)
//
ExecuteContentEvent(content.Cms_Schema.UUID, functions, dataContext, contentProvider, content, contentValues, content.Cms_Schema);
}
return content;
}
/// <summary>
/// Updates the content.
/// </summary>
/// <param name="values">The values.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="files">The files.</param>
/// <returns></returns>
public virtual Cms_Content UpdateContent(NameValueCollection values, string userName, HttpFileCollectionBase files, bool updateAllField)
{
var contentUUID = new Guid(values["oldData.UUID"]);
return UpdateContent(contentUUID, values, userName, files, updateAllField);
}
#endregion
#region Set Properties
/// <summary>
/// Adds the binarycontents.
/// </summary>
/// <param name="content">The content.</param>
private void AddBinarycontents(Cms_Content content, IEverestCmsDataContext dataContext, NameValueCollection values)
{
StringBuilder binaryContentsBuilder = new StringBuilder(values["BinaryContents"]);
string oldBinaryContentId = values["oldData.BinaryContents"]; //
foreach (var key in values.AllKeys)
{
if (key.StartsWith("Bin_"))
{
var value = values[key];
if (!StringExtensions.IsNullOrEmptyTrim(value))
{
binaryContentsBuilder.AppendFormat(",{0}", value.Trim());
}
}
}
var binaryContents = binaryContentsBuilder.ToString();
if (binaryContents != oldBinaryContentId)
{
//delete old binary content in the attachment.
if (!StringExtensions.IsNullOrEmptyTrim(oldBinaryContentId))
{
var intOldBinaryContentIds = oldBinaryContentId.Split(',');
foreach (var binaryContentUUID in intOldBinaryContentIds)
{
if (!StringExtensions.IsNullOrEmptyTrim(binaryContentUUID))
{
var binaryContentuuid = new Guid(binaryContentUUID);
var contentFile = dataContext.QueryContentFile(content.UUID, binaryContentuuid).First();
dataContext.DeleteObject(contentFile);
}
}
}
if (!StringExtensions.IsNullOrEmptyTrim(binaryContents))
{
var binaryContentsUUID = binaryContents.Split(',');
foreach (var item in binaryContentsUUID)
{
if (!StringExtensions.IsNullOrEmptyTrim(item))
{
Guid uuid = new Guid(item);
Cms_ContentFile contentFile = new Cms_ContentFile();
contentFile.BinaryContent = dataContext.QueryContent(uuid).First();
content.ContentFiles.Add(contentFile);
}
}
}
}
}
/// <summary>
/// Adds the referencing contents.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="dataContext">The data context.</param>
/// <param name="values">The values.</param>
private void AddReferencingContents(Cms_Content content, IEverestCmsDataContext dataContext, NameValueCollection values)
{
StringBuilder referenceContentsBuilder = new StringBuilder(values["ReferenceContents"]);
var oldReferenceContents = values["oldData.ReferenceContents"]; //
foreach (var key in values.AllKeys)
{
if (key.StartsWith("Ref_"))
{
var value = values[key];
if (!StringExtensions.IsNullOrEmptyTrim(value))
{
referenceContentsBuilder.AppendFormat(",{0}", value.Trim());
}
}
}
var referenceContents = referenceContentsBuilder.ToString();
if (oldReferenceContents == null)
{
oldReferenceContents = string.Empty;
}
if (referenceContents != oldReferenceContents)
{
//delete old binary content in the attachment.
content.ClearReferencing(dataContext);
if (!StringExtensions.IsNullOrEmptyTrim(referenceContents))
{
var contentsUUID = referenceContents.Split(',');
foreach (var contentUUID in contentsUUID)
{
if (!StringExtensions.IsNullOrEmptyTrim(contentUUID))
{
var c = dataContext.QueryContent(new Guid(contentUUID)).FirstOrDefault();
if (c != null)
{
Cms_ContentReferencing contentRef = new Cms_ContentReferencing();
contentRef.Cms_Content = content;
contentRef.Cms_ReferencedContent = c;
contentRef.ReferencedContentOriginalUUID = c.OriginalUUID;
content.Cms_ContentReferencing.Add(contentRef);
}
}
}
}
}
}
/// <summary>
/// Uploads the files.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="files">The files.</param>
private void UploadFiles(Cms_Content content, HttpFileCollectionBase files, NameValueCollection values)
{
if (files != null && files.Count > 0)
{
content.AddContentFiles(files, values);
}
}
/// <summary>
/// Deletes the files.
/// </summary>
/// <param name="dataContext">The data context.</param>
/// <param name="deletedFiles">The deleted files.</param>
private void DeleteFiles(IEverestCmsDataContext dataContext, Guid contentId, string deletedFiles)
{
//
if (!StringExtensions.IsNullOrEmptyTrim(deletedFiles))
{
//
if (deletedFiles == DeleteAllFileTag)
{
var files = dataContext.QueryContentFileByTextContent(contentId).ToArray();
foreach (var file in files)
{
dataContext.DeleteObject(file);
}
}
else
{
var deletedFilesUUID = deletedFiles.Split(',');
foreach (var contentFileUUID in deletedFilesUUID)
{
if (!StringExtensions.IsNullOrEmptyTrim(contentFileUUID))
{
Guid uuid = new Guid(contentFileUUID);
var contentFile = dataContext.QueryContentFile(uuid).FirstOrDefault();
if (contentFile != null)
{
//contentFile.DeleteFile();
dataContext.DeleteObject(contentFile);
}
}
}
}
}
}
#endregion
#region QueryContent
/// <summary>
/// Queries the sub contents.
/// </summary>
/// <param name="schemaUUID">The schema UUID.</param>
/// <param name="parentUUID">The parent UUID.</param>
/// <param name="expression">The expression.</param>
/// <param name="parameterValues">The parameter values.</param>
/// <param name="orderStatement">The order statement.</param>
/// <param name="start">The start.</param>
/// <param name="limit">The limit.</param>
/// <param name="contentCount">The content count.</param>
/// <returns></returns>
public virtual IEnumerable<IDictionary<string, object>> QuerySubContents(Guid schemaUUID, Guid? parentUUID, string expression,
NameValueCollection parameterValues, string orderStatement, int start, int limit, out int contentCount)
{
IEverestCmsDataContext dataContext = EverestCmsEntities.GetDataContext();
//query sub contents
var schema = dataContext.QuerySchema(schemaUUID).First();
expression = DynamicExpression(expression, schema.UUID, parameterValues);
contentProvider.TextContentQuerier.SetQueryType(QueryType.All);
var contents = contentProvider.TextContentQuerier.QuerySubContents(dataContext, expression.ToString(), orderStatement,
parameterValues.ToDictionary(), schema, parentUUID, start, limit, null);
contentCount = contentProvider.TextContentQuerier.CountSubContents(dataContext, expression.ToString(),
parameterValues.ToDictionary(), schema, parentUUID, null);
return contents;
}
public string DynamicExpression(string expression, Guid schemaUUID, NameValueCollection parameterValues)
{
StringBuilder expressionBuilder = new StringBuilder();
if (StringExtensions.IsNullOrEmptyTrim(expression) || parameterValues == null)
{
expressionBuilder.Append("1=1");
}
else
{
expressionBuilder.Append(expression);
}
var columns = CachedData.GetColumnsBySchema(schemaUUID);
foreach (var key in parameterValues.AllKeys)
{
if (!StringExtensions.IsNullOrEmptyTrim(parameterValues[key]))
{
var column = columns.Where(c => c.ColumnName.Equals(key, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
if (column != null)
{
if (column.DataType == ColumnDataType.String.ToString())
{
expressionBuilder.AppendFormat(" AND {0} LIKE '%' + {{{0}}} + '%'", key);
}
else
expressionBuilder.AppendFormat(" AND {0} = {{0}}", key);
}
}
}
return expressionBuilder.ToString();
}
/// <summary>
/// Queries the contents.
/// </summary>
/// <param name="folderUUID">The folder UUID.</param>
/// <param name="expression">The expression.</param>
/// <param name="parameterValues">The parameter values.</param>
/// <param name="orderStatement">The order statement.</param>
/// <param name="start">The start.</param>
/// <param name="limit">The limit.</param>
/// <param name="contentCount">The content count.</param>
/// <returns></returns>
public virtual IEnumerable<IDictionary<string, object>> QueryContents(Guid folderUUID, string expression, NameValueCollection parameterValues,
string orderStatement, string userName, bool? isProcessed, int start, int limit, out int contentCount)
{
IEverestCmsDataContext dataContext = EverestCmsEntities.GetDataContext();
var folder = CachedData.GetFolder(folderUUID);
var schema = CachedData.GetSchemaByFolder(folderUUID);
expression = DynamicExpression(expression, schema.UUID, parameterValues);
var contents = contentProvider.TextContentManager.QueryContents(dataContext, expression.ToString(), orderStatement, parameterValues.ToDictionary(), folder,
folder.GetBaseFoldersRecusive(), userName, isProcessed, start, limit);
contentCount = contentProvider.TextContentManager.CountContents(dataContext, expression.ToString(), parameterValues.ToDictionary(), folder,
folder.GetBaseFoldersRecusive(), userName, isProcessed);
return contents;
}
public virtual IDictionary<string, object> QueryContent(int contentId, string userName)
{
IEverestCmsDataContext dataContext = EverestCmsEntities.GetDataContext();
var content = dataContext.QueryContent(contentId);
return QueryContent(dataContext, content, userName);
}
/// <summary>
/// Gets the content.
/// </summary>
/// <param name="contentUUID">The content UUID.</param>
/// <returns></returns>
public virtual IDictionary<string, object> QueryContent(Guid contentUUID, string userName)
{
IEverestCmsDataContext dataContext = EverestCmsEntities.GetDataContext();
var content = dataContext.QueryContent(contentUUID);
return QueryContent(dataContext, content, userName);
}
private IDictionary<string, object> QueryContent(IEverestCmsDataContext dataContext, IQueryable<Cms_Content> contentQueryable, string userName)
{
var workflowService = UnityManager.Resolve<WorkflowService>();
var content = contentQueryable.
Select(c => new
{
Content = c,
Folder = c.Cms_Folder,
c.aspnet_Applications.ApplicationName
}).First();
var contentFiles = dataContext.Cms_ContentFile.Where(f => f.TextContent.UUID == content.Content.UUID);
IDictionary<string, object> dic = contentProvider.TextContentManager.QueryContent(dataContext, content.Content);
//add binarycontents
var binaryContents = contentFiles.Where(f => f.BinaryContent != null).Select(f => new
{
f.BinaryContent.Title,
f.BinaryContent.UUID,
SchemaUUID = f.BinaryContent.Cms_Schema.UUID,
SchemaName = f.BinaryContent.Cms_Schema.SchemaName
}).ToArray();
dic.Add("BinaryContents", string.Join(",", binaryContents.Select(b => b.UUID.ToString()).ToArray()));
var binaryGrouping = binaryContents.GroupBy(b => b.SchemaUUID);
foreach (var grouping in binaryGrouping)
{
var refContentSelect = new RefContentSelect() { SchemaUUID = grouping.Key };
List<string> titles = new List<string>();
List<Guid> uuids = new List<Guid>();
foreach (var item in binaryContents.Where(b => b.SchemaUUID == grouping.Key))
{
refContentSelect.SchemaName = item.SchemaName;
titles.Add(item.Title);
uuids.Add(item.UUID);
}
refContentSelect.Title = titles.ToArray();
refContentSelect.UUID = uuids.ToArray();
dic.Add("Bin_" + refContentSelect.SchemaName, refContentSelect);
}
//add referencing contents
var referencedContents = dataContext.QueryReferencedContents(content.Content.UUID).Select(c => new
{
c.Title,
c.UUID,
SchemaUUID = c.Cms_Schema.UUID,
SchemaName = c.Cms_Schema.SchemaName
}).ToArray();
dic.Add("ReferenceContents", string.Join(",", referencedContents.Select(c => c.UUID.ToString()).ToArray()));
var referecedGrouping = referencedContents.GroupBy(b => b.SchemaUUID);
foreach (var grouping in referecedGrouping)
{
var refContentSelect = new RefContentSelect() { SchemaUUID = grouping.Key };
List<string> titles = new List<string>();
List<Guid> uuids = new List<Guid>();
foreach (var item in referencedContents.Where(b => b.SchemaUUID == grouping.Key))
{
refContentSelect.SchemaName = item.SchemaName;
titles.Add(item.Title);
uuids.Add(item.UUID);
}
refContentSelect.Title = titles.ToArray();
refContentSelect.UUID = uuids.ToArray();
dic.Add("Ref_" + refContentSelect.SchemaName, refContentSelect);
}
//add file attachments
var fileAttachments = contentFiles.Where(f => f.BinaryContent == null).Select(f => f);
dic.Add("Attachments", fileAttachments.ToArray().Select(f => new FileInContent()
{
FileUrl = f.FileUrl,
FilePath = f.FilePath,
ContentFileUUID = f.ContentFileUUID
})
);
dic.Add("Readonly", !workflowService.CanEditContentByStatus(content.Content.UUID, (int)ContentStatus.Published, userName));
//can update ContentStatus
//dic.Add("CanUpdateContentStatus", workflowService.CanEditContentByStatus(content.Content.UUID, (int)ContentStatus.Published, userName));
//Published
dic.Add("Published", (int)dic["ContentStatus"] == (int)ContentStatus.Published);
dic.Add("Application", content.ApplicationName);
return dic;
}
public IEnumerable<IDictionary<string, object>> QueryContentsBySchema(Guid schemaUUID, string application, string queryStatement, string orderBy,
NameValueCollection queryValues, int startIndex, int pageSize, out int contentCount, TimeSpan? cacheTime)
{
IEverestCmsDataContext dataContext = EverestCmsEntities.GetDataContext();
StringBuilder queryExpression = new StringBuilder("(1 <> 1");
var dic = queryValues.ToDictionary();
var baseApps = CachedData.GetBaseApplications(application);
int i = 0;
foreach (var app in baseApps)
{
string param = "application" + i.ToString() + "";
queryExpression.AppendFormat(" OR ApplicationId = {{{0}}}", param);
dic.Add(param, CachedData.GetApplication(app).ApplicationId);
i++;
}
queryExpression.Append(")");
if (!StringExtensions.IsNullOrEmptyTrim(queryStatement))
{
queryExpression.AppendFormat(" AND {0}", queryStatement.Trim());
}
var schema = CachedData.GetSchema(schemaUUID);
contentProvider.TextContentQuerier.SetQueryType(QueryType.All);
var contents = contentProvider.TextContentQuerier.QuerySubContents(dataContext, queryExpression.ToString(), orderBy, dic, schema, null, startIndex, pageSize, cacheTime);
contentCount = contentProvider.TextContentQuerier.CountSubContents(dataContext, queryExpression.ToString(), dic, schema, null, cacheTime);
return contents;
}
#endregion
#region Delete
/// <summary>
/// Delete content
/// </summary>
/// <param name="contentId">content id</param>
/// <param name="userName">the user name.</param>
/// <returns>delete result</returns>
public bool Delete(int contentId, string userName)
{
var dataContext = EverestCmsEntities.GetDataContext();
var content = dataContext.QueryContent(contentId).First();
return this.Delete(dataContext, content, userName);
}
/// <summary>
/// Delete content
/// </summary>
/// <param name="contentUUID">content uuid</param>
/// <param name="userName">the user name.</param>
/// <returns>delete result</returns>
public bool Delete(Guid contentUUID, string userName)
{
var dataContext = EverestCmsEntities.GetDataContext();
var content = dataContext.QueryContent(contentUUID).First();
return this.Delete(dataContext, content, userName);
}
/// <summary>
/// Delete content.
/// </summary>
/// <param name="content">content instance.</param>
/// <param name="userName">the user name.</param>
/// <returns>delte result</returns>
protected bool Delete(IEverestCmsDataContext dataContext, Cms_Content content, string userName)
{
if (BeReferenced(dataContext, content.UUID))
{
throw new Exception(string.Format(Resources.ItemCouldNotBeDeleted, content.Title));
}
else
{
WorkflowService workflowService = UnityManager.Resolve<WorkflowService>();
var canEdit = workflowService.CanEditContentByStatus(content.UUID, content.ContentStatus, userName);
if (!canEdit)
{
throw new Exception(Resources.NotAllowToDelete);
}
content.Cms_SchemaReference.Load(content.Cms_Schema, content.EntityState);
var schema = content.Cms_Schema;
var functions = CachedData.GetFunctionBySchema(schema.UUID, FunctionType.BeforeDelete);
if (functions.Count() > 0)
{
var contentValues = contentProvider.TextContentManager.QueryContent(dataContext, content).ToNameValueCollection();
//
// Updated trigger script prototype
//
// string Execute(IEverestCmsDataContext dataContext, IContentProvider contentProvider, Cms_Content content,NameValueCollection contentValues,Cms_Schema schema)
//
var result = ExecuteContentEvent(content.Cms_Schema.UUID, functions, dataContext, contentProvider, content, contentValues, content.Cms_Schema);
foreach (var r in result)
{
if (r != null && !StringExtensions.IsNullOrEmptyTrim(r.ToString()))
{
throw new Exception(r.ToString());
}
}
}
content.Cms_FolderReference.Load();
var deletedUUID = content.UUID;
var ownFolder = content.Cms_Folder;
List<string> contentFileDirectories = new List<string>();
contentFileDirectories.Add(content.GetContentFileDirectory());
// contentProvider.DeleteContent(content);
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.SubContents.Load();
while (content.SubContents.Count > 0)
{
var subContent = content.SubContents.First();
contentFileDirectories.Add(subContent.GetContentFileDirectory());
dataContext.DeleteObject(subContent);
}
contentProvider.TextContentManager.DeleteContent(dataContext, content);
dataContext.DeleteObject(content);
dataContext.SaveChanges();
dbTrans.Commit();
}
}
#region ContentTrigger
try
{
//delete from index
//content.DeleteFromIndex();
content.ClearVersions();
foreach (var trigger in contentTriggers)
{
trigger.OnDeleted(deletedUUID, ownFolder);
}
}
catch (Exception e)
{
Everest.Library.HealthMonitor.HealthMonitoringLogging.LogError(e);
}
#endregion
try
{
foreach (var dir in contentFileDirectories)
{
if (System.IO.Directory.Exists(dir))
{
System.IO.Directory.Delete(dir, true);
}
}
}
catch { }
CacheManager.RemoveCacheGroup(schema.UUID.ToString());
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="uuid">The UUID.</param>
/// <returns></returns>
private bool BeReferenced(IEverestCmsDataContext dataContext, Guid uuid)
{
if (dataContext.QueryReferencingContents(uuid).Exists())
{
return true;
}
if (dataContext.QueryContentLocalizations(uuid).Exists())
{
return true;
}
return false;
}
#endregion
#region Localize
public virtual Cms_Content Localize(Guid contentUUID, Guid folderUUID, string userName)
{
var dataContext = EverestCmsEntities.GetDataContext();
var folder = dataContext.QueryFolder(folderUUID).First();
folder.aspnet_ApplicationsReference.Load(folder.aspnet_Applications, folder.EntityState);
var originalContent = dataContext.QueryContent(contentUUID).FirstOrDefault();
if (originalContent != null)
{
Cms_Content localizedContent = new Cms_Content();
localizedContent.aspnet_Applications = folder.aspnet_Applications;
localizedContent.ApplicationLevel = localizedContent.aspnet_Applications.ApplicationLevel;
localizedContent.Cms_Folder = folder;
localizedContent.FolderLevel = localizedContent.Cms_Folder.FolderLevel;
localizedContent.Base = originalContent;
localizedContent.UserKey = originalContent.UserKey;
localizedContent.OriginalUUID = originalContent.OriginalUUID;
if (!originalContent.Cms_SchemaReference.IsLoaded)
{
originalContent.Cms_SchemaReference.Load();
}
localizedContent.Cms_Schema = originalContent.Cms_Schema;
localizedContent.Title = originalContent.Title;
localizedContent.ModifiedDate = DateTime.Now;
localizedContent.UserName = userName;
localizedContent.PostDate = DateTime.Now;
//set original content except for the folder
//Cms_ContentLocalized contentLocalized = new Cms_ContentLocalized();
//contentLocalized.Cms_Folder = folder;
//contentLocalized.Cms_Content = originalContent;
//dataContext.AddToCms_ContentLocalized(contentLocalized);
//dataContext.AddToCms_Content(localizedContent);
#region Copy ContentFiles Ref
originalContent.ContentFiles.Load();
foreach (var file in originalContent.ContentFiles)
{
Cms_ContentFile contentFile = new Cms_ContentFile();
file.BinaryContentReference.Load();
contentFile.BinaryContent = file.BinaryContent;
contentFile.FilePath = file.FilePath;
localizedContent.ContentFiles.Add(contentFile);
}
#endregion
#region Copy Ref Contents
originalContent.Cms_ContentReferencing.Load();
foreach (var refContent in originalContent.Cms_ContentReferencing)
{
refContent.Cms_ReferencedContentReference.Load();
Cms_ContentReferencing newRefContent = new Cms_ContentReferencing();
//contentRef.Cms_Content = refContent.Cms_Content;
newRefContent.Cms_ReferencedContent = refContent.Cms_ReferencedContent;
newRefContent.ReferencedContentOriginalUUID = refContent.ReferencedContentOriginalUUID;
localizedContent.Cms_ContentReferencing.Add(newRefContent);
}
#endregion
Exclude(contentUUID, folderUUID);
dataContext.SaveChanges();
WorkflowService workflowService = UnityManager.Resolve<WorkflowService>();
workflowService.StartWorkflow(dataContext, localizedContent);
//copy content
contentProvider.TextContentManager.CopyContent(dataContext, originalContent, localizedContent);
//query
localizedContent.ContentFieldValues = contentProvider.TextContentManager.QueryContent(dataContext, localizedContent);
//check in and add to index..
localizedContent.Checkin(userName, string.Format(Resources.CheckinByLocalization, originalContent.ContentId));
//localizedContent.AddToIndex(localizedContent.ContentFieldValues.ToNameValueCollection());
#region ContentTrigger
try
{
foreach (var trigger in contentTriggers)
{
trigger.OnLocalized(originalContent, localizedContent);
}
}
catch (Exception e)
{
Everest.Library.HealthMonitor.HealthMonitoringLogging.LogError(e);
}
#endregion
//clear the schema cache group
CacheManager.RemoveCacheGroup(localizedContent.Cms_Schema.UUID.ToString());
//return the localized content to edit
return localizedContent;
}
return null;
}
#endregion
#region relations
public IList<Dictionary<string, object>> UserBy(Guid uuid, string dataUrl)
{
var dataContext = EverestCmsEntities.GetDataContext();
IList<Dictionary<string, object>> treeNodes = new List<Dictionary<string, object>>();
#region Referenced By
var referencedByNodes = new TreeNode();
treeNodes.Add(referencedByNodes.Attributes);
referencedByNodes.Text = Resources.ReferencedBy;
referencedByNodes.IconCls = FolderType.TextContent.ToString();
referencedByNodes.Expanded = true;
var referencedBy = dataContext.QueryReferencingContents(uuid)
.Select(c => new
{
c.aspnet_Applications.ApplicationName,
c.UUID,
c.Title
});
referencedByNodes.children = new List<IDictionary<string, object>>();
foreach (var content in referencedBy)
{
var contentNode = new TreeNode();
referencedByNodes.AddChild(contentNode);
contentNode.Text = new UniqueName(content.ApplicationName, content.Title).ToString();
contentNode.IconCls = FolderType.TextContent.ToString();
contentNode.AddAttribute("uuid", content.UUID);
contentNode.AddAttribute("dataUrl", dataUrl);
}
#endregion
#region Localized By
var localizedByNodes = new TreeNode();
treeNodes.Add(localizedByNodes.Attributes);
localizedByNodes.Text = Resources.LocalizedBy;
localizedByNodes.IconCls = FolderType.TextContent.ToString();
localizedByNodes.Expanded = true;
var localizations = dataContext.QueryContentLocalizations(uuid)
.Select(c => new
{
c.aspnet_Applications.ApplicationName,
c.UUID,
c.Title
});
localizedByNodes.children = new List<IDictionary<string, object>>();
foreach (var content in localizations)
{
var contentNode = new TreeNode();
localizedByNodes.AddChild(contentNode);
contentNode.Text = new UniqueName(content.ApplicationName, content.Title).ToString();
contentNode.IconCls = FolderType.TextContent.ToString();
contentNode.AddAttribute("uuid", content.UUID);
contentNode.AddAttribute("dataUrl", dataUrl);
}
#endregion
#region Localize From
var localizeFromNodes = new TreeNode();
treeNodes.Add(localizeFromNodes.Attributes);
localizeFromNodes.Text = Resources.LocalizeFrom;
localizeFromNodes.IconCls = FolderType.TextContent.ToString();
localizeFromNodes.Expanded = true;
var localizeFrom = dataContext.QueryContent(uuid).Where(c => c.Base != null)
.Select(c => new
{
c.Base.aspnet_Applications.ApplicationName,
c.Base.UUID,
c.Base.Title
});
localizeFromNodes.children = new List<IDictionary<string, object>>();
foreach (var content in localizeFrom)
{
var contentNode = new TreeNode();
localizeFromNodes.AddChild(contentNode);
contentNode.Text = new UniqueName(content.ApplicationName, content.Title).ToString();
contentNode.IconCls = FolderType.TextContent.ToString();
contentNode.AddAttribute("uuid", content.UUID);
contentNode.AddAttribute("dataUrl", dataUrl);
}
#endregion
return treeNodes;
}
#endregion
#region For Index
public virtual SearchedContent GetContentForIndex(Guid contentUUID)
{
IContentProvider contentProvider = UnityManager.Resolve<IContentProvider>();
IEverestCmsDataContext dataContext = EverestCmsEntities.GetDataContext();
var content = dataContext.QueryContent(contentUUID).FirstOrDefault();
if (content == null)
{
return null;
}
//delete the draft content.
if (content.ContentStatus == (int)ContentStatus.Draft)
{
return null;
}
var schema = CachedData.GetSchema(content.SchemaUUIDFromReference);
IDictionary<string, object> contentValues;
string queryStatement = string.Format("UUID='{0}'", contentUUID);
if ((SchemaType)schema.SchemaType == SchemaType.Text)
{
contentValues = contentProvider.TextContentQuerier.QueryContent(dataContext, schema
, queryStatement, "", null, null);
}
else
{
contentValues = contentProvider.BinaryContentQuerier.QueryContent(dataContext, queryStatement, "", null, null);
}
if (contentValues == null)
{
return null;
}
if (contentValues["FolderUUID"] == DBNull.Value)
{
return null;
}
content.aspnet_ApplicationsReference.Load(content.aspnet_Applications, content.EntityState);
SearchedContent searchedContent = new SearchedContent();
searchedContent.Title = contentValues["Title"].ToString();
searchedContent.Application = content.aspnet_Applications.ApplicationName;
searchedContent.ContentId = Convert.ToInt32(contentValues["ContentId"]);
searchedContent.ContentUUID = (Guid)contentValues["UUID"];
searchedContent.UserKey = contentValues["UserKey"] == DBNull.Value ? "" : (string)contentValues["UserKey"];
searchedContent.SchemaUUID = (Guid)contentValues["SchemaUUID"];
var folder = CachedData.GetFolder((Guid)contentValues["FolderUUID"]);
searchedContent.FolderUUID = folder.UUID;
searchedContent.OriginalFolderUUID = folder.OriginalUUID;
searchedContent.UserName = (string)contentValues["UserName"];
if (contentValues["BaseUUID"] == DBNull.Value)
{
searchedContent.BaseUUID = null;
}
else
{
searchedContent.BaseUUID = (Guid)contentValues["BaseUUID"];
}
searchedContent.OriginalUUID = (Guid)contentValues["OriginalUUID"];
searchedContent.PostDate = (DateTime)contentValues["PostDate"];
if (contentValues.Keys.Contains("ModifiedDate") && contentValues["ModifiedDate"] != DBNull.Value)
{
searchedContent.ModifiedDate = (DateTime)contentValues["ModifiedDate"];
}
foreach (var column in CachedData.GetColumnsBySchema(schema.UUID))
{
if (column.Indexable != null && column.Indexable.Value == true)
{
searchedContent.ExtendedFields.Add(new ExtendedFieldValue(column.ColumnName, contentValues[column.ColumnName], column.ControlType));
}
}
//categories
StringBuilder categories = new StringBuilder();
var refrencedContent = dataContext.QueryReferencedContents(contentUUID);
foreach (var referencing in refrencedContent)
{
categories.AppendFormat("{0} ,", referencing.Title);
}
searchedContent.Categories = categories.ToString();
//applications
StringBuilder applications = new StringBuilder(content.aspnet_Applications.ApplicationName);
var contentInclusion = dataContext.QueryContentInclusion(contentUUID).Select(c => c.Cms_Folder.aspnet_Applications.ApplicationName).ToArray();
foreach (var includsion in contentInclusion)
{
applications.AppendFormat(" {0}", includsion);
}
searchedContent.Applications = applications.ToString();
//child schemas is Guid
if (!StringExtensions.IsNullOrEmptyTrim(schema.ChildSchemas))
{
searchedContent.ChildContentText = GetChildContentText(dataContext, contentUUID, schema.ChildSchemas);
}
return searchedContent;
}
private string GetChildContentText(IEverestCmsDataContext dataContext, Guid parentContent, string childSchemaUUIDs)
{
string[] childSchemas = childSchemaUUIDs.Split(',');
StringBuilder childContentText = new StringBuilder();
foreach (var childSchemaUUID in childSchemas)
{
if (!StringExtensions.IsNullOrEmptyTrim(childSchemaUUID))
{
var childSchema = CachedData.GetSchema(new Guid(childSchemaUUID));
var childContents = contentProvider.TextContentQuerier.QuerySubContents(dataContext, "", "", null, childSchema,
parentContent, 0, 100, null);
foreach (var item in childContents)
{
childContentText.AppendFormat("{0} ", item["Title"]);
foreach (var column in CachedData.GetColumnsBySchema(childSchema.UUID))
{
if (column.Indexable != null && column.Indexable.Value == true)
{
childContentText.AppendFormat("{0} ", item[column.ColumnName]);
}
}
}
}
}
return childContentText.ToString();
}
#endregion
#region Content Trigger
private IEnumerable<object> ExecuteContentEvent(Guid schemaUUID, IEnumerable<QueriedFunction> functions, params object[] paramsList)
{
try
{
List<object> result = new List<object>();
foreach (var item in functions)
{
var r = DynamicScriptExecutor.Execute(item.Script, "*.Execute", paramsList);
if (r != null)
{
result.Add(r);
}
}
return result;
}
catch (Exception e)
{
throw new Exception(string.Format(Resources.RunTriggerScriptError, e.Message), e);
}
}
#endregion
#region Partial Operation
/// <summary>
/// Gets the categories.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="schemaUUID">The schema UUID.</param>
/// <returns></returns>
public IEnumerable<IDictionary<string, object>> GetCategories(string application, Guid schemaUUID)
{
var schema = CachedData.GetSchema(schemaUUID);
var categories = new List<IDictionary<string, object>>();
if (string.IsNullOrEmpty(schema.ReferencingSchemas))
{
return categories;
}
var categorySchemas = schema.ReferencingSchemas.Split(',');
int count;
foreach (var categorySchema in categorySchemas)
{
Guid guid;
if (GuidHelper.TryParseGuid(categorySchema, out guid))
{
var contents = this.QueryContentsBySchema(guid, application, "", "", new NameValueCollection(), 1, int.MaxValue, out count, TimeSpan.Parse("00:30:00"));
categories.AddRange(contents);
}
}
return categories;
}
/// <summary>
/// Adds the binary content to one text content
/// </summary>
/// <param name="textContentUUID">The text content UUID.</param>
/// <param name="binaryContentUUID">The binary content UUID.</param>
public void AddBinaryContentToContent(Guid textContentUUID, Guid binaryContentUUID)
{
var dataContext = EverestCmsEntities.CreateDataContext(false);
Cms_ContentFile contentFile = new Cms_ContentFile();
var content = dataContext.QueryContent(textContentUUID).First();
contentFile.BinaryContent = dataContext.QueryContent(binaryContentUUID).First();
content.ContentFiles.Add(contentFile);
dataContext.SaveChanges();
}
/// <summary>
/// Removes the content of the binary content from text.
/// </summary>
/// <param name="textContentUUID">The text content UUID.</param>
/// <param name="binaryContentUUID">The binary content UUID.</param>
public void RemoveBinaryContentFromContent(Guid textContentUUID, Guid binaryContentUUID)
{
var dataContext = EverestCmsEntities.CreateDataContext(false);
var contentFile = dataContext.QueryContentFile(textContentUUID, binaryContentUUID).FirstOrDefault();
if (contentFile != null)
{
dataContext.DeleteObject(contentFile);
dataContext.SaveChanges();
}
}
/// <summary>
/// Adds the content of the category to.
/// </summary>
/// <param name="contentUUID">The content UUID.</param>
/// <param name="categoryUUID">The category UUID.</param>
public void AddCategoryToContent(Guid contentUUID, Guid categoryUUID)
{
var dataContext = EverestCmsEntities.CreateDataContext(false);
Cms_ContentReferencing contentRef = new Cms_ContentReferencing();
contentRef.Cms_Content = dataContext.QueryContent(contentUUID).First();
contentRef.Cms_ReferencedContent = dataContext.QueryContent(categoryUUID).First();
contentRef.ReferencedContentOriginalUUID = contentRef.Cms_ReferencedContent.OriginalUUID;
dataContext.AddToCms_ContentReferencing(contentRef);
dataContext.SaveChanges();
}
/// <summary>
/// Removes the content of the category from.
/// </summary>
/// <param name="contentUUID">The content UUID.</param>
/// <param name="categoryUUID">The category UUID.</param>
public void RemoveCategoryFromContent(Guid contentUUID, Guid categoryUUID)
{
var dataContext = EverestCmsEntities.CreateDataContext(false);
var contentRef = dataContext.Cms_ContentReferencing.Where(it => it.Cms_Content.UUID == contentUUID && it.Cms_ReferencedContent.UUID == categoryUUID).FirstOrDefault();
if (contentRef != null)
{
dataContext.DeleteObject(contentRef);
dataContext.SaveChanges();
}
}
#endregion
}
}
|