using LexBlog.ContentMigration.Classes;
using Sitecore.Data;
using
Sitecore.Data.Fields;
using
Sitecore.Data.Items;
using
Sitecore.Data.Managers;
using
Sitecore.Globalization;
using System;
using
System.Collections.Generic;
using System.Data;
using
System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using
System.Threading.Tasks;
using
Sitecore.Security.Accounts;
using
Sitecore.Resources.Media;
using
System.Text.RegularExpressions;
namespace LexBlog.ContentMigration.Utility
{
public class ImportBlog
{
public void
ImportBlogRecordsUseLess()
{
string destinationPath =
"{E5D9B768-57DF-400F-9858-C6B25D93391C}";
string connetionString =
string.Format(ConnectionString.ConnectionStringDataExcel,
"sampleblog");
string blogURL = "www.sampleblog.com";
string
blogMediaFolderName = "sampleblog";
string
BlogCategoryFolder = "{8B266C45-9EB1-4006-B4BB-BD2B47716878}";
string BlogTagFolder = "{ED84594E-47E2-4FA1-9689-6BCF874DC04F}";
}
public void
ImportBlogRecords()
{
string ParentId = "{0359FC3F-9B7D-4757-98CE-EA79EA1A2F47}";
string TargetTemplateId
= "{A444B71D-D695-44FD-B980-FC062FDD171E}";
List<Item> ParentFolderChildrens = new List<Item>();
Item ParentFolderItem
= Database.GetDatabase("master").GetItem(new Sitecore.Data.ID(ParentId));
ParentFolderChildrens = ParentFolderItem.Axes.GetDescendants().Where(x
=>
x.TemplateID.ToString().ToLower().Equals(TargetTemplateId.ToLower().Trim())).ToList();
var lookupUtility = new LookupUtility();
var allBlogInfo = LexBlogConstants.GetAllBlogInfo();
foreach (var singleBlogInfo in allBlogInfo)
{
try
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "<<<<<<<<<<<<<<<<<<
New blog started >>>>>>>>>" + singleBlogInfo.blogMediaFolderName + Environment.NewLine);
var cnn = LexBlogConstants.GetConnectionStringLocal(singleBlogInfo.connetionString);
var
lookupFolderItem = Database.GetDatabase("master").GetItem(singleBlogInfo.destinationPath);
var query
= "select MainItem.title,
MainItem.post_date, MainItem.main_content, MainItem.post_name,
MainItem.post_id from MainItem where "
+ singleBlogInfo.WhereCluase;
cnn.Open();
SqlCommand cmd = new SqlCommand(query, cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet
dsLookup = new DataSet();
da.Fill(dsLookup);
string
mainItemTitle = string.Empty;
string
mainItemPostDate = string.Empty;
string
mainItemDescription = string.Empty;
string
mainItemPostName = string.Empty;
string
mainItemPostId = string.Empty;
if
(dsLookup.Tables.Count > 0)
{
if
(dsLookup.Tables[0].Rows.Count > 0)
{
for (int row = 0; row <=
dsLookup.Tables[0].Rows.Count - 1; row++)
{
try
{
List<string> Categories = new List<string>();
List<string> Tags = new List<string>();
List<string> Authors = new List<string>();
mainItemTitle = !DBNull.Value.Equals(dsLookup.Tables[0].Rows[row][0]) ? Convert.ToString(dsLookup.Tables[0].Rows[row][0])
: "";
mainItemPostDate = !DBNull.Value.Equals(dsLookup.Tables[0].Rows[row][1]) ? Convert.ToString(dsLookup.Tables[0].Rows[row][1])
: "";
mainItemDescription = !DBNull.Value.Equals(dsLookup.Tables[0].Rows[row][2]) ? Convert.ToString(dsLookup.Tables[0].Rows[row][2])
: "";
mainItemPostName
= !DBNull.Value.Equals(dsLookup.Tables[0].Rows[row][3])
? Convert.ToString(dsLookup.Tables[0].Rows[row][3])
: "";
mainItemPostId = !DBNull.Value.Equals(dsLookup.Tables[0].Rows[row][4]) ? Convert.ToString(dsLookup.Tables[0].Rows[row][4])
: "";
string itemName = (string.IsNullOrEmpty(mainItemTitle)
? (string.IsNullOrEmpty(mainItemPostName)
? string.Empty
: LexBlogConstants.ValidateItemName(mainItemPostName)) : LexBlogConstants.ValidateItemName(mainItemTitle)).Trim();
if (!string.IsNullOrEmpty(itemName))
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + (row + 1).ToString() + " >>>> New Article creation started.
Article Name is ----" + itemName + Environment.NewLine);
string
mediaLinksReplacement = mainItemDescription;
Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
MatchCollection
matches = regx.Matches(mediaLinksReplacement.ToString());
foreach (Match matchedItems in matches)
{
if
(matchedItems.Value.Contains(singleBlogInfo.blogURL)) //To Change
{
var
extension = matchedItems.Value.ToString().Split('.').Last();
if
(extension == "jpg" || extension == "png" || extension == "pdf" || extension == "gif")
{
string
FileName = Path.GetFileName(matchedItems.ToString());
string NewFileName = LexBlogConstants.RemoveSpecialChars(FileName);
NewFileName = NewFileName.Insert(NewFileName.Length - 3, "_");
string filePath = "/sitecore/media
library/LexBlog/Images/Blog Images/" +
singleBlogInfo.blogMediaFolderName + "/" + NewFileName; //To
Change
Item
MediaItem = Database.GetDatabase("master").GetItem(filePath);
if
(MediaItem != null)
{
string
MediaId = MediaItem.ID.ToString().Replace("{", "").Replace("}", "").Replace("-", "").ToLower();
if (!string.IsNullOrEmpty(MediaId))
{
string
ReplacementPath = "~/media/" + MediaId + ".ashx";
mediaLinksReplacement =
mediaLinksReplacement.Replace(matchedItems.ToString(), ReplacementPath);
}
else
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Media
Item does not Exist ----" + FileName + Environment.NewLine);
}
}
else
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Media
Item does not Exist ----" + FileName + Environment.NewLine);
}
}
}
}
var queryCategory = "select Item_Category.nicename, Item_Category.post_id
from Item_Category where post_id = '" +
mainItemPostId + "' order by
nicename";
SqlCommand
cmdCategory = new SqlCommand(queryCategory, cnn);
SqlDataAdapter
daCategory = new SqlDataAdapter(cmdCategory);
DataSet dsLookupCategory
= new DataSet();
daCategory.Fill(dsLookupCategory);
if (dsLookupCategory.Tables.Count
> 0)
{
if
(dsLookupCategory.Tables[0].Rows.Count > 0)
{
for (int rowCategory = 0;
rowCategory <= dsLookupCategory.Tables[0].Rows.Count - 1; rowCategory++)
{
string
CategoryNiceName = !DBNull.Value.Equals(dsLookupCategory.Tables[0].Rows[rowCategory][0])
? Convert.ToString(dsLookupCategory.Tables[0].Rows[rowCategory][0])
: "";
Item
BlogCategoryFolderItem = Database.GetDatabase("master").GetItem(singleBlogInfo.BlogCategoryFolder);
if
(BlogCategoryFolderItem != null)
{
var
CategoryItemId = BlogCategoryFolderItem.Children.Where(x => x.Fields["NiceName"].Value.ToLower().Trim().Equals(CategoryNiceName.ToLower().Trim())).Select(x
=> x.ID.ToString()).FirstOrDefault();
if (!string.IsNullOrEmpty(CategoryItemId))
{
Categories.Add(CategoryItemId);
}
else
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Category
not found. Category Nicename is ----" +
CategoryNiceName + Environment.NewLine);
}
}
else
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Blog
Category Folder does not exist!! ----"
+ Environment.NewLine);
}
}
}
}
var queryTags = "select Item_Tag.nicename, Item_Tag.post_id from
Item_Tag where post_id = '" +
mainItemPostId + "' order by
nicename";
SqlCommand
cmdTags = new SqlCommand(queryTags, cnn);
SqlDataAdapter
daTags = new SqlDataAdapter(cmdTags);
DataSet dsLookupTags = new DataSet();
daTags.Fill(dsLookupTags);
if (dsLookupTags.Tables.Count
> 0)
{
if (dsLookupTags.Tables[0].Rows.Count > 0)
{
for (int rowTags = 0; rowTags <=
dsLookupTags.Tables[0].Rows.Count - 1; rowTags++)
{
string
TagNiceName = !DBNull.Value.Equals(dsLookupTags.Tables[0].Rows[rowTags][0]) ?
Convert.ToString(dsLookupTags.Tables[0].Rows[rowTags][0])
: "";
Item TagFolderItem = Database.GetDatabase("master").GetItem(singleBlogInfo.BlogTagFolder);
if
(TagFolderItem != null)
{
var TagItemId =
TagFolderItem.Children.Where(x => x.Fields["Slug"].Value.ToLower().Trim().Equals(TagNiceName.ToLower().Trim())).Select(x
=> x.ID.ToString()).FirstOrDefault();
if (!string.IsNullOrEmpty(TagItemId))
{
Tags.Add(TagItemId);
}
else
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Tag
not found. Tag Nicename is ----" +
TagNiceName + Environment.NewLine);
}
}
else
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Blog
Tag Folder does not exist!! ----" + Environment.NewLine);
}
}
}
}
var queryAuthors = "select Author.author_display_name, Item_Author.post_id,
Author.author_id, Author.author_email from Item_Author inner join Author on
Item_Author.author_id = Author.author_id where Item_Author.post_id = '" + mainItemPostId + "'
order by Author.author_display_name";
SqlCommand
cmdAuthors = new SqlCommand(queryAuthors, cnn);
SqlDataAdapter
daAuthors = new SqlDataAdapter(cmdAuthors);
DataSet dsLookupAuthors =
new DataSet();
daAuthors.Fill(dsLookupAuthors);
StringBuilder
otherAuthors = null;
if
(dsLookupAuthors.Tables.Count > 0)
{
if
(dsLookupAuthors.Tables[0].Rows.Count > 0)
{
otherAuthors = new StringBuilder();
for (int rowAuthors = 0; rowAuthors <=
dsLookupAuthors.Tables[0].Rows.Count - 1; rowAuthors++)
{
string
AuthorDisplayName = !DBNull.Value.Equals(dsLookupAuthors.Tables[0].Rows[rowAuthors][0])
? Convert.ToString(dsLookupAuthors.Tables[0].Rows[rowAuthors][0])
: "";
string
AuthorId = !DBNull.Value.Equals(dsLookupAuthors.Tables[0].Rows[rowAuthors][2])
? Convert.ToString(dsLookupAuthors.Tables[0].Rows[rowAuthors][2])
: "";
string
AuthorEmail = !DBNull.Value.Equals(dsLookupAuthors.Tables[0].Rows[rowAuthors][3])
? Convert.ToString(dsLookupAuthors.Tables[0].Rows[rowAuthors][3])
: "";
otherAuthors.Append("," +
AuthorDisplayName);
}
}
}
MigratedBlogs
newBlog = new MigratedBlogs();
newBlog.MainItemTitle = mainItemTitle;
newBlog.MainItemPostName =
mainItemPostName;
newBlog.MainItemPostId = mainItemPostId;
newBlog.MainItemDescription = mediaLinksReplacement;
newBlog.MainItemPostDate =
mainItemPostDate;
if (otherAuthors != null && !string.IsNullOrEmpty(Convert.ToString(otherAuthors)))
{
newBlog.OtherAuthors = Convert.ToString(otherAuthors).TrimStart(',');
}
CreateSitecoreItem(singleBlogInfo.destinationPath, itemName, LexBlogConstants.BlogTemplateId,
newBlog, Categories, Tags, Authors);
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Processing
of Item done Successfully!" + Environment.NewLine);
}
}
catch (Exception ex)
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Item
encountered error in For Loop. Item exception is ----"
+ ex + Environment.NewLine);
}
}
}
}
}
catch (Exception ex)
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Error
occured in Main Entry. Error is -----"
+ ex + Environment.NewLine);
}
}
}
public static Item
CreateSitecoreItem(string destinationPath, string itemName, string targetTemplateId, MigratedBlogs itemFields, List<string> blogCats, List<string> blogTags, List<string> blogAuthors)
{
Item sitecoreItem = null;
try
{
// The SecurityDisabler overrides the current security
model, allowing you
// to access the item without any security. It's like
the user being an administrator
using (new Sitecore.SecurityModel.SecurityDisabler())
{
// Get the master database
Database
master = Database.GetDatabase("master");
// Get the place in the site tree where
the new item must be inserted
Item
parentItem = master.GetItem(destinationPath);
if (parentItem != null)
{
// Get the template to base the new
item
BranchItem template = master.GetItem(targetTemplateId);
// Add the item to the site tree
sitecoreItem = parentItem.Add(itemName, template);
}
if
(sitecoreItem != null)
{
using
(new
Sitecore.SecurityModel.SecurityDisabler())
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Blog
Creation Started. Blog Name is
----" + itemName + Environment.NewLine);
LexBlogConstants.SetItemTitles(sitecoreItem,
itemFields.MainItemTitle);
sitecoreItem.Editing.BeginEdit();
sitecoreItem.Fields["Title"].Value = itemFields.MainItemTitle;
sitecoreItem.Fields["Description"].Value = itemFields.MainItemDescription;
sitecoreItem.Fields["PublishDate"].Value = Sitecore.DateUtil.ToIsoDate(Convert.ToDateTime(itemFields.MainItemPostDate));
sitecoreItem.Name
= itemName;
sitecoreItem.Fields["OtherAuthors"].Value
= itemFields.OtherAuthors;
var multiListFldCategory = (MultilistField)sitecoreItem.Fields["Categories"];
foreach (var itemId in blogCats)
{
multiListFldCategory.Add(itemId);
}
var multiListFldTags = (MultilistField)sitecoreItem.Fields["Tags"];
foreach (var itemId in blogTags)
{
multiListFldTags.Add(itemId);
}
var treeListFldAuthors = (MultilistField)sitecoreItem.Fields["Authors"];
foreach (var itemId in blogAuthors)
{
treeListFldAuthors.Add(itemId);
}
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Blog
Creation done successfully!"+ Environment.NewLine);
sitecoreItem.Editing.EndEdit();
}
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "With
Category " + blogCats.Count
+ " Tags=" +
blogTags.Count + " Authors=" + blogAuthors.Count + Environment.NewLine);
}
}
}
catch (Exception ex)
{
File.AppendAllText(LexBlogConstants.LogPath,
Environment.NewLine + "Error
occured during blog creation. Error is -----" + ex + Environment.NewLine);
}
return sitecoreItem;
}
}
}
|