/// <summary> /// </summary> /// <param name="parentId"></param> /// <param name="cmsItem"></param> /// <returns></returns> public bool IfMappedItemExists(string parentId, CmsItem cmsItem) { if (parentId != null) { using (new SecurityDisabler()) { using (new LanguageSwitcher(cmsItem.Language)) { var validName = ItemUtil.ProposeValidItemName(cmsItem.Title); var parent = ContextDatabase.GetItem(new ID(parentId)); if (parent != null) { var items = parent.Axes.SelectItems(string.Format("./*[@@name='{0}' and @GCPath!='']", validName)); if (items != null && items.Any()) { return(true); } } } } } return(false); }
public ActionResult Index(HttpPostedFileBase file, string parentPath) { IEnumerable <Event> events = null; string message = null; using (var reader = new StreamReader(file.InputStream)) { var contents = reader.ReadToEnd(); try { events = JsonConvert.DeserializeObject <IEnumerable <Event> >(contents); } catch (Exception ex) { throw; } } Database database = Sitecore.Configuration.Factory.GetDatabase("master"); Item parentItem = database.GetItem(parentPath); TemplateID templateID = new TemplateID(new ID("{B24333BC-4FD0-43F9-BB4F-A9166EC0968D}")); using (new SecurityDisabler()) { foreach (var ev in events) { string name = ItemUtil.ProposeValidItemName(ev.Name); Item item = parentItem.Add(name, templateID); item.Editing.BeginEdit(); //assign values for all the fields, for example for ContentHeading: item["ContentHeading"] = ev.ContentHeading; item[FieldIDs.Workflow] = "{40EE4287-A777-4B84-8056-4DF0291AFB71}"; item[FieldIDs.WorkflowState] = "{3032ED70-3876-4DB8-9D0E-C93968B92C0B}"; item.Editing.EndEdit(); } } return(View()); }
public override void Process(MediaSyncItemImportArgs args) { Assert.ArgumentNotNull(args, "args"); Assert.ArgumentNotNull(args.Entity, "args.Entity"); Assert.ArgumentNotNull(args.AccountItem, "args.AccountItem"); Assert.ArgumentNotNull(args.Synchronizer, "args.Synchronizer"); if (!this.ValidateActivity(args, SyncAllowActivity.CreateItem)) { return; } if (args.SearchResultItem == null && args.Item == null) { Item rootItem = args.Synchronizer.GetRootItem(args.Entity, args.AccountItem); if (this.CheckCreate(rootItem)) { var mediaData = args.Synchronizer.GetMediaData(args.Entity); string itemName = ItemUtil.ProposeValidItemName(mediaData.EntityName); ID itemId = this.GenerateItemId(args.AccountItem, mediaData); args.Item = this.Create(itemName, mediaData.TemplateId, rootItem, itemId); if (args.Item != null) { LogHelper.Debug(string.Format("Item has been created. Entity:{0}; Item: {1}", args.Entity, args.Item.Uri), this); } else { LogHelper.Debug("Item could not be created. Entity:" + args.Entity, this); } } } }
protected virtual Item CreateMedia(string rootPath, File mediaFile, string extension, Stream mediaStream) { using (new SecurityDisabler()) { var validItemName = ItemUtil.ProposeValidItemName(mediaFile.FileName); var filesFolder = GetItemByPath(rootPath); if (filesFolder != null) { var files = filesFolder.Children; var item = files.FirstOrDefault(f => f.Name == validItemName && DateUtil.IsoDateToDateTime(f.Fields["__Created"].Value) >= mediaFile.UpdatedDate); if (item != null) { return(item); } } var mediaOptions = new MediaCreatorOptions { Database = ContextDatabase, FileBased = false, IncludeExtensionInItemName = false, #if SC72 || SC80 || SC81 KeepExisting = true, //till sc8.2, in 9.0 removed #else OverwriteExisting = false, //from sc8.2 #endif Versioned = false, Destination = string.Concat(rootPath, "/", validItemName) }; var previewImgItem = MediaManager.Creator.CreateFromStream(mediaStream, validItemName + "." + extension, mediaOptions); return(previewImgItem); } }
public JsonResult Upload(string database = "master", string mediaFolderPath = "/sitecore/media library/Uploaded Files") { SitecoreViewModelResult result = new SitecoreViewModelResult(); try { Database db = Factory.GetDatabase(database); if (db == null) { return(result); } foreach (string file in Request.Files) { HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase; if (hpf.ContentLength == 0 || !ValidateFile(hpf, result)) { continue; } string fileName = ItemUtil.ProposeValidItemName(Path.GetFileName(hpf.FileName)); MediaCreatorOptions md = new MediaCreatorOptions(); md.Destination = StringUtil.EnsurePostfix('/', StringUtil.EnsurePrefix('/', mediaFolderPath)) + fileName; md.Database = db; using (new SecurityDisabler()) { Item mediaItem = MediaManager.Creator.CreateFromStream(hpf.InputStream, fileName, md); } } } catch (Exception ex) { Log.Error("could not upload", ex, this); } return(result); }
private void SaveEvents(HttpPostedFileBase file, string parentPath) { Database database = Sitecore.Configuration.Factory.GetDatabase("master"); Item parentItem = database.GetItem(parentPath); TemplateID templateId = new TemplateID(new ID("{372F0C56-2CCF-4352-A479-5CFE8ECE91E7}")); using (new SecurityDisabler()) { foreach (var ev in GetEvents(file)) { string name = ItemUtil.ProposeValidItemName(ev.Name); //if event exists then edit event else add event var item = parentItem.GetChildren().FirstOrDefault(x => x.Name == name); if (item == null) { item = parentItem.Add(name, templateId); } if (item != null) { item.Editing.BeginEdit(); //assign values for all the fields, for example for ContentHeading: item["Name"] = ev.Name; item["ContentHeading"] = ev.ContentHeading; item["ContentIntro"] = ev.ContentIntro; item["Highlights"] = ev.Highlights; item["StartDate"] = Sitecore.DateUtil.ToIsoDate(ev.StartDate); item["Duration"] = ev.Duration.ToString(); item["Difficulty"] = ev.Difficulty.ToString(); item.Editing.EndEdit(); } } } }
private void CreateExecutionReport(string jobName, ID itemID, string logData, string lastRunTime) { try { string contextDbName = Settings.GetSetting(SitecronConstants.SettingsNames.SiteCronContextDB, "master"); Database contextDb = Factory.GetDatabase(contextDbName); //The bucket is not publishable so it will stay only on the master. This way it will not cause any publishing delays. Item executionReportFolderItem = contextDb.GetItem(new ID(SitecronConstants.ItemIds.SiteCronExecutionReportsFolderID)); if (executionReportFolderItem != null) { string newItemName = ItemUtil.ProposeValidItemName(string.Concat(jobName, DateTime.Now.ToString(" dddd MMMM dd yyyy HH mm ss ffff"))); using (new SecurityDisabler()) { Item executionReport = executionReportFolderItem.Add(newItemName, new TemplateID(SitecronConstants.Templates.SiteCronExecutionReportTemplateID)); if (executionReport != null) { executionReport.Editing.BeginEdit(); { executionReport[SitecronConstants.FieldNames.LastRunUTC] = lastRunTime; executionReport[SitecronConstants.FieldNames.Log] = logData; if (!ID.IsNullOrEmpty(itemID)) { executionReport[SitecronConstants.FieldNames.SitecronJob] = itemID.ToString(); } } executionReport.Editing.EndEdit(); } } } } catch (Exception ex) { Log.Error("Sitecron ERROR creating Execution report: " + ex.Message, ex, this); } }
public void Process(Instance item) { counter++; if (counter % 1000 == 0) { Sitecore.Diagnostics.Log.Info("---> Created: " + counter, this); } var place = placesFolder.Add(ItemUtil.ProposeValidItemName(item.Label), placeTemplateId); place.Editing.BeginEdit(); var categoriesField = new MultilistField(place.Fields["categories"]); foreach (var category in item.Categories) { categoriesField.Add(GetCategory(category)); } place["id"] = item.ID; place["label"] = item.Label; place["description"] = item.Description; place["point"] = (item.Point != "" && item.Point != "NULL") ? item.Point : ""; place.Editing.EndEdit(); }
public Item CreateItem(string itemName, Database contentDatabase) { Item item = null; try { Item parentItem = contentDatabase.GetItem(Source); //Now we need to get the template from which the item is created TemplateItem template = contentDatabase.GetTemplate(TagTemplateId); //Now we can add the new item as a child to the parent var name = ItemUtil.ProposeValidItemName(itemName); item = parentItem.Add(name, template); item.Editing.BeginEdit(); item[TitleField] = itemName; item.Editing.EndEdit(); } catch (Exception ex) { Log.Error("TagField - CreateItem method caused an unhandled exception", ex, this); } return(item); }
public override Item UpdateItem(object entity, Item accountItem, Item item) { var labelEntity = (Label)entity; if (item.Parent[FieldIDs.Label.Id] != labelEntity.ParentId) { Item parentItem = this.GetParentItem(labelEntity, accountItem); if (parentItem != null) { item.MoveTo(parentItem); } } using (new EditContext(item)) { item.Name = ItemUtil.ProposeValidItemName(labelEntity.Name); item[FieldIDs.Label.Id] = labelEntity.Id; item[FieldIDs.Label.FullName] = labelEntity.FullName; item[FieldIDs.Label.Name] = labelEntity.Name; } return(item); }
/// <summary>Create tag in tag storage from given TagData</summary> /// <param name="data"></param> /// <returns></returns> protected virtual ID CreateTag(TagData data) { var template = new TemplateItem(Database.GetItem(BucketConfigurationSettings.TagRepositoryId)); var repositoryItem = Context.ContentDatabase.GetItem(_tagRepositoryId); if (repositoryItem == null) { return(null); } var name = ItemUtil.ProposeValidItemName(RemoveDiacritics(data.TagName), "tag"); using (new SecurityDisabler()) { var tagItem = repositoryItem.Add(name, template); if (name == data.TagName) { return(tagItem.ID); } tagItem.Editing.BeginEdit(); tagItem.Fields["__Display Name"].Value = data.TagName; tagItem.Editing.EndEdit(); return(tagItem.ID); } }
public ActionResult Index(HttpPostedFileBase file, string parentPath) { IEnumerable <Event> events = null; string message = null; using (var reader = new System.IO.StreamReader(file.InputStream)) { var contents = reader.ReadToEnd(); try { events = JsonConvert.DeserializeObject <IEnumerable <Event> >(contents); } catch (Exception ex) { // .. } } var database = Sitecore.Configuration.Factory.GetDatabase("master"); var parentItem = database.GetItem(parentPath); var templateID = new TemplateID(new ID("{1CBFF12A-7B97-409F-920C-C3766B93C451}")); using (new SecurityDisabler()) { foreach (var ev in events) { var name = ItemUtil.ProposeValidItemName(ev.ContentHeading); Item item = parentItem.Add(name, templateID); item.Editing.BeginEdit(); item["ContentHeading"] = ev.ContentHeading; item.Editing.EndEdit(); } } return(View()); }
private static void CreateImportedAuthorsInSitecore(Sitecore.Data.Database master, List <WPAuthor> authors, XBlogAuthors xbAuthors) { Sitecore.Data.Items.TemplateItem blogAuthorTemplate = master.GetItem(Author.AuthorTemplateId); foreach (WPAuthor wpa in authors) { try { string authorsName = ItemUtil.ProposeValidItemName(wpa.Name); Author a = xbAuthors.InnerItem.Add(authorsName, blogAuthorTemplate).CreateAs <Author>(); using (new EditContext(a.InnerItem)) { a.InnerItem.SetString(Author.AuthorFullNameFieldId, wpa.Name.Replace(".", " ")); a.InnerItem.SetString(Author.AuthorEmailAddressFieldId, wpa.Email); a.InnerItem.SetString(Author.CreatorFieldId, wpa.Creator); } } catch (Exception ex) { Log.Error("failed to create author: " + wpa.Name + ex.Message, "XB Creator"); } } }
public static Sitecore.Data.Items.MediaItem AddFile(Sitecore.Data.Database database, UploadFileInfo uploadFileInfo, string destination) { var itemName = ItemUtil.ProposeValidItemName(uploadFileInfo.FileNameWithoutExtension); // Create the options var options = new Sitecore.Resources.Media.MediaCreatorOptions(); // Store the file in the database, not as a file options.FileBased = false; // Remove file extension from item name options.IncludeExtensionInItemName = false; // Overwrite any existing file with the same name options.OverwriteExisting = true; // Do not make a versioned template options.Versioned = false; // set the path options.Destination = destination + "/" + itemName; // Set the database options.Database = database; using (var stream = new MemoryStream(uploadFileInfo.Bytes)) { return(Sitecore.Resources.Media.MediaManager.Creator.CreateFromStream(stream, uploadFileInfo.Name, options)); } }
public override Item UpdateItem(object entity, Item accountItem, Item item) { Video video = (Video)entity; using (new EditContext(item)) { item.Name = ItemUtil.ProposeValidItemName(video.Name); item[FieldIDs.MediaElement.Id] = video.Id; item[FieldIDs.MediaElement.Name] = video.Name; item[FieldIDs.MediaElement.ReferenceId] = video.ReferenceId; item[FieldIDs.MediaElement.ThumbnailUrl] = (video.Images != null && video.Images.Thumbnail != null) ? video.Images.Thumbnail.Src?.Replace("http://", "https://") : null; item[FieldIDs.MediaElement.ShortDescription] = video.ShortDescription; item[FieldIDs.Video.CreationDate] = video.CreationDate.ToString(); item[FieldIDs.Video.LongDescription] = video.LongDescription; item[FieldIDs.Video.PublishedDate] = video.PublishedDate.ToString(); item[FieldIDs.Video.LastModifiedDate] = video.LastModifiedDate.ToString(); item[FieldIDs.Video.Economics] = video.Economics.ToString(); item[FieldIDs.Video.LinkUrl] = video.Link != null ? video.Link.URL : null; item[FieldIDs.Video.LinkText] = video.Link != null ? video.Link.Text : null; item[FieldIDs.Video.VideoStillUrl] = (video.Images != null && video.Images.Poster != null) ? video.Images.Poster.Src?.Replace("http://", "https://") : null; item[FieldIDs.Video.CustomFields] = this.GetCustomFields(video); item[FieldIDs.Video.Duration] = video.Duration.HasValue ? video.Duration.ToString() : string.Empty; item[FieldIDs.Video.IngestJobId] = video.IngestJobId; // Sharing section starts if (video.Sharing != null) { item[FieldIDs.Video.ByExternalAcct] = video.Sharing.ByExternalAcct ? "1" : "0"; item[FieldIDs.Video.ById] = video.Sharing.ById; item[FieldIDs.Video.SourceId] = video.Sharing.SourceId; item[FieldIDs.Video.ToExternalAcct] = video.Sharing.ToExternalAcct ? "1" : "0"; item[FieldIDs.Video.ByReference] = video.Sharing.ByReference ? "1" : "0"; } } return(item); }
public ReadResult Read(object source, DataAccessContext context) { if (!(source is JObject jsonObject)) { return(ReadResult.NegativeResult(DateTime.UtcNow)); } var result = ReadResult.NegativeResult(DateTime.UtcNow); var token = jsonObject.SelectToken(this.JsonPath); if (token != null) { var value = IsItemName ? ItemUtil.ProposeValidItemName(token.ToString()) : token.ToString(); result = ReadResult.PositiveResult(HttpUtility.HtmlDecode(value), DateTime.UtcNow); } if (token is JArray tokenArray) { result = ReadResult.PositiveResult(tokenArray.ToObject <string[]>(), DateTime.UtcNow); } return(result); }
public override void Execute(CommandContext context) { Assert.IsNotNull(context, "context"); Assert.IsNotNull(context.Parameters["id"], "id"); string contextDbName = Settings.GetSetting(SitecronConstants.SettingsNames.SiteCronContextDB, "master"); Database contextDb = Factory.GetDatabase(contextDbName); Item scriptItem = contextDb.GetItem(new ID(context.Parameters["id"])); if (scriptItem != null && TemplateManager.IsFieldPartOfTemplate(SitecronConstants.SiteCronFieldIds.CronExpression, scriptItem)) { string newItemName = ItemUtil.ProposeValidItemName(string.Concat("Execute Now ", scriptItem.Name, DateTime.Now.ToString(" yyyyMMddHHmmss"))); Item autoFolderItem = contextDb.GetItem(SitecronConstants.ItemIds.AutoFolderID); if (autoFolderItem != null) { Item newScriptItem = scriptItem.CopyTo(autoFolderItem, newItemName); double addExecutionSeconds = 20; if (!Double.TryParse(Settings.GetSetting(SitecronConstants.SettingsNames.SiteCronExecuteNowSeconds), out addExecutionSeconds)) { addExecutionSeconds = 20; } using (new EditContext(newScriptItem, Sitecore.SecurityModel.SecurityCheck.Disable)) { DateTime executeTime = DateTime.Now.AddSeconds(addExecutionSeconds); newScriptItem[SitecronConstants.FieldNames.CronExpression] = string.Format("{0} {1} {2} 1/1 * ? * ", executeTime.ToString("ss"), executeTime.ToString("mm"), executeTime.ToString("HH")); newScriptItem[SitecronConstants.FieldNames.ArchiveAfterExecution] = "1"; newScriptItem[SitecronConstants.FieldNames.ExecuteExactlyAtDateTime] = ""; newScriptItem[SitecronConstants.FieldNames.Disable] = "0"; } } } }
public ActionResult Index(sc80basicsitecoremvc.Models.CommentForm commentsForm) { using (new SecurityDisabler()) { Database master = Sitecore.Configuration.Factory.GetDatabase("master"); master.GetItem("/sitecore/content/home"); Item item = Sitecore.Context.Database.GetItem(new ID("{C9E3730D-E1C6-466F-9524-DA44861A45CB}")); ID sitecoreID = new Sitecore.Data.ID(item.ID.ToString()); TemplateID templateID = new TemplateID(sitecoreID); string name = ItemUtil.ProposeValidItemName(Sitecore.DateUtil.IsoNow); Item newComment = Sitecore.Context.Item.Add(name, templateID); newComment.Editing.BeginEdit(); newComment.Fields["Comment Author"].Value = commentsForm.CommentsAuthor.ToString(); newComment.Fields["Comment Text"].Value = commentsForm.CommentsText.ToString(); LinkField website = newComment.Fields["Comment Author Website"]; website.Url = commentsForm.CommentsAuthorWebsite.ToString(); website.Text = commentsForm.CommentsAuthorWebsite.ToString(); website.Target = "_blank"; website.LinkType = "external"; newComment.Editing.EndEdit(); } return(View()); }
/// <summary> /// Imports an image into the root of the Sitecore media library /// </summary> /// <param name="sampleImage"></param> public static void ImportImage(string sampleImage) { FileInfo imageFile = new FileInfo(sampleImage); Item parentItem = Sitecore.Context.Database.GetItem("/sitecore/media library"); var mediaCreatorOptions = new MediaCreatorOptions(); mediaCreatorOptions.Database = Sitecore.Context.Database; mediaCreatorOptions.Language = Sitecore.Context.Language; mediaCreatorOptions.Versioned = false; mediaCreatorOptions.Destination = string.Format("{0}/{1}", parentItem.Paths.FullPath, ItemUtil.ProposeValidItemName(Path.GetFileNameWithoutExtension(sampleImage))); mediaCreatorOptions.FileBased = Sitecore.Configuration.Settings.Media.UploadAsFiles; var mc = new MediaCreator(); mc.CreateFromFile(sampleImage, mediaCreatorOptions); }
public ActionResult Index(HttpPostedFileBase file, string parentPath) { IEnumerable <Event> events = null; string message = ""; using (var reader = new System.IO.StreamReader(file.InputStream)) { var contents = reader.ReadToEnd(); try { events = JsonConvert.DeserializeObject <IEnumerable <Event> >(contents); } catch { message = "Error"; } } var database = Sitecore.Configuration.Factory.GetDatabase("master"); var parentItem = database.GetItem(parentPath); var templateID = new TemplateID(new ID("{724BC583-2DAE-40FE-AEF0-9901AA91F476}")); int CountAdded = 0; int CountEdited = 0; using (new SecurityDisabler()) { foreach (var e in events) { var name = ItemUtil.ProposeValidItemName(e.ContentHeading); Item item = parentItem.GetChildren().FirstOrDefault(a => a.Name == name); if (item != null) { // 12.3 optional var id = item.ID; item.Versions.AddVersion(); item = database.GetItem(id); CountEdited++; } else { item = parentItem.Add(name, templateID); CountAdded++; } item.Editing.BeginEdit(); if (item != null && item.State != null) // && !item.State.GetWorkflowState().FinalState) { item[FieldIDs.Workflow] = "{4F39DC00-3194-4F35-BE0A-FA4CCCDE7A37}"; item[FieldIDs.WorkflowState] = "{89AE0EB4-A3B4-43F3-A6B7-05049C3A5411}"; } item["ContentHeading"] = e.ContentHeading; item["ContentIntro"] = e.ContentIntro; item["Difficulty"] = e.Difficulty; item["Duration"] = e.Duration; item["Highlights"] = e.Highlights; item["StartDate"] = DateUtil.ToIsoDate(e.StartDate); item.Editing.EndEdit(); } } TempData["results"] = string.Format("{0} items edited; {1} items added", CountEdited.ToString(), CountAdded.ToString()); TempData["message"] = message; return(View()); }
public override FieldList GetItemFields(ItemDefinition itemDefinition, VersionUri versionUri, CallContext context) { if (this.CanProcessItem(itemDefinition.ID, context)) { context.Abort(); if (context.DataManager.DataSource.ItemExists(itemDefinition.ID)) { ReflectionUtil.CallMethod( typeof(ItemCache), CacheManager.GetItemCache(context.DataManager.Database), "RemoveItem", true, true, new object[] { itemDefinition.ID }); } var sitecoreId = itemDefinition.ID; var key = this.GetIdTableExternalKey(sitecoreId, this.IdTablePrefix); var itemName = this.DataProviderDamHelper.GetItemName(key); if (itemName == "Undefined") { return(base.GetItemFields(itemDefinition, versionUri, context)); } var result = new CoreItem.Builder(itemDefinition.ID, ItemUtil.ProposeValidItemName(Path.GetFileNameWithoutExtension(itemName)), itemDefinition.TemplateID, context.DataManager); result.AddField("__Created", DateTime.Now.ToString(SitecoreDateFormat)); result.AddField("__Updated", DateTime.Now.ToString(SitecoreDateFormat)); result.AddField("__Owner", this.SettingsHelper.GetSetting("Kumquat.IconFormat", "sitecore\\admin")); var fields = this.DataProviderDamHelper.GetItemFields(key); this.DataProviderHelper.MapFields(result, fields, this.DataProviderDamHelper.ProcessingParentFieldNames); var values = result.ItemData.Fields[new ID("{E992FBF9-2F76-4BBA-A613-D17087AA609C}")]; values += result.ItemData.Fields[new ID("{3D70C570-614F-455A-8DEF-E4424033BCC5}")]; var revision = GetHashString(values); result.AddField("__Revision", revision); if (key.StartsWith(this.DataProviderDamHelper.FolderIdPrefix)) { result.AddField("__Sortorder", "1"); return(result.ItemData.Fields); } if (this.DataProviderDamHelper.EnabledMethods.Contains(DataProviderMethods.BlobStreamExists)) { result.AddField("Blob", itemDefinition.ID.ToString()); var iconFormat = this.SettingsHelper.GetSetting("Kumquat.IconFormat", "-/media/{0}.ashx?h=16&thn=1&w=16"); var iconUrl = String.Format(iconFormat, itemDefinition.ID.ToShortID()); result.AddField("__Icon", iconUrl); var extension = ""; if (!String.IsNullOrEmpty(itemName)) { extension = itemName.Split('.').Last(); } var resolver = new MimeResolver(); var mimeType = resolver.GetMimeType(extension); result.AddField("Extension", extension); result.AddField("Mime Type", mimeType); } //result.AddField("Size", fields["size"]); result.AddField("Linked Asset", "1"); result.AddField("__Sortorder", "2"); return(result.ItemData.Fields); } return(base.GetItemFields(itemDefinition, versionUri, context)); }
public virtual string ResolveMediaPath(CmsItem item, Item createdItem, CmsField cmsField) { string path; //Field scField = createdItem.Fields[new ID(cmsField.TemplateField.FieldId)]; //string dataSourcePath = GetItem(scField.ID.ToString())["Source"]; //if (!string.IsNullOrEmpty(dataSourcePath) && GetItem(dataSourcePath) != null) //{ // path = dataSourcePath; //} //else //{ if (string.Equals(item.Template.TemplateName.ToLower(), "deal")) { publishParentMediaFolder = string.Format(DealsFolderRoot + "/{0}/", ItemUtil.ProposeValidItemName(item.Title)); path = string.IsNullOrEmpty(cmsField.TemplateField.FieldName) ? string.Format(DealsFolderRoot + "/{0}/", ItemUtil.ProposeValidItemName(item.Title)) : string.Format(DealsFolderRoot + "/{0}/{1}/", ItemUtil.ProposeValidItemName(item.Title), ItemUtil.ProposeValidItemName(cmsField.TemplateField.FieldName)); SetDatasourcePath(createdItem, cmsField.TemplateField.FieldId, DealsFolderRoot); } else if (string.Equals(item.Template.TemplateName.ToLower(), "event")) { publishParentMediaFolder = string.Format(EventsFolderRoot + "/{0}/", ItemUtil.ProposeValidItemName(item.Title)); path = string.IsNullOrEmpty(cmsField.TemplateField.FieldName) ? string.Format(EventsFolderRoot + "/{0}/", ItemUtil.ProposeValidItemName(item.Title)) : string.Format(EventsFolderRoot + "/{0}/{1}/", ItemUtil.ProposeValidItemName(item.Title), ItemUtil.ProposeValidItemName(cmsField.TemplateField.FieldName)); SetDatasourcePath(createdItem, cmsField.TemplateField.FieldId, EventsFolderRoot); } else { publishParentMediaFolder = string.Format(MediaFolderRoot + "/{0}/", ItemUtil.ProposeValidItemName(item.Title)); path = string.IsNullOrEmpty(cmsField.TemplateField.FieldName) ? string.Format(MediaFolderRoot + "/{0}/", ItemUtil.ProposeValidItemName(item.Title)) : string.Format(MediaFolderRoot + "/{0}/{1}/", ItemUtil.ProposeValidItemName(item.Title), ItemUtil.ProposeValidItemName(cmsField.TemplateField.FieldName)); SetDatasourcePath(createdItem, cmsField.TemplateField.FieldId, MediaFolderRoot); } //} return(path); }
public override IDList GetChildIDs(ItemDefinition itemDefinition, CallContext context) { if (this.CanProcessParent(itemDefinition.ID, context)) { context.Abort(); var idList = new IDList(); ID parentId = itemDefinition.ID; var database = context.DataManager.Database; var actualItem = database.GetItem(parentId); var values = this.DataProviderDamHelper.ProcessingParentFieldNames.ToDictionary(fieldName => fieldName, fieldName => actualItem[fieldName]); var keyList = this.DataProviderDamHelper.GetChildKeys(values); var keys = keyList as string[] ?? keyList.ToArray(); if (!keys.Any()) { return(new IDList()); } foreach (var key in keys) { if (string.IsNullOrEmpty(key)) { continue; } var keyString = key + "|" + parentId.ToShortID(); IDTableEntry idEntry = IDTable.GetID(this.IdTablePrefix, keyString); ID newID; if (idEntry == null) { var itemName = this.DataProviderDamHelper.GetItemName(key); if (itemName == "Undefined") { continue; } newID = ID.NewID; IDTable.Add(this.IdTablePrefix, keyString, newID, parentId, ItemUtil.ProposeValidItemName(Path.GetFileNameWithoutExtension(itemName))); } else { newID = idEntry.ID; } idList.Add(newID); } context.DataManager.Database.Caches.DataCache.Clear(); return(idList); } return(base.GetChildIDs(itemDefinition, context)); }
public async Task <ViewResult> ImportAttributesTypes() { //create the http client to request the json with var httpClient = new HttpClient(); //create the initial response attribute types var responseAttributeTypesList = new List <AttributesTypesModel>(); // create the api response var response = await httpClient.GetAsync("http://atlas.atdw-online.com.au/api/atlas/attributetypes?key=996325374125&out=json"); //check if we get a successs status back if (response.IsSuccessStatusCode) { //try and read the contents and convert them into a json object try { var responseStream = response.Content.ReadAsStringAsync(); //assign the json response to our attributes model responseAttributeTypesList = JsonConvert.DeserializeObject <List <AttributesTypesModel> >(responseStream.Result); } catch (Exception) { //catch the error return(View("AttributesTypesImporter")); } } else { //get the response status code //var errorStatusCode = response.StatusCode; //var responseError = errorStatusCode.ToString(); } //now get the attribute types from the model if (responseAttributeTypesList.Any()) { //get the attribute type templates to use late var atdwSettingsItemId = _standardHelper.GetItemIdFromConfig("ATDWSettingsItemID"); var atdwAttributeTypeTemplateId = _standardHelper.GetTemplateIdFromConfig("ATDWAttributeParentTemplateID"); //check if the template are valid if (atdwAttributeTypeTemplateId.ID != ID.Null) { var database = Sitecore.Configuration.Factory.GetDatabase("master"); //get the atdw settings item to use as the parent to insert the types var atdwSettingsItem = database.GetItem(atdwSettingsItemId); if (atdwSettingsItem != null) { var attributeTypeTemplateId = new TemplateID(atdwAttributeTypeTemplateId); // use the security disabler to create or update items using (new SecurityDisabler()) { //go through the attribute type to add foreach (var attributeType in responseAttributeTypesList) { var attributeTypeCode = attributeType.AttributeTypeId; var hasAttributeType = atdwSettingsItem.Children .Any(typeItem => typeItem.Fields["AttributeTypeId"].Value == attributeTypeCode); if (!hasAttributeType) { var name = ItemUtil.ProposeValidItemName(attributeType.Description); Item attributeTypeItem = atdwSettingsItem.Add(name, attributeTypeTemplateId); try { //initiate the editing attributeTypeItem.Editing.BeginEdit(); // fill in the parents type and description attributeTypeItem["AttributeTypeId"] = attributeType.AttributeTypeId; attributeTypeItem["Description"] = attributeType.Description; //terminate the editing attributeTypeItem.Editing.EndEdit(); } catch (Exception) { attributeTypeItem.Editing.CancelEdit(); //catch the error and return it in the model return(View("AttributesTypesImporter")); } } } } } } } return(View("AttributesTypesImporter")); }
public async Task <ViewResult> AttributesImporter(string attributeType, AttributesModel model) { //create a the counter for the imported attributes var attributeCounter = 0; //check if we have a selected attribute type if (string.IsNullOrWhiteSpace(model.SelectedAttributeType)) { //prefill the model with dropdown items PrepareAttributesModel(model); model.ErrorMessage = "Please select the attribute type to import"; return(View(model)); } //get the selected attribute type var selectedAttributeType = model.SelectedAttributeType; //create the http client to request the json with var httpClient = new HttpClient(); //create the initial response attributes IEnumerable <AttributesJsonModel> responseAttributes; // create the api response var response = await httpClient.GetAsync( "http://atlas.atdw-online.com.au/api/atlas/attributes?key=996325374125&types=" + selectedAttributeType + "&out=json"); //check if we get a successs status back if (response.IsSuccessStatusCode) { //trya and read the contents and convert them into a json object try { var responseStream = response.Content.ReadAsStringAsync(); //assign the json response to our attributes model responseAttributes = JsonConvert .DeserializeObject <IEnumerable <AttributesJsonModel> >(responseStream.Result).ToList(); } catch (Exception ex) { //catch the error //prefill the model with dropdown items PrepareAttributesModel(model); model.ErrorMessage = "There was an error reading the data from ATDW, please try again, see :" + ex.Message; return(View(model)); } } else { //get the response status code var errorStatusCode = response.StatusCode; var responseError = errorStatusCode.ToString(); PrepareAttributesModel(model); model.ErrorMessage = "There was an error reading the data from ATDW, please try again, see :" + responseError; return(View(model)); } //now get the attributes from the model if (responseAttributes.Any()) { //get the attribute templates to use late var atdwSettingsItemId = _standardHelper.GetItemIdFromConfig("ATDWSettingsItemID"); var atdwAttributeTemplateId = _standardHelper.GetTemplateIdFromConfig("ATDWAttributeTemplateID"); var atdwAttributeParentTemplateId = _standardHelper.GetTemplateIdFromConfig("ATDWAttributeParentTemplateID"); //check if the templates are valid if (atdwAttributeTemplateId.ID != ID.Null && atdwAttributeParentTemplateId.ID != ID.Null) { var database = Sitecore.Configuration.Factory.GetDatabase("master"); //get the atdw settings item to look for the parent with var atdwSettingsItem = database.GetItem(atdwSettingsItemId); if (atdwSettingsItem != null) { var atdwAttributeParentItem = atdwSettingsItem.Children .FirstOrDefault(item => item["AttributeTypeId"].ToString() == selectedAttributeType && item.TemplateID == atdwAttributeParentTemplateId); //check if the parent to insert on is not null if (atdwAttributeParentItem != null) { var attributeTemplateId = new TemplateID(atdwAttributeTemplateId); // use the security disabler to creae or update items using (new SecurityDisabler()) { //go through the attributes to add foreach (var attributeTypeItem in responseAttributes) { try { //initiate the editing atdwAttributeParentItem.Editing.BeginEdit(); // fill in the parents type and description atdwAttributeParentItem["AttributeTypeId"] = attributeTypeItem.AttributeTypeId; atdwAttributeParentItem["Description"] = attributeTypeItem.Description; //terminate the editing atdwAttributeParentItem.Editing.EndEdit(); //get the attribute items from the parent if (attributeTypeItem.Attributes.Any()) { foreach (var attribute in attributeTypeItem.Attributes) { //check if the parent doesnt alread have the attribute var attributeCode = attribute.AttributeId; var hasAttribute = atdwAttributeParentItem.Children .Any(attributeItem => attributeItem.Fields["Attribute-Id"].Value == attributeCode); if (!hasAttribute) { //get a valid name from the description var name = ItemUtil.ProposeValidItemName(attribute.Description); //create the new attribute to add Item attributeItem = atdwAttributeParentItem.Add(name, attributeTemplateId); //initiate the editing attributeItem.Editing.BeginEdit(); // fill in the attribute properties attributeItem["Attribute-Type-Id"] = attributeTypeItem.AttributeTypeId; attributeItem["Attribute-Id"] = attribute.AttributeId; attributeItem["Attribute-Description"] = attribute.Description; attributeItem["Attribute-ATDW-Id"] = attribute.AttributeId; //initiate the editing attributeItem.Editing.EndEdit(); attributeCounter++; } } } } catch (Exception ex) { atdwAttributeParentItem.Editing.CancelEdit(); //prefill the model with dropdown items PrepareAttributesModel(model); model.ErrorMessage = "There was an error reading the data from ATDW, please try again, see :" + ex.Message; return(View(model)); } } } } } } } PrepareAttributesModel(model); model.SuccessMessage = attributeCounter + " attributes for the type: " + model.SelectedAttributeType + " have been imported successfully"; return(View(model)); }
public void Process(GenericItemProviderArgs args) { var rootItem = args.RootItem; if (!rootItem.TemplateID.ToString().Equals(ContainerTemplateId)) { return; } if (!Switcher <bool, IntegrationDisabler> .CurrentValue && CacheHelper.IsExpired(rootItem)) { CacheHelper.SetAsCached(rootItem); using (new IntegrationDisabler()) { var startTime = DateTime.Now; var queryPath = rootItem.Paths.FullPath; var entityTemplate = rootItem.Database.GetTemplate(EntityTemplateId); using (new SecurityDisabler()) { using (new BulkUpdateContext()) { foreach (var data in Data.Take(MaxFetch)) { if (!(data is IEntity)) { continue; } var entity = data as IEntity; var entityName = ItemUtil.ProposeValidItemName(entity.GetItemName()); if (entityName.IsNullOrEmpty()) { continue; } var language = ResolveLanguage(entity); var path = string.Format("{0}{1}", StringUtil.EnsurePostfix('/', queryPath), entityName); var startQuery = DateTime.Now; var existingItem = rootItem.Database.GetItem(path); if (existingItem != null && existingItem.HasVersions()) { ProcessExisting(existingItem, entity, language, true); continue; } Logger.Info("item not found creating : " + entityName); ProcessNew(rootItem, entity, entityTemplate, language); var endQuery = DateTime.Now; var timeTaken = endQuery - startQuery; Logger.Info(string.Format("query time : {0} ms for {1}", timeTaken.TotalMilliseconds.ToString(), path)); } } } var endTime = DateTime.Now; Logger.Info("Contract Sync: Start Time {0}, End Time {1}".FormatWith(startTime.ToString(), endTime.ToString())); } } }
/// <summary> /// This is used to get a trimmed down name suitable for Sitecore /// </summary> public static string GetNewItemName(string nameValue, int maxLength) { string newItemName = StripInvalidChars(ItemUtil.ProposeValidItemName(nameValue)); return(TrimText(newItemName, maxLength, string.Empty)); }
public void Process(CreateCommentArgs args) { Assert.ArgumentNotNull(args, "args cannot be null"); Assert.IsNotNull(args.Database, "Database cannot be null"); Assert.IsNotNull(args.Comment, "Comment cannot be null"); Assert.IsNotNull(args.EntryID, "Entry ID cannot be null"); Assert.IsNotNull(args.Language, "Language cannot be null"); var entryItem = args.Database.GetItem(args.EntryID, args.Language); if (entryItem != null) { var blogItem = BlogManager.GetCurrentBlog(entryItem); if (blogItem != null) { var template = args.Database.GetTemplate(blogItem.BlogSettings.CommentTemplateID); var itemName = ItemUtil.ProposeValidItemName(string.Format("Comment at {0} by {1}", GetDateTime().ToString("yyyyMMdd HHmmss"), args.Comment.AuthorName)); if (itemName.Length > 100) { itemName = itemName.Substring(0, 100); } // verify the comment item name is unique for this entry var query = BuildFastQuery(entryItem, itemName); var num = 1; var nondupItemName = itemName; while (entryItem.Database.SelectSingleItem(query) != null) { nondupItemName = itemName + " " + num; num++; query = BuildFastQuery(entryItem, nondupItemName); } // need to create the comment within the shell site to ensure workflow is applied to comment var shellSite = SiteContextFactory.GetSiteContext(Sitecore.Constants.ShellSiteName); SiteContextSwitcher siteSwitcher = null; try { if (shellSite != null) { siteSwitcher = new SiteContextSwitcher(shellSite); } using (new SecurityDisabler()) { var newItem = entryItem.Add(nondupItemName, template); var newComment = new CommentItem(newItem); newComment.BeginEdit(); newComment.Name.Field.Value = args.Comment.AuthorName; newComment.Email.Field.Value = args.Comment.AuthorEmail; newComment.Comment.Field.Value = args.Comment.Text; foreach (var entry in args.Comment.Fields) { newComment.InnerItem[entry.Key] = entry.Value; } newComment.EndEdit(); args.CommentItem = newComment; } } finally { siteSwitcher?.Dispose(); } } else { var message = "Failed to find blog for entry {0}\r\nIgnoring comment: name='{1}', email='{2}', commentText='{3}'"; Logger.Error(string.Format(message, args.EntryID, args.Comment.AuthorName, args.Comment.AuthorEmail, args.Comment.Text), typeof(CreateCommentItem)); } } else { var message = "Failed to find blog entry {0}\r\nIgnoring comment: name='{1}', email='{2}', commentText='{3}'"; Logger.Error(string.Format(message, args.EntryID, args.Comment.AuthorName, args.Comment.AuthorEmail, args.Comment.Text), typeof(CreateCommentItem)); } }
private Item InstallValueFolder(DemandbaseAttribute attribute, Item defaultValuesFolder) { Item folder = defaultValuesFolder.Database.DataManager.DataEngine.CreateItem(ItemUtil.ProposeValidItemName(attribute.Name), defaultValuesFolder, new ID(DemandbaseConstants.ValueListTemplateId), GuidUtility.GetId("demandbasevaluefolder" + defaultValuesFolder.ID, attribute.Id)); folder.BeginVersionCheckEditing(); folder["Attribute Id"] = attribute.Id; folder.Editing.EndEdit(); foreach (string value in attribute.DefaultValues) { InstallValue(attribute, value, folder); } return(folder); }
//Save the Feed to Sitecore private void ProcessNewBlogItem(IBlogItem doc) { string message = string.Format("Creating New Item [docId:{0}] - \"{1}\"", doc.Id, doc.BlogTitle); Sitecore.Diagnostics.Log.Error(message, "RssFeedImport"); IBlogItem blog = null; var masterDb = Database.GetDatabase("master"); var item = masterDb.GetItem("/sitecore/system/Modules/RSSFeedSettings"); Sitecore.Data.Fields.LinkField linkField = item.Fields["BlogLocation"]; Guid folderTemplateId = IBlog_FolderConstants.TemplateId.Guid; DateTime rsspubdate = new DateTime(); if (doc.BlogDisplayDate != null) { rsspubdate = System.Convert.ToDateTime(doc.BlogDisplayDate.ToString()); } ; var year = rsspubdate.Year; var month = rsspubdate.Month; var rootItemId = new ID(new Guid(BlogFeedLocId)); var parentPubItem = masterDb.GetItem(rootItemId); var yearFolder = BlogImportHelper.EnsureChildFolder(parentPubItem, year.ToString(), folderTemplateId); var monthFolder = BlogImportHelper.EnsureChildFolder(yearFolder, month.ToString("00"), folderTemplateId); using (new Sitecore.SecurityModel.SecurityDisabler()) { var itemname = ItemUtil.ProposeValidItemName(doc.BlogTitle); var blogItem = monthFolder.Add(itemname, new TemplateID(IBlogItemConstants.TemplateId)); var db = Sitecore.Configuration.Factory.GetDatabase("master"); if (db != null) { if (blogItem != null) { blogItem.Fields.ReadAll(); blogItem.Editing.BeginEdit(); try { //Should be able to add name here blogItem.Fields["BlogID"].Value = doc.BlogID; blogItem.Fields["BlogTitle"].Value = doc.BlogTitle; blogItem.Fields["BlogAbstract"].Value = doc.BlogAbstract; blogItem.Fields["BlogDisplayDate"].Value = doc.BlogDisplayDate; blogItem.Fields["BlogSourceUrl"].Value = doc.BlogSourceUrl; } catch (Exception ex) { Sitecore.Diagnostics.Log.Error("Error while creating the New Item: " + BlogName + ": " + ex.Message, "RssFeedImport"); } blogItem.Editing.EndEdit(); } } } }