protected virtual IEnumerable<Field> GetTypedFields(ClientContext context, FieldCollection items) { context.Load(items); context.ExecuteQueryWithTrace(); return items.ToArray(); }
public bool GetBoolValue(FieldCollection fc, string fieldName, bool defaultValue) { if (!IsEmptyStrField(fc, fieldName)) return fc[fieldName].GetValueAsBool(); return defaultValue; }
protected override IEnumerable<Field> GetTypedFields(ClientContext context, FieldCollection items) { var typedFields = context.LoadQuery(items.Where(i => i.FieldTypeKind == FieldType.User)); context.ExecuteQueryWithTrace(); return typedFields; }
protected override IEnumerable<Field> GetTypedFields(ClientContext context, FieldCollection items) { var typedFields = context.LoadQuery(items.Where(i => i.TypeAsString == BuiltInPublishingFieldTypes.HTML)); context.ExecuteQueryWithTrace(); return typedFields; }
/// <summary> /// 自动读数据库载入数据的构造函数 /// </summary> /// <param name="tablename">表名</param> /// <param name="db">操作数据类</param> /// <param name="IsLoadDt">是否从数据库载入数据到类中</param> /// <param name="fields">Field集合</param> public DataOperation_Complex(string DefConnID, string DefTableID, FieldCollection fc) { _dbConn_fc_Dir = new Dictionary<string, Dictionary<string, FieldCollection>>(); _fields = fc.Clone(); defaultConnID = DefConnID; defaultTableID = DefTableID; decompose(_fields); }
public DateTime GetDateTimeValue(FieldCollection fc, string fieldName, DateTime defaultValue) { if (!IsEmptyStrField(fc, fieldName)) //if (fc[fieldName].AllowModify) return fc[fieldName].GetValueAsDateTime(); return defaultValue; }
public decimal GetDecimalValue(FieldCollection fc, string fieldName, decimal defaultValue) { if (!IsEmptyStrField(fc, fieldName)) //if (fc[fieldName].AllowModify) return fc[fieldName].GetValueAsDecimal(); return defaultValue; }
public static void RegisterWAPMessage(FieldCollection fc) { if (fc == null) return; if(MessageDict.ContainsKey(GetWAPMessageID(fc))) return; MessageDict.Add(GetWAPMessageID(fc), fc); }
public bool Validate(FieldCollection sourceCollection, FieldCollection targetCollection, TokenParser tokenParser) { Dictionary<string, string[]> parserSettings = new Dictionary<string, string[]>(); parserSettings.Add("SchemaXml", new string[] { "~sitecollection", "~site", "{sitecollectiontermstoreid}", "{termsetid}" }); bool isFieldMatch = ValidateObjectsXML(sourceCollection, targetCollection, "SchemaXml", new List<string> { "ID" }, tokenParser, parserSettings); Console.WriteLine("-- Field validation " + isFieldMatch); return isFieldMatch; }
public void Add(FieldCollection fcp) { FieldCollection tmpfc = fcp.Clone(); decompose(tmpfc); if (isLoadDT) { _fields = tmpfc; } }
public DataOperation_Complex( FieldCollection fc) { if (fc != null) { _dbConn_fc_Dir = new Dictionary<string, Dictionary<string, FieldCollection>>(); _fields = fc.Clone(); decompose(_fields); } }
private static void AppendFieldInfo(StringBuilder sb, FieldCollection fields, string header, Func<Field, bool> predicate) { sb.AppendLine(string.Empty); sb.AppendLine(header); foreach (var field in fields.Where(predicate)) { sb.AppendLine(string.Format("\"{0}\":\"{1}\"", field.Name, field.Value)); } }
public static string GetExceptionDescription(FieldCollection fc) { if (fc != null) { var fcFormat = new FieldCollectionFormat(); if (!fcFormat.IsEmptyStrField(fc, "ExceptionDescription")) return fc["ExceptionDescription"].GetValueAsString(); } return ""; }
protected override IEnumerable<Field> GetTypedFields(ClientContext context, FieldCollection items) { var typedFields = context.LoadQuery( items.Where(i => i.FieldTypeKind == FieldType.Number) .IncludeWithDefaultProperties()); context.ExecuteQueryWithTrace(); return typedFields; }
public static UInt32 GetWAPMessageID(FieldCollection fc) { if(fc!=null) { var fcFormat = new FieldCollectionFormat(); if(!fcFormat.IsEmptyStrField(fc,"MessageID")) return (UInt32)fc["MessageID"].GetValueAsInt(); } return 0; }
public static string GetClassName(FieldCollection fc) { if (fc != null) { var fcFormat = new FieldCollectionFormat(); if (!fcFormat.IsEmptyStrField(fc, "ClassName")) return fc["ClassName"].GetValueAsString(); } return ""; }
public FieldCollection fillFcField(FieldCollection fc, string fieldName,object objValue) { if (IsExistField(fc, fieldName)) { fc[fieldName].AllowModify = true; fc[fieldName].Value = objValue; } return fc; }
public ItemDefinition(Guid id, Guid templateId, string name, string path, Language language, bool hasVersion, FieldCollection fields) { Id = id; TemplateId = templateId; Name = name; Key = name.ToLowerInvariant(); Path = path; Language = language; HasVersion = hasVersion; Fields = fields; }
public bool ValidateSiteFields(FieldCollection sElements, FieldCollection tElements, TokenParser sParser, TokenParser tParser) { List<Localization> sColl = LoadFields(sElements); List<Localization> tColl = LoadFields(tElements); if (sColl.Count > 0) { if (!Validatelocalization(sColl, tColl, sParser, tParser)) { return false; } } return true; }
protected virtual void AddFieldsIncludedBySection(FieldCollection fieldCol, List<Field> includedFields, GetRenderingPropertiesArgs args) { var sectionsParam = args.ClientParameters["sections"]; if (string.IsNullOrEmpty(sectionsParam)) { return; } var sectionNames = sectionsParam.Split(new[] { '|' }).Where(name => !string.IsNullOrWhiteSpace(name)).ToList(); var fields = fieldCol.Where(f => sectionNames.Contains(f.Section)); includedFields.AddRange(fields); }
public FieldCollection fillDateTimeFcField(FieldCollection fc, string fieldName, object objValue) { if (IsExistField(fc, fieldName)) { fc[fieldName].AllowModify = true; if ((DateTime)objValue == new DateTime()) fc[fieldName].Value = null; else fc[fieldName].Value = objValue; } return fc; }
public double GetDoubleValue(FieldCollection fc, string fieldName, double defaultValue) { try { if (!IsEmptyStrField(fc, fieldName)) //if (fc[fieldName].AllowModify) return Convert.ToDouble(fc[fieldName].GetValueAsSObject()); return defaultValue; } catch { return defaultValue; } }
protected override IEnumerable<Field> GetTypedFields(ClientContext context, FieldCollection items) { var typedFields = context.LoadQuery(items.Where(i => i.TypeAsString == BuiltInFieldTypes.TaxonomyFieldType)); context.ExecuteQueryWithTrace(); var result = new List<Field>(); result.AddRange(typedFields); typedFields = context.LoadQuery(items.Where(i => i.TypeAsString == BuiltInFieldTypes.TaxonomyFieldTypeMulti)); context.ExecuteQueryWithTrace(); result.AddRange(typedFields); return result; }
public static DataOperation GetDataOperation(string tablename, DBService db, bool IsLoadDt, FieldCollection fields) { if(db == null) db = DBServiceFactory.GetDBService(); switch (db.DBType) { case eDBType.SqlServer: return null; case eDBType.Oracle: return new DataOperationOracle(tablename,db,IsLoadDt,fields); case eDBType.XML: return new DataOperation_XML(tablename, db, IsLoadDt, fields); default: return new DataOperationOracle(tablename, db, IsLoadDt, fields); } }
/// <summary> /// 自动读数据库载入数据的构造函数 /// </summary> /// <param name="tablename">表名</param> /// <param name="db">操作数据类</param> /// <param name="IsLoadDt">是否从数据库载入数据到类中</param> /// <param name="fields">Field集合</param> public DataOperation(string tablename, DBService db, bool IsLoadDt, FieldCollection fields) { this.TableName = tablename; if(db == null) throw WAPExceptionHelper.GetWAPException(10001052, "A DBService must be inputted into the constructer", null); else this.theDB = db; if (fields == null || fields.Count == 0) throw WAPExceptionHelper.GetWAPException(10001051, "A FieldCollection must be inputted into the constructer", null); else this.Fields = fields; if (IsLoadDt) { this.InitData(); } this.WhereFields = new FieldCollection(); }
public static Item CreateTestItem(string id = null, string name = "Test Item", Guid templateId = default(Guid), FieldCollection fields = null) { Item item = new ShimItem() { NameGet = () => name ?? "Test Item", IDGet = () => new Sitecore.Data.ID(id ?? new Guid().ToString()), TemplateIDGet = () => new Sitecore.Data.ID(templateId), FieldsGet = () => fields ?? CreateTestFields(), }; new ShimBaseItem(item) { ItemGetString = fieldName => item.Fields[fieldName].Value }; return item; }
/// <summary> /// Function to get the WssID for the Practice group, Area of law and Sub area of law terms /// </summary> /// <param name="clientContext">SP client context</param> /// <param name="matterMetadata">Object containing meta data for Matter</param> /// <param name="fields">Field Collection object</param> /// <returns>An Object containing meta data for Matter</returns> internal static MatterMetadata GetWSSId(ClientContext clientContext, MatterMetadata matterMetadata, FieldCollection fields) { ClientResult<TaxonomyFieldValue> practiceGroupResult = clientContext.CastTo<TaxonomyField> (fields.GetByInternalNameOrTitle(ServiceConstantStrings.ContentTypeColumnPracticeGroup)) .GetFieldValueAsTaxonomyFieldValue(matterMetadata.PracticeGroupTerm.Id); ClientResult<TaxonomyFieldValue> areaOfLawResult = clientContext.CastTo<TaxonomyField> (fields.GetByInternalNameOrTitle(ServiceConstantStrings.ContentTypeColumnAreaOfLaw)) .GetFieldValueAsTaxonomyFieldValue(matterMetadata.AreaTerm.Id); ClientResult<TaxonomyFieldValue> subareaOfLawResult = clientContext.CastTo<TaxonomyField> (fields.GetByInternalNameOrTitle(ServiceConstantStrings.ContentTypeColumnSubareaOfLaw)) .GetFieldValueAsTaxonomyFieldValue(matterMetadata.SubareaTerm.Id); clientContext.ExecuteQuery(); matterMetadata.PracticeGroupTerm.WssId = practiceGroupResult.Value.WssId; matterMetadata.AreaTerm.WssId = areaOfLawResult.Value.WssId; matterMetadata.SubareaTerm.WssId = subareaOfLawResult.Value.WssId; return matterMetadata; }
private List<Localization> LoadFields(FieldCollection coll) { string attribute1 = "DisplayName"; string attribute2 = "Description"; string key = "ID"; List<Localization> loc = new List<Localization>(); foreach (Field item in coll) { XElement element = XElement.Parse(item.SchemaXml); string sTokenValue1 = GetPropertyValue(attribute1, element); string sTokenValue2 = GetPropertyValue(attribute2, element); string sKey = GetPropertyValue(key, element); loc.Add(new Localization(sKey, sTokenValue1, sTokenValue2)); } return loc; }
public Section(string label, FieldCollection fields) : this(label) { this.Fields = fields; }
void GenerateSQLServerCode() { // string startPath = @"c:\project\tests"; string zipPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\Resources\SobyGrid_WebAPIExample.zip"; string extractPath = GetTempPath(); // ZipFile.CreateFromDirectory(startPath, zipPath); ZipFile.ExtractToDirectory(zipPath, extractPath); Process.Start("Explorer.exe", extractPath); string rootPath = extractPath + "\\SobyGrid_WebAPIExample\\SobyGrid_WebAPIExample"; string modelsPath = rootPath + "\\Models"; string controllersPath = rootPath + "\\Controllers"; string appStartPath = rootPath + "\\App_Start"; XmlDocument doc = new XmlDocument(); doc.Load(rootPath + "\\SobyGrid_WebAPIExample.csproj"); XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003"); // XmlNode node = xmldoc.SelectSingleNode("//msbld:Compile", ns); XmlNode nodeItemGroup = doc.SelectSingleNode("//msbld:Compile", ns).ParentNode; XmlNode contentNodeItemGroup = doc.SelectSingleNode("//msbld:Content", ns).ParentNode; Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters["Tables"] = _MainObject.Folders; GenerateWebAPIConfigCodeFile(appStartPath + "\\WebApiConfig.cs", parameters); GenerateTaskServiceContextCodeFile(modelsPath + "\\TaskServiceContext.cs", parameters); SiteSetting siteSetting = ApplicationContext.Current.Configuration.SiteSettings[_MainObject.SiteSettingID]; foreach (Folder folder in _MainObject.Folders) { FieldCollection fields = ApplicationContext.Current.GetFields(siteSetting, folder); FieldCollection primaryKeyFields = new FieldCollection(); string[] primaryKeys = ApplicationContext.Current.GetPrimaryKeys(siteSetting, folder); if (primaryKeys.Count() == 0) { continue; } List <Field> primaryKeyFieldObjects = (from x in fields where primaryKeys.Contains(x.Name) select x).ToList(); foreach (Field field in fields) { if (primaryKeys.Contains(field.Name)) { field.IsPrimary = true; } } string tableName = folder.Title; parameters = new Dictionary <string, object>(); parameters["TableName"] = tableName; parameters["Fields"] = fields; GenerateModelCodeFile(modelsPath + "\\" + tableName + "Record.cs", parameters); GenerateControllerCodeFile(controllersPath + "\\" + tableName + "Controller.cs", parameters); GenerateSobyGridPageTemplateCodeFile(rootPath + "\\" + tableName + "Management.html", parameters); XmlElement htmlElement = doc.CreateElement("Content", "http://schemas.microsoft.com/developer/msbuild/2003"); XmlAttribute includeAttribute = doc.CreateAttribute("Include"); includeAttribute.Value = tableName + "Management.html"; htmlElement.Attributes.Append(includeAttribute); contentNodeItemGroup.AppendChild(htmlElement); XmlElement modelElement = doc.CreateElement("Compile", "http://schemas.microsoft.com/developer/msbuild/2003"); includeAttribute = doc.CreateAttribute("Include"); includeAttribute.Value = "Models\\" + tableName + "Record.cs"; modelElement.Attributes.Append(includeAttribute); nodeItemGroup.AppendChild(modelElement); XmlElement newChild = doc.CreateElement("Compile", "http://schemas.microsoft.com/developer/msbuild/2003"); includeAttribute = doc.CreateAttribute("Include"); includeAttribute.Value = "Controllers\\" + tableName + "Controller.cs"; newChild.Attributes.Append(includeAttribute); nodeItemGroup.AppendChild(newChild); } doc.Save(rootPath + "\\SobyGrid_WebAPIExample.csproj"); MessageBox.Show("Code generation completed successfully."); }
private void CopyDataToClipboard(FieldCollection selectedFields) { StringBuilder clipboardText = new StringBuilder(); string fieldSeperator = ((ComboBoxSeperator)comboBoxFieldSeperator.SelectedItem).Value; string recordSeperator = ((ComboBoxSeperator)comboBoxRecordSeperator.SelectedItem).Value; // Header-Zeile schreiben? if (checkBoxFieldsInFirstLine.Checked) { int iCount = 0; foreach (Field field in selectedFields) { clipboardText.Append(dataBase.GetNameOfFieldFull(field)); if (iCount < selectedFields.Count - 1) { clipboardText.Append(fieldSeperator); } iCount++; } clipboardText.Append(recordSeperator); } progressBar.Maximum = records.Length; progressBar.Value = 0; CDQueryDataSet cdQuery = null; if (copyTracks) { cdQuery = dataBase.ExecuteTrackQuery(); } else { cdQuery = dataBase.ExecuteCDQuery(); } foreach (int id in records) { if (copyTracks) { string filter = string.Format("TrackID={0}", id); CDQueryDataSet.TrackRow liedRow = (CDQueryDataSet.TrackRow)cdQuery.Track.Select(filter)[0]; int iCount = 0; foreach (Field field in selectedFields) { object value = liedRow.GetValueByField(dataBase, field); if (checkBoxQuoteTextFields.Checked && value is string) { clipboardText.Append("\"" + value + "\""); } else { clipboardText.Append(value); } if (iCount < selectedFields.Count - 1) { clipboardText.Append(fieldSeperator); } iCount++; } } else { string filter = string.Format("CDID={0}", id); CDQueryDataSet.CDRow cdRow = (CDQueryDataSet.CDRow)cdQuery.CD.Select(filter)[0]; int iCount = 0; foreach (Field field in selectedFields) { object value = cdRow.GetValueByField(field); if (checkBoxQuoteTextFields.Checked && value is string) { clipboardText.Append("\"" + value + "\""); } else { clipboardText.Append(value); } if (iCount < selectedFields.Count - 1) { clipboardText.Append(fieldSeperator); } iCount++; } } clipboardText.Append(recordSeperator); progressBar.Value++; progressBar.Update(); Application.DoEvents(); } Clipboard.SetText(clipboardText.ToString(), TextDataFormat.Text); }
public ExportTable Export() { // 取得縣市對照表 XmlElement schoolLocationList = Config.GetSchoolLocationList().GetContent().BaseElement; // 取得匯出規則描述 XmlElement descElement = StudentBulkProcess.GetExportDescription(); IFieldFormater fieldFormater = new BaseFieldFormater(); IResponseFormater responseFormater = new ResponseFormater(); FieldCollection fieldCollection = fieldFormater.Format(descElement); ExportFieldCollection exportFields = responseFormater.Format(descElement); fieldCollection = FieldUtil.Match(fieldCollection, _selectFields); exportFields = FieldUtil.Match(exportFields, _selectFields); //// 有選狀態時加入 //if (_selectFields.FindByDisplayText("狀態") != null) //{ // fieldCollection.Add(_selectFields.FindByDisplayText("狀態")); // ExportField ex = new ExportField(); // ex.DisplayText = "狀態"; // ex.RequestName = "StudentStatus"; // ex.ColumnIndex = exportFields.Length; // ex.DataType = ""; // ex.XPath = ""; // exportFields.Add(ex); //} IRequestGenerator reqGenerator = new ExportStudentRequestGenerator(); _selectFieldsID = new FieldCollection(); foreach (Field fd in _selectFields) { _selectFieldsID.Add(fd); } if (_selectFieldsID.Find("StudentID") == null) { Field fd1 = new Field(); fd1.FieldName = "StudentID"; fd1.DisplayText = "學生系統編號"; _selectFieldsID.Add(fd1); } reqGenerator.SetSelectedFields(_selectFieldsID); // 預設找-1, 不然會傳回所有學生 ICondition condition = new BaseCondition("ID", "-1"); reqGenerator.AddCondition(condition); foreach (string id in _conditions) { ICondition condition2 = new BaseCondition("ID", id); reqGenerator.AddCondition(condition2); } reqGenerator.AddOrder(new Order("GradeYear")); reqGenerator.AddOrder(new Order("Department")); reqGenerator.AddOrder(new Order("RefClassID")); reqGenerator.AddOrder(new Order("SeatNo")); DSRequest request = reqGenerator.Generate(); DSResponse response = QueryStudent.GetExportList(request); ExportTable table = new ExportTable(); foreach (ExportField field in exportFields) { table.AddColumn(field); } //// 取得學生狀態 //Dictionary<string, string> StudStatusDic = new Dictionary<string, string>(); //foreach (JHSchool.Data.JHStudentRecord stud in JHSchool.Data.JHStudent.SelectByIDs(K12.Presentation.NLDPanels.Student.SelectedSource )) // StudStatusDic.Add(stud.ID, stud.Status.ToString()); foreach (XmlElement record in response.GetContent().GetElements("Student")) { ExportRow row = table.AddRow(); foreach (ExportField column in table.Columns) { int columnIndex = column.ColumnIndex; ExportCell cell = row.Cells[columnIndex]; XmlNode cellNode = record.SelectSingleNode(column.XPath); //if(column.DisplayText !="狀態") // cellNode = record.SelectSingleNode(column.XPath); // CustodianOtherInfo/CustodianOtherInfo[1]/EducationDegree[1] #region 這段程式是處理匯入/匯出程式不一致問題 if (column.XPath.StartsWith("CustodianOtherInfo/Custodian")) { if (cellNode == null) { string x = column.XPath.Replace("CustodianOtherInfo/Custodian", "CustodianOtherInfo/CustodianOtherInfo"); cellNode = record.SelectSingleNode(x); if (cellNode == null) { x = column.XPath.Replace("CustodianOtherInfo/CustodianOtherInfo", "CustodianOtherInfo/Custodian"); cellNode = record.SelectSingleNode(x); } } } if (column.XPath.StartsWith("FatherOtherInfo/Father")) { if (cellNode == null) { string x = column.XPath.Replace("FatherOtherInfo/Father", "FatherOtherInfo/FatherOtherInfo"); cellNode = record.SelectSingleNode(x); if (cellNode == null) { x = column.XPath.Replace("FatherOtherInfo/FatherOtherInfo", "FatherOtherInfo/Father"); cellNode = record.SelectSingleNode(x); } } } if (column.XPath.StartsWith("MotherOtherInfo/Mother")) { if (cellNode == null) { string x = column.XPath.Replace("MotherOtherInfo/Mother", "MotherOtherInfo/MotherOtherInfo"); cellNode = record.SelectSingleNode(x); if (cellNode == null) { x = column.XPath.Replace("MotherOtherInfo/MotherOtherInfo", "MotherOtherInfo/Mother"); cellNode = record.SelectSingleNode(x); } } } #endregion if (cellNode != null) { if (column.FieldName == "GraduateSchoolLocationCode") { cell.Value = GetCounty(schoolLocationList, cellNode.InnerText); } else if (column.FieldName == "DeptName") //處理科別繼承問題。 { //這個欄位的資料一定會被回傳,因為設定了 Mandatory 屬性。 XmlNode selfDept = record.SelectSingleNode("SelfDeptName"); if (string.IsNullOrEmpty(selfDept.InnerText)) { cell.Value = cellNode.InnerText; } else { cell.Value = selfDept.InnerText; } } else if (column.FieldName == "Status") { cell.Value = GetStudStatusStr(cellNode.InnerText); } else { cell.Value = cellNode.InnerText; } } //if (column.DisplayText == "狀態")//record.SelectSingleNode("StudentID")!=null ) //{ // // 學生狀態 // if (StudStatusDic.ContainsKey(record.SelectSingleNode("StudentID").InnerText)) // cell.Value = StudStatusDic[record.SelectSingleNode("StudentID").InnerText]; //} } } return(table); }
protected override void ExecuteCmdlet() { if (List != null) { var list = List.GetList(SelectedWeb); Field field = null; FieldCollection fieldCollection = null; if (list != null) { if (Identity.Id != Guid.Empty) { field = list.Fields.GetById(Identity.Id); } else if (!string.IsNullOrEmpty(Identity.Name)) { field = list.Fields.GetByInternalNameOrTitle(Identity.Name); } else { fieldCollection = list.Fields; ClientContext.Load(fieldCollection, fc => fc.IncludeWithDefaultProperties(RetrievalExpressions)); ClientContext.ExecuteQueryRetry(); } } if (field != null) { ClientContext.Load(field, RetrievalExpressions); ClientContext.ExecuteQueryRetry(); WriteObject(field); } else if (fieldCollection != null) { if (!string.IsNullOrEmpty(Group)) { WriteObject(fieldCollection.Where(f => f.Group.Equals(Group, StringComparison.InvariantCultureIgnoreCase)), true); } else { WriteObject(fieldCollection, true); } } else { WriteObject(null); } } else { if (Identity.Id == Guid.Empty && string.IsNullOrEmpty(Identity.Name)) { if (InSiteHierarchy.IsPresent) { ClientContext.Load(SelectedWeb.AvailableFields, fc => fc.IncludeWithDefaultProperties(RetrievalExpressions)); } else { ClientContext.Load(SelectedWeb.Fields, fc => fc.IncludeWithDefaultProperties(RetrievalExpressions)); } ClientContext.ExecuteQueryRetry(); if (!string.IsNullOrEmpty(Group)) { if (InSiteHierarchy.IsPresent) { WriteObject(SelectedWeb.AvailableFields.Where(f => f.Group.Equals(Group, StringComparison.InvariantCultureIgnoreCase)).OrderBy(f => f.Title), true); } else { WriteObject(SelectedWeb.Fields.Where(f => f.Group.Equals(Group, StringComparison.InvariantCultureIgnoreCase)).OrderBy(f => f.Title), true); } } else { if (InSiteHierarchy.IsPresent) { WriteObject(SelectedWeb.AvailableFields.OrderBy(f => f.Title), true); } else { WriteObject(SelectedWeb.Fields.OrderBy(f => f.Title), true); } } } else { Field field = null; if (Identity.Id != Guid.Empty) { if (InSiteHierarchy.IsPresent) { field = SelectedWeb.AvailableFields.GetById(Identity.Id); } else { field = SelectedWeb.Fields.GetById(Identity.Id); } } else if (!string.IsNullOrEmpty(Identity.Name)) { if (InSiteHierarchy.IsPresent) { field = SelectedWeb.AvailableFields.GetByInternalNameOrTitle(Identity.Name); } else { field = SelectedWeb.Fields.GetByInternalNameOrTitle(Identity.Name); } } ClientContext.Load(field, RetrievalExpressions); ClientContext.ExecuteQueryRetry(); switch (field.FieldTypeKind) { case FieldType.DateTime: { WriteObject(ClientContext.CastTo <FieldDateTime>(field)); break; } case FieldType.Choice: { WriteObject(ClientContext.CastTo <FieldChoice>(field)); break; } case FieldType.Calculated: { WriteObject(ClientContext.CastTo <FieldCalculated>(field)); break; } case FieldType.Computed: { WriteObject(ClientContext.CastTo <FieldComputed>(field)); break; } case FieldType.Geolocation: { WriteObject(ClientContext.CastTo <FieldGeolocation>(field)); break; } case FieldType.User: { WriteObject(ClientContext.CastTo <FieldUser>(field)); break; } case FieldType.Currency: { WriteObject(ClientContext.CastTo <FieldCurrency>(field)); break; } case FieldType.Guid: { WriteObject(ClientContext.CastTo <FieldGuid>(field)); break; } case FieldType.URL: { WriteObject(ClientContext.CastTo <FieldUrl>(field)); break; } case FieldType.Lookup: { WriteObject(ClientContext.CastTo <FieldLookup>(field)); break; } case FieldType.MultiChoice: { WriteObject(ClientContext.CastTo <FieldMultiChoice>(field)); break; } case FieldType.Number: { WriteObject(ClientContext.CastTo <FieldNumber>(field)); break; } case FieldType.Invalid: { if (field.TypeAsString.StartsWith("TaxonomyFieldType")) { WriteObject(ClientContext.CastTo <TaxonomyField>(field)); break; } goto default; } default: { WriteObject(field); break; } } } } }
protected Field GetField(object modelHost, FieldDefinition definition) { FieldCollection fields = FieldLookupService.GetFieldCollection(modelHost); return(FieldLookupService.GetField(fields, definition.Id, definition.InternalName, definition.Title)); }
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { if (template.Lists.Any()) { var rootWeb = (web.Context as ClientContext).Site.RootWeb; web.EnsureProperties(w => w.ServerRelativeUrl); web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl)); web.Context.ExecuteQueryRetry(); var existingLists = web.Lists.AsEnumerable <List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList(); var serverRelativeUrl = web.ServerRelativeUrl; #region DataRows foreach (var listInstance in template.Lists) { if (listInstance.DataRows != null && listInstance.DataRows.Any()) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Processing_data_rows_for__0_, listInstance.Title); // Retrieve the target list var list = web.Lists.GetByTitle(listInstance.Title); web.Context.Load(list); // Retrieve the fields' types from the list FieldCollection fields = list.Fields; web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind)); web.Context.ExecuteQueryRetry(); foreach (var dataRow in listInstance.DataRows) { try { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_list_item__0_, listInstance.DataRows.IndexOf(dataRow) + 1); var listitemCI = new ListItemCreationInformation(); var listitem = list.AddItem(listitemCI); foreach (var dataValue in dataRow.Values) { Field dataField = fields.FirstOrDefault( f => f.InternalName == parser.ParseString(dataValue.Key)); if (dataField != null) { String fieldValue = parser.ParseString(dataValue.Value); switch (dataField.FieldTypeKind) { case FieldType.Geolocation: // FieldGeolocationValue - Expected format: Altitude,Latitude,Longitude,Measure var geolocationArray = fieldValue.Split(','); if (geolocationArray.Length == 4) { var geolocationValue = new FieldGeolocationValue { Altitude = Double.Parse(geolocationArray[0]), Latitude = Double.Parse(geolocationArray[1]), Longitude = Double.Parse(geolocationArray[2]), Measure = Double.Parse(geolocationArray[3]), }; listitem[parser.ParseString(dataValue.Key)] = geolocationValue; } else { listitem[parser.ParseString(dataValue.Key)] = fieldValue; } break; case FieldType.Lookup: // FieldLookupValue - Expected format: LookupID var lookupValue = new FieldLookupValue { LookupId = Int32.Parse(fieldValue), }; listitem[parser.ParseString(dataValue.Key)] = lookupValue; break; case FieldType.URL: // FieldUrlValue - Expected format: URL,Description var urlArray = fieldValue.Split(','); var linkValue = new FieldUrlValue(); if (urlArray.Length == 2) { linkValue.Url = urlArray[0]; linkValue.Description = urlArray[1]; } else { linkValue.Url = urlArray[0]; linkValue.Description = urlArray[0]; } listitem[parser.ParseString(dataValue.Key)] = linkValue; break; case FieldType.User: // FieldUserValue - Expected format: loginName var user = web.EnsureUser(fieldValue); web.Context.Load(user); web.Context.ExecuteQueryRetry(); if (user != null) { var userValue = new FieldUserValue { LookupId = user.Id, }; listitem[parser.ParseString(dataValue.Key)] = userValue; } else { listitem[parser.ParseString(dataValue.Key)] = fieldValue; } break; default: listitem[parser.ParseString(dataValue.Key)] = fieldValue; break; } } listitem.Update(); } web.Context.ExecuteQueryRetry(); // TODO: Run in batches? if (dataRow.Security != null && dataRow.Security.RoleAssignments.Count != 0) { listitem.SetSecurity(parser, dataRow.Security); } } catch (Exception ex) { scope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_failed___0_____1_, ex.Message, ex.StackTrace); throw; } } } } #endregion } } return(parser); }
private static IEnumerable <SchemaEvent> SyncFields <T>( FieldCollection <T> source, FieldCollection <T> target, IJsonSerializer serializer, Func <long> idGenerator, NamedId <long> parentId, SchemaSynchronizationOptions options) where T : class, IField { FieldEvent E(FieldEvent @event) { @event.ParentFieldId = parentId; return(@event); } var sourceIds = new List <NamedId <long> >(source.Ordered.Select(x => x.NamedId())); var sourceNames = sourceIds.Select(x => x.Name).ToList(); if (!options.NoFieldDeletion) { foreach (var sourceField in source.Ordered) { if (!target.ByName.TryGetValue(sourceField.Name, out var targetField)) { var id = sourceField.NamedId(); sourceIds.Remove(id); sourceNames.Remove(id.Name); yield return(E(new FieldDeleted { FieldId = id })); } } } foreach (var targetField in target.Ordered) { NamedId <long> id = null; var canCreateField = true; if (source.ByName.TryGetValue(targetField.Name, out var sourceField)) { canCreateField = false; id = sourceField.NamedId(); if (CanUpdate(sourceField, targetField)) { if (!sourceField.RawProperties.EqualsJson(targetField.RawProperties, serializer)) { yield return(E(new FieldUpdated { FieldId = id, Properties = targetField.RawProperties })); } } else if (!sourceField.IsLocked && !options.NoFieldRecreation) { canCreateField = true; sourceIds.Remove(id); sourceNames.Remove(id.Name); yield return(E(new FieldDeleted { FieldId = id })); } } if (canCreateField) { var partitioning = (string)null; if (targetField is IRootField rootField) { partitioning = rootField.Partitioning.Key; } id = NamedId.Of(idGenerator(), targetField.Name); yield return(new FieldAdded { Name = targetField.Name, ParentFieldId = parentId, Partitioning = partitioning, Properties = targetField.RawProperties, FieldId = id }); sourceIds.Add(id); sourceNames.Add(id.Name); } if (id != null && (sourceField == null || CanUpdate(sourceField, targetField))) { if (!targetField.IsLocked.BoolEquals(sourceField?.IsLocked)) { yield return(E(new FieldLocked { FieldId = id })); } if (!targetField.IsHidden.BoolEquals(sourceField?.IsHidden)) { yield return(targetField.IsHidden ? E(new FieldHidden { FieldId = id }) : E(new FieldShown { FieldId = id })); } if (!targetField.IsDisabled.BoolEquals(sourceField?.IsDisabled)) { yield return(targetField.IsDisabled ? E(new FieldDisabled { FieldId = id }) : E(new FieldEnabled { FieldId = id })); } if ((sourceField == null || sourceField is IArrayField) && targetField is IArrayField targetArrayField) { var fields = (sourceField as IArrayField)?.FieldCollection ?? FieldCollection <NestedField> .Empty; var events = SyncFields(fields, targetArrayField.FieldCollection, serializer, idGenerator, id, options); foreach (var @event in events) { yield return(@event); } } } } if (sourceNames.Count > 1) { var targetNames = target.Ordered.Select(x => x.Name); if (sourceNames.Intersect(targetNames).Count() == target.Ordered.Count && !sourceNames.SequenceEqual(targetNames)) { yield return(new SchemaFieldsReordered { FieldIds = sourceIds.Select(x => x.Id).ToList(), ParentFieldId = parentId }); } } }
public static Field AddNote(this FieldCollection fields, String displayName, bool addToDefaultView) { return(fields.AddFieldAsXml(String.Format("<Field DisplayName='{0}' Type='{1}' />", displayName, FieldType.Note), addToDefaultView, AddFieldOptions.DefaultValue)); }
private void button1_Click(object sender, System.EventArgs e) { // clear report _c1r.Clear(); _c1r.ReportName = "Images"; _c1r.Font = new Font("Tahoma", 9); _c1r.Layout.MarginLeft = 600; // configure detail section Section section = _c1r.Sections[SectionTypeEnum.Detail]; Rectangle rc = new Rectangle(0, 0, 1600, 1200); section.Height = rc.Height; section.Visible = true; section.CanGrow = true; // add fields FieldCollection fc = section.Fields; // create ID field Field f = fc.Add("fldID", "ID", rc); f.Align = FieldAlignEnum.LeftTop; f.Calculated = true; f.BorderStyle = BorderStyleEnum.Solid; // create file name field rc.Offset(rc.Width + 100, 0); f = fc.Add("fldFileName", "FileName", rc); f.Align = FieldAlignEnum.LeftTop; f.WordWrap = true; f.Calculated = true; f.BorderStyle = BorderStyleEnum.Solid; // create 1st image field (directly from db) rc.Offset(rc.Width + 100, 0); rc.Width = 4000; rc.Height = 4000; f = fc.Add("fldImage", "Image", rc); f.Picture = "Image"; f.PictureAlign = PictureAlignEnum.Zoom; f.BorderStyle = BorderStyleEnum.Solid; // create 2nd image field (laoded from file at render time) rc.Offset(rc.Width + 100, 0); f = fc.Add("fldFileImage", "", rc); f.PictureAlign = PictureAlignEnum.Zoom; f.BorderStyle = BorderStyleEnum.Solid; // use script to set Picture property at render time: // this takes the iamge filename from the 'fldFileName' calculated field. section.OnPrint = "fldFileImage.Picture = fldFileName"; // set data source _c1r.DataSource.Recordset = _dt; // show it C1.Win.C1Preview.C1PrintPreviewDialog dlg = new C1.Win.C1Preview.C1PrintPreviewDialog(); dlg.Document = _c1r; dlg.ShowDialog(); }
public void SetSelectedFields(FieldCollection fields) { _selectFields = fields; }
public static object TryGetField(this FieldCollection collection, string fieldName) { var fields = collection.OfType <Field>(); return(fields.FirstOrDefault(e => e.FieldDefinition.ReferenceName == fieldName)?.Value); }
public SampleStatReportSettings() { StatFields = new FieldCollection(); HeadFields = new FieldCollection(); DecisionsFields = new FieldCollection(); }
private void HandleIncorectlyDeletedTaxonomyField(FieldDefinition fieldModel, FieldCollection fields) { var context = fields.Context; var isTaxField = fieldModel.FieldType.ToUpper() == BuiltInFieldTypes.TaxonomyFieldType.ToUpper() || fieldModel.FieldType.ToUpper() == BuiltInFieldTypes.TaxonomyFieldTypeMulti.ToUpper(); if (!isTaxField) { return; } var existingIndexedFieldName = fieldModel.Title + "_0"; var query = from field in fields where field.Title == existingIndexedFieldName select field; var result = context.LoadQuery(query); context.ExecuteQueryWithTrace(); if (result.Count() > 0) { var existingIndexedField = result.FirstOrDefault(); if (existingIndexedField != null && existingIndexedField.FieldTypeKind == FieldType.Note) { existingIndexedField.DeleteObject(); context.ExecuteQueryWithTrace(); } } }
public Section() { this.Fields = new FieldCollection(); }
private Field FindField(FieldCollection fields, ContentTypeFieldLinkDefinition listFieldLinkModel) { var context = fields.Context; var scope = new ExceptionHandlingScope(context); Field field = null; if (listFieldLinkModel.FieldId.HasGuidValue()) { var id = listFieldLinkModel.FieldId.Value; using (scope.StartScope()) { using (scope.StartTry()) { fields.GetById(id); } using (scope.StartCatch()) { } } } else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName)) { var fieldInternalName = listFieldLinkModel.FieldInternalName; using (scope.StartScope()) { using (scope.StartTry()) { fields.GetByInternalNameOrTitle(fieldInternalName); } using (scope.StartCatch()) { } } } context.ExecuteQueryWithTrace(); if (!scope.HasException) { if (listFieldLinkModel.FieldId.HasGuidValue()) { field = fields.GetById(listFieldLinkModel.FieldId.Value); } else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName)) { field = fields.GetByInternalNameOrTitle(listFieldLinkModel.FieldInternalName); } context.Load(field); context.Load(field, f => f.SchemaXml); context.ExecuteQueryWithTrace(); } return(field); }
/// <summary> /// Perform cleanup of web part fields /// </summary> /// <param name="webPartFields">List of extracted web parts</param> /// <param name="spFields">Collection of fields</param> /// <returns></returns> private List <WebPartField> CleanExtractedWebPartFields(List <WebPartField> webPartFields, FieldCollection spFields) { List <WebPartField> cleanedWebPartFields = new List <WebPartField>(); try { foreach (var webPartField in webPartFields) { if (PublishingDefaults.IgnoreWebPartFieldControls.Contains(webPartField.Name)) { // This is field we're ignoring as it's not meant to be translated into a web part on the modern page continue; } Guid fieldId = Guid.Empty; Guid.TryParse(webPartField.Name, out fieldId); // Find the field, we'll use the field's type to get the 'default' transformation behaviour var spField = spFields.Where(p => p.StaticName.Equals(webPartField.Name, StringComparison.InvariantCultureIgnoreCase) || p.Id == fieldId).FirstOrDefault(); if (spField != null) { var webPartFieldDefaults = PublishingDefaults.WebPartFieldProperties.Where(p => p.FieldType.Equals(spField.TypeAsString)); if (webPartFieldDefaults.Any()) { // Copy basic fields WebPartField wpf = new WebPartField() { Name = spField.StaticName, Row = webPartField.Row, //RowSpecified = webPartField.RowSpecified, Column = webPartField.Column, //ColumnSpecified = webPartField.ColumnSpecified, TargetWebPart = webPartFieldDefaults.First().TargetWebPart, }; if (fieldId != Guid.Empty) { wpf.FieldId = fieldId.ToString(); } // Copy the default target web part properties var properties = PublishingDefaults.WebPartFieldProperties.Where(p => p.FieldType.Equals(spField.TypeAsString)); if (properties.Any()) { List <WebPartProperty> webPartProperties = new List <WebPartProperty>(); foreach (var property in properties) { webPartProperties.Add(new WebPartProperty() { Name = property.Name, Type = this.CastToEnum <WebPartProperyType>(property.Type), Functions = property.Functions, }); } wpf.Property = webPartProperties.ToArray(); } cleanedWebPartFields.Add(wpf); } } } }catch (Exception ex) { LogError(LogStrings.Error_AnalyserCleaningExtractedWebPartFields, LogStrings.Heading_PageLayoutAnalyser, ex); } return(cleanedWebPartFields); }
public DataField(DataSet dataSet) { name = dataSet.name; Fields = new FieldCollection(); }
static void CreateSPTaxFields(List <string[]> listOfColumns) { using (ClientContext clientContext = new ClientContext(ConfigurationConstants.XYZSharepointSiteCollectionUrl)) { NetworkCredential credentials = new NetworkCredential(ConfigurationConstants.XYZSharepointAdminUserName, ConfigurationConstants.XYZSharepointAdminUserPassword, ConfigurationConstants.XYZSharepointDomain); clientContext.Credentials = credentials; Web web = clientContext.Web; clientContext.Load(web, w => w.AvailableFields); clientContext.ExecuteQuery(); FieldCollection collFields = web.AvailableFields; foreach (string[] spColumn in listOfColumns) { bool spColumnAlreadyCreated = false; foreach (Field spField in collFields) { if (spColumn[0].ToLower() == spField.InternalName.ToLower()) { spColumnAlreadyCreated = true; break; } } if (!spColumnAlreadyCreated) // if sharepoint site column not alredy created, create now { string spColumnType = spColumn[2]; if (spColumnType == "TaxonomyFieldType") { string columnTaxonomyGenericSchema = @"<Field Type='TaxonomyFieldType' Name='{0}' DisplayName='{1}' ShowField='Term1033' />"; string columnTaxonomySchema = string.Format(columnTaxonomyGenericSchema, spColumn[0], spColumn[1]); var session = TaxonomySession.GetTaxonomySession(clientContext); var store = session.TermStores.GetByName(ConfigurationConstants.XYZTermStoreName); var group = store.Groups.GetByName(ConfigurationConstants.XYZTermGroupName); var set = group.TermSets.GetByName(spColumn[3]); clientContext.Load(store, s => s.Id); clientContext.Load(set, s => s.Id); clientContext.ExecuteQuery(); var taxField = web.Fields.AddFieldAsXml(columnTaxonomySchema, false, AddFieldOptions.DefaultValue); clientContext.Load(taxField); clientContext.ExecuteQuery(); var taxfield2 = clientContext.CastTo <TaxonomyField>(taxField); taxfield2.SspId = store.Id; taxfield2.TermSetId = set.Id; taxfield2.Update(); clientContext.ExecuteQuery(); //LogMessages.Instance.LogMessageToTextFile(" Site column " + spColumn[0] + " type " + spColumn[2] + " succesfully created "); } } else { //LogMessages.Instance.LogMessageToTextFile(" Site column " + spColumn[0] + " was already created "); } } } }
/// <summary> /// /// </summary> /// <param name="db"></param> /// <param name="recs"></param> /// <param name="tracks">true, wenn es sich um Track-IDs handelt.</param> public FormCopyToClipboard(DataBase db, int[] recs, bool tracks) { InitializeComponent(); FormThemeManager.SetTheme(this); records = recs; dataBase = db; copyTracks = tracks; comboBoxFieldSeperator.Items.Add(new ComboBoxSeperator("TAB", "\t")); comboBoxFieldSeperator.Items.Add(new ComboBoxSeperator(";", ";")); comboBoxFieldSeperator.Items.Add(new ComboBoxSeperator(",", ",")); comboBoxRecordSeperator.Items.Add(new ComboBoxSeperator("CR/LF", "\r\n")); FieldCollection selectedFields; string[] defaultFields; if (copyTracks) { defaultFields = new string[2]; defaultFields[0] = ((int)Field.ArtistTrackName).ToString(); defaultFields[1] = ((int)Field.TrackTitle).ToString(); } else { defaultFields = new string[2]; defaultFields[0] = ((int)Field.ArtistCDName).ToString(); defaultFields[1] = ((int)Field.Title).ToString(); } using (RegistryKey regKey = Registry.CurrentUser.OpenSubKey(Global.HitbaseRegistryKey)) { regKey.OpenSubKey(Global.HitbaseRegistryKey); string[] stringFields; if (copyTracks) { stringFields = (string[])regKey.GetValue("CopyToClipboardTrackFields", defaultFields); } else { stringFields = (string[])regKey.GetValue("CopyToClipboardCDFields", defaultFields); } int iCount = 0; selectedFields = new FieldCollection(); foreach (string s in stringFields) { selectedFields.Add((Field)Convert.ToInt32(s)); } string fieldSep = (string)regKey.GetValue("CopyToClipboardFieldSeperator"); if (fieldSep != null) { foreach (ComboBoxSeperator sep in comboBoxFieldSeperator.Items) { if (sep.Value == fieldSep) { comboBoxFieldSeperator.SelectedItem = sep; break; } } } else { comboBoxFieldSeperator.SelectedIndex = 0; } string recordSep = (string)regKey.GetValue("CopyToClipboardRecordSeperator"); if (recordSep != null) { foreach (ComboBoxSeperator sep in comboBoxRecordSeperator.Items) { if (sep.Value == recordSep) { comboBoxRecordSeperator.SelectedItem = sep; break; } } } else { comboBoxRecordSeperator.SelectedIndex = 0; } checkBoxFieldsInFirstLine.Checked = Convert.ToBoolean(regKey.GetValue("CopyToClipboardFieldsInFirstLine", true)); checkBoxQuoteTextFields.Checked = Convert.ToBoolean(regKey.GetValue("CopyToClipboardQuoteTextFields", false)); } chooseFieldControl.Init(dataBase, copyTracks ? FieldType.TrackAndCD : FieldType.CD, selectedFields); chooseFieldControl.SelectionChanged += new ChooseFieldControl.SelectionChangedDelegate(chooseFieldControl_SelectionChanged); }
public override void Provision(bool forceOverwrite, ProvisionLevel level) { if (Field != null && Model != null && Model.Context != null && Model.Context.Context != null) { if (Field.Behavior == ProvisionBehavior.None) { return; } if (level != ProvisionLevel.Default) { //Field.Level = level; } else if (Field.Level == ProvisionLevel.Default) { if (ContentType != null) { level = ContentType.Level; } if (level == ProvisionLevel.Default) { level = List != null && List.Behavior != ProvisionBehavior.None ? ProvisionLevel.List : ProvisionLevel.Web; } } if (Field.Behavior == ProvisionBehavior.Default) { if (level == ProvisionLevel.List) { if (List != null) { Field.Behavior = List.Behavior; } } if (Field.Behavior == ProvisionBehavior.Default && ContentType != null) { Field.Behavior = ContentType.Behavior; } } if (Field.DataType == FieldType.ContentTypeId || Field.DataType == FieldType.Counter || Field.DataType == FieldType.Computed || Field.DataType == FieldType.File) { return; } var context = Model.Context.Context; Web web = context.Web; List list = null; Field field = null; if (List != null && List.Behavior != ProvisionBehavior.None) { if (List.Id != default) { list = context.Web.Lists.GetById(List.Id); } else if (List.Url != null) { list = context.Web.GetList($"{ new Uri(Model.Context.SiteUrl).LocalPath.TrimEnd('/')}/{List.Url.TrimStart('/')}"); } else if (!string.IsNullOrEmpty(List.Title)) { list = context.Web.Lists.GetByTitle(List.Title); } //if (list != null) //{ // context.Load(list); // try // { // context.ExecuteQuery(); // } // catch (Exception ex) // { // list = null; // } //} } FieldCollection fields = null; field = web.AvailableFields.GetByInternalNameOrTitle(Field.Name); fields = web.Fields; context.Load(field); try { context.ExecuteQuery(); } catch (Exception) { field = null; } if (level == ProvisionLevel.List && list != null) { Field existField = list.Fields.GetByInternalNameOrTitle(Field.Name); context.Load(existField); try { context.ExecuteQuery(); } catch (Exception ex) { existField = null; } if (existField != null) { field = existField; } else { field = null; } fields = list.Fields; } if (!forceOverwrite /*&& !Field.Overwrite*/ && Field.Behavior != ProvisionBehavior.Overwrite && field != null) { OnProvisioned?.Invoke(this, field); return; } if (fields != null) { if (Field.DataType == FieldType.Calculated) { string formula = null; string fieldRefs = null; string newFormula = null; if (typeof(CalculatedFieldAttribute).IsAssignableFrom(Field.GetType())) { fieldRefs = (Field as CalculatedFieldAttribute).FieldRefs == null ? null : string.Join("", (Field as CalculatedFieldAttribute).FieldRefs.Select(fieldRef => new Caml.CamlFieldRef() { Name = fieldRef }.ToString())); formula = (Field as CalculatedFieldAttribute).Formula; if (!string.IsNullOrEmpty(fieldRefs) && !string.IsNullOrEmpty(formula)) { if (level == ProvisionLevel.List) { var refFields = new List <Field>(); foreach (string fieldName in (Field as CalculatedFieldAttribute).FieldRefs) { var refField = (level == ProvisionLevel.Web ? web.AvailableFields : fields).GetByInternalNameOrTitle(fieldName); context.Load(refField, f => f.Title, f => f.InternalName, f => f.Id); refFields.Add(refField); } context.ExecuteQuery(); foreach (Field refField in refFields) { newFormula = formula.Replace($"[{refField.InternalName}]", $"[{refField.Title}]"); } } } } if (field == null) { string fieldXml = $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' ResultType='{{2}}'><Formula>{{0}}</Formula><FieldRefs>{{1}}</FieldRefs></Field>"; fieldXml = string.Format(fieldXml, System.Security.SecurityElement.Escape(newFormula), fieldRefs, (Field as CalculatedFieldAttribute).ResultType); field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } if (Field is CalculatedFieldAttribute) { (Field as CalculatedFieldAttribute).Formula = newFormula; } try { field = ApplyField(field); } finally { if (Field is CalculatedFieldAttribute) { (Field as CalculatedFieldAttribute).Formula = formula; } } OnProvisioning?.Invoke(this, field); } else { if (Field.DataType == FieldType.Lookup) { if (_valueType != null && (typeof(ISpEntityLookup).IsAssignableFrom(_valueType) || typeof(ISpEntityLookupCollection).IsAssignableFrom(_valueType)) || typeof(IListItemEntity).IsAssignableFrom(_valueType)) { bool allowMultipleValues = false; if (typeof(LookupFieldAttribute).IsAssignableFrom(Field.GetType())) { allowMultipleValues = (Field as LookupFieldAttribute).IsMultiple; } if (field == null) { string fieldXml = allowMultipleValues ? $"<Field Type='LookupMulti' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' Mult='TRUE' />" : $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } else { field = null; } } else if (Field.DataType == FieldType.User) { bool allowMultipleValues = false; if (typeof(LookupFieldAttribute).IsAssignableFrom(Field.GetType())) { allowMultipleValues = (Field as LookupFieldAttribute).IsMultiple; } if (field == null) { string fieldXml = allowMultipleValues ? $"<Field Type='UserMulti' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' Mult='TRUE' />" : $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } else if ((Field.DataType == FieldType.Choice || Field.DataType == FieldType.MultiChoice) && _valueType.IsEnum) { if (field == null) { string fieldXml = $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } else if (Field.DataType == FieldType.Note) { if (field == null) { string fieldXml = $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' RichText='{(Field is NoteFieldAttribute && (Field as NoteFieldAttribute).RichText ? "TRUE" : "FALSE")}' RichTextMode='{(Field is NoteFieldAttribute && (Field as NoteFieldAttribute).RichText ? "FullHtml" : "Compatible")}' IsolateStyles='{(Field is NoteFieldAttribute && (Field as NoteFieldAttribute).RichText ? "TRUE" : "FALSE")}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } else { if (field == null) { string fieldXml = $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } } if (field != null) { field.Update(); context.Load(field); context.ExecuteQuery(); OnProvisioned?.Invoke(this, field); } } } }
public MutableItemDefinition() { Fields = new FieldCollection(Enumerable.Empty <Field>()); Language = Language.Default; }
public static Item CreateTestItem(string id = null, string name = "Test Item", Guid templateId = default(Guid), FieldCollection fields = null) { Item item = new ShimItem() { NameGet = () => name ?? "Test Item", IDGet = () => new Sitecore.Data.ID(id ?? new Guid().ToString()), TemplateIDGet = () => new Sitecore.Data.ID(templateId), FieldsGet = () => fields ?? CreateTestFields(), }; new ShimBaseItem(item) { ItemGetString = fieldName => item.Fields[fieldName].Value }; return(item); }
public virtual void Initialize() { _orders = new List <Order>(); _conditions = new List <ICondition>(); _fieldCollection = new FieldCollection(); }
public static List EnsureLocalNavConfigList(Web web) { List list = null; try { Logger.LogInfoMessage(String.Format("Ensuring Local Nav Config list for {0} ...", web.Url), true); list = web.GetListByUrl(Constants.LocalNavListWebRelativeUrl); if (list == null) { Logger.LogInfoMessage(String.Format("Creating Local Nav Config list ..."), true); list = web.CreateList(Microsoft.SharePoint.Client.ListTemplateType.GenericList, Constants.LocalNavListTitle, false, true, Constants.LocalNavListWebRelativeUrl, false); } FieldCollection fields = list.Fields; View defaultView = list.DefaultView; ViewFieldCollection viewFields = defaultView.ViewFields; web.Context.Load(fields); web.Context.Load(defaultView); web.Context.Load(viewFields); web.Context.ExecuteQueryRetry(); Logger.LogInfoMessage(String.Format("- Ensuring List Field [{0}] ...", Constants.PnPDisplayOrder_DisplayName), false); if (list.FieldExistsById(new Guid(Constants.PnPDisplayOrder_GUID)) == false) { fields.Add(web.GetFieldById <Field>(new Guid(Constants.PnPDisplayOrder_GUID), true)); viewFields.Add(Constants.PnPDisplayOrder_InternalName); defaultView.Update(); } Logger.LogInfoMessage(String.Format("- Ensuring List Field [{0}] ...", Constants.PnPLinkText_DisplayName), false); if (list.FieldExistsById(new Guid(Constants.PnPLinkText_GUID)) == false) { fields.Add(web.GetFieldById <Field>(new Guid(Constants.PnPLinkText_GUID), true)); viewFields.Add(Constants.PnPLinkText_InternalName); defaultView.Update(); } Logger.LogInfoMessage(String.Format("- Ensuring List Field [{0}] ...", Constants.PnPLinkUrl_DisplayName), false); if (list.FieldExistsById(new Guid(Constants.PnPLinkUrl_GUID)) == false) { fields.Add(web.GetFieldById <Field>(new Guid(Constants.PnPLinkUrl_GUID), true)); viewFields.Add(Constants.PnPLinkUrl_InternalName); defaultView.Update(); } string viewQuery = String.Format(Constants.ListViewQueryFormatString, Constants.PnPDisplayOrder_InternalName); if (!defaultView.ViewQuery.Equals(viewQuery, StringComparison.InvariantCultureIgnoreCase)) { defaultView.ViewQuery = viewQuery; defaultView.Update(); } list.Update(); web.Context.ExecuteQueryRetry(); //Initialize the list ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery()); web.Context.Load(listItems); web.Context.ExecuteQueryRetry(); // Initialize the list only if it is empty. if (listItems.Count == 0) { Logger.LogInfoMessage(String.Format("Initializing Local Nav Config list ..."), false); for (int i = 0; i < 5; i++) { Logger.LogInfoMessage(String.Format("- Adding list item..."), false); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem listItem = list.AddItem(itemCreateInfo); listItem["Title"] = String.Format("Local Link {0}", i + 1); listItem[Constants.PnPDisplayOrder_InternalName] = (i + 1); listItem[Constants.PnPLinkText_InternalName] = String.Format("{0} Link {1}", web.Title, i + 1); listItem[Constants.PnPLinkUrl_InternalName] = Constants.LocalNavLinkUrl; listItem.Update(); web.Context.ExecuteQueryRetry(); } } Logger.LogSuccessMessage(String.Format("Ensured Local Nav Config list for {0}", web.Url), false); } catch (Exception ex) { Logger.LogErrorMessage(String.Format("EnsureLocalNavConfigList() failed for {0}: Error={1}", web.Url, ex.Message), false); } return(list); }
public virtual void SetSelectedFields(FieldCollection selectedFields) { _fieldCollection = selectedFields; }
public override List <ServiceObject> DescribeServiceObjects() { List <ServiceObject> SOs = new List <ServiceObject>(); using (ClientContext context = InitializeContext(base.SiteURL)) { Web spWeb = context.Web; ListCollection lists = spWeb.Lists; context.Load(lists); context.ExecuteQuery(); //Making this dummy call to load the Micorsoft.Sharepoint.Client.Taxanomy assembly (https://blogs.msdn.microsoft.com/boodablog/2014/07/04/taxonomy-fields-return-as-dictionaries-using-the-client-objcet-model-in-sharepoint-2013/) TaxonomyItem dummy = new TaxonomyItem(context, null); foreach (List list in lists) { if (list.Hidden == false || (list.Hidden && base.IncludeHiddenLists)) { if (list.BaseType == BaseType.DocumentLibrary) { context.Load(list.ContentTypes); context.ExecuteQuery(); } ServiceObject so = Helper.CreateServiceObject(list.Title, list.Title, list.Description); so.MetaData.DisplayName = list.Title; so.MetaData.Description = list.Description; if (list.BaseType == BaseType.DocumentLibrary) { so.MetaData.AddServiceElement(Constants.InternalProperties.ServiceFolder, "Document Libraries"); } else { so.MetaData.AddServiceElement(Constants.InternalProperties.ServiceFolder, "List Items"); } so.MetaData.AddServiceElement(Constants.InternalProperties.ListTitle, list.Title); so.MetaData.AddServiceElement(Constants.InternalProperties.IsFolderEnabled, list.EnableFolderCreation); so.MetaData.AddServiceElement(Constants.InternalProperties.ListBaseType, list.BaseType); if (list.BaseType == BaseType.DocumentLibrary && GetDocumentSetContentType(list.ContentTypes) != null) { so.MetaData.AddServiceElement(Constants.InternalProperties.IsListDocumentSet, true); } else { so.MetaData.AddServiceElement(Constants.InternalProperties.IsListDocumentSet, false); } FieldCollection fields = list.Fields; context.Load(fields); context.ExecuteQuery(); foreach (Field f in fields) { if (f.Hidden == false || (f.Hidden == true && base.IncludeHiddenFields)) { // We'll use InternalName as the system name and Title as the display name. // See http://blogs.perficient.com/microsoft/2009/04/static-name-vs-internal-name-vs-display-name-in-sharepoint/ for some background // Some fields have no title, so then we just take the internalname. string fieldTitle = f.Title; if (string.IsNullOrEmpty(fieldTitle)) { fieldTitle = f.InternalName; } // Because the field title can be duplicate, we see if it already exists. // If it does, we change the displayname of both existing and newly found property to something unique. // This behaviour can also be forced by the Show Internal Names option. Property existingProp = GetExistingProperty(so, fieldTitle); string displayName = fieldTitle; if (ShowInternalNames) { displayName = string.Format("{0} ({1})", fieldTitle, f.InternalName); } if (existingProp != null) { existingProp.MetaData.DisplayName = string.Format("{0} ({1})", existingProp.MetaData.GetServiceElement <string>(Constants.InternalProperties.Title), existingProp.MetaData.GetServiceElement <string>(Constants.InternalProperties.InternalName)); displayName = string.Format("{0} ({1})", fieldTitle, f.InternalName); } AddFieldProperty(so, f); FieldType _fieldtype; //We will find the Fieldtype from the MapHelper class (To get the correctoutput for field type Calculated) SoType soType = MapHelper.SPTypeField(f, out _fieldtype); Property prop = Helper.CreateSpecificProperty(f.InternalName, displayName, f.Description, soType); prop.MetaData.AddServiceElement(Constants.InternalProperties.Hidden, f.Hidden); prop.MetaData.AddServiceElement(Constants.InternalProperties.Title, fieldTitle); prop.MetaData.AddServiceElement(Constants.InternalProperties.InternalName, f.InternalName); prop.MetaData.AddServiceElement(Constants.InternalProperties.Id, f.Id); prop.MetaData.AddServiceElement(Constants.InternalProperties.ReadOnly, AssignReadonly(f)); prop.MetaData.AddServiceElement(Constants.InternalProperties.Required, f.Required); prop.MetaData.AddServiceElement(Constants.InternalProperties.FieldTypeKind, _fieldtype); prop.MetaData.AddServiceElement(Constants.InternalProperties.SPFieldType, f.TypeAsString); prop.MetaData.AddServiceElement(Constants.InternalProperties.Internal, false); so.Properties.Add(prop); } } AddInputServiceObjectPropertie(so); AddServiceObjectMethods(so); SOs.Add(so); } } ServiceObject ctSo = Helper.CreateServiceObject("ContentTypes", "Content Types", "Manage the collection of content types, which enables consistent handling of content across sites."); ctSo.MetaData.DisplayName = "Content Types"; ctSo.MetaData.Description = "Manage the collection of content types, which enables consistent handling of content across sites."; ctSo.MetaData.AddServiceElement(Constants.InternalProperties.ServiceFolder, "Management"); ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeName, "Name", "Name", SoType.Text)); //so.Properties.Add(Helper.CreateSpecificProperty("SiteURL", "Site URL", "Site URL", SoType.Text)); ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeGroup, "Group", "Group", SoType.Text)); ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeReadOnly, "ReadOnly", "ReadOnly", SoType.YesNo)); ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeHidden, "Hidden", "Hidden", SoType.Text)); ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeCount, "Count", "Count", SoType.Number)); ctSo.Properties.Add(Helper.CreateSpecificProperty(Constants.SOProperties.ContentTypeID, "Content Type ID", "Content Type ID", SoType.Text)); AddContentTypeServiceObjectMethods(ctSo); SOs.Add(ctSo); return(SOs); } }
protected virtual void HandleIncorectlyDeletedTaxonomyField(FieldDefinition fieldModel, FieldCollection fields) { return; // excluded due ot potential data corruption // such issues shoud be handled by end user manually //var context = fields.Context; //var isTaxField = // fieldModel.FieldType.ToUpper() == BuiltInFieldTypes.TaxonomyFieldType.ToUpper() // || fieldModel.FieldType.ToUpper() == BuiltInFieldTypes.TaxonomyFieldTypeMulti.ToUpper(); //if (!isTaxField) // return; //var existingIndexedFieldName = fieldModel.Title + "_0"; //var query = from field in fields // where field.Title == existingIndexedFieldName // select field; //var result = context.LoadQuery(query); //context.ExecuteQueryWithTrace(); //if (result.Count() > 0) //{ // var existingIndexedField = result.FirstOrDefault(); // if (existingIndexedField != null && existingIndexedField.FieldTypeKind == FieldType.Note) // { // // tmp fix // // https://github.com/SubPointSolutions/spmeta2/issues/521 // try // { // existingIndexedField.DeleteObject(); // context.ExecuteQueryWithTrace(); // } // catch (Exception e) // { // } // } //} }
/// <summary> /// Assign field values for specified content types to the specified matter (document library) /// </summary> /// <param name="matterMetadata">Object containing metadata for Matter</param> /// <param name="fields">Field Collection object</param> internal static void SetFieldValues(MatterMetadata matterMetadata, FieldCollection fields) { fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientId"]).DefaultValue = matterMetadata.Client.ClientId; fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientId"]).ReadOnlyField = true; fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientId"]).SetShowInDisplayForm(true); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientId"]).Update(); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientName"]).ReadOnlyField = true; fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientName"]).SetShowInDisplayForm(true); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientName"]).DefaultValue = matterMetadata.Client.ClientName; fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientName"]).Update(); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterId"]).DefaultValue = matterMetadata.Matter.MatterId; fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterId"]).ReadOnlyField = true; fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterId"]).SetShowInDisplayForm(true); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterId"]).Update(); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterName"]).DefaultValue = matterMetadata.Matter.MatterName; fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterName"]).ReadOnlyField = true; fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterName"]).SetShowInDisplayForm(true); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterName"]).Update(); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnPracticeGroup"]).DefaultValue = string.Format(CultureInfo.InvariantCulture, Constants.MetadataDefaultValue, matterMetadata.PracticeGroupTerm.WssId, matterMetadata.PracticeGroupTerm.TermName, matterMetadata.PracticeGroupTerm.Id); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnPracticeGroup"]).SetShowInDisplayForm(true); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnPracticeGroup"]).Update(); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnAreaOfLaw"]).DefaultValue = string.Format(CultureInfo.InvariantCulture, Constants.MetadataDefaultValue, matterMetadata.AreaTerm.WssId, matterMetadata.AreaTerm.TermName, matterMetadata.AreaTerm.Id); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnAreaOfLaw"]).SetShowInDisplayForm(true); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnAreaOfLaw"]).Update(); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnSubareaOfLaw"]).DefaultValue = string.Format(CultureInfo.InvariantCulture, Constants.MetadataDefaultValue, matterMetadata.SubareaTerm.WssId, matterMetadata.SubareaTerm.TermName, matterMetadata.SubareaTerm.Id); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnSubareaOfLaw"]).SetShowInDisplayForm(true); fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnSubareaOfLaw"]).Update(); }
private void Populate() { if (QueryResult.SiteSetting == null) { return; } if (SourceFolder == null) { SiteSetting siteSetting = (SiteSetting)QueryResult.SiteSetting; SourceFolder = ApplicationContext.Current.GetFolder((SiteSetting)QueryResult.SiteSetting, new BasicFolderDefinition() { FolderUrl = siteSetting.Url + "/" + QueryResult.FolderPath, SiteSettingID = QueryResult.SiteSetting.ID }); } else { QueryResult.Filters = new CamlFilters(); QueryResult.ReferenceFields = new List <QueryResultReferenceField>(); } SourceSelectButton.Content = SourceFolder.GetPath(); QueryResult.ListName = SourceFolder.GetListName(); QueryResult.Name = SourceFolder.GetListName(); SourceSiteSetting = ApplicationContext.Current.GetSiteSetting(SourceFolder.SiteSettingID); SourceFields = ApplicationContext.Current.GetFields(SourceSiteSetting, SourceFolder); string[] requiredFields = new string[] { QueryResult.PrimaryIdFieldName, QueryResult.PrimaryNameFieldName, QueryResult.PrimaryFileReferenceFieldName, QueryResult.ModifiedByFieldName, QueryResult.ModifiedOnFieldName }; requiredFields = requiredFields.Where(x => !string.IsNullOrEmpty(x)).ToArray(); foreach (string requiredField in requiredFields) { Field sourceField = SourceFields.Where(t => t.Name.Equals(requiredField, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (sourceField == null) { SourceFields.Add(new Field() { Name = requiredField, Type = FieldTypes.Text, DisplayName = requiredField }); } } QueryResult.SiteSetting = (SiteSetting)SourceSiteSetting; /* * List<string> tempSourceFields = new List<string>(); * tempSourceFields.AddRange(QueryResult.Fields); * foreach(string requiredField in RequiredFields) * { * if(tempSourceFields.Contains(requiredField) == false) * { * tempSourceFields.Add(requiredField); * } * } * QueryResult.Fields = tempSourceFields.ToArray(); */ QueryResult.IsDocumentLibrary = SourceFolder.IsDocumentLibrary; PopulateFilters(); ViewFieldsMenuItem.Items.Clear(); foreach (Field field in SourceFields) { MenuItem mi = new MenuItem(); CheckBox checkBox = new CheckBox(); checkBox.Tag = field; checkBox.Content = field.DisplayName; checkBox.HorizontalAlignment = HorizontalAlignment.Left; checkBox.Margin = new Thickness(0, 0, 0, 0); checkBox.VerticalAlignment = VerticalAlignment.Top; checkBox.Click += CheckBox_Click; if (requiredFields.Contains(field.Name) == true) { checkBox.IsChecked = true; checkBox.IsEnabled = false; ViewFieldsCheckBoxChanged(checkBox, field); //CheckBox_Click(checkBox, new RoutedEventArgs() { Source = checkBox }); } else { checkBox.IsChecked = (localQueryResultMappingSelectFields.Where(t => t.FieldName.Equals(field.Name) == true).Count() > 0 ? true : false); } mi.Header = checkBox; ViewFieldsMenuItem.Items.Add(mi); } /* * if (SourceFolder.IsDocumentLibrary == true) * { * if(QueryResult.Fields.Contains("FileRef") == false) * { * List<string> newArray = QueryResult.Fields.ToList(); * newArray.Add("FileRef"); * * QueryResult.Fields = newArray.ToArray(); * } * } */ }
private Field FindField(FieldCollection fields, ContentTypeFieldLinkDefinition listFieldLinkModel) { var context = fields.Context; var scope = new ExceptionHandlingScope(context); Field field = null; if (listFieldLinkModel.FieldId.HasGuidValue()) { var id = listFieldLinkModel.FieldId.Value; using (scope.StartScope()) { using (scope.StartTry()) { fields.GetById(id); } using (scope.StartCatch()) { } } } else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName)) { var fieldInternalName = listFieldLinkModel.FieldInternalName; using (scope.StartScope()) { using (scope.StartTry()) { fields.GetByInternalNameOrTitle(fieldInternalName); } using (scope.StartCatch()) { } } } context.ExecuteQueryWithTrace(); if (!scope.HasException) { if (listFieldLinkModel.FieldId.HasGuidValue()) { field = fields.GetById(listFieldLinkModel.FieldId.Value); } else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName)) { field = fields.GetByInternalNameOrTitle(listFieldLinkModel.FieldInternalName); } context.Load(field); context.Load(field, f => f.SchemaXml); context.ExecuteQueryWithTrace(); } return field; }
protected override void ExecuteCmdlet() { if (List != null) { var list = this.SelectedWeb.GetList(List); Field f = null; FieldCollection c = null; if (list != null) { if (Identity.Id != Guid.Empty) { f = list.Fields.GetById(Identity.Id); } else if (!string.IsNullOrEmpty(Identity.Name)) { f = list.Fields.GetByInternalNameOrTitle(Identity.Name); } else { c = list.Fields; ClientContext.Load(c); ClientContext.ExecuteQuery(); } } if (f != null) { ClientContext.Load(f); ClientContext.ExecuteQuery(); WriteObject(f); } else if (c != null) { WriteObject(c, true); } else { WriteObject(null); } } else { // Get a site column if (Identity.Id == Guid.Empty && string.IsNullOrEmpty(Identity.Name)) { // Get all columns ClientContext.Load(this.SelectedWeb.Fields); ClientContext.ExecuteQuery(); WriteObject(this.SelectedWeb.Fields, true); } else { Field f = null; if (Identity.Id != Guid.Empty) { f = this.SelectedWeb.Fields.GetById(Identity.Id); } else if (!string.IsNullOrEmpty(Identity.Name)) { f = this.SelectedWeb.Fields.GetByInternalNameOrTitle(Identity.Name); } ClientContext.Load(f); ClientContext.ExecuteQuery(); WriteObject(f); } } }