void AddFields() { SPField assignmentId = AddField(DropBox.ColumnAssignmentId, SPFieldType.Text, false); assignmentId.Indexed = true; assignmentId.Update(); dropBoxList.Update(); web.Update(); AddField(DropBox.ColumnAssignmentDate, SPFieldType.DateTime, true); AddField(DropBox.ColumnAssignmentName, SPFieldType.Text, true); AddField(DropBox.ColumnIsLatest, SPFieldType.Boolean, true); AddField(DropBox.ColumnLearner, SPFieldType.User, true); AddField(DropBox.ColumnLearnerId, SPFieldType.Text, false); dropBoxList.Update(); web.Update(); SPFieldCalculated assignmentKey = (SPFieldCalculated)AddField(DropBox.ColumnAssignmentKey, SPFieldType.Calculated, true, false); // The formula depends on the regional settings of the web, notably the list separator required. // So for a standard english site the formula will be // =TEXT(AssignmentDate,"yyyy-mm-dd")&" "&AssignmentName // but for many regions, notably Europe, the list separator is ; so the formula needs to be // =TEXT(AssignmentDate;"yyyy-mm-dd")&" "&AssignmentName // SharePoint automatically converts formulae when you change the regional settings. Originally the code changed the web Locale before adding the fields // and then changed back at the end, but this is simpler, and in some environments that change caused errors which prevented any fields being added. string formula = "=TEXT([{0}]{2} \"yyyy-mm-dd\")&\" \"&[{1}]"; assignmentKey.Formula = string.Format(formula, DropBox.ColumnAssignmentDate, DropBox.ColumnAssignmentName, web.Locale.TextInfo.ListSeparator); assignmentKey.Update(); dropBoxList.Update(); web.Update(); }
public static Control GetFieldControl(this SPFieldCalculated calcField) { Control control = null; switch (calcField.OutputType) { case SPFieldType.Number: case SPFieldType.Currency: control = new TextBox() { CssClass = "ms-long" }; break; case SPFieldType.DateTime: DateTimeControl dtcValueDate = new DateTimeControl(); dtcValueDate.DateOnly = (calcField.DateFormat == SPDateTimeFieldFormatType.DateOnly); control = dtcValueDate; break; case SPFieldType.Boolean: control = new CheckBox(); break; default: control = new TextBox() { CssClass = "ms-long" }; break; } return(control); }
public static string GetDateFormat(this SPFieldCalculated field) { var value = field.DateFormat.ToString();; // also, wihtint expected range field.GetDateFormatString(); return(field.DateFormat.ToString()); }
public override bool AllowDateParsing(RecordProperty prop) { SPFieldCalculated property = prop.Property as SPFieldCalculated; if (property != null) { return(property.OutputType == SPFieldType.DateTime); } return(true); }
public static string FormatValueAsText(this SPFieldCalculated calcField, string rawValue) { string result = rawValue; CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; switch (calcField.OutputType) { case SPFieldType.Number: try { var numberValue = Convert.ToDouble(rawValue); result = SPFieldNumber.GetFieldValueAsText(numberValue, currentCulture, calcField.ShowAsPercentage, calcField.DisplayFormat); } catch { result = string.Empty; } break; case SPFieldType.DateTime: try { var dateValue = Convert.ToDateTime(rawValue); result = SPFieldDateTime.GetFieldValueAsText(dateValue, SPContext.Current.Web, calcField.DateFormat == SPDateTimeFieldFormatType.DateTime ? SPDateFormat.DateTime : SPDateFormat.DateOnly); } catch { result = string.Empty; } break; case SPFieldType.Currency: try { double data = Convert.ToDouble(rawValue, CultureInfo.InvariantCulture); result = SPFieldCurrency.GetFieldValueAsText(data, currentCulture, calcField.CurrencyLocaleId, calcField.DisplayFormat); } catch { result = string.Empty; } break; case SPFieldType.Boolean: try { result = Convert.ToBoolean(Convert.ToByte(rawValue)).ToString(); } catch { } break; default: break; } return(result); }
public static string GetFieldValueAsTextEx(this SPFieldCalculated calcField, Control control, bool ignoreValidation) { string value = string.Empty; switch (calcField.OutputType) { case SPFieldType.Number: case SPFieldType.Currency: TextBox txtNumber = (TextBox)control; if (!ignoreValidation && string.IsNullOrEmpty(txtNumber.Text)) { break; } value = txtNumber.Text; break; case SPFieldType.DateTime: DateTimeControl dtcValueDate = (DateTimeControl)control; if (!ignoreValidation && dtcValueDate.IsDateEmpty) { break; } value = SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtcValueDate.SelectedDate); break; case SPFieldType.Boolean: CheckBox chkField = (CheckBox)control; value = chkField.Checked ? "1" : "0"; break; default: TextBox txtString = (TextBox)control; if (!ignoreValidation && string.IsNullOrEmpty(txtString.Text)) { break; } value = txtString.Text; break; } return(value); }
public static Control SetValueToControl(this SPFieldCalculated calcField, Control control, string value) { switch (calcField.OutputType) { case SPFieldType.DateTime: DateTimeControl dtcValueDate = (DateTimeControl)control; dtcValueDate.SelectedDate = Convert.ToDateTime(value).ToUniversalTime(); break; case SPFieldType.Boolean: CheckBox chkField = (CheckBox)control; chkField.Checked = Convert.ToBoolean(Convert.ToByte(value)); break; default: TextBox txtInput = (TextBox)control; txtInput.Text = value; break; } return(control); }
public static string GetDateFormat(this SPFieldCalculated field) { return(field.DateFormat.ToString()); }
public static string GetOutputType(this SPFieldCalculated field) { return(field.OutputType.ToString()); }
public static void AddColForSortToList(string siteUrl) { if (!string.IsNullOrEmpty(siteUrl)) { string colName = "ColForSort"; List <string> listNameCollection = new List <string>() { "Change Shift Management", "Leave Of Absence For Overtime Management", "Vehicle Management", "Leave Management" }; //"Overtime Management", "Overtime Employee Details", try { SPSecurity.RunWithElevatedPrivileges(delegate() { Console.Write("Processing..."); using (SPSite spSite = new SPSite(siteUrl)) { using (SPWeb spWeb = spSite.RootWeb) { #region CalculatedField foreach (var listName in listNameCollection) { SPList spList = spWeb.Lists.TryGetList(listName); if (spList != null) { Console.WriteLine(); Console.Write("List Name: {0}", listName); spWeb.AllowUnsafeUpdates = true; if (spList.Fields.ContainsField(colName) == false) { spList.Fields.Add(colName, SPFieldType.Calculated, false); SPField spField = spList.Fields.TryGetFieldByStaticName(colName); if (spField != null) { SPFieldCalculated calculatedField = spField as SPFieldCalculated; calculatedField.OutputType = SPFieldType.Number; calculatedField.DisplayFormat = SPNumberFormatTypes.NoDecimal; calculatedField.Formula = "=IF([Approval Status]=\"Approved\",INT(\"7\"),IF([Approval Status]=\"Rejected\",INT(\"8\"),IF([Approval Status]=\"Cancelled\",INT(\"9\"),INT(\"0\"))))"; calculatedField.Update(); Console.Write(" -> Done"); } else { Console.Write(" -> Failed"); } } else { Console.Write(" -> Existed"); } spWeb.AllowUnsafeUpdates = false; } else { Console.WriteLine(); Console.Write("Cannot find list: {0}", listName); } } #endregion #region Create ColForSort for Overtime Management List string overtimeManagementListName = "Overtime Management"; Console.WriteLine(); Console.Write("List Name: {0}", overtimeManagementListName); SPList overtimeManagementList = spWeb.Lists.TryGetList(overtimeManagementListName); if (overtimeManagementList != null) { if (overtimeManagementList.Fields.ContainsField(colName) == false) { spWeb.AllowUnsafeUpdates = true; overtimeManagementList.Fields.Add(colName, SPFieldType.Number, false); SPField spField = overtimeManagementList.Fields.TryGetFieldByStaticName(colName); if (spField != null) { SPFieldNumber spFieldNumber = spField as SPFieldNumber; spFieldNumber.DisplayFormat = SPNumberFormatTypes.NoDecimal; spFieldNumber.Update(); Console.Write(" -> Done"); } else { Console.Write(" -> Failed"); } spWeb.AllowUnsafeUpdates = false; } else { Console.Write(" -> Existed"); } } else { Console.WriteLine(); Console.Write("Cannot find list: {0}", overtimeManagementListName); } #endregion #region Create CalculateField ColForSort for Overtime Employee Details list string overtimeDetailsListName = "Overtime Employee Details"; Console.WriteLine(); Console.Write("List Name: {0}", overtimeDetailsListName); SPList overtimeDetailsList = spWeb.Lists.TryGetList(overtimeDetailsListName); SPList overtimeList = spWeb.Lists.TryGetList("Overtime Management"); if (overtimeDetailsList != null && overtimeList != null) { if (overtimeDetailsList.Fields.ContainsField(colName) == false && overtimeList.Fields.ContainsField(colName) == true) { spWeb.AllowUnsafeUpdates = true; overtimeDetailsList.Fields.AddDependentLookup(colName, new Guid("{878e2996-150c-4e63-b632-ba90dec566a0}")); SPField spField = overtimeDetailsList.Fields.TryGetFieldByStaticName(colName); if (spField != null) { SPFieldLookup spFieldLookup = spField as SPFieldLookup; spFieldLookup.LookupField = colName; spFieldLookup.Update(); Console.Write(" -> Done"); } else { Console.Write(" -> Failed"); } spWeb.AllowUnsafeUpdates = false; } else { Console.Write(" -> Existed"); } } #endregion } } }); } catch (Exception ex) { Console.WriteLine(string.Format("Error: {0}", ex.Message)); } Console.WriteLine(); //Console.Write("Press any key to exit..."); //Console.Read(); } else { Console.Write("Troll?"); Console.Read(); } }
protected override void Render(HtmlTextWriter __w) { int num2 = 40; Guid guid; SPQuery query; bool flag = "1".Equals(base.Request["b"]); bool flag2 = false; bool flag3 = false; bool flag4 = false; int num = 40; int num3 = 0; int num4 = -1; int num5 = 0; string str = base.Request["fs"]; string str6 = (base.Request["q"] + string.Empty).Trim(); string str7 = (flag = flag ? true : ((str6.Length != 1) ? false : ProductPage.Config <bool>(ProductPage.GetContext(), "Auto1Begins"))) ? "BeginsWith" : "Contains"; SPList list = null; SPView defaultView = null; SPListItemCollection collection = null; List <string> list2 = new List <string>(); List <string> list3 = new List <string>(); List <SPField> list4 = new List <SPField>(); if (!int.TryParse(ProductPage.Config(ProductPage.GetContext(), "AutoLimit"), out num2) || (num2 <= 1)) { num2 = num; } //if (!int.TryParse(base.Request["limit"], out num2) || (num2 <= 1)) //{ // num2 = num; //} try { list = SPContext.Current.Web.Lists[ProductPage.GetGuid(base.Request["l"])]; } catch { } if (list == null) { __w.Write(ProductPage.GetProductResource("AutoNoList", new object[] { ProductPage.GetGuid(base.Request["l"]) })); goto Label_0876; } SPField field = ProductPage.GetField(list, base.Request["f"]); if (field == null) { __w.Write(ProductPage.GetProductResource("AutoNoField", new object[] { base.Request["f"] })); goto Label_0876; } if (string.IsNullOrEmpty(str6)) { goto Label_0876; } foreach (string str8 in (base.Request["sf"] + string.Empty).Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { SPField field2 = ProductPage.GetField(list, str8); if (field2 != null) { list4.Add(field2); } } SPFieldCalculated calculated = field as SPFieldCalculated; SPFieldUrl url = field as SPFieldUrl; SPFieldLookup lookup = field as SPFieldLookup; if (!string.IsNullOrEmpty(base.Request["v"]) && !Guid.Empty.Equals(guid = ProductPage.GetGuid(base.Request["v"]))) { try { defaultView = list.Views[guid]; } catch { } } if (defaultView == null) { defaultView = list.DefaultView; } Label_02A7: for (int queryNum = 0; queryNum < 2; queryNum++) { if (list2.Count >= num2) { break; } query = new SPQuery(defaultView); query.Folder = list.RootFolder; query.IncludeAllUserPermissions = query.IncludeMandatoryColumns = query.IncludePermissions = query.IndividualProperties = query.AutoHyperlink = query.ExpandRecurrence = query.ExpandUserField = query.IncludeAttachmentVersion = query.IncludeAttachmentUrls = query.ItemIdQuery = false; query.ViewAttributes = "FailIfEmpty=\"FALSE\" RequiresClientIntegration=\"FALSE\" Threaded=\"FALSE\" Scope=\"Recursive\""; query.ViewFields = "<FieldRef Name=\"" + field.InternalName + "\"/>"; foreach (SPField field3 in list4) { query.ViewFields = query.ViewFields + "<FieldRef Name=\"" + field3.InternalName + "\"/>"; } string str5 = (calculated != null) ? calculated.OutputType.ToString() : field.TypeAsString; flag2 = Array.IndexOf <string>(nonTextFieldTypes, field.TypeAsString) >= 0; Array.IndexOf <string>(unsupportedFieldTypes, field.TypeAsString); ArrayList alist = new ArrayList(); if (queryNum == 0) { alist.Add(str6); query.Query = (flag4 ? string.Empty : ("<Where><" + str7 + "><FieldRef Name=\"" + field.InternalName + "\" /><Value Type=\"" + (flag3 ? "Text" : str5) + "\">" + str6 + "</Value></" + str7 + "></Where>")) + "<OrderBy><FieldRef Name=\"" + field.InternalName + "\"/></OrderBy>"; } else { try { Segment segment = new Segment(); Segment.Init(Server.MapPath("/_layouts/PanGuSegment/PanGu.xml")); ICollection <WordInfo> words = segment.DoSegment(str6); string queryCondition = ""; Dictionary <string, string> listCamls = new Dictionary <string, string>(); string testDrawCamlTree = ""; int i = 1; foreach (WordInfo wordInfo in words) { if (wordInfo != null && wordInfo.Word.Replace(" ", "") != "" && wordInfo.Word.Length == 1) { alist.Add(wordInfo.Word); testDrawCamlTree += "0-And:" + i + ";"; listCamls.Add(i.ToString(), "<" + str7 + "><FieldRef Name=\"" + field.InternalName + "\" /><Value Type=\"" + (flag3 ? "Text" : str5) + "\">" + wordInfo.Word + "</Value></" + str7 + ">"); i++; } } if (listCamls.Count > 0) { query.Query = (flag4 ? string.Empty : "<Where>" + BSTUtils.DrawCamlTree(testDrawCamlTree.TrimEnd(';'), listCamls) + "</Where>") + "<OrderBy><FieldRef Name=\"" + field.InternalName + "\"/></OrderBy>"; } else { break; } } catch (Exception ex) { break; } } query.RowLimit = (uint)100000; collection = list.GetItems(query); if (collection != null) { num4 = 0; foreach (SPListItem item in ProductPage.TryEach <SPListItem>(collection)) { string lookupValue; string str3 = string.Empty; string str4 = string.Empty; foreach (SPField field4 in list4) { if ((field4 != null) && !Guid.Empty.Equals(field4.Id)) { try { str4 = item[field4.Id] + string.Empty; } catch { str4 = string.Empty; } } if (!string.IsNullOrEmpty(str4)) { string str11 = str3; str3 = str11 + "<div class=\"rox-acsecfield\"><i>" + base.Server.HtmlEncode(field4.Title) + ":</i> " + str4.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ") + "</div>"; } } num4++; string[] strArray = null; object obj2 = ProductPage.GetFieldVal(item, field, true); if (!string.IsNullOrEmpty(lookupValue = (obj2 == null) ? string.Empty : field.GetFieldValueAsText(obj2))) { if (!IsContains(lookupValue.Trim(), alist)) { lookupValue = string.Empty; } else if (lookup != null) { SPFieldUserValueCollection values2 = obj2 as SPFieldUserValueCollection; if (values2 != null) { lookupValue = string.Empty; strArray = values2.ConvertAll <string>(uv => uv.LookupValue).ToArray(); } else { SPFieldLookupValueCollection values = obj2 as SPFieldLookupValueCollection; if (values != null) { lookupValue = string.Empty; strArray = values.ConvertAll <string>(lv => lv.LookupValue).ToArray(); } else { SPFieldLookupValue value2 = obj2 as SPFieldLookupValue; if (value2 != null) { lookupValue = value2.LookupValue; } } } } else { SPFieldUrlValue value3; if ((url != null) && ((value3 = obj2 as SPFieldUrlValue) != null)) { lookupValue = value3.Url; } else if (field.Type == SPFieldType.MultiChoice) { strArray = (obj2 + string.Empty).Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries); } else if (!string.IsNullOrEmpty(str)) { strArray = (obj2 + string.Empty).Split(new string[] { str }, StringSplitOptions.RemoveEmptyEntries); } } } if (!IsContains(lookupValue.Trim(), alist)) { lookupValue = string.Empty; } if (strArray != null) { for (int i = 0; i < strArray.Length; i++) { if (!IsContains(strArray[i].Trim(), alist)) { strArray[i] = string.Empty; } } } else if (!string.IsNullOrEmpty(lookupValue)) { strArray = new string[] { lookupValue }; } else { strArray = new string[0]; } if (strArray.Length > 0) { num3++; foreach (string str9 in strArray) { if ((!string.IsNullOrEmpty(str9) && (IsContains(str9.Trim(), alist))) && !list2.Contains(str9.Trim())) { list3.Add(str3); list2.Add(str9.Trim()); } } } if (list2.Count >= num2) { break; } } } } if (num4 < (flag2 ? 1 : 0)) { if (flag2 && !flag3) { flag3 = true; goto Label_02A7; } if (!flag4) { flag4 = true; goto Label_02A7; } } Label_0876: //list2.Sort(); foreach (string str10 in list2) { __w.Write(str10.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ") + list3[num5++] + "\r\n"); } }
public static string CalculatedFieldToString(this SPListItem item, string fieldName) { SPFieldCalculated cf = (SPFieldCalculated)item.Fields.GetField(fieldName);; return(cf.GetFieldValueForEdit(item[fieldName])); }
public static string GetFieldValueAsTextOrHtml(this SPFieldCalculated calcField, object value, bool asHtml) { if (value == null) { return(string.Empty); } string strType = string.Empty; string str2 = string.Empty; string str3 = value as string; if (str3 == null) { throw new ArgumentOutOfRangeException(); } str2 = str3; int length = StsBinaryCompareIndexOf(str2, ";#"); if (length < 0) { throw new ArgumentOutOfRangeException(); } strType = str2.Substring(0, length).ToUpper(CultureInfo.InvariantCulture); str2 = str2.Substring(length + ";#".Length); if (((calcField.OutputType == SPFieldType.Invalid) || (calcField.OutputType == SPFieldType.Error)) || (strType == "ERROR")) { string formattedErrorValue = GetFormattedErrorValue(strType, str2); if (asHtml) { return(SPHttpUtility.HtmlEncode(formattedErrorValue)); } return(formattedErrorValue); } try { bool flag = false;; switch (strType) { case "FLOAT": { //double data = Convert.ToDouble(str2, CultureInfo.InvariantCulture); //CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture; //if (calcField.OutputType == SPFieldType.Currency) //{ // string valueToEncode = FormatValue(data, calcField.Currency..DisplayFormat); // if (asHtml) // { // valueToEncode = SPHttpUtility.HtmlEncode(valueToEncode); // } // return valueToEncode; //} //if (asHtml) //{ // return SPFieldNumber.GetFieldValueAsHtml(data, currentCulture, calcField.ShowAsPercentage, calcField.DisplayFormat); //} //return SPFieldNumber.GetFieldValueAsText(data, currentCulture, calcField.ShowAsPercentage, calcField.DisplayFormat); } break; case "DATETIME": { //SPDateFormat dateTime; //if (base.IsXLVWPConnection) //{ // return str2; //} //DateTime time = SPUtility.CreateSystemDateTimeFromXmlDataDateTimeFormat(str2); //if (this.DateFormat == SPDateTimeFieldFormatType.DateTime) //{ // dateTime = SPDateFormat.DateTime; //} //else //{ // dateTime = SPDateFormat.DateOnly; //} //if (asHtml) //{ // return SPFieldDateTime.GetFieldValueAsHtml(time, base.Fields.Web, dateTime); //} //return SPFieldDateTime.GetFieldValueAsText(time, base.Fields.Web, dateTime); } break; default: if (!(strType == "BOOLEAN")) { goto Label_01FA; } switch (str2) { case "TRUE": case "-1": case "1": flag = true; break; } flag = false; break; } //if (asHtml) //{ // return SPFieldBoolean.GetFieldValueAsHtml(flag); //} return(SPFieldBoolean.GetFieldValueAsText(flag)); Label_01FA: if (asHtml) { return(SPHttpUtility.HtmlEncode(str2)); } return(str2); } catch (ArgumentOutOfRangeException) { if (asHtml) { return(SPHttpUtility.HtmlEncode(str2)); } return(str2); } //return string.Empty; }
private string getFieldValue(string fieldname, string value) { try { SPField oField = base.list.Fields.GetFieldByInternalName(fieldname); switch (oField.Type) { case SPFieldType.DateTime: if (value != "") { try { DateTime dt = (DateTime)oField.GetFieldValue(value); return(dt.ToString("yyyy-MM-dd HH:mm:ss")); } catch { } } return(value); case SPFieldType.Number: SPFieldNumber num = (SPFieldNumber)oField; if (num.ShowAsPercentage) { if (value.Contains("%")) { return(value.Replace("%", "")); } else { return((float.Parse(value, providerEn) * 100).ToString(providerEn)); } } else { return(float.Parse(value, providerEn).ToString(providerEn)); } case SPFieldType.Calculated: if (oField.Description == "Indicator") { if (value != "" && !value.StartsWith("<img src")) { value = "<img src=\"/_layouts/images/" + value.ToLower() + "\">"; } } SPFieldCalculated calc = (SPFieldCalculated)oField; if (calc.ShowAsPercentage) { if (value.Contains("%")) { return(value.Replace("%", "")); } else { return((float.Parse(value, providerEn) * 100).ToString(providerEn)); } } else { return(float.Parse(value, providerEn).ToString(providerEn)); } case SPFieldType.Boolean: if (value.ToLower() == "true") { return("1"); } return("0"); case SPFieldType.Note: return(HttpUtility.HtmlDecode(value)); default: switch (oField.TypeAsString) { case "TotalRollup": return(oField.GetFieldValueAsText(value)); default: return(HttpUtility.HtmlDecode(value)); } } } catch { } return(value); }
protected override void outputXml() { tb.AddTimer(); XmlDocument doc = new XmlDocument(); doc.LoadXml(Properties.Resources.txtGanttLayout.Replace("#gridid#", base.gridname)); XmlNode ndHeader = doc.FirstChild.SelectSingleNode("//Header"); XmlNode ndCols = doc.FirstChild.SelectSingleNode("//LeftCols"); //XmlNode ndLeftCols = doc.FirstChild.SelectSingleNode("//LeftCols"); if (showCheckboxes) { doc.FirstChild.SelectSingleNode("//Panel").Attributes["Visible"].Value = "1"; } ArrayList arrFields = new ArrayList(); string sTitleField = "Title"; foreach (string field in aViewFields) { try { SPField oField = getRealField(list.Fields.GetFieldByInternalName(field)); if (oField.InternalName == "Title") { sTitleField = field; } arrFields.Add(oField.InternalName); XmlNode ndNew = doc.CreateNode(XmlNodeType.Element, "C", doc.NamespaceURI); XmlAttribute attr = doc.CreateAttribute("Name"); attr.Value = oField.InternalName; if (attr.Value == "State") { attr.Value = "FState"; } ndNew.Attributes.Append(attr); attr = doc.CreateAttribute("CaseSensitive"); attr.Value = "0"; ndNew.Attributes.Append(attr); XmlDocument oDoc = new XmlDocument(); oDoc.LoadXml(oField.SchemaXml); string sFormat = getFormat(oField, oDoc, SPContext.Current.Web); string sType = "Html"; string sTitle = oField.Title; string sTitleAlign = "Left"; if (sFormat != "") { attr = doc.CreateAttribute("Format"); attr.Value = sFormat; ndNew.Attributes.Append(attr); if (oField.Type == SPFieldType.Currency) { SPFieldCurrency c = (SPFieldCurrency)oField; System.Globalization.NumberFormatInfo nInfo = System.Globalization.CultureInfo.GetCultureInfo(c.CurrencyLocaleId).NumberFormat; if (sFormat.Contains(nInfo.CurrencySymbol)) { attr = doc.CreateAttribute("EditFormat"); attr.Value = sFormat.Replace(nInfo.CurrencySymbol, string.Empty); ndNew.Attributes.Append(attr); } } else { attr = doc.CreateAttribute("EditFormat"); attr.Value = sFormat; ndNew.Attributes.Append(attr); } } if (oField.InternalName == "Edit") { attr = doc.CreateAttribute("Width"); attr.Value = "50"; ndNew.Attributes.Append(attr); } else if (oField.InternalName == "Title") { attr = doc.CreateAttribute("MinWidth"); attr.Value = "300"; ndNew.Attributes.Append(attr); attr = doc.CreateAttribute("Button"); attr.Value = "Html"; ndNew.Attributes.Append(attr); attr = doc.CreateAttribute("RelWidth"); attr.Value = "1"; ndNew.Attributes.Append(attr); } else if (oField.InternalName == "WorkspaceUrl") { attr = doc.CreateAttribute("Width"); attr.Value = "60"; ndNew.Attributes.Append(attr); attr = doc.CreateAttribute("Align"); attr.Value = "Center"; sTitleAlign = "Center"; ndNew.Attributes.Append(attr); attr = doc.CreateAttribute("WorkspaceUrl"); attr.Value = "h"; ndHeader.Attributes.Append(attr); sTitle = ""; } else { string sWidth = "150"; switch (oField.Type) { case SPFieldType.Text: sWidth = "150"; break; case SPFieldType.Number: attr = doc.CreateAttribute("Align"); attr.Value = "Right"; sTitleAlign = "Right"; ndNew.Attributes.Append(attr); sType = "Float"; break; case SPFieldType.Currency: attr = doc.CreateAttribute("Align"); attr.Value = "Right"; sTitleAlign = "Right"; ndNew.Attributes.Append(attr); sType = "Float"; break; case SPFieldType.DateTime: attr = doc.CreateAttribute("Align"); attr.Value = "Left"; ndNew.Attributes.Append(attr); sType = "Date"; break; case SPFieldType.Boolean: sType = "Bool"; break; case SPFieldType.Calculated: SPFieldCalculated oFC = (SPFieldCalculated)oField; if (oFC.OutputType == SPFieldType.Number || oFC.OutputType == SPFieldType.Currency || oFC.OutputType == SPFieldType.DateTime) { attr = doc.CreateAttribute("Align"); attr.Value = "Right"; sTitleAlign = "Right"; ndNew.Attributes.Append(attr); if (oFC.OutputType == SPFieldType.DateTime) { sType = "Date"; } else { sType = "Float"; } } else if (oFC.Description == "Indicator") { attr = doc.CreateAttribute("Align"); attr.Value = "Center"; sTitleAlign = "Center"; ndNew.Attributes.Append(attr); sWidth = "80"; } break; case SPFieldType.Choice: sType = "Enum"; { //Reference: http://longboo.com/demo/ejs-treegrid/Doc/TypeEnum.htm string senum = ""; string senumrange = ""; SPFieldChoice oCField = (SPFieldChoice)oField; //Used to prepare dropdown with field choice options foreach (string sChoice in oCField.Choices) { senum += ";" + sChoice.Replace(";", ""); } //Used to prepare count for an item //for (int i = 0; i < oCField.Choices.Count; i++) // senumrange += ";" + i.ToString(); senumrange = senum; attr = doc.CreateAttribute("Enum"); attr.Value = senum; ndNew.Attributes.Append(attr); attr = doc.CreateAttribute("EnumKeys"); attr.Value = senumrange; ndNew.Attributes.Append(attr); } sWidth = "150"; break; case SPFieldType.Lookup: sWidth = "150"; sType = "Enum"; attr = doc.CreateAttribute("Enum"); attr.Value = ""; ndNew.Attributes.Append(attr); attr = doc.CreateAttribute("EnumKeys"); attr.Value = ""; ndNew.Attributes.Append(attr); if (oField.TypeAsString.Equals("LookupMulti", StringComparison.InvariantCultureIgnoreCase)) { attr = doc.CreateAttribute("Range"); attr.Value = "1"; ndNew.Attributes.Append(attr); } hshLookupEnums.Add(oField.InternalName, new ArrayList()); hshLookupEnumKeys.Add(oField.InternalName, new ArrayList()); break; case SPFieldType.MultiChoice: { string senum = ""; SPFieldMultiChoice oCField = (SPFieldMultiChoice)oField; foreach (string sChoice in oCField.Choices) { senum += ";" + sChoice.Replace(";", ""); } attr = doc.CreateAttribute("Enum"); attr.Value = senum; ndNew.Attributes.Append(attr); attr = doc.CreateAttribute("Range"); attr.Value = "1"; ndNew.Attributes.Append(attr); } sType = "Enum"; sWidth = "150"; break; case SPFieldType.Note: sWidth = "200"; break; case SPFieldType.URL: sWidth = "150"; break; case SPFieldType.User: sWidth = "150"; attr = doc.CreateAttribute("CaseSensitive"); attr.Value = "0"; ndNew.Attributes.Append(attr); break; default: switch (oField.TypeAsString) { case "TotalRollup": attr = doc.CreateAttribute("Align"); attr.Value = "Right"; sTitleAlign = "Right"; ndNew.Attributes.Append(attr); break; } break; } attr = doc.CreateAttribute("MinWidth"); attr.Value = sWidth; ndNew.Attributes.Append(attr); } attr = doc.CreateAttribute("Wrap"); attr.Value = "0"; ndNew.Attributes.Append(attr); attr = doc.CreateAttribute("Type"); attr.Value = sType; ndNew.Attributes.Append(attr); ndCols.AppendChild(ndNew); if (oField.InternalName == "Title") { ndCols = doc.FirstChild.SelectSingleNode("//Cols"); } string iFieldName = oField.InternalName; if (iFieldName == "State") { iFieldName = "FState"; } attr = doc.CreateAttribute(iFieldName); attr.Value = sTitle; ndHeader.Attributes.Append(attr); attr = doc.CreateAttribute(oField.InternalName + "Align"); attr.Value = sTitleAlign; ndHeader.Attributes.Append(attr); if (arrHidden.Contains(oField.InternalName)) { attr = doc.CreateAttribute("Visible"); attr.Value = "0"; ndNew.Attributes.Append(attr); } } catch { } } XmlNode ndGantt = doc.FirstChild.SelectSingleNode("//RightCols/C[@Name='G']"); ndGantt.Attributes["GanttStart"].Value = StartDateField; ndGantt.Attributes["GanttEnd"].Value = DueDateField; ndGantt.Attributes["GanttComplete"].Value = ProgressField; ndGantt.Attributes["GanttText"].Value = InfoField; if (bShowGantt) { ndGantt.Attributes["Visible"].Value = "1"; } XmlNodeList ndRows = docXml.FirstChild.SelectNodes("row"); XmlNode ndParent = doc.FirstChild.SelectSingleNode("//B"); XmlNodeList ndOldCols = docXml.FirstChild.SelectNodes("//head/column"); XmlNode ndSummary = doc.FirstChild.SelectSingleNode("//Def/D[@Name='Summary']"); if (StartDateField != "") { XmlAttribute attr = doc.CreateAttribute(StartDateField + "Formula"); attr.Value = "ganttstart()"; ndSummary.Attributes.Append(attr); } if (DueDateField != "") { XmlAttribute attr = doc.CreateAttribute(DueDateField + "Formula"); attr.Value = "ganttend()"; ndSummary.Attributes.Append(attr); } if (ProgressField != "") { XmlAttribute attr = doc.CreateAttribute(ProgressField + "Formula"); attr.Value = "ganttpercent()"; ndSummary.Attributes.Append(attr); } //PercentCompleteFormula="ganttpercent('StartDate','DueDate','d')" foreach (XmlNode ndRow in ndRows) { ProcessItems(ndParent, ndRow, ndOldCols, doc); } foreach (XmlNode ndRow in doc.FirstChild.SelectNodes("//I[@Predecessors!='']")) { processPredecessors(ndRow, doc); } foreach (DictionaryEntry de in hshLookupEnums) { XmlNode nd = doc.FirstChild.SelectSingleNode("//C[@Name='" + de.Key.ToString() + "']"); if (nd != null) { nd.Attributes["EnumKeys"].Value = ";" + string.Join(";", (int[])((ArrayList)de.Value).ToArray(Type.GetType("System.Int32"))); } } foreach (DictionaryEntry de in hshLookupEnumKeys) { XmlNode nd = doc.FirstChild.SelectSingleNode("//C[@Name='" + de.Key.ToString() + "']"); if (nd != null) { nd.Attributes["Enum"].Value = ";" + string.Join(";", (string[])((ArrayList)de.Value).ToArray(Type.GetType("System.String"))); } } XmlNode ndPag = docXml.SelectSingleNode("//call[@command='setuppaging']"); XmlNode ndCfg = doc.SelectSingleNode("//Cfg"); if (ndPag != null) { XmlAttribute attr = doc.CreateAttribute("PagInfo"); attr.Value = ndPag.InnerText; ndSummary.Attributes.Append(attr); ndCfg.Attributes.Append(attr); attr = doc.CreateAttribute("PagSize"); attr.Value = view.RowLimit.ToString(); ndSummary.Attributes.Append(attr); ndCfg.Attributes.Append(attr); } XmlAttribute attrT = doc.CreateAttribute("LinkTitleField"); attrT.Value = sTitleField; ndCfg.Attributes.Append(attrT); tb.StopTimers(); if (epmdebug != null && epmdebug == "true") { XmlNode ndNew = doc.CreateNode(XmlNodeType.Element, "I", doc.NamespaceURI); XmlAttribute attr = doc.CreateAttribute("Title"); attr.Value = tb.GetHtml(); ndNew.Attributes.Append(attr); doc.FirstChild.SelectSingleNode("//B").AppendChild(ndNew); } if (list.BaseType == SPBaseType.DocumentLibrary) { XmlAttribute attr = doc.CreateAttribute("NameCol"); attr.Value = "FileLeafRef"; ndCfg.Attributes.Append(attr); attr = doc.CreateAttribute("MainCol"); attr.Value = "FileLeafRef"; ndCfg.Attributes.Append(attr); } else { XmlAttribute attr = doc.CreateAttribute("NameCol"); attr.Value = "Title"; ndCfg.Attributes.Append(attr); attr = doc.CreateAttribute("MainCol"); attr.Value = "Title"; ndCfg.Attributes.Append(attr); } data = doc.OuterXml; }
public void btnlist_Click(object sender, EventArgs e) { listname = cmblist.Text; try { if (String.IsNullOrEmpty(listname)) { throw new Exception("Please choose subsite"); } using (SPSite site = new SPSite(siteurl)) { using (SPWeb web = site.OpenWeb(subsite)) { SPList list = web.Lists[listname]; SPView view = list.DefaultView; SPListItemCollection items = list.GetItems(); StringCollection viewFields = view.ViewFields.ToStringCollection(); DataTable dt = new DataTable(); DataRow dtrow; Int16 i = 1; foreach (SPListItem item in items) { dtrow = dt.NewRow(); foreach (string fieldname in viewFields) { string decodefield = XmlConvert.DecodeName(fieldname); if (i == 1) { dt.Columns.Add(decodefield); } SPField field = list.Fields.GetField(decodefield); if (field.Type == SPFieldType.Calculated && item[decodefield] != null) { SPFieldCalculated cf = (SPFieldCalculated)item.Fields[decodefield]; dtrow[decodefield] = cf.GetFieldValueAsText(item[decodefield]); } else if (field.Type == SPFieldType.Lookup && item[decodefield] != null) { dtrow[decodefield] = new SPFieldLookupValue(item[decodefield].ToString()).LookupValue; } else { dtrow[decodefield] = item[decodefield]; } } dt.Rows.Add(dtrow); i++; } gridlist.DataSource = dt; } } lblmessage3.Visible = false; } catch (Exception ex) { lblmessage3.Text = ex.Message; lblmessage3.Visible = true; } }