//public static ExpandoObject GetExpandoForItem(Item item, ModuleConfiguration config) //{ //} public static ExpandoObject GetExpandoForItem(Item item) { var fields = Field.GetAllForDefinition(item.DefinitionGuid); if (fields == null || item == null) { return(null); } dynamic itemExpando = new ExpandoObject(); itemExpando.Guid = item.ItemGuid; itemExpando.SortOrder = item.SortOrder; List <ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(item.ItemGuid); foreach (Field field in fields) { foreach (ItemFieldValue fieldValue in fieldValues) { if (field.FieldGuid == fieldValue.FieldGuid) { ((IDictionary <String, Object>)itemExpando)[field.Name] = fieldValue.FieldValue; } } } return(itemExpando); }
public override void DeleteSiteContent(int siteId) { SiteSettings siteSettings = new SiteSettings(siteId); ItemFieldValue.DeleteBySite(siteSettings.SiteGuid); Item.DeleteBySite(siteSettings.SiteGuid); Field.DeleteBySite(siteSettings.SiteGuid); }
public PopulatedItem(Item item, List <Field> fields) { List <ItemFieldValue> values = ItemFieldValue.GetByItemGuids(new List <Guid> { item.ItemGuid }); new PopulatedItem(item, fields, values); }
public void Post([FromBody] ItemFieldValue value) { // TODO: Add data validation using (var dataContext = new APIDBContext()) { dataContext.ItemFieldValues.Add(value); dataContext.SaveChanges(); } }
public IActionResult Delete(int id) { ItemFieldValue value = new ItemFieldValue(); value.ID = id; db.ItemFieldValues.Remove(value); db.SaveChanges(); return(Ok()); }
/// <summary> /// Saves fields from list to database /// </summary> /// <param name="definedFields"></param> /// <param name="siteGuid"></param> /// <param name="featureGuid"></param> public static void SaveFieldsToDB(List <Field> definedFields, Guid siteGuid, Guid featureGuid, bool deleteOrphans = false) { Guid definitionGuid = definedFields[0].DefinitionGuid; List <Field> savedFields = Field.GetAllForDefinition(definitionGuid, true); FieldComparer fieldComp = new FieldComparer(); SimpleFieldComparer simpleFieldComp = new SimpleFieldComparer(); List <Field> matchedFields = savedFields.Where(i => definedFields.Contains(i, simpleFieldComp)).ToList <Field>(); foreach (Field match in matchedFields) { Field updatedField = definedFields.Where(i => i.Name == match.Name).Single(); if (updatedField != null && !savedFields.Contains(updatedField, fieldComp)) { updatedField.IsDeleted = false; //in case field was deleted, we're going to undelete it updatedField.FieldGuid = match.FieldGuid; updatedField.SiteGuid = match.SiteGuid; updatedField.FeatureGuid = match.FeatureGuid; updatedField.Save(); } } List <Field> newFields = definedFields.Except(matchedFields, simpleFieldComp).ToList(); foreach (Field newField in newFields) { newField.SiteGuid = siteGuid; newField.FeatureGuid = featureGuid; newField.Save(); matchedFields.Add(newField); } savedFields = Field.GetAllForDefinition(definitionGuid, true); /// orphans are those fields which exist in the db but no longer exist in the definition /// if we don't delete the fields, they will continue to show up on the edit page. /// If we delete the fields we have to delete any values associated with them. List <Field> orphans = savedFields.Except(matchedFields, simpleFieldComp).ToList(); if (deleteOrphans) { foreach (Field orphan in orphans) { ItemFieldValue.DeleteByField(orphan.FieldGuid); Field.Delete(orphan.FieldGuid); } } else { foreach (Field orphan in orphans) { Field.MarkAsDeleted(orphan.FieldGuid); } } }
protected void Page_Load(object sender, EventArgs e) { //LoadSettings(); //SetupScripts(); module = new Module(moduleId); moduleTitle = module.ModuleTitle; siteSettings = CacheHelper.GetCurrentSiteSettings(); pageSettings = new PageSettings(siteSettings.SiteId, pageId); if (config.MarkupDefinition != null) { displaySettings = config.MarkupDefinition; } if (config.ProcessItems) { fields = Field.GetAllForDefinition(config.FieldDefinitionGuid); if (config.IsGlobalView) { items = Item.GetAllForDefinition(config.FieldDefinitionGuid, config.DescendingSort); fieldValues = ItemFieldValue.GetItemValuesByDefinition(config.FieldDefinitionGuid); } else { items = Item.GetModuleItems(moduleId, config.DescendingSort); fieldValues = ItemFieldValue.GetItemValuesByModule(module.ModuleGuid); } } if (SiteUtils.IsMobileDevice() && config.MobileMarkupDefinition != null) { displaySettings = config.MobileMarkupDefinition; } if (config.MarkupScripts.Count > 0 || (SiteUtils.IsMobileDevice() && config.MobileMarkupScripts.Count > 0)) { if (SiteUtils.IsMobileDevice() && config.MobileMarkupScripts.Count > 0) { SuperFlexiHelpers.SetupScripts(config.MobileMarkupScripts, config, displaySettings, IsEditable, IsPostBack, ClientID, ModuleId, PageId, Page, this); } else { SuperFlexiHelpers.SetupScripts(config.MarkupScripts, config, displaySettings, IsEditable, IsPostBack, ClientID, ModuleId, PageId, Page, this); } } if (config.MarkupCSS.Count > 0) { SuperFlexiHelpers.SetupStyle(config.MarkupCSS, config, displaySettings, ClientID, ModuleId, PageId, Page, this); } //if (Page.IsPostBack) { return; } PopulateControls(); }
public void Put(int id, [FromBody] ItemFieldValue value) { // TODO: Add data validation value.ID = id; using (var dataContext = new APIDBContext()) { dataContext.ItemFieldValues.Update(value); dataContext.SaveChanges(); } }
public PopulatedItem(Item item) { List <Field> fields = Field.GetAllForDefinition(item.DefinitionGuid); //var itemGuids = items.Select(x => x.ItemGuid).ToList(); List <ItemFieldValue> values = ItemFieldValue.GetByItemGuids(new List <Guid> { item.ItemGuid }); new PopulatedItem(item, fields, values); }
protected override void RenderFieldForDisplay(HtmlTextWriter writer) { if (SPContext.Current.FormContext.FormMode == SPControlMode.New) { writer.Write(" "); } else { writer.Write(ItemFieldValue == null ? " " : SPEncode.HtmlEncode(ItemFieldValue.ToString())); } }
public void Delete(int id) { ItemFieldValue value = new ItemFieldValue(); value.ID = id; using (var dataContext = new APIDBContext()) { dataContext.ItemFieldValues.Remove(value); dataContext.SaveChanges(); } }
public IActionResult Post([FromBody] ItemFieldValue value) { // TODO: Add data validation int itemQuery = Convert.ToInt32(HttpContext.Request.Query["Item"]); int itemFieldQuery = Convert.ToInt32(HttpContext.Request.Query["ItemField"]); value.Item = db.Items.Find(itemQuery); value.ItemField = db.ItemFields.Find(itemFieldQuery); db.ItemFieldValues.Add(value); db.SaveChanges(); return(Ok(value.ID)); }
private bool AreFieldsEqual(Field local, IItemFieldValue remote) { var localField = new ItemFieldValue(local, local.Value); foreach (IFieldComparer comparer in Comparers) { if (!comparer.CanCompare(localField, remote)) { continue; } return(comparer.AreEqual(localField, remote)); } return(false); }
protected override void RenderContents(HtmlTextWriter output) { string featuredImageUrl = string.Empty; featuredImageUrl = String.IsNullOrWhiteSpace(config.InstanceFeaturedImage) ? featuredImageUrl : SiteUtils.GetNavigationSiteRoot() + config.InstanceFeaturedImage; //dynamic expando = new ExpandoObject(); var superFlexiItemClass = CreateClass(); var itemModels = new List <object> (); //var model = expando as IDictionary<string, object>; WidgetModel model = new WidgetModel { Module = new ModuleModel { Id = module.ModuleId, Guid = module.ModuleGuid, Title = module.ModuleTitle, TitleElement = module.HeadElement }, Config = Config, Page = new PageModel { Id = CurrentPage.PageId, Url = CurrentPage.Url, Name = CurrentPage.PageName }, Site = new SiteModel { Id = module.SiteId, SkinPath = SiteUtils.DetermineSkinBaseUrl(SiteUtils.GetSkinName(true, this.Page)) }, SiteRoot = SiteUtils.GetNavigationSiteRoot() }; //dynamic dModel = model; foreach (Item item in items) { var itemObject = Activator.CreateInstance(superFlexiItemClass); bool itemIsEditable = IsEditable || WebUser.IsInRoles(item.EditRoles); bool itemIsViewable = WebUser.IsInRoles(item.ViewRoles) || itemIsEditable; if (!itemIsViewable) { continue; } string itemEditUrl = SiteUtils.GetNavigationSiteRoot() + "/SuperFlexi/Edit.aspx?pageid=" + PageId + "&mid=" + item.ModuleID + "&itemid=" + item.ItemID; SetItemClassProperty(itemObject, "Id", item.ItemID); SetItemClassProperty(itemObject, "Guid", item.ItemGuid); SetItemClassProperty(itemObject, "SortOrder", item.SortOrder); SetItemClassProperty(itemObject, "EditUrl", itemEditUrl); //dynamic itemModel = new ExpandoObject(); //itemModel.Id = item.ItemID; //itemModel.Guid = item.ItemGuid; //itemModel.SortOrder = item.SortOrder; //itemModel.EditUrl = itemEditUrl; List <ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(item.ItemGuid); //foreach (Field field in fields) //{ // foreach (ItemFieldValue fieldValue in fieldValues) // { // if (field.FieldGuid == fieldValue.FieldGuid) // { // if (field.ControlType == "CheckBox") // { // ((IDictionary<string, object>)itemModel)[field.Name] = Convert.ToBoolean(fieldValue.FieldValue); // } // ((IDictionary<string, object>)itemModel)[field.Name] = fieldValue.FieldValue; // } // } //} //var itemModel = new //{ // Id = item.ItemID, // Guid = item.ItemGuid, // SortOrder = item.SortOrder, // EditUrl = itemEditUrl, //}; foreach (Field field in fields) { foreach (ItemFieldValue fieldValue in fieldValues) { if (field.FieldGuid == fieldValue.FieldGuid) { switch (field.ControlType) { case "CheckBox": SetItemClassProperty(itemObject, field.Name, Convert.ToBoolean(fieldValue.FieldValue)); break; case "CheckBoxList": case "DynamicCheckBoxList": SetItemClassProperty(itemObject, field.Name, fieldValue.FieldValue.SplitOnCharAndTrim(';')); break; case "DateTime": case "Date": if (!string.IsNullOrWhiteSpace(fieldValue.FieldValue)) { DateTime.TryParse(fieldValue.FieldValue, out DateTime dt); SetItemClassProperty(itemObject, field.Name, dt); } break; case "TextBox": default: SetItemClassProperty(itemObject, field.Name, fieldValue.FieldValue); break; } } } } itemModels.Add(itemObject); } model.Items = itemModels; var viewPath = config.RelativeSolutionLocation + "/" + config.ViewName; string text; try { text = RazorBridge.RenderPartialToString(viewPath, model, "SuperFlexi"); } catch (Exception ex) { renderDefaultView(ex.ToString()); } void renderDefaultView(string error = "") { if (!string.IsNullOrWhiteSpace(error)) { log.ErrorFormat( "chosen layout ({0}) for _SuperFlexiRazor was not found in skin {1} or SuperFlexi Solution. Perhaps it is in a different skin or Solution. Error was: {2}", config.ViewName, SiteUtils.GetSkinBaseUrl(true, Page), error ); } text = RazorBridge.RenderPartialToString("_SuperFlexiRazor", model, "SuperFlexi"); } output.Write(text); }
public ReturnObject GetFieldValues(RequestObject r) { siteSettings = CacheHelper.GetCurrentSiteSettings(); currentPage = new PageSettings(siteSettings.SiteId, r.PageId); var allowed = false; if (currentPage != null) { allowed = WebUser.IsInRoles(currentPage.AuthorizedRoles); } module = new Module(r.ModuleId); if (module != null) { allowed = WebUser.IsInRoles(module.ViewRoles); } if (!allowed) { return(new ReturnObject() { Status = "error", ExtraData = new Dictionary <string, string> { ["ErrorCode"] = "100", ["ErrorMessage"] = "Not Allowed" } }); } config = new ModuleConfiguration(module); var fieldValues = ItemFieldValue.GetPageOfValues( module.ModuleGuid, config.FieldDefinitionGuid, r.Field, r.PageNumber, r.PageSize, out int totalPages, out int totalRows ); // much of the below is temporary, we needed to implement in a hurry // TODO: implement distinct on sql side var values = new List <string>(); var dbField = new Field(fieldValues.Select(fv => fv.FieldGuid).FirstOrDefault()); switch (dbField.ControlType) { case "DynamicCheckBoxList": foreach (ItemFieldValue val in fieldValues) { values.AddRange(val.FieldValue.SplitOnCharAndTrim(';')); } break; default: values = fieldValues.Select(fv => fv.FieldValue).ToList(); break; //we will add the other cases later } values = values.Distinct().OrderBy(v => v).ToList(); totalRows = values.Count(); return(new ReturnObject() { Status = "success", Data = values, TotalPages = totalPages, TotalRows = totalRows }); }
private IndexItem GetIndexItem(PageSettings pageSettings, int moduleID, Item item) { Module module = new Module(moduleID); log.Debug($"moduleid: {moduleID} for module {module.ModuleTitle}"); ModuleConfiguration config = new ModuleConfiguration(module); if (!config.IncludeInSearch) { return(null); } SuperFlexiDisplaySettings displaySettings = new SuperFlexiDisplaySettings(); ModuleDefinition flexiFeature = new ModuleDefinition(config.FeatureGuid); IndexItem indexItem = new IndexItem(); indexItem.SiteId = pageSettings.SiteId; indexItem.PageId = pageSettings.PageId; indexItem.PageName = pageSettings.PageName; indexItem.ViewRoles = pageSettings.AuthorizedRoles; indexItem.FeatureId = flexiFeature.FeatureGuid.ToString(); indexItem.FeatureName = String.IsNullOrWhiteSpace(config.ModuleFriendlyName) ? module.ModuleTitle : config.ModuleFriendlyName; indexItem.FeatureResourceFile = flexiFeature.ResourceFile; indexItem.ItemId = item.ItemID; indexItem.CreatedUtc = item.CreatedUtc; indexItem.LastModUtc = item.LastModUtc; if (pageSettings.UseUrl) { if (pageSettings.UrlHasBeenAdjustedForFolderSites) { indexItem.ViewPage = pageSettings.UnmodifiedUrl.Replace("~/", string.Empty); } else { indexItem.ViewPage = pageSettings.Url.Replace("~/", string.Empty); } indexItem.UseQueryStringParams = false; } SearchDef searchDef = SearchDef.GetByFieldDefinition(item.DefinitionGuid); bool hasSearchDef = true; if (searchDef == null) { searchDef = new SearchDef(); hasSearchDef = false; } System.Text.StringBuilder sbTitle = new System.Text.StringBuilder(searchDef.Title); System.Text.StringBuilder sbKeywords = new System.Text.StringBuilder(searchDef.Keywords); System.Text.StringBuilder sbDescription = new System.Text.StringBuilder(searchDef.Description); System.Text.StringBuilder sbLink = new System.Text.StringBuilder(searchDef.Link); System.Text.StringBuilder sbLinkQueryAddendum = new System.Text.StringBuilder(searchDef.LinkQueryAddendum); SiteSettings siteSettings = new SiteSettings(pageSettings.SiteGuid); SuperFlexiHelpers.ReplaceStaticTokens(sbTitle, config, false, displaySettings, module, pageSettings, siteSettings, out sbTitle); SuperFlexiHelpers.ReplaceStaticTokens(sbKeywords, config, false, displaySettings, module, pageSettings, siteSettings, out sbKeywords); SuperFlexiHelpers.ReplaceStaticTokens(sbDescription, config, false, displaySettings, module, pageSettings, siteSettings, out sbDescription); SuperFlexiHelpers.ReplaceStaticTokens(sbLink, config, false, displaySettings, module, pageSettings, siteSettings, out sbLink); SuperFlexiHelpers.ReplaceStaticTokens(sbLinkQueryAddendum, config, false, displaySettings, module, pageSettings, siteSettings, out sbLinkQueryAddendum); var fieldValues = ItemFieldValue.GetItemValues(item.ItemGuid); log.Debug($"SuperFlexi Index: total field value count for ItemGuid ({item.ItemGuid}) is {fieldValues.Count}"); foreach (ItemFieldValue fieldValue in fieldValues) { Field field = new Field(fieldValue.FieldGuid); if (field == null || !field.Searchable) { continue; } if (hasSearchDef) { sbTitle.Replace(field.Token, fieldValue.FieldValue); sbKeywords.Replace(field.Token, fieldValue.FieldValue); sbDescription.Replace(field.Token, fieldValue.FieldValue); sbLink.Replace(field.Token, fieldValue.FieldValue); sbLinkQueryAddendum.Replace(field.Token, fieldValue.FieldValue); } else { sbKeywords.Append(fieldValue.FieldValue); } if (debugLog) { log.DebugFormat("RebuildIndex indexing item [{0} = {1}]", field.Name, fieldValue.FieldValue); } } if (hasSearchDef) { sbTitle.Replace("$_ItemID_$", item.ItemID.ToString()); sbKeywords.Replace("$_ItemID_$", item.ItemID.ToString()); sbDescription.Replace("$_ItemID_$", item.ItemID.ToString()); sbLink.Replace("$_ItemID_$", item.ItemID.ToString()); sbLinkQueryAddendum.Replace("$_ItemID_$", item.ItemID.ToString()); indexItem.Content = sbDescription.ToString(); indexItem.Title = sbTitle.ToString(); if (sbLink.Length > 0) { indexItem.ViewPage = sbLink.ToString(); } if (sbLinkQueryAddendum.Length > 0) { indexItem.QueryStringAddendum = sbLinkQueryAddendum.ToString(); indexItem.UseQueryStringParams = false; } } else { indexItem.ModuleTitle = pageSettings.PageName; indexItem.Title = String.IsNullOrWhiteSpace(config.ModuleFriendlyName) ? module.ModuleTitle : config.ModuleFriendlyName; } indexItem.PageMetaKeywords = sbKeywords.ToString(); indexItem.Categories = sbKeywords.ToString(); return(indexItem); }
protected override void RenderFieldForDisplay(HtmlTextWriter writer) { if (ItemFieldValue == null) { writer.Write(" "); return; } if (IsLookupField) { var web = SPContext.Current.Web; if (ItemFieldValue is SPFieldUserValueCollection) { var users = (SPFieldUserValueCollection)ItemFieldValue; writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0"); writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0"); writer.RenderBeginTag(HtmlTextWriterTag.Table); foreach (var user in users) { writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-vb"); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "GoToLinkOrDialogNewWindow(this);return false;"); writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("/_layouts/userdisp.aspx?ID={0}", user.LookupId)); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(SPEncode.HtmlEncode(user.LookupValue)); writer.RenderEndTag(); // a writer.RenderEndTag(); // td writer.RenderEndTag(); // tr } writer.RenderEndTag(); // table return; } if (ItemFieldValue is SPFieldLookupValueCollection) { var field = (SPFieldLookup)Field; var list = web.Lists[new Guid(field.LookupList)]; var lookups = (SPFieldLookupValueCollection)ItemFieldValue; for (var index = 0; index < lookups.Count; index++) { var lookup = lookups[index]; writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "GoToLinkOrDialogNewWindow(this);return false;"); writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("{0}{1}?ID={2}", web.Url, list.DefaultDisplayFormUrl, lookup.LookupId)); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(SPEncode.HtmlEncode(lookup.LookupValue)); writer.RenderEndTag(); // a if (index < lookups.Count - 1) { writer.Write("; "); } } return; } var split = ItemFieldValue.ToString().Split(new [] { ";#" }, StringSplitOptions.None); if (Field is SPFieldUser) { writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "GoToLinkOrDialogNewWindow(this);return false;"); writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("/_layouts/userdisp.aspx?ID={0}", split[0])); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(SPEncode.HtmlEncode(split[1])); writer.RenderEndTag(); // a } else { var field = (SPFieldLookup)Field; var list = web.Lists[new Guid(field.LookupList)]; writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "GoToLinkOrDialogNewWindow(this);return false;"); writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("{0}{1}?ID={2}", web.Url, list.DefaultDisplayFormUrl, split[1])); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(SPEncode.HtmlEncode(split[1])); writer.RenderEndTag(); // a } } else { var values = Convert.ToString(ItemFieldValue).Split(new[] { ";#", "; ", "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries).ToList(); writer.Write(MultiLine ? string.Join("<br/>", values.Select(SPEncode.HtmlEncode).ToArray()) : string.Join("; ", values.Select(SPEncode.HtmlEncode).ToArray())); } }
private void ImportBtn_Click(object sender, EventArgs e) { var results = new StringBuilder(); var importCount = 0; var partialImportCount = 0; var updateCount = 0; var partialUpdateCount = 0; var failCount = 0; if (uploader.HasFile) { var recordsToImport = ImportHelper.GetDynamicListFromCSV(uploader.FileContent); if (recordsToImport != null) { if (chkDelete.Checked) { _ = ItemFieldValue.DeleteByModule(module.ModuleGuid); _ = Item.DeleteByModule(module.ModuleGuid); } foreach (IDictionary <string, object> record in recordsToImport) { var existingGuid = Guid.Empty; var hasGuid = false; if (record.ContainsKey("Guid")) { hasGuid = Guid.TryParse(Convert.ToString(record["Guid"]), out existingGuid); } var isUpdate = true; Item importedItem = null; if (hasGuid && chkUpdate.Checked) { importedItem = new Item(existingGuid); } if (importedItem == null || importedItem.DefinitionGuid != config.FieldDefinitionGuid || importedItem.ModuleGuid != module.ModuleGuid) { //todo: report to user why record isn't being updated isUpdate = false; importedItem = new Item { SiteGuid = siteSettings.SiteGuid, FeatureGuid = config.FeatureGuid, ModuleGuid = module.ModuleGuid, ModuleID = module.ModuleId, DefinitionGuid = config.FieldDefinitionGuid, ItemGuid = Guid.NewGuid() }; } var sortOrder = 500; if (record.ContainsKey("SortOrder")) { var sortOrderStr = Convert.ToString(record["SortOrder"]); if (!string.IsNullOrWhiteSpace(sortOrderStr)) { sortOrder = int.Parse(sortOrderStr); } } importedItem.SortOrder = sortOrder; importedItem.LastModUtc = DateTime.UtcNow; //we don't want to do this on each item that has been imported because that's a lot of work during the import process //importedItem.ContentChanged += new ContentChangedEventHandler(sflexiItem_ContentChanged); if (importedItem.Save()) { var fullyImported = true; //partialCount++; List <Field> fields = null; if (config.FieldDefinitionGuid != Guid.Empty) { fields = Field.GetAllForDefinition(config.FieldDefinitionGuid); } else { //todo: need to show a message about definition guid missing log.ErrorFormat("definitionGuid is missing from the field configuration file named {0}.", config.FieldDefinitionSrc); return; } if (fields == null) { return; } foreach (Field field in fields) { foreach (var kvp in record) { if (field.Name == kvp.Key.Replace(" ", string.Empty)) { List <ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(importedItem.ItemGuid); ItemFieldValue fieldValue = null; try { fieldValue = fieldValues.Where(saved => saved.FieldGuid == field.FieldGuid).Single(); } catch (InvalidOperationException) { //field is probably new fieldValue = new ItemFieldValue(); } //ItemFieldValue fieldValue = new ItemFieldValue(item.ItemGuid, field.FieldGuid); fieldValue.FieldGuid = field.FieldGuid; fieldValue.SiteGuid = field.SiteGuid; fieldValue.FeatureGuid = field.FeatureGuid; fieldValue.ModuleGuid = module.ModuleGuid; fieldValue.ItemGuid = importedItem.ItemGuid; fieldValue.FieldValue = kvp.Value.ToString(); if (!fieldValue.Save()) { fullyImported = false; _ = results.AppendLine(string.Format("<div><strong>Partial Failure:</strong> {0}</div>", string.Join(";", record.Select(x => x.Key + "=" + x.Value)))); } } } } if (fullyImported) { if (isUpdate) { updateCount++; } else { importCount++; } } else { if (isUpdate) { partialUpdateCount++; } else { partialImportCount++; } } } else { failCount++; _ = results.AppendFormat("<div><strong>Failed:</strong> {0}</div>", string.Join(";", record.Select(x => x.Key + "=" + x.Value))); } } _ = results.Insert(0, string.Format(@" <div><strong>Imported</strong> {0}</div> <div><strong>Partially Imported</strong> {1}</div> <div><strong>Updated</strong> {2}</div> <div><strong>Partially Updated</strong> {3}</div> <div><strong>Failed</strong> {4}</div>" , importCount.ToString() , partialImportCount.ToString() , updateCount.ToString() , partialUpdateCount.ToString() , failCount.ToString())); } else { _ = results.Insert(0, "<div class=\"alert alert-danger\">No records found in CSV file</div>"); } litResults.Text = results.ToString(); CacheHelper.ClearModuleCache(moduleId); SuperFlexiIndexBuilderProvider indexBuilder = new SuperFlexiIndexBuilderProvider(); indexBuilder.RebuildIndex(CacheHelper.GetCurrentPage(), IndexHelper.GetSearchIndexPath(siteSettings.SiteId)); SiteUtils.QueueIndexing(); } }
protected virtual bool PasteUnversionedLanguage(Item item, IItemLanguage serializedLanguage, bool newItemWasCreated, List <TemplateMissingFieldException> softErrors, IFieldValueManipulator fieldValueManipulator) { Language language = Language.Parse(serializedLanguage.Language.Name); Item targetItem = item.Database.GetItem(item.ID, language); if (targetItem == null) { // this can occasionally occur when syncing a tpSync config CacheManager.ClearAllCaches(); targetItem = item.Database.GetItem(item.ID, language); } Assert.IsNotNull(targetItem, "Target item language to paste unversioned fields into was null."); bool commitEdit = false; try { targetItem.Editing.BeginEdit(); targetItem.RuntimeSettings.ReadOnlyStatistics = true; targetItem.RuntimeSettings.SaveAll = true; var allTargetUnversionedFields = serializedLanguage.Fields.ToLookup(field => field.FieldId); foreach (Field field in targetItem.Fields) { // field was not serialized. Which means the field is either blank or has its standard value, so let's reset it if (field.Unversioned && fieldValueManipulator?.GetFieldValueTransformer(field.Name) == null && !field.Shared && !allTargetUnversionedFields.Contains(field.ID.Guid) && _fieldFilter.Includes(field.ID.Guid)) { _logger.ResetFieldThatDidNotExistInSerialized(field); field.Reset(); commitEdit = true; } } var transformersArray = fieldValueManipulator?.GetFieldValueTransformers(); List <IFieldValueTransformer> transformersList = new List <IFieldValueTransformer>(); if (transformersArray != null) { transformersList = new List <IFieldValueTransformer>(transformersArray); } foreach (var field in serializedLanguage.Fields) { try { if (PasteField(targetItem, field, newItemWasCreated, fieldValueManipulator)) { commitEdit = true; } var t = transformersList.FirstOrDefault(x => x.FieldName.Equals(field.NameHint)); if (t != null) { transformersList.Remove(t); } } catch (TemplateMissingFieldException tex) { softErrors.Add(tex); } } // Whatever remains here are field transformers that are NOT represented in the serialized data foreach (var t in transformersList) { var fieldMeta = targetItem.Template.GetField(t.FieldName); // If the field doesn't exist on the target template, it's time to just skip if (fieldMeta != null) { if (!fieldMeta.IsUnversioned) { continue; } var existingField = targetItem.Fields[fieldMeta.ID]; if (t.ShouldDeployFieldValue(existingField.Value, null)) { var fakeField = new ItemFieldValue(existingField, null); if (PasteField(targetItem, fakeField, newItemWasCreated, fieldValueManipulator)) { commitEdit = true; } } } } // we commit the edit context - and write to the DB - only if we changed something if (commitEdit) { targetItem.Editing.EndEdit(); return(true); } } finally { if (targetItem.Editing.IsEditing) { targetItem.Editing.CancelEdit(); } } return(false); }
protected virtual Tuple <bool, Item> PasteVersion(Item item, IItemVersion serializedVersion, bool creatingNewItem, List <TemplateMissingFieldException> softErrors, IFieldValueManipulator fieldValueManipulator) { Language language = Language.Parse(serializedVersion.Language.Name); var targetVersion = Version.Parse(serializedVersion.VersionNumber); Item languageItem = item.Database.GetItem(item.ID, language); if (languageItem == null) { throw new InvalidOperationException("Item retrieved from the database was null. This may indicate issues with the Sitecore cache. Recycle your app pool and try again and it should work."); } Item languageVersionItem = languageItem.Versions[targetVersion]; IDictionary <Guid, IItemFieldValue> serializedVersionFieldsLookup = serializedVersion.Fields.ToDictionary(field => field.FieldId); // Add a new version if we need to for the serialized version we're pasting // NOTE: normally Sitecore will return an empty version when requested (e.g. you can ask for 'en#25' and get a blank version back) // so this null check is only here for legacy support if (languageVersionItem == null) { languageVersionItem = languageItem.Versions.AddVersion(); if (languageVersionItem == null) { throw new InvalidOperationException("Failed to add a new version: AddVersion() returned null."); } if (!creatingNewItem) { _logger.AddedNewVersion(languageVersionItem); } } // Based on the note above, in order to detect the modern form where item.Versions[] returns a blank version no matter what, // we need to check again to see if the version we requested is actually currently present on the item or not, so we can correctly log version adds // ReSharper disable once SimplifyLinqExpression if (!languageVersionItem.Versions.GetVersionNumbers().Any(x => x.Number == languageVersionItem.Version.Number)) { if (!creatingNewItem) { _logger.AddedNewVersion(languageVersionItem); } } // begin writing the version data bool commitEdit = false; try { languageVersionItem.Editing.BeginEdit(); languageVersionItem.RuntimeSettings.ReadOnlyStatistics = true; if (languageVersionItem.Versions.Count == 0) { languageVersionItem.Fields.ReadAll(); } // find versioned fields that need to be reset to standard value, because they are not in serialized // (we do all these checks so we can back out of the edit context and avoid a DB write if we don't need one) foreach (Field field in languageVersionItem.Fields) { // if the field is excluded by the fieldFilter if (!_fieldFilter.Includes(field.ID.Guid)) { continue; } // shared/unversioned fields = ignore, those are handled in their own paste methods if (field.Shared || field.Unversioned) { continue; } // if we have a value in the serialized item, we don't need to reset the field if (serializedVersionFieldsLookup.ContainsKey(field.ID.Guid)) { continue; } // If the field manipulator has something to say about the field, we won't reset it (it might not be present in the serialization data, but needs to be forced a value) if (fieldValueManipulator?.GetFieldValueTransformer(field.Name) != null) { continue; } // if the field is one of revision, updated, or updated by we can specially ignore it, because these will get set below if actual field changes occur // so there's no need to reset them as well if (field.ID == FieldIDs.Revision || field.ID == FieldIDs.UpdatedBy || field.ID == FieldIDs.Updated) { continue; } _logger.ResetFieldThatDidNotExistInSerialized(field); field.Reset(); commitEdit = true; } var transformersArray = fieldValueManipulator?.GetFieldValueTransformers(); List <IFieldValueTransformer> transformersList = new List <IFieldValueTransformer>(); if (transformersArray != null) { transformersList = new List <IFieldValueTransformer>(transformersArray); } bool wasOwnerFieldParsed = false; foreach (IItemFieldValue field in serializedVersion.Fields) { if (field.FieldId == FieldIDs.Owner.Guid) { wasOwnerFieldParsed = true; } try { if (PasteField(languageVersionItem, field, creatingNewItem, fieldValueManipulator)) { commitEdit = true; } var t = transformersList.FirstOrDefault(x => x.FieldName.Equals(field.NameHint)); if (t != null) { transformersList.Remove(t); } } catch (TemplateMissingFieldException tex) { softErrors.Add(tex); } } // Whatever remains here are field transformers that are NOT represented in the serialized data for Versioned fields foreach (var t in transformersList) { var fieldMeta = languageVersionItem.Template.GetField(t.FieldName); // If the field doesn't exist on the target template, it's time to just skip if (fieldMeta != null) { // We're only dealing with Versioned fields here if (fieldMeta.IsUnversioned || fieldMeta.IsShared) { continue; } var existingField = languageVersionItem.Fields[fieldMeta.ID]; if (t.ShouldDeployFieldValue(existingField.Value, null)) { var fakeField = new ItemFieldValue(existingField, null); if (PasteField(languageVersionItem, fakeField, creatingNewItem, fieldValueManipulator)) { commitEdit = true; } } } } if (!wasOwnerFieldParsed) { languageVersionItem.Fields[FieldIDs.Owner].Reset(); commitEdit = true; } // if the item came with blank statistics, and we're creating the item or have version updates already, let's set some sane defaults - update revision, set last updated, etc if (creatingNewItem || commitEdit) { if (!serializedVersionFieldsLookup.ContainsKey(FieldIDs.Revision.Guid)) { languageVersionItem.Fields[FieldIDs.Revision].SetValue(Guid.NewGuid().ToString(), true); } if (!serializedVersionFieldsLookup.ContainsKey(FieldIDs.Updated.Guid)) { languageVersionItem[FieldIDs.Updated] = DateUtil.ToIsoDate(DateTime.UtcNow); } if (!serializedVersionFieldsLookup.ContainsKey(FieldIDs.UpdatedBy.Guid)) { languageVersionItem[FieldIDs.UpdatedBy] = @"sitecore\unicorn"; } } // we commit the edit context - and write to the DB - only if we changed something if (commitEdit) { languageVersionItem.Editing.EndEdit(); } } finally { if (languageVersionItem.Editing.IsEditing) { languageVersionItem.Editing.CancelEdit(); } } if (commitEdit) { ClearCaches(languageVersionItem.Database, languageVersionItem.ID); ResetTemplateEngineIfItemIsTemplate(languageVersionItem); } return(new Tuple <bool, Item>(commitEdit, languageVersionItem)); }
protected virtual bool PasteSharedFields(IItemData serializedItemData, Item targetItem, bool newItemWasCreated, List <TemplateMissingFieldException> softErrors, IFieldValueManipulator fieldValueManipulator) { bool commitEdit = false; try { targetItem.Editing.BeginEdit(); targetItem.RuntimeSettings.ReadOnlyStatistics = true; targetItem.RuntimeSettings.SaveAll = true; var allTargetSharedFields = serializedItemData.SharedFields.ToLookup(field => field.FieldId); foreach (Field field in targetItem.Fields) { if (field.Shared && fieldValueManipulator?.GetFieldValueTransformer(field.Name) == null && !allTargetSharedFields.Contains(field.ID.Guid) && _fieldFilter.Includes(field.ID.Guid)) { _logger.ResetFieldThatDidNotExistInSerialized(field); field.Reset(); commitEdit = true; } } var transformersArray = fieldValueManipulator?.GetFieldValueTransformers(); List <IFieldValueTransformer> transformersList = new List <IFieldValueTransformer>(); if (transformersArray != null) { transformersList = new List <IFieldValueTransformer>(transformersArray); } foreach (var field in serializedItemData.SharedFields) { try { if (PasteField(targetItem, field, newItemWasCreated, fieldValueManipulator)) { commitEdit = true; } var t = transformersList.FirstOrDefault(x => x.FieldName.Equals(field.NameHint)); if (t != null) { transformersList.Remove(t); } } catch (TemplateMissingFieldException tex) { softErrors.Add(tex); } } // Whatever remains here are field transformers that are NOT represented in the serialized data shared fields foreach (var t in transformersList) { var fieldMeta = targetItem.Template.GetField(t.FieldName); // If the field doesn't exist on the target template, it's time to just skip if (fieldMeta != null) { // We're only dealing with Shared Fields in this method if (!fieldMeta.IsShared) { continue; } var existingField = targetItem.Fields[fieldMeta.ID]; if (t.ShouldDeployFieldValue(existingField.Value, null)) { var fakeField = new ItemFieldValue(existingField, null); if (PasteField(targetItem, fakeField, newItemWasCreated, fieldValueManipulator)) { commitEdit = true; } } } } // we commit the edit context - and write to the DB - only if we changed something if (commitEdit) { targetItem.Editing.EndEdit(); ClearCaches(targetItem.Database, new ID(serializedItemData.Id)); targetItem.Reload(); ResetTemplateEngineIfItemIsTemplate(targetItem); return(true); } } finally { if (targetItem.Editing.IsEditing) { targetItem.Editing.CancelEdit(); } } return(false); }
private void PopulateControls() { string featuredImageUrl = string.Empty; featuredImageUrl = String.IsNullOrWhiteSpace(config.InstanceFeaturedImage) ? featuredImageUrl : SiteUtils.GetNavigationSiteRoot() + config.InstanceFeaturedImage; //dynamic expando = new ExpandoObject(); var itemModels = new List <dynamic>(); //var model = expando as IDictionary<string, object>; WidgetModel model = new WidgetModel(); model.ModuleGuid = module.ModuleGuid; model.ModuleId = module.ModuleId; model.ModuleTitle = module.ModuleTitle; model.ModuleFriendlyName = config.ModuleFriendlyName; model.SortDescending = config.DescendingSort; model.GlobalView = config.IsGlobalView; model.GlobalViewSortOrder = config.GlobalViewSortOrder; model.Header = config.HeaderContent; model.Footer = config.FooterContent; model.FeaturedImage = featuredImageUrl; model.PageId = pageSettings.PageId; model.PageUrl = pageSettings.Url; model.PageName = pageSettings.PageName; //dynamic dModel = model; foreach (Item item in items) { bool itemIsEditable = isEditable || WebUser.IsInRoles(item.EditRoles); bool itemIsViewable = WebUser.IsInRoles(item.ViewRoles) || itemIsEditable; if (!itemIsViewable) { continue; } string itemEditUrl = SiteUtils.GetNavigationSiteRoot() + "/SuperFlexi/Edit.aspx?pageid=" + pageId + "&mid=" + item.ModuleID + "&itemid=" + item.ItemID; //var itemModel = new ItemModel(); //itemModel.Id = item.ItemID; //itemModel.Guid = item.ItemGuid; //itemModel.SortOrder = item.SortOrder; //itemModel.EditUrl = itemEditUrl; dynamic itemModel = new ExpandoObject(); itemModel.Id = item.ItemID; itemModel.Guid = item.ItemGuid; itemModel.SortOrder = item.SortOrder; itemModel.EditUrl = itemEditUrl; //var itemModel = localexpando as IDictionary<string, object>; //itemModel.Add("Id", item.ItemID); //itemModel.Add("Guid", item.ItemGuid); //itemModel.Add("SortOrder", item.SortOrder); //itemModel.Add("EditUrl", itemEditUrl); List <ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(item.ItemGuid); //using item.ModuleID here because if we are using a 'global view' we need to be sure the item edit link uses the correct module id. //string itemEditLink = itemIsEditable ? String.Format(displaySettings.ItemEditLinkFormat, itemEditUrl) : string.Empty; foreach (Field field in fields) { foreach (ItemFieldValue fieldValue in fieldValues) { if (field.FieldGuid == fieldValue.FieldGuid) { ((IDictionary <String, String>)itemModel)[field.Name] = fieldValue.FieldValue; //var thisItem = itemModel; //itemModel.AddProperty(field.Name.ToString(), fieldValue.FieldValue); //itemModel = thisItem; //dItemModel[field.Name.ToString()] = fieldValue.FieldValue; //itemModel.Add(field.Name.ToString(), fieldValue.FieldValue); } } } itemModels.Add(itemModel); } //dModel["Items"] = itemModels; model.Items = itemModels; //model.AddProperty("Items", itemModels); //theLit.Text = RazorBridge.RenderPartialToString("_SuperFlexiRazor", model, "SuperFlexi"); theLit.Text = RazorBridge.RenderPartialToString("_SuperFlexiRazor", model, "SuperFlexi"); }
public override void DeleteContent(int moduleId, Guid moduleGuid) { ItemFieldValue.DeleteByModule(moduleGuid); Item.DeleteByModule(moduleGuid); Module module = new Module(moduleGuid); ModuleConfiguration config = new ModuleConfiguration(module); //having field definitions in the database when the fields aren't used by any module is just clutter. //we'll delete the field definitions from the database when they aren't used but of course we don't touch the actual field definition XML files. bool deleteOrphanFields = ConfigHelper.GetBoolProperty("SuperFlexi:DeleteFieldDefinitionsWhenNotUsed", true); //we didn't implement the delete handler for a year or so after building superflexi so we have a lot of instances in the wild that probably have orphaned items //if we upgrade those to this version, create a module instance, and then delete it, these orphaned items will be removed bool deleteOrphanItems = ConfigHelper.GetBoolProperty("SuperFlexi:DeleteOrphanedItemsWhenDeletingModules", true); //clean up search definitions bool deleteOrphanSearchDefinitions = ConfigHelper.GetBoolProperty("SuperFlexi:DeleteOrphanedSearchDefinitions", true); if (deleteOrphanFields || deleteOrphanItems || deleteOrphanSearchDefinitions) { List <Item> sflexiItems = Item.GetForModule(module.ModuleId); List <Guid> definitionGuids = new List <Guid>(); foreach (Item item in sflexiItems) { //add definitionGuids here b/c we'll need them for all three checks definitionGuids.Add(item.DefinitionGuid); if (deleteOrphanItems) { Module checkModule = new Module(item.ModuleGuid); if (checkModule == null) { ItemFieldValue.DeleteByModule(item.ModuleGuid); Item.DeleteByModule(item.ModuleGuid); } } } if (deleteOrphanFields) { definitionGuids = definitionGuids.Distinct().ToList(); foreach (Guid guid in definitionGuids) { List <Item> definitionItems = Item.GetForDefinition(guid, module.SiteGuid); if (definitionItems.Count == 0) { //delete field definitions when there are no more modules using them Field.DeleteByDefinition(guid); if (deleteOrphanSearchDefinitions) { //delete search definitions when there are no more modules using their definition SearchDef.DeleteByFieldDefinition(guid); } } } } } }
private void PopulateControls() { string featuredImageUrl = string.Empty; string markupTop = string.Empty; string markupBottom = string.Empty; featuredImageUrl = String.IsNullOrWhiteSpace(config.InstanceFeaturedImage) ? featuredImageUrl : WebUtils.GetRelativeSiteRoot() + config.InstanceFeaturedImage; markupTop = displaySettings.ModuleInstanceMarkupTop; markupBottom = displaySettings.ModuleInstanceMarkupBottom; strOutput.Append(markupTop); if (config.UseHeader && config.HeaderLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.HeaderContent) && !String.Equals(config.HeaderContent, "<p> </p>")) { try { strOutput.Append(string.Format(displaySettings.HeaderContentFormat, config.HeaderContent)); } catch (FormatException ex) { log.ErrorFormat(markupErrorFormat, "HeaderContentFormat", moduleTitle, ex); } } StringBuilder jsonString = new StringBuilder(); StringWriter stringWriter = new StringWriter(jsonString); JsonTextWriter jsonWriter = new JsonTextWriter(stringWriter); // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateTimeZoneHandling.htm jsonWriter.DateTimeZoneHandling = DateTimeZoneHandling.Utc; // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateFormatHandling.htm jsonWriter.DateFormatHandling = DateFormatHandling.IsoDateFormat; string jsonObjName = "sflexi" + module.ModuleId.ToString() + (config.IsGlobalView ? "Modules" : "Items"); if (config.RenderJSONOfData) { jsonWriter.WriteRaw("var " + jsonObjName + " = "); if (config.JsonLabelObjects || config.IsGlobalView) { jsonWriter.WriteStartObject(); } else { jsonWriter.WriteStartArray(); } } List <IndexedStringBuilder> itemsMarkup = new List <IndexedStringBuilder>(); //List<Item> categorizedItems = new List<Item>(); bool usingGlobalViewMarkup = !String.IsNullOrWhiteSpace(displaySettings.GlobalViewMarkup); int currentModuleID = -1; foreach (Item item in items) { bool itemIsEditable = isEditable || WebUser.IsInRoles(item.EditRoles); bool itemIsViewable = WebUser.IsInRoles(item.ViewRoles) || itemIsEditable; if (!itemIsViewable) { continue; } //int itemCount = 0; //StringBuilder content = new StringBuilder(); IndexedStringBuilder content = new IndexedStringBuilder(); ModuleConfiguration itemModuleConfig = new ModuleConfiguration(module); item.ModuleFriendlyName = itemModuleConfig.ModuleFriendlyName; if (String.IsNullOrWhiteSpace(itemModuleConfig.ModuleFriendlyName)) { Module itemModule = new Module(item.ModuleGuid); if (itemModule != null) { item.ModuleFriendlyName = itemModule.ModuleTitle; } } if (config.IsGlobalView) { content.SortOrder1 = itemModuleConfig.GlobalViewSortOrder; content.SortOrder2 = item.SortOrder; } else { content.SortOrder1 = item.SortOrder; } List <ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(item.ItemGuid); //using item.ModuleID here because if we are using a 'global view' we need to be sure the item edit link uses the correct module id. string itemEditUrl = WebUtils.GetSiteRoot() + "/SuperFlexi/Edit.aspx?pageid=" + pageId + "&mid=" + item.ModuleID + "&itemid=" + item.ItemID; string itemEditLink = itemIsEditable ? String.Format(displaySettings.ItemEditLinkFormat, itemEditUrl) : string.Empty; if (config.RenderJSONOfData) { if (config.IsGlobalView) { if (currentModuleID != item.ModuleID) { if (currentModuleID != -1) { jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); } currentModuleID = item.ModuleID; //always label objects in globalview jsonWriter.WritePropertyName("m" + currentModuleID.ToString()); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("Module"); jsonWriter.WriteValue(item.ModuleFriendlyName); jsonWriter.WritePropertyName("Items"); jsonWriter.WriteStartObject(); } } if (config.JsonLabelObjects || config.IsGlobalView) { jsonWriter.WritePropertyName("i" + item.ItemID.ToString()); } jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("ItemId"); jsonWriter.WriteValue(item.ItemID.ToString()); jsonWriter.WritePropertyName("SortOrder"); jsonWriter.WriteValue(item.SortOrder.ToString()); if (IsEditable) { jsonWriter.WritePropertyName("EditUrl"); jsonWriter.WriteValue(itemEditUrl); } } content.Append(displaySettings.ItemMarkup); foreach (Field field in fields) { if (String.IsNullOrWhiteSpace(field.Token)) { field.Token = "$_NONE_$"; //just in case someone has loaded the database with fields without using a source file. } bool fieldValueFound = false; foreach (ItemFieldValue fieldValue in fieldValues) { if (field.FieldGuid == fieldValue.FieldGuid) { fieldValueFound = true; if (String.IsNullOrWhiteSpace(fieldValue.FieldValue) || fieldValue.FieldValue.StartsWith("&deleted&") || fieldValue.FieldValue.StartsWith("&deleted&") || fieldValue.FieldValue.StartsWith("<p>&deleted&</p>") || fieldValue.FieldValue.StartsWith("<p>&deleted&</p>")) { content.Replace("^" + field.Token + "^", string.Empty); content.Replace("^" + field.Token, string.Empty); content.Replace(field.Token + "^", string.Empty); content.Replace(field.Token, string.Empty); } else { if (IsDateField(field)) { DateTime dateTime = new DateTime(); if (DateTime.TryParse(fieldValue.FieldValue, out dateTime)) { /// ^field.Token is used when we don't want the preTokenString and postTokenString to be used content.Replace("^" + field.Token + "^", dateTime.ToString(field.DateFormat)); content.Replace("^" + field.Token, dateTime.ToString(field.DateFormat) + field.PostTokenString); content.Replace(field.Token + "^", field.PreTokenString + dateTime.ToString(field.DateFormat)); content.Replace(field.Token, field.PreTokenString + dateTime.ToString(field.DateFormat) + field.PostTokenString); } } if (IsCheckBoxListField(field) || IsRadioButtonListField(field)) { foreach (CheckBoxListMarkup cblm in config.CheckBoxListMarkups) { if (cblm.Field == field.Name) { StringBuilder cblmContent = new StringBuilder(); List <string> values = fieldValue.FieldValue.SplitOnCharAndTrim(';'); if (values.Count > 0) { foreach (string value in values) { //why did we use _ValueItemID_ here instead of _ItemID_? cblmContent.Append(cblm.Markup.Replace(field.Token, value).Replace("$_ValueItemID_$", item.ItemID.ToString()) + cblm.Separator); cblm.SelectedValues.Add(new CheckBoxListMarkup.SelectedValue { Value = value, ItemID = item.ItemID }); //cblm.SelectedValues.Add(fieldValue); } } cblmContent.Length -= cblm.Separator.Length; content.Replace(cblm.Token, cblmContent.ToString()); } } } //else //{ /// ^field.Token is used when we don't want the preTokenString and postTokenString to be used content.Replace("^" + field.Token + "^", fieldValue.FieldValue); content.Replace("^" + field.Token, fieldValue.FieldValue + field.PostTokenString); content.Replace(field.Token + "^", field.PreTokenString + fieldValue.FieldValue); content.Replace(field.Token, field.PreTokenString + fieldValue.FieldValue + field.PostTokenString); //} } //if (!String.IsNullOrWhiteSpace(field.LinkedField)) //{ // Field linkedField = fields.Find(delegate(Field f) { return f.Name == field.LinkedField; }); // if (linkedField != null) // { // ItemFieldValue linkedValue = fieldValues.Find(delegate(ItemFieldValue fv) { return fv.FieldGuid == linkedField.FieldGuid; }); // content.Replace(linkedField.Token, linkedValue.FieldValue); // } //} if (config.RenderJSONOfData) { jsonWriter.WritePropertyName(field.Name); //if (IsDateField(field)) //{ // DateTime dateTime = new DateTime(); // if (DateTime.TryParse(fieldValue.FieldValue, out dateTime)) // { // jsonWriter.WriteValue(dateTime); // } //} //else //{ jsonWriter.WriteValue(fieldValue.FieldValue); //} } } } if (!fieldValueFound) { content.Replace(field.Token, field.DefaultValue); } } if (config.RenderJSONOfData) { //if (config.IsGlobalView) //{ // jsonWriter.WriteEndObject(); //} jsonWriter.WriteEndObject(); } content.Replace("$_EditLink_$", itemEditLink); content.Replace("$_ItemID_$", item.ItemID.ToString()); content.Replace("$_SortOrder_$", item.SortOrder.ToString()); if (!String.IsNullOrWhiteSpace(content)) { itemsMarkup.Add(content); } } if (config.DescendingSort) { itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b) { int xdiff = b.SortOrder1.CompareTo(a.SortOrder1); if (xdiff != 0) { return(xdiff); } else { return(b.SortOrder2.CompareTo(a.SortOrder2)); } }); } else { itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b) { int xdiff = a.SortOrder1.CompareTo(b.SortOrder1); if (xdiff != 0) { return(xdiff); } else { return(a.SortOrder2.CompareTo(b.SortOrder2)); } }); } StringBuilder allItems = new StringBuilder(); if (displaySettings.ItemsPerGroup == -1) { foreach (IndexedStringBuilder sb in itemsMarkup) { //allItems.Append(displaySettings.GlobalViewModuleGroupMarkup.Replace("$_ModuleGroupName_$", sb.GroupName)); allItems.Append(sb.ToString()); } if (usingGlobalViewMarkup) { strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, displaySettings.GlobalViewMarkup.Replace("$_ModuleGroups_$", allItems.ToString())); } else { strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, allItems.ToString()); } } else { int itemIndex = 0; decimal totalGroupCount = Math.Ceiling(itemsMarkup.Count / Convert.ToDecimal(displaySettings.ItemsPerGroup)); if (totalGroupCount < 1 && itemsMarkup.Count > 0) { totalGroupCount = 1; } int currentGroup = 1; List <StringBuilder> groups = new List <StringBuilder>(); while (currentGroup <= totalGroupCount && itemIndex < itemsMarkup.Count) { StringBuilder group = new StringBuilder(); group.Append(displaySettings.ItemsRepeaterMarkup); //group.SortOrder1 = itemsMarkup[itemIndex].SortOrder1; //group.SortOrder2 = itemsMarkup[itemIndex].SortOrder2; //group.GroupName = itemsMarkup[itemIndex].GroupName; for (int i = 0; i < displaySettings.ItemsPerGroup; i++) { if (itemIndex < itemsMarkup.Count) { group.Replace("$_Items[" + i.ToString() + "]_$", itemsMarkup[itemIndex].ToString()); itemIndex++; } else { break; } } groups.Add(group); currentGroup++; } //groups.Sort(delegate (IndexedStringBuilder a, IndexedStringBuilder b) { // int xdiff = a.SortOrder1.CompareTo(b.SortOrder1); // if (xdiff != 0) return xdiff; // else return a.SortOrder2.CompareTo(b.SortOrder2); //}); foreach (StringBuilder group in groups) { allItems.Append(group.ToString()); } strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, Regex.Replace(allItems.ToString(), @"(\$_Items\[[0-9]+\]_\$)", string.Empty, RegexOptions.Multiline)); } //strOutput.Append(displaySettings.ItemListMarkupBottom); if (config.RenderJSONOfData) { if (config.JsonLabelObjects || config.IsGlobalView) { jsonWriter.WriteEndObject(); if (config.IsGlobalView) { jsonWriter.WriteEndObject(); jsonWriter.WriteEnd(); } } else { jsonWriter.WriteEndArray(); } MarkupScript jsonScript = new MarkupScript(); jsonWriter.Close(); stringWriter.Close(); jsonScript.RawScript = stringWriter.ToString(); jsonScript.Position = config.JsonRenderLocation; jsonScript.ScriptName = "sflexi" + module.ModuleId.ToString() + config.MarkupDefinitionName.ToCleanFileName() + "-JSON"; List <MarkupScript> scripts = new List <MarkupScript>(); scripts.Add(jsonScript); SuperFlexiHelpers.SetupScripts(scripts, config, displaySettings, IsEditable, IsPostBack, ClientID, ModuleId, PageId, Page, this); } if (config.UseFooter && config.FooterLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.FooterContent) && !String.Equals(config.FooterContent, "<p> </p>")) { try { strOutput.AppendFormat(displaySettings.FooterContentFormat, config.FooterContent); } catch (System.FormatException ex) { log.ErrorFormat(markupErrorFormat, "FooterContentFormat", moduleTitle, ex); } } strOutput.Append(markupBottom); SuperFlexiHelpers.ReplaceStaticTokens(strOutput, config, isEditable, displaySettings, module.ModuleId, pageSettings, siteSettings, out strOutput); //this is for displaying all of the selected values from the items outside of the items themselves foreach (CheckBoxListMarkup cblm in config.CheckBoxListMarkups) { StringBuilder cblmContent = new StringBuilder(); if (fields.Count > 0 && cblm.SelectedValues.Count > 0) { Field theField = fields.Where(field => field.Name == cblm.Field).Single(); if (theField != null) { List <CheckBoxListMarkup.SelectedValue> distinctSelectedValues = new List <CheckBoxListMarkup.SelectedValue>(); foreach (CheckBoxListMarkup.SelectedValue selectedValue in cblm.SelectedValues) { CheckBoxListMarkup.SelectedValue match = distinctSelectedValues.Find(i => i.Value == selectedValue.Value); if (match == null) { distinctSelectedValues.Add(selectedValue); } else { match.Count++; } } //var selectedValues = cblm.SelectedValues.GroupBy(selectedValue => selectedValue.Value) // .Select(distinctSelectedValue => new { Value = distinctSelectedValue.Key, Count = distinctSelectedValue.Count(), ItemID = distinctSelectedValue.ItemID }) // .OrderBy(x => x.Value); foreach (CheckBoxListMarkup.SelectedValue value in distinctSelectedValues) { cblmContent.Append(cblm.Markup.Replace(theField.Token, value.Value).Replace("$_ValueItemID_$", value.ItemID.ToString()) + cblm.Separator); cblmContent.Replace("$_CBLValueCount_$", value.Count.ToString()); } } if (cblmContent.Length >= cblm.Separator.Length) { cblmContent.Length -= cblm.Separator.Length; } strOutput.Replace(cblm.Token, cblmContent.ToString()); } strOutput.Replace(cblm.Token, string.Empty); } theLit.Text = strOutput.ToString(); }
public ReturnObject GetModuleItems(RequestObject r) { siteSettings = CacheHelper.GetCurrentSiteSettings(); currentPage = new PageSettings(siteSettings.SiteId, r.PageId); bool allowed = false; bool canEdit = false; if (currentPage != null) { allowed = WebUser.IsInRoles(currentPage.AuthorizedRoles); } module = new Module(r.ModuleId); if (module != null) { allowed = WebUser.IsInRoles(module.ViewRoles); } if (!allowed) { return(new ReturnObject() { Status = "error", ExtraData = new Dictionary <string, string> { ["ErrorCode"] = "100", ["ErrorMessage"] = "Not Allowed" } }); } config = new ModuleConfiguration(module); int totalPages = 0; int totalRows = 0; List <Item> items = new List <Item>(); if (r.SearchObject != null && r.SearchObject.Count > 0) { foreach (var set in r.SearchObject) { if (set.Value.Contains(";")) { foreach (var setA in set.Value.SplitOnCharAndTrim(';')) { items.AddRange(GetItems( module.ModuleGuid, 1, 99999, out totalPages, out totalRows, setA, set.Key, r.GetAllForSolution )); } } else { items.AddRange(GetItems( module.ModuleGuid, 1, 99999, out totalPages, out totalRows, set.Value, set.Key, r.GetAllForSolution )); } //we have to figure out paging with this } items = items.Distinct(new SimpleItemComparer()).ToList(); } else { items.AddRange(GetItems( module.ModuleGuid, r.PageNumber, r.PageSize, out totalPages, out totalRows, r.SearchTerm, r.SearchField, r.GetAllForSolution, r.SortDescending)); } List <PopulatedItem> popItems = new List <PopulatedItem>(); SuperFlexiObject sfObject = new SuperFlexiObject() { FriendlyName = config.ModuleFriendlyName, ModuleTitle = module.ModuleTitle, GlobalSortOrder = config.GlobalViewSortOrder, Items = popItems }; if (items != null && items.Count > 0) { List <Field> fields = Field.GetAllForDefinition(config.FieldDefinitionGuid); var itemGuids = items.Select(x => x.ItemGuid).ToList(); List <ItemFieldValue> values = ItemFieldValue.GetByItemGuids(itemGuids); Module itemModule = null; Guid currentModuleGuid = Guid.Empty; foreach (Item item in items.OrderBy(x => x.ModuleID).ToList()) { if (item.ModuleGuid != currentModuleGuid) { currentModuleGuid = item.ModuleGuid; itemModule = new Module(item.ModuleGuid); } if (itemModule == null) { continue; } if (!WebUser.IsInRoles(itemModule.ViewRoles)) { continue; } var populatedItem = new PopulatedItem(item, fields, values.Where(v => v.ItemGuid == item.ItemGuid).ToList(), canEdit); if (populatedItem != null) { if (r.SearchObject != null && r.SearchObject.Count > 0) { int matchCount = 0; foreach (var searchItem in r.SearchObject) { var value = populatedItem.Values[searchItem.Key]; List <string> itemValArray = value as List <string>; List <string> searchItemValArray = searchItem.Value.SplitOnCharAndTrim(';'); //log.Info($"[{searchItem.Key}]={searchItem.Value}"); /* Check if itemValArray == null because if it is, that means the value is just a plain value, not a List<string>. * If we try to do a comparison on value.ToString() when value is a List<string>, .ToString() returns System.Collections.Generic... * and then our comparison is actually looking for matches in "System.Collections.Generic...". We had that happen with the word * "Collections". Oops. */ if ((itemValArray == null && value.ToString().ToLower().IndexOf(searchItem.Value.ToLower()) >= 0) || (itemValArray != null && itemValArray.Any(s => s.Equals(searchItem.Value, StringComparison.OrdinalIgnoreCase))) || (searchItemValArray != null && searchItemValArray.Any(s => s.Equals(value.ToString(), StringComparison.OrdinalIgnoreCase)))) { matchCount++; } } if (matchCount == r.SearchObject.Count) { popItems.Add(populatedItem); } } else { popItems.Add(populatedItem); } } } } return(new ReturnObject() { Status = "success", Data = sfObject, TotalPages = totalPages, TotalRows = totalRows == popItems.Count ? totalRows : popItems.Count, AllowEdit = ShouldAllowEdit(), CmsModuleId = module.ModuleId, CmsPageId = module.PageId }); }
private void ImportBtn_Click(Object sender, EventArgs e) { StringBuilder results = new StringBuilder(); int importCount = 0; int partialImportCount = 0; int updateCount = 0; int partialUpdateCount = 0; int failCount = 0; if (uploader.HasFile) { var recordsToImport = ImportHelper.GetDynamicListFromCSV(uploader.FileContent); if (recordsToImport != null) { foreach (IDictionary <string, object> record in recordsToImport) { var existingGuid = record.ContainsKey("Guid") ? Guid.Parse(record["Guid"].ToString()) : Guid.Empty; bool isUpdate = true; Item importedItem = null; if (existingGuid != Guid.Empty && chkUpdate.Checked) { importedItem = new Item(existingGuid); } if (importedItem == null || importedItem.DefinitionGuid != config.FieldDefinitionGuid || importedItem.ModuleGuid != module.ModuleGuid) { //todo: report to use why record isn't being updated isUpdate = false; importedItem = new Item(); importedItem.SiteGuid = siteSettings.SiteGuid; importedItem.FeatureGuid = config.FeatureGuid; importedItem.ModuleGuid = module.ModuleGuid; importedItem.ModuleID = module.ModuleId; importedItem.DefinitionGuid = config.FieldDefinitionGuid; importedItem.ItemGuid = Guid.NewGuid(); } int sortOrder = record.ContainsKey("SortOrder") ? int.Parse(record["SortOrder"].ToString()) : 500; importedItem.SortOrder = sortOrder; importedItem.LastModUtc = DateTime.UtcNow; importedItem.ContentChanged += new ContentChangedEventHandler(sflexiItem_ContentChanged); if (importedItem.Save()) { bool fullyImported = true; //partialCount++; List <Field> fields = null; if (config.FieldDefinitionGuid != Guid.Empty) { fields = Field.GetAllForDefinition(config.FieldDefinitionGuid); } else { //todo: need to show a message about definition guid missing log.ErrorFormat("definitionGuid is missing from the field configuration file named {0}.", config.FieldDefinitionSrc); return; } if (fields == null) { return; } foreach (Field field in fields) { foreach (var kvp in record) { if (field.Name == kvp.Key.Replace(" ", string.Empty)) { List <ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(importedItem.ItemGuid); ItemFieldValue fieldValue; try { fieldValue = fieldValues.Where(saved => saved.FieldGuid == field.FieldGuid).Single(); } catch (System.InvalidOperationException ex) { //field is probably new fieldValue = new ItemFieldValue(); } //ItemFieldValue fieldValue = new ItemFieldValue(item.ItemGuid, field.FieldGuid); fieldValue.FieldGuid = field.FieldGuid; fieldValue.SiteGuid = field.SiteGuid; fieldValue.FeatureGuid = field.FeatureGuid; fieldValue.ModuleGuid = module.ModuleGuid; fieldValue.ItemGuid = importedItem.ItemGuid; fieldValue.FieldValue = kvp.Value.ToString(); if (!fieldValue.Save()) { fullyImported = false; results.AppendLine(String.Format("<div><strong>Partial Failure:</strong> {0}</div>", string.Join(";", record.Select(x => x.Key + "=" + x.Value)))); } } } } CacheHelper.ClearModuleCache(importedItem.ModuleID); SiteUtils.QueueIndexing(); if (fullyImported) { if (isUpdate) { updateCount++; } else { importCount++; } } else { if (isUpdate) { partialUpdateCount++; } else { partialImportCount++; } } } else { failCount++; results.AppendFormat("<div><strong>Failed:</strong> {0}</div>", string.Join(";", record.Select(x => x.Key + "=" + x.Value))); } } results.Insert(0, String.Format(@" <div><strong>Imported</strong> {0}</div> <div><strong>Partially Imported</strong> {1}</div> <div><strong>Updated</strong> {2}</div> <div><strong>Partially Updated</strong> {3}</div> <div><strong>Failed</strong> {4}</div>" , importCount.ToString() , partialImportCount.ToString() , updateCount.ToString() , partialUpdateCount.ToString() , failCount.ToString())); } else { results.Insert(0, "<div class=\"alert alert-danger\">No records found in CSV file</div>"); } litResults.Text = results.ToString(); } }
/// <summary> /// Настройка элементов управления для форм /// </summary> protected override void CreateChildControls() { base.CreateChildControls(); if (Field == null) { return; } //чтение свойств поля _connString = Field.GetCustomProperty("ConnectionString").ToString(); _queryString = Field.GetCustomProperty("QueryString").ToString(); _pickerEntityMode = (bool)Field.GetCustomProperty("PickerEntity"); SharedModule.CheckConnectionProperties(FieldName, _connString, _queryString); //В НАДЕЖДЕ НА СВЕТЛОЕ БУДУЩЕЕ //this.multiSelectMode = Field.GetCustomProperty("MultiSelect"); MultiSelectMode = Field.TypeAsString == "CustomExternalLookupMulti"; //создание и настройка контролов для режима отображения if (ControlMode == SPControlMode.Display) { _fieldValueLiteral = TemplateContainer.FindControl("FieldValueLiteral") as EncodedLiteral; if (_fieldValueLiteral == null) { MissingControlException("FieldValueLiteral"); } if (ItemFieldValue != null && ItemFieldValue.ToString() != "") { _fieldValueLiteral.Text = MultiSelectMode ? SharedModule.BuildHtmlForDisplayMultiColumn(ItemFieldValue) : ItemFieldValue.ToString(); } return; } //создание и настройка контролов для режимов создания и редактирования элемента _fieldPanel = TemplateContainer.FindControl("FieldPanel") as Panel; if (_fieldPanel == null) { MissingControlException("FieldPanel"); } _messagesLiteral = TemplateContainer.FindControl("MessagesLiteral") as EncodedLiteral; if (_messagesLiteral == null) { MissingControlException("MessagesLiteral"); } //в настроках включён выбор с помощью EntityPicker'a if (_pickerEntityMode) { _entityEditor = (CustomExternalLookupEditor)TemplateContainer.FindControl("EntityEditor"); if (_entityEditor == null) { MissingControlException("EntityEditor"); } _entityEditor.Visible = true; if (MultiSelectMode) { //множественный выбор _entityEditor.MultiSelect = true; _entityEditor.Rows = 8; _entityEditor.MaximumEntities = 0; _entityEditor.PlaceButtonsUnderEntityEditor = true; } else { _entityEditor.MultiSelect = false; _entityEditor.Rows = 2; _entityEditor.MaximumEntities = 1; _entityEditor.PlaceButtonsUnderEntityEditor = false; } _entityEditor.DialogWidth = 800; _entityEditor.DialogHeight = 600; _entityEditor.ToolTip = Field.Title; } //иначе - выбор из списков else { if (MultiSelectMode) { _listBoxesPanel = TemplateContainer.FindControl("ListBoxesPanel") as Panel; if (_listBoxesPanel == null) { MissingControlException("ListBoxesPanel"); } _listBoxesPanel.Visible = true; _leftListBox = TemplateContainer.FindControl("LeftListBox") as ListBox; if (_leftListBox == null) { MissingControlException("LeftListBox"); } _rightListBox = TemplateContainer.FindControl("RightListBox") as ListBox; if (_rightListBox == null) { MissingControlException("RightListBox"); } _rightListBoxValues = TemplateContainer.FindControl("RightListBoxValues") as HiddenField; if (_rightListBoxValues == null) { MissingControlException("RightListBoxValues"); } //настройка размеров листбоксов для множественного выбора int height = 125, width = 143; object heightTemp = Field.GetCustomProperty("Height"); if (heightTemp != null) { height = Convert.ToInt32(heightTemp); } object widthTemp = Field.GetCustomProperty("Width"); if (widthTemp != null) { width = Convert.ToInt32(widthTemp); } _leftListBox.Width = _rightListBox.Width = width; _leftListBox.Height = _rightListBox.Height = height; //настройка вертикального расположения var vertical = (bool)Field.GetCustomProperty("Vertical"); if (vertical) { var CELGroup1 = TemplateContainer.FindControl("CELGroup1") as Panel; if (CELGroup1 == null) { MissingControlException("CELGroup1"); } var CELGroupButtons = TemplateContainer.FindControl("CELGroupButtons") as Panel; if (CELGroupButtons == null) { MissingControlException("CELGroupButtons"); } var CELGroup2 = TemplateContainer.FindControl("CELGroup2") as Panel; if (CELGroup2 == null) { MissingControlException("CELGroup2"); } CELGroup1.CssClass = CELGroup2.Attributes["class"] = "CELGroupVertical"; CELGroupButtons.CssClass = "CELButtonsVertical"; var AddButton = TemplateContainer.FindControl("AddButton") as Button; if (AddButton == null) { MissingControlException("AddButton"); } var RemoveButton = TemplateContainer.FindControl("RemoveButton") as Button; if (RemoveButton == null) { MissingControlException("RemoveButton"); } AddButton.Text = "∨ Добавить"; RemoveButton.Text = "∧ Удалить"; } } else { _dropDownList = TemplateContainer.FindControl("DropDownList") as DropDownList; if (_dropDownList == null) { MissingControlException("DropDownList"); } _dropDownList.Visible = true; _dropDownList.ToolTip = Field.Title; } } }