I want to be able to create a KPI List on my MOSS 2007 installation via the object model. Is this possible?
using (SPWeb web1 = properties.Feature.Parent as SPWeb)
{
using (SPSite objSite = new SPSite(web1.Site.ID))
{
using (SPWeb web = objSite.OpenWeb(web1.ID))
{
SPListTemplate template = null;
foreach (SPListTemplate t in web.ListTemplates)
{
if (t.Type.ToString() == "432")
{
template = t;
break;
}
}
Guid gG = Guid.Empty;
SPList list = null;
string sListTitle = "Status List";
SPSecurity.RunWithElevatedPrivileges(delegate
{
try
{
web.AllowUnsafeUpdates = true;
gG = web.Lists.Add(sListTitle, sListTitle, template);
list = web.Lists[gG];
}
catch
{
// exists
list = web.Lists[sListTitle];
}
SPContentType ct =
list.ContentTypes["SharePoint List based Status Indicator"];
//declare each item which u want to insert in the kpi list
SPListItem item1 = list.Items.Add();
SPFieldUrlValue value1 = new SPFieldUrlValue();
item1["ContentTypeId"] = ct.Id;
item1.SystemUpdate();
item1["Title"] = "Project Specific Doc.Lib.Rating";
value1.Url = web.Url + "/Lists/Project Specific Documents";
item1["DataSource"] = value1;
item1["Indicator Goal Threshold"] = "3";
item1["Indicator Warning Threshold"] = "3";
item1["Value Expression"] =
"Average;Average_x0020_Rating:Number";
item1.SystemUpdate();
}
}
}
average is the calculation value and the column is Average_x0020_Rating.
http://alonsorobles.com/2010/03/17/important-custom-sharepoint-list-template-notes/
I found that the Template ID for a Status Indicator (KPI List) is 432. Google for this to find some info on creating a new list. I'm needing to read up what properties I can set on this list.
this is work for me:
private void CreateKPIDocumentLibrary(List<PageStructure> list)
{
SPListTemplate kpi = null;
foreach (SPListTemplate t in web.ListTemplates)
{
if (t.Type.ToString() == "432")
{
kpi = t;
break;
}
}
foreach (PageStructure st in list)
{
bool find = false;
string[] periodType = st.tag.Split('_');
string name = periodType[0] + "-" + st.effdate + "-" + st.template;
SPListCollection lstCol = site.OpenWeb().GetListsOfType(SPBaseType.GenericList);
foreach (SPList l in lstCol)
{
string title = l.Title;
if (title == name)
{
find = true;
break;
}
}
if (find == false)
{
Guid docLibID = web.Lists.Add(name, "", kpi);
}
SPList itemList = web.Lists[name];
SPListItem item = itemList.Items.Add();
SPFieldUrlValue value = new SPFieldUrlValue();
item["Title"] = st.tag;
value.Url = st.docUrl;
item["DetailLink"] = st.url;
item["DataSource"] = value;
item["Indicator Goal Threshold"] = "2";
item["Indicator Warning Threshold"] = "1";
item["View Name"] = "All Documents";
item.SystemUpdate();
web.Update();
KpiObject kp = new KpiObject(name, SPContext.Current.Site.Url + itemList.DefaultViewUrl);
this.kpiList.Add(kp);
}
}
Related
I am new to SharePoint programming.
Can anyone tell me how I can export list data to Excel using a timer job with some custom code?
Please go through the below link for creating timer jobs in sharepoint.
This article is contain the detailed process.
https://www.mssqltips.com/sqlservertip/3801/custom-sharepoint-timer-job/
The below code will help you to export the list data.
public void Export(List<int> ids)
{
DataTable table = new DataTable();
try
{
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteE = new SPSite(site.ID))
{
using (SPWeb webE = siteE.OpenWeb(web.ID))
{
webE.AllowUnsafeUpdates = true;
SPList list = webE.Lists["Stationery"];
table.Columns.Add("Product", typeof(string));
table.Columns.Add("Quantity", typeof(Decimal));
DataRow newRow;
GridView gv = new GridView();
foreach (SPListItem item in list.Items)
{
if (ids.Contains(Convert.ToInt32(item["ID"].ToString())) && (item["Status"].ToString() == "New"))
{
newRow = table.Rows.Add();
newRow["Product"] = item["Product"].ToString();
newRow["Quantity"] = Convert.ToDecimal(item["Quantity"].ToString());
item["Status"] = "Exported";
item.Update();
}
}
SPBoundField boundField = new SPBoundField();
boundField.HeaderText = "Product";
boundField.DataField = "Product";
gv.Columns.Add(boundField);
boundField = new SPBoundField();
boundField.HeaderText = "Quantity";
boundField.DataField = "Quantity";
boundField.ControlStyle.Width = new Unit(120);
gv.Columns.Add(boundField);
gv.AutoGenerateColumns = false;
gv.DataSource = table.DefaultView;
gv.DataBind();
gv.AllowSorting = false;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
string attachment = "attachment; filename=export" + "_" + DateTime.Now.ToShortTimeString() + ".xls";
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/Excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
HttpContext.Current.Response.End();
webE.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HttpContext.Current.Response.Write(ex.ToString());
}
list of documents thats contains custom taxonomy field column named subject.
Need to update subject of thousands records/documents.
Please any idea to update the taxonomy field such subject programtically using C# CSOM
Please try to use this method:
public void UpdateTaxonomyField(ClientContext ctx, List list,ListItem listItem,string fieldName,string fieldValue)
{
Field field = list.Fields.GetByInternalNameOrTitle(fieldName);
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = new TaxonomyFieldValue();
string[] term = fieldValue.Split('|');
termValue.Label = term[0];
termValue.TermGuid = term[1];
termValue.WssId = -1;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
ctx.Load(listItem);
ctx.ExecuteQuery();
}
public static void UpdateListofLibraryHavingTaxonomyField()
{
string siteUrl = "http://abc:55555/sites/xyz/";
string libName = "Knowledge Repos";
string strTermGuid = "Your new/update term guid";
try
{
Dictionary<string, string> dictIdsSubjectsChange = ReadFromExcel();//Here to read all records (approx 2000 records) that we want to change
ClientContext clientContext = new ClientContext(siteUrl);
List list = clientContext.Web.Lists.GetByTitle(libName);
FieldCollection fields = list.Fields;
Field field = fields.GetByInternalNameOrTitle("Subject1");
ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(listItems, items => items.Include(i => i["Subject1"], i => i["ID"]));
clientContext.Load(fields);
clientContext.Load(field);
clientContext.ExecuteQuery();
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = null;
if (dictIdsSubjectsChange != null)
{
foreach (ListItem listItem in listItems)//Loop through all items of the document library
{
string strCurrentID = "0";
try
{
strCurrentID = listItem["ID"].ToString();
}
catch (Exception) { }
if (dictIdsSubjectsChange.ContainsKey(strCurrentID))//Checking to change ot not
{
termValue = new TaxonomyFieldValue();
termValue.Label = "Special Knowledge";
termValue.TermGuid = strTermGuid;
termValue.WssId = 246;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
clientContext.Load(listItem);
}
}
clientContext.ExecuteQuery();
}
}
catch (Exception ex) { }
}
}
I am uploading a document to Document library. Along with this I am creating a field called 'FieldID' by combining 2 values. However I am unable to see this field in the document library and hence unable to query the document with this field.How can I see this field or how can I retrieve documents using this 'FieldID'. This is the code.
if (UploadFile.PostedFile != null || (UploadFile.PostedFile.ToString() != string.Empty))
{
String fileName = UploadFile.PostedFile.FileName.ToString();
string userLogin = SPContext.Current.Web.CurrentUser.LoginName;
Guid siteID = SPContext.Current.Site.ID;
SPDocumentLibrary exposureLibrary = null;
SPList listDoc = null;
SPFolder myLibrary = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSite = new SPSite(siteID))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
// exposureLibrary
try
{
// Check if the document library already exists
exposureLibrary = (oWeb.Lists[SharepointCommon.Constants.USERINTERFACECUSTOMIZATIONSFEATURERECEIVER_EXPOSURE_DOCUMENTLIBRARY_NAME] as SPDocumentLibrary);
exposureLibrary.ContentTypesEnabled = false;
exposureLibrary.EnableAttachments = false;
exposureLibrary.EnableFolderCreation = false;
exposureLibrary.EnableVersioning = true;
exposureLibrary.NoCrawl = true;
exposureLibrary.OnQuickLaunch = false;
/* create a Text field for ID */
SPFieldText field = (exposureLibrary.Fields["FILEID"] as SPFieldText);
// Check if the field is available
if (field == null)
{
SPFieldText fldID = (SPFieldText)exposureLibrary.Fields.CreateNewField(
SPFieldType.Text.ToString(), "FILEID");
fldID.Required = true;
fldID.MaxLength = 100;
fldID.Hidden = false;
exposureLibrary.Fields.Add(fldID);
}
//exposureLibrary.Update();
myLibrary = exposureLibrary.RootFolder;
}
catch
{
// Determine the GUID of the document library
Guid ExposureDocumentLibraryId = oWeb.Lists.Add(SharepointCommon.Constants.USERINTERFACECUSTOMIZATIONSFEATURERECEIVER_EXPOSURE_DOCUMENTLIBRARY_NAME, SharepointCommon.Constants.USERINTERFACECUSTOMIZATIONSFEATURERECEIVER_EXPOSURE_DOCUMENTLIBRARY_DESCRIPTION, SPListTemplateType.DocumentLibrary);
listDoc = oWeb.Lists[ExposureDocumentLibraryId];
/* create a Text field for ID */
SPFieldText fldID = (SPFieldText)listDoc.Fields.CreateNewField(
SPFieldType.Text.ToString(), "FILEID");
fldID.Required = true;
fldID.MaxLength = 100;
fldID.Hidden = false;
listDoc.Fields.Add(fldID);
// Set properties of the document library
listDoc.ContentTypesEnabled = false;
listDoc.EnableAttachments = false;
listDoc.EnableFolderCreation = false;
listDoc.EnableVersioning = true;
listDoc.NoCrawl = true;
listDoc.OnQuickLaunch = false;
listDoc.Update();
myLibrary = listDoc.RootFolder;
}
// Prepare to upload
Boolean replaceExistingFiles = true;
// Upload document
SPFile spfile = myLibrary.Files.Add(UploadFile.FileName + "(" + ViewState[UIConstants.CUSTOMERID].ToString() + " - "+ViewState[UIConstants.MondiPlantID].ToString()+ ")", UploadFile.FileContent, replaceExistingFiles);
//spfile.Item["FILEID"]= ViewState[UIConstants.CUSTOMERID].ToString() + " _ " + ViewState[UIConstants.MondiPlantID].ToString();
//myLibrary.Item["ID"] = ViewState[UIConstants.CUSTOMERID].ToString() + " _ " + ViewState[UIConstants.MondiPlantID].ToString();
spfile.Item.Update();
oWeb.AllowUnsafeUpdates = false;`enter code here`
// Commit
myLibrary.Update();
// Update the document library
oWeb.Update();
}
}
});
}
exposureLibrary.Fields.Add(fldID); //after this step
//exposureLibrary.Update();
you need to uncomment this, because after a field is created in try block, list/library is not being updated
My Task have multiple relateddocId for example RelatedDoc="3,5,2,6", now i need to add multiplevalue to the sharepoint lookup fields called related Document which is in task list. how to add this?
For ref see my code below
private static void CreateItem(SPWeb web, SPList TaskList, string FolderURL, string ItemName, string RelatedDoc)
{
var ParentURL = string.Empty;
if (!TaskList.ParentWebUrl.Equals("/"))
{
ParentURL = TaskList.ParentWebUrl;
}
SPListItem _taskList = TaskList.AddItem(ParentURL + FolderURL, SPFileSystemObjectType.File, null);
_taskList["Title"] = ItemName;
string DocName = "4,6,3,6";//Document ref id.
SPFieldLookupValue lookupvalue = new SPFieldLookupValue();
if (DocName != "")
lookupvalue = new SPFieldLookupValue(RelatedDoc, DocName);
_taskList["EYRelatedSharedDocument"] = lookupvalue;
_taskList.Update();
}
SPFieldLookupValueCollection documents = new SPFieldLookupValueCollection();
foreach ( ... )
{
documents.Add(new SPFieldLookupValue(documentId, documentTitle));
}
_taskList["EYRelatedSharedDocument"] = documents;
_taskList.Update();
the error i get is
The security validation for this page is invalid. Click Back in your Web browser, refresh the page and try the operation again.
i am using moss 2007
protected void btnSubmit_Click(Object sender, EventArgs e)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.ValidateFormDigest();
using (SPSite mySite = new SPSite(_sLibUrl))
{
TextBox txtFirstName = (TextBox)usercontrol.FindControl("txtFirstName");
TextBox txtLastName = (TextBox)usercontrol.FindControl("txtLastName");
TextBox txtPhone = (TextBox)usercontrol.FindControl("txtPhone");
TextBox txtEmail = (TextBox)usercontrol.FindControl("txtEmail");
TextBox txtSubject = (TextBox)usercontrol.FindControl("txtSubject");
TextBox txtContant = (TextBox)usercontrol.FindControl("txtContant");
mySite.AllowUnsafeUpdates = true;
SPListItemCollection listItems = mySite.AllWebs[WebName].Lists[_sLibName].Items;
SPListItem item = listItems.Add();
item["FirstName"] = txtFirstName.Text;
item["LastName"] = txtLastName.Text;
item["Phone"] = txtPhone.Text;
item["Email"] = txtEmail.Text;
item["Subject"] = txtSubject.Text;
item["Contant"] = txtContant.Text;
item.Update();
mySite.AllowUnsafeUpdates = false;
mySite.AllWebs[WebName].Lists[_sLibName].Update();
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtPhone.Text = string.Empty;
txtEmail.Text = string.Empty;
txtSubject.Text = string.Empty;
txtContant.Text = string.Empty;
}
Label lblMessage = (Label)usercontrol.FindControl("lblMessage");
// lblMessage.Text = "טופס נשלח בהצלחה";
});
}
catch (Exception ex)
{
Label lbl = (Label)usercontrol.FindControl("lblMessage");
lbl.Text = ex.Message;
}
}
Try putting mySite.AllowUnsafeUpdates = false; after mySite.AllWebs[WebName].Lists[_sLibName].Update();
i found the solution what i need to do is to remove the
mySite.AllowUnsafeUpdates = true;
and
mySite.AllowUnsafeUpdates = false;
and it works
I work with this solution always
using (var site = new SPSite(SPContext.Current.Site.ID))
using (var web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//add, update and etc. programatically crud operations with lists
web.AllowUnsafeUpdates = false;
}