protected void Page_Load(object sender, EventArgs e) { StringBuilder fileurls = new StringBuilder(); int i = 0; Helpers.Log("Entered the Page Loag method of the ConfirmDownload.aspx page"); Helpers.Log("Reading Configuration values"); GetConfigurationValues(); Helpers.Log("Reading query string values"); ReadQueryStringParameters(); if (!Page.IsPostBack) { Helpers.Log("Adding EULA"); AddEULA(); Helpers.Log("Getting total file size"); selectedFilesTotalSize = GetFileSize(); if (selectedFilesTotalSize > selectedFilesTotalSizeLimit) { Helpers.Log("File size exceeds."); btnSubmit.Enabled = false; lblTotalFileSize.Text = String.Format("Total file size exceeds {0} MB", selectedFilesTotalSizeLimit); } else { Helpers.Log("Setting file size"); SetFileSizeInPage(); } using (SPSite site = new SPSite(webUrl)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists[listId]; SPListItem item = list.GetItemById(itemIds[0]); fileName = Path.GetFileNameWithoutExtension(item.File.Name); foreach (int itemId in itemIds) { item = list.GetItemById(itemId); fileurls.Append(web.Url + "/" + item.File.Url); if (i.ToString() != (itemIds.Count - 1).ToString()) { fileurls.Append("|"); } i++; } ScriptManager.RegisterHiddenField(this, "hdnfileurls", fileurls.ToString()); ScriptManager.RegisterHiddenField(this, "hdnusername", SPContext.Current.Web.CurrentUser.LoginName.ToString()); } } } }
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { ActivityActivationReference.IsAllowed(this, __Context.Web); // Get the workflow context for the workflow activity. NWWorkflowContext ctx = NWWorkflowContext.GetContext(__Context, new Guid(__ListId), __ListItem.Id, WorkflowInstanceId, this); base.LogProgressStart(ctx); //BLOG. this function // get all the properties you need here string aggreementName = ctx.AddContextDataToString(this.AgreementName); string approversProp = ctx.AddContextDataToString(this.Approvers); string qryUrl = ctx.AddContextDataToString(this.UrlMiscInfo); string compDocsIds = ctx.AddContextDataToString(this.CompendiumDocsID); try { SPList spList = this.__Context.Web.Lists[new Guid(this.__ListId)]; SPListItem spItm = spList.GetItemById(this.__ListItem.Id); aggreementName = string.IsNullOrEmpty(aggreementName) ? spList.Title + "-" + spItm.ID + "-" + spItm.File.Name : aggreementName; List <string> lstApprovers = Akki.AdobeSign.Common.Utilities.GetUserEmails(approversProp, ctx.Web.Url); this.HistoryListMessage = "Initiator Email " + ctx.WorkflowInitiator.Email; // get the bytes for all the compendium documents List <byte[]> comDocBytes = null; if (!string.IsNullOrEmpty(compDocsIds)) { comDocBytes = new List <byte[]>(); var docsID = compDocsIds.Split(Constants.Delimiter); foreach (var doc in docsID) { int docId = int.Parse(doc); var spItmCompDoc = spList.GetItemById(docId); comDocBytes.Add(spItmCompDoc.File.OpenBinary()); } } var response = AdobeOperations.SendDocumentByBytesForAuthoring(spItm.File.OpenBinary(), comDocBytes, aggreementName, lstApprovers.ToArray(), ctx.WorkflowInitiator.Email, qryUrl); this.HistoryListMessage = string.Format(Constants.MsgAgreemntID, response.agreementId); this.OutAdobeAgreementID = response.agreementId; this.OutAuthoringUrl = response.url; } catch (Exception e) { //log.Error("[Execute]:", e); throw; } base.LogProgressEnd(ctx, executionContext); return(ActivityExecutionStatus.Closed); }
public SPListItem GetItemByID(int itemId, string listName) { SPListItem item = null; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite spSite = new SPSite(SPContext.Current.Site.ID)) //找到网站集 { using (SPWeb web = spSite.OpenWeb(SPContext.Current.Web.ID)) { SPList list = web.Lists.TryGetList(listName); if (list != null) { try { item = list.GetItemById(itemId); } catch (Exception) { item = null; } } } } }); return(item); }
private void AddValues(SPItemEventProperties properties) { base.ItemAdded(properties); this.EventFiringEnabled = false; SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(properties.Site.ID)) { using (SPWeb web = site.OpenWeb(properties.Web.ID)) { SPList list = web.Lists[properties.ListId]; SPListItem item = list.GetItemById(properties.ListItemId); web.AllowUnsafeUpdates = true; try { #region SPFieldChoice SPFieldChoice choices = new SPFieldChoice(item.Fields, "Action"); //choices.Choices.Clear(); if (!choices.Choices.Contains(properties.UserDisplayName)) { choices.Choices.Add(properties.UserDisplayName); } //需要提升权限,否则 会出现权限错误 choices.Update(); } catch (Exception ex) { } #endregion web.AllowUnsafeUpdates = false; } } }); this.EventFiringEnabled = true; }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { Thread.Sleep(60000); base.EventFiringEnabled = false; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(properties.WebUrl)) { using (SPWeb web = site.OpenWeb()) { SPList oList = properties.Web.Lists["ReviewDocs"]; string itemId = properties.ListItem["ID"].ToString(); SPListItem sourceItem = oList.GetItemById(Convert.ToInt32(itemId)); SPView oView = oList.Views["Delete"]; SPQuery query = new SPQuery(oView); SPListItemCollection listItemsCollection = oList.GetItems(query); for (int i = listItemsCollection.Count - 1; i >= 0; i--) { SPListItem file = listItemsCollection[i]; file.File.Delete(); } } } }); base.EventFiringEnabled = true; }
protected void ModalOk_Click(object sender, EventArgs e) { try { string urlSite = SPContext.Current.Web.Url; string COLUMN_NAME = AttachedColumn; using (SPSite currentsite = new SPSite(urlSite)) { using (SPWeb DestWeb = currentsite.OpenWeb()) { SPList listdata = DestWeb.Lists[new Guid(Request.QueryString["ListId"])]; SPListItem listitemtoadd = listdata.GetItemById(Convert.ToInt16(Convert.ToString(Request.QueryString["ItemId"]))); string text = string.Empty; string sharePointNewLine = "<br/>"; text = getAttachments(sharePointNewLine, text); listitemtoadd[COLUMN_NAME] = text; listitemtoadd.Update(); Response.Clear(); Response.Write(String.Format(@"<script language=""javascript"" type=""text/javascript""> window.frameElement.commonModalDialogClose(1, ""{0}"");</script>", "")); Response.End(); } } } catch (Exception ex) { } }
public static void Update_Objectives(string columnToBeUpdated, DataTable tblObjectives) { SPSecurity.RunWithElevatedPrivileges(delegate() { SPSite oSite = new SPSite(SPContext.Current.Web.Url); SPWeb spWeb = oSite.OpenWeb(); spWeb.AllowUnsafeUpdates = true; SPList spList = spWeb.GetList(SPUrlUtility.CombineUrl(spWeb.ServerRelativeUrl, "lists/" + "Objectives")); if (tblObjectives != null) { foreach (DataRow row in tblObjectives.Rows) { SPListItem oListItem = spList.GetItemById(int.Parse(row["ID"].ToString())); oListItem[columnToBeUpdated] = row[columnToBeUpdated].ToString(); oListItem.Update(); } } else { } spWeb.AllowUnsafeUpdates = false; }); }
private void SaveNews(SPModerationStatusType moderationStatus) { //SPSecurity.RunWithElevatedPrivileges(delegate() //{ using (SPSite mysite = new SPSite(SPContext.Current.Site.ID)) { using (SPWeb myweb = mysite.AllWebs[SPContext.Current.Web.ID]) { myweb.AllowUnsafeUpdates = true; SPList list = myweb.Lists.TryGetList(webpartObj.ListName); SPListItem item = list.GetItemById(itemID); if (moderationStatus == 0) //审批通过保存新闻内容,否则只保存审批相关内容 { item["标题"] = txtTitle.Text.ToString(); item["正文"] = txt1Body.Text.ToString(); item["是否主页显示"] = chkIsPage.Checked == true ? true : false; item["是否图片要闻"] = chkIsPic.Checked == true ? true : false; item["新闻类别"] = ddlNewsType.SelectedItem.Value + ";#" + ddlNewsType.SelectedItem.Text; } //item["审批者评论"] = txtModerationComments.Text.ToString(); item.ModerationInformation.Comment = txtModerationComments.Text.ToString(); item.ModerationInformation.Status = moderationStatus; item.Update(); //item["审批状态"] = moderationStatus.ToString (); ////item.SystemUpdate(); //item.mo myweb.AllowUnsafeUpdates = false; } } //}); }
/// <summary> /// Publishes all list items for a given list. /// </summary> /// <param name="list">The list.</param> /// <param name="test">If true test the change only (don't make any changes).</param> /// <param name="comment">The comment.</param> /// <param name="takeOver">if set to <c>true</c> [take over].</param> /// <param name="filterExpression">The filter expression.</param> public void Publish(SPList list, bool test, string comment, bool takeOver, string filterExpression) { Logger.Write("Processing List: " + list.DefaultViewUrl); string source = "\"Publish-SPListItems\""; foreach (SPListItem item in list.Items) { PublishListItem(item, list, test, source, comment, filterExpression); } foreach (SPListItem item in list.Folders) { PublishListItem(item, list, test, source, comment, filterExpression); } if (list is SPDocumentLibrary && takeOver) { foreach (SPCheckedOutFile file in ((SPDocumentLibrary)list).CheckedOutFiles) { file.TakeOverCheckOut(); SPListItem item = list.GetItemById(file.ListItemId); PublishListItem(item, list, test, source, comment, filterExpression); } } Logger.Write("Finished Processing List: " + list.DefaultViewUrl + "\r\n"); }
public static string Get_EmailById(SPWeb web, int operatorId) { SPList list = web.Lists.TryGetList(targetList); SPListItem item = list.GetItemById(operatorId); return(item["colEmail"] != null ? item["colEmail"].ToString() : string.Empty); }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { SPFieldUserValueCollection users = (SPFieldUserValueCollection)properties.ListItem["Inviter"]; foreach (SPFieldUserValue user in users) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(properties.Site.ID, user.User.UserToken)) { using (SPWeb web = site.OpenWeb(properties.Web.ID)) { SPList list = web.Lists.TryGetList("SPForumsMessageList"); SPList post = web.Lists.TryGetList("SPForumsPostList"); SPListItem postItem = post.GetItemById(Convert.ToInt32(properties.ListItem["Title"])); SPListItem itemAdd = list.Items.Add(); itemAdd["Title"] = "[Reply Invite]Post Title:" + postItem["Title"]; itemAdd["MessageLink"] = post.DefaultDisplayFormUrl + "?ID=" + properties.ListItem["Title"]; itemAdd["ReplyContent"] = properties.ListItem["Reply"]; itemAdd["IsRead"] = "No"; itemAdd.SystemUpdate(); } } }); } //base.ItemAdded(properties); }
private void AddAssistant(int id, DateTime dt, int during, int actionID) { SPWeb web = SPContext.Current.Web; int userID = web.CurrentUser.ID; SPList lstAction = web.Lists.TryGetList(objWeb.ListName); SPListItem item; string custID; if (id > 0) { item = lstAction.GetItemById(id); custID = item[lstAction.Fields.GetFieldByInternalName("CustAction").Title].ToString(); if (actionID != int.Parse(Regex.Split(custID, ";#")[0])) { item = lstAction.AddItem(); } } else { item = lstAction.AddItem(); } item[lstAction.Fields.GetFieldByInternalName("CustAction").Title] = actionID; item[lstAction.Fields.GetFieldByInternalName("ActualDate").Title] = dt; item[lstAction.Fields.GetFieldByInternalName("ActualDuring").Title] = during; item.Update(); }
private bool getHOD(SPWeb oSPWeb, string departmentID, string responsiblepersonEmailAddress) { try { if (oSPWeb != null) { SPList spList = oSPWeb.Lists["Department"]; SPListItem listItem = spList.GetItemById(Convert.ToInt32(departmentID)); if (listItem != null) { if (Convert.ToString(listItem["HODEmail"]).Equals(responsiblepersonEmailAddress, StringComparison.OrdinalIgnoreCase)) { return(true); } } } } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("SL.FG.PFL(WorkQueue-GetHOD)", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace); message_div.InnerHtml = "Something went wrong!!! Please Contact the administrator."; } return(false); }
protected void CopyItem(object sender, EventArgs e) { int itemid = Convert.ToInt32(Request.QueryString["ItemId"]); Guid listid = new Guid(Request.QueryString["ListId"]); SPWeb sourceweb = SPControl.GetContextWeb(HttpContext.Current); SPList sourcelist = sourceweb.Lists[listid]; SPListItem sourceitem = sourcelist.GetItemById(itemid); lblListItem.Text = sourceitem.Name; TreeNodeContext ctx = new TreeNodeContext(tvSite.SelectedValue); SPSite destcol = new SPSite(ctx.SiteCollection); SPWeb destweb = destcol.AllWebs[ctx.WebID]; if (ctx.IsList) { SPList destlist = destweb.Lists[ctx.ListID]; SPListItem destitem = destlist.Items.Add(); SPFolder folder = destlist.RootFolder; try { folder.Files.Add(sourceitem.Name, sourceitem.File.OpenBinary()); } catch (Exception ex) { lblStatus.Text = string.Format("Error uploading File {0}", sourceitem.Name); } lblStatus.Text = string.Format("{0} copied successfully to {1}", sourceitem.Name, destlist.Title); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string en_id = Request.QueryString["en_ID"].ToString(); if (en_id != string.Empty) { HiddenField1.Value = en_id; using (SPSite site = new SPSite(MyConfiguration.GetSiteURL(SPContext.Current))) { SPWeb hrWeb = site.AllWebs["HRMV02"]; SPList entitylist = hrWeb.Lists["Entity"]; //SPQuery qry_edit_entity = new SPQuery(); //qry_edit_entity.Query = @"<Where><Eq><FieldRef Name='ID'/><Value Type='Counter'>"+en_id+@"</Value></Eq></Where>"; SPListItem edit_entitylist_item = entitylist.GetItemById(Convert.ToInt32(en_id.ToString())); txtbox_edit_EntityName.Text = edit_entitylist_item["Title"].ToString(); rbtn_EntityStatus.Items.Clear(); SPFieldChoice rbt_entity_status = new SPFieldChoice(edit_entitylist_item.Fields, "Status"); for (int i = 0; i <= (Convert.ToInt16(rbt_entity_status.Choices.Count.ToString()) - 1); i++) { rbtn_EntityStatus.Items.Add(rbt_entity_status.Choices[i].ToString()); if (rbtn_EntityStatus.Items[i].Text == edit_entitylist_item["Status"].ToString()) { rbtn_EntityStatus.Items[i].Selected = true; //rbtn_EntityStatus.Items[i].Attributes["AutoPostBack"] = "false"; } } } } } }
private SPListItem GetResourcepoolItem(string sid) { SPListItem li = null; //Check for SID IF present, then try to update the resource. if (_hasSID && _resourcePool.Rows.Count > 0) { try { string filter = "SID='" + sid + "'"; DataRow[] result = _resourcePool.Select(filter); //If resource found, get resourcepool item if (result != null && result.Length > 0) { int itemID = int.Parse(_resourcePool.Select(filter)[0]["ID"].ToString()); li = _list.GetItemById(itemID); } else // Add resource. { li = _list.Items.Add(); } } catch (Exception ex) { _ExecutionLogs.Add(" ERROR -- Location: GetResourcepoolItem() -- SID: " + sid + " -- Message: " + ex.Message); _hasErrors = true; } } else // Add resource. { li = _list.Items.Add(); } return(li); }
/// <summary> /// Validate if document type is valid for PDF conversion /// </summary> /// <param name="listItemId"></param> /// <param name="list"></param> /// <returns> /// Returns true if document type is a word format. /// </returns> public bool isDocIDValidated(string listItemId, SPList list) { bool validDoc = false; try { //Get the details of selected documents using (SPWeb spWeb = SPContext.Current.Site.OpenWeb(SPContext.Current.Web.ServerRelativeUrl)) { SPListItem listItem = list.GetItemById(int.Parse(listItemId)); PDFConverterHelper PDFConvert = new PDFConverterHelper(""); if ((listItem.FileSystemObjectType == SPFileSystemObjectType.File) && PDFConvert.IsFileTypeDoc(listItem.File, "")) { validDoc = true; } PDFConvert = null; } } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ClassName, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, "isDocValidated - " + ex.Message, ex.StackTrace); } return(validDoc); }
private SPListItem GetClass(string classId) { SPList classesList = currentWeb.Lists["Classes"]; SPListItem theClass = classesList.GetItemById(Convert.ToInt32(classId)); return(theClass); }
private void changeStatus(string flag) { string Id = ""; string siteUrl = SPContext.Current.Site.Url; if (!string.IsNullOrEmpty(webObj.WebUrl)) { siteUrl = webObj.WebUrl; } try { using (SPSite spSite = new SPSite(siteUrl)) //找到网站集 { using (SPWeb spWeb = spSite.OpenWeb()) { spWeb.AllowUnsafeUpdates = true; SPList spList = spWeb.Lists.TryGetList(webObj.ListName); if (spList != null) { Id = hdId.Value; int id = int.Parse(Id); SPListItem item = spList.GetItemById(id); item["Flag"] = flag; item.Update(); } spWeb.AllowUnsafeUpdates = false; checkFlag(flag); } } } catch (Exception ex) { divErr.InnerHtml = "状态变更错误:ID=" + Id + ";" + ex.ToString(); } }
static void TestUpdate(SPWeb spWeb) { try { Console.WriteLine(spWeb.AllowUnsafeUpdates); string listName = "Чернетки внутрішніх документів"; SPList list = spWeb.Lists[listName]; int id = 1; SPListItem item = list.GetItemById(id); string value = string.Format("{0} ({1})", (string)item["dn_ct_Text"], DateTime.Now.ToString()); item["dn_ct_Text"] = value; item.Update(); //spListItem.SystemUpdate(); } catch (Exception eException) { Console.WriteLine(eException.GetType().FullName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + (eException.InnerException != null && !string.IsNullOrEmpty(eException.InnerException.Message) ? "InnerException.Message" + eException.InnerException.Message + Environment.NewLine : string.Empty) + "StackTrace:" + Environment.NewLine + eException.StackTrace); } }
protected void Page_Load(object sender, EventArgs e) { Act act = new Act(Web); if (act.CheckFeatureLicense(ActFeature.AppsAndCommunities) != 0) { Microsoft.SharePoint.Utilities.SPUtility.Redirect("epmlive/applications/noact.aspx", Microsoft.SharePoint.Utilities.SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current); } API.ApplicationDef appDef = API.Applications.GetApplicationInfo(Request["AppId"]); ApplicationName = appDef.Title; sFullWebUrl = Web.Url; try { SPList oList = Web.Lists.TryGetList("Installed Applications"); if (oList != null) { SPListItem li = oList.GetItemById(int.Parse(Request["CommId"])); API.Applications.AddAppToCommunity(li, int.Parse(Request["AppId"])); } sbOutput.Append("<div class=\"alert alert-success\">This application has been successfully added to the community.</div>"); } catch (Exception ex) { sbOutput.Append("<div class=\"alert alert-error\">There was an error adding this application to the community: " + ex.Message + "</div>"); } }
public static bool Check_IfExist(SPWeb web, int urzadId) { Debug.WriteLine("BLL.dicUrzedySkarbowe.Check_IfExist"); Debug.WriteLine("urzadId=" + urzadId.ToString()); if (urzadId > 0) { SPList list = GetList(web); SPListItem item = null; try { item = list.GetItemById(urzadId); Debug.WriteLine("urzadId=" + urzadId.ToString() + " znaleziony"); } catch (Exception) { Debug.WriteLine("urzadId=" + urzadId.ToString() + " nie znaleziony"); } if (item != null) { return(true); } else { return(false); } } return(false); }
private Table GetTableForSingleArchive() { Table table = new Table(); try { string currentusername = SPContext.Current.Web.CurrentUser.Name.ToString(); using (SPSite site = new SPSite(webUrl)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists[listId]; SPListItem item = list.GetItemById(itemIds[0]); fileName = Path.GetFileNameWithoutExtension(item.File.Name); } } String downloadLink = String.Format("{0}/_layouts/BulkAssetDownload/BulkAssetDownloadHandler.ashx?webUrl={1}&listId={2}&itemIds={3}&fileName={4}", webUrl, webUrl, listId.ToString(), itemIdsString, fileName); TableRow row = new TableRow(); TableCell cell = new TableCell(); HyperLink downloadLinkControl = new HyperLink(); downloadLinkControl.Text = fileName; downloadLinkControl.Target = "_self"; downloadLinkControl.NavigateUrl = downloadLink; cell.Controls.Add(downloadLinkControl); row.Cells.Add(cell); table.Rows.Add(row); } catch (Exception e) { Helpers.Log(e); throw e; } return(table); }
private Table GetTableForNoArchiving() { Table table = new Table(); try { foreach (int itemId in itemIds) { using (SPSite site = new SPSite(webUrl)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists[listId]; SPListItem item = list.GetItemById(itemId); String downloadLink = String.Format("{0}/_layouts/download.aspx?SourceUrl={1}", webUrl, item.File.Url); TableRow row = new TableRow(); TableCell cell = new TableCell(); HyperLink downloadLinkControl = new HyperLink(); downloadLinkControl.Target = "_self"; downloadLinkControl.Text = Path.GetFileNameWithoutExtension(item.File.Name); downloadLinkControl.NavigateUrl = downloadLink; cell.Controls.Add(downloadLinkControl); row.Cells.Add(cell); table.Rows.Add(row); } } } } catch (Exception e) { Helpers.Log(e); throw e; } return(table); }
public int SaveOrUpdate(SPWeb spWeb, BusinessTripEmployeeDetail item) { int itemId = 0; SPList spList = spWeb.GetList($"{spWeb.Url}{ListUrl}"); SPListItem spListItem; if (item.ID > 0) { spListItem = spList.GetItemById(item.ID); } else { spListItem = spList.AddItem(); } spListItem[StringConstant.BusinessTripEmployeeDetailsList.Fields.BusinessTripManagementID] = item.BusinessTripManagementID.LookupId; spListItem[StringConstant.BusinessTripEmployeeDetailsList.Fields.Employee] = item.Employee.LookupId; spWeb.AllowUnsafeUpdates = true; spListItem.Update(); itemId = spListItem.ID; spWeb.AllowUnsafeUpdates = false; return(itemId); }
private List <SPFile> ProcessSelectedItems(string[] itemsId, SPList spList) { List <SPFile> itemsForDownload = new List <SPFile>(); foreach (string id in itemsId) { int s = Convert.ToInt32(id); SPListItem spListItem = spList.GetItemById(s); if (spListItem.FileSystemObjectType == SPFileSystemObjectType.Folder) { var files = GetAllItemsFromFolder(spListItem); if (files != null) { itemsForDownload.AddRange(files); } } if (spListItem.FileSystemObjectType == SPFileSystemObjectType.File) { itemsForDownload.Add(spListItem.File); } } return(itemsForDownload); }
protected void DeleteEntityVersion(int entityId, int versionId) { SPListItem item = SPList.GetItemById(entityId); SPListItemVersion version = item.Versions.GetVersionFromLabel(versionId.ToString(CultureInfo.InvariantCulture)); version.Delete(); }
public override void WithResolvingModelHost(object modelHost, DefinitionBase model, Type childModelType, Action <object> action) { var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull()); var listItemModel = model.WithAssertAndCast <ListItemDefinition>("model", value => value.RequireNotNull()); SPListItem item = null; SPList list = null; if (modelHost is ListModelHost) { list = (modelHost as ListModelHost).HostList; var rootFolder = (modelHost as ListModelHost).HostList.RootFolder; item = EnsureListItem(list, rootFolder, listItemModel); } else if (modelHost is FolderModelHost) { // suppose it is a list, ir must be list = (modelHost as FolderModelHost).CurrentList; var rootFolder = (modelHost as FolderModelHost).CurrentListItem.Folder; item = EnsureListItem(list, rootFolder, listItemModel); } // naaaaah, just gonna get a new one list item // keep it simple and safe, really really really safe with all that SharePoint stuff... var currentItem = list.GetItemById(item.ID); action(currentItem); currentItem.Update(); }
protected LocationItem getLocation(string locationTitle) { LocationItem myLocation = null; try { using (SPSite site = new SPSite(SPContext.Current.Web.Url)) { int locationId = Convert.ToInt32(locationTitle.Split(';')[0]); using (SPWeb web = site.OpenWeb()) { SPList list = (SPList)web.Lists["Locations"]; SPListItem location = list.GetItemById(locationId); string title = Convert.ToString(location["Title"]); string address = Convert.ToString(location["Address"]); string contact = Convert.ToString(location["Contact"]); string link = Convert.ToString(location["Link"]); myLocation = new LocationItem(title, address, contact, link); } } } catch (Exception e) { Label lblError = new Label(); this.Controls.Add(lblError); if (e.InnerException != null) { lblError.Text = "No Address found" + e.InnerException.ToString(); } } return(myLocation); }
public static bool Update(int id, string name, string country) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite oSpSite = new SPSite("http://dev2016:69/NewSite/")) { ////............... UPDATE QUERY................... SPWeb oSPWeb = oSpSite.OpenWeb(); SPList oSpList = oSPWeb.Lists.TryGetList("testlist"); SPListItem updateItem = oSpList.GetItemById(id); updateItem["Title"] = "Demo"; updateItem["name"] = name; updateItem["my country"] = country; updateItem.Update(); //Console.WriteLine("Updated Successfully"); //Console.ReadLine(); } }); return(true); } catch (Exception e) { return(false); } }
private void getApprovalEntryNames(SPList currentList) { SPListItem currentItem = currentList.GetItemById(__ListItem); if (currentItem[EntriesColumn] != null) { SPFieldLookupValueCollection entries = new SPFieldLookupValueCollection(currentItem[EntriesColumn].ToString()); if (entries != null && entries.Count > 0) { foreach (SPFieldLookupValue entry in entries) { _approvalEntries.Add(entry.LookupValue); } return; } } __ActivationProperties.LogToWorkflowHistory(SPWorkflowHistoryEventType.None, __ActivationProperties.Web.CurrentUser, "Skipped: There is no Approval Entry defined.", string.Empty); }
private static void UpdateReportForMonth(SPList report, DateTime reportStart, SPListItemCollection monthlyCosts) { double monthlySum = 0; foreach (SPListItem cost in monthlyCosts) { monthlySum += (double)cost["Cost"]; } string reportsQueryString = string.Format( "<Where>" + "<Eq>" + "<FieldRef Name='{0}'></FieldRef>" + "<Value Type='DateTime'>{1}</Value>" + "</Eq>" + "</Where>", DelegationsFields.MonthIndicator.Name, SPUtility.CreateISO8601DateTimeFromSystemDateTime(reportStart)); SPQuery monthlyReportQuery = new SPQuery(); monthlyReportQuery.Query = reportsQueryString; SPListItemCollection monthlyReports = report.GetItems(monthlyReportQuery); if (monthlyReports.Count > 0) { var item = report.GetItemById((int)(monthlyReports[0]["ID"])); item[DelegationsFields.MonthlyCost] = monthlySum; item.Update(); } else { var item = report.AddItem(); item[DelegationsFields.MonthIndicator] = reportStart; item[DelegationsFields.MonthlyCost] = monthlySum; item.Update(); } }
/// <summary> /// Publishes all list items for a given list. /// </summary> /// <param name="list">The list.</param> /// <param name="test">If true test the change only (don't make any changes).</param> /// <param name="comment">The comment.</param> /// <param name="takeOver">if set to <c>true</c> [take over].</param> /// <param name="filterExpression">The filter expression.</param> public void Publish(SPList list, bool test, string comment, bool takeOver, string filterExpression) { Logger.Write("Processing List: " + list.DefaultViewUrl); string source = "\"Publish-SPListItems\""; foreach (SPListItem item in list.Items) { PublishListItem(item, list, test, source, comment, filterExpression); } foreach (SPListItem item in list.Folders) { PublishListItem(item, list, test, source, comment, filterExpression); } if (list is SPDocumentLibrary && takeOver) { foreach (SPCheckedOutFile file in ((SPDocumentLibrary)list).CheckedOutFiles) { file.TakeOverCheckOut(); SPListItem item = list.GetItemById(file.ListItemId); PublishListItem(item, list, test, source, comment, filterExpression); } } Logger.Write("Finished Processing List: " + list.DefaultViewUrl + "\r\n"); }
public virtual void Save(SPList list) { if (ID == null) { // new item var item = list.Items.Add(); SaveProperties(item); item.Update(); ID = item.ID; } else { var item = list.GetItemById(ID.Value); SaveProperties(item); item.Update(); } }
private SPFieldLookupValue UpdateRequestDetail(SPList RequestDetailList, int id, string productName, string quantity, string price, string description) { try { SPFieldLookupValue spFieldLookupValue = null; SPListItem RequestDetailItem = RequestDetailList.GetItemById(id); if (RequestDetailItem != null) { RequestDetailItem[SPBuiltInFieldId.Title] = productName; RequestDetailItem["Quantity"] = quantity; RequestDetailItem["Price"] = price; RequestDetailItem["Description"] = description; RequestDetailItem.Update(); spFieldLookupValue = new SPFieldLookupValue(RequestDetailItem.ID, RequestDetailItem.Title); } return spFieldLookupValue; } catch (Exception ex) { return null; throw; } }
private static void ClearOld(LinkedLookupSettings config, int listItemId, List<int> removeItems, SPField remoteLookup, SPList remoteList) { foreach (int id in removeItems) { SPListItem remoteItem; try { remoteItem = remoteList.GetItemById(id); } catch { continue; } // pokusit se z lookupu v remoteItemu smazat polozku, na ktere aktualne bezi receiver // pokud je to multilookup, chceme si zachovat zbytek hodnot if (( (SPFieldLookup) remoteLookup ).AllowMultipleValues && ( remoteItem[remoteLookup.InternalName] ?? "" ).ToString().Trim() != "") { // stavajici obsah lookupu SPFieldLookupValueCollection existingCollection = new SPFieldLookupValueCollection(( remoteItem[remoteLookup.InternalName] ?? "" ).ToString()); SPFieldLookupValue toRemove = existingCollection.FirstOrDefault(lookup => lookup.LookupId == listItemId); // ze stavajiciho obsahu odstranime polozku, na ktere bezi receiver if (toRemove != null) existingCollection.Remove(toRemove); // upraveny obsah vratime zpatky remoteItem[remoteLookup.InternalName] = existingCollection; } // pokud je to jednoduchy lookup, a neni prazdny, proste tam nastavime aktualni polozku else if (( remoteItem[remoteLookup.InternalName] ?? "" ).ToString().Trim() != "") { SPFieldLookupValue existingVal = new SPFieldLookupValue(( remoteItem[remoteLookup.InternalName] ?? "" ).ToString()); if (existingVal.LookupId == listItemId) { remoteItem[remoteLookup.InternalName] = null; } } if (config.RegularUpdate) { remoteItem.Update(false); } else { // pokud jsou receivery na obou stranach, nechceme se dostat do smycky remoteItem.SystemUpdate(config.UpdateVersion, false); } } }
private static void AddNew(LinkedLookupSettings config, SPItemEventProperties props, List<int> addItems, SPField remoteLookup, SPList remoteList) { foreach (int id in addItems) { // najit odpovidajici remote listitem SPListItem remoteItem; try { remoteItem = remoteList.GetItemById(id); } catch { continue; } // do kazde z nich pridal lookup na nasi polozku // pokud je remoteLookup multilookup, overime, ze tam jeste neni, a pridame ke stavajicim if (( (SPFieldLookup) remoteLookup ).AllowMultipleValues) { SPFieldLookupValueCollection existingCollection = ( remoteItem[remoteLookup.InternalName] ?? "" ).ToString().Trim() != "" ? new SPFieldLookupValueCollection(remoteItem[remoteLookup.InternalName].ToString()) : new SPFieldLookupValueCollection(); // zkontrolovat, jestli už tam dané ID není, ale ID, ktere menime!!!! bool exists = existingCollection.Any(lookupVal => lookupVal.LookupId == props.ListItemId); if (!exists) { existingCollection.Add(new SPFieldLookupValue(props.ListItemId, ( props.AfterProperties[( (SPFieldLookup) remoteLookup ).LookupField] ?? props.ListItem[( (SPFieldLookup) remoteLookup ).LookupField] ).ToString())); remoteItem[remoteLookup.InternalName] = existingCollection; } } // pokud je to single lookup, proste to tam pridame else { if (props.AfterProperties[( (SPFieldLookup) remoteLookup ).LookupField] != null) { SPFieldLookupValue newVal = new SPFieldLookupValue(props.ListItemId, props.AfterProperties[( (SPFieldLookup) remoteLookup ).LookupField].ToString()); remoteItem[remoteLookup.InternalName] = newVal; } else { SPFieldLookupValue newVal = new SPFieldLookupValue(props.ListItemId, props.ListItem[( (SPFieldLookup) remoteLookup ).LookupField].ToString()); remoteItem[remoteLookup.InternalName] = newVal; } } if (config.RegularUpdate) { remoteItem.Update(false); } else { // pokud jsou receivery na obou stranach, nechceme se dostat do smycky remoteItem.SystemUpdate(config.UpdateVersion, false); } } }
public virtual SPGENRepositoryDataItem GetDataItem(SPList list, int itemId, string[] fieldNames, bool includeAllItemFields, SPGENEntityFileOperationArguments fileOperationParams) { SPListItem listItem = (includeAllItemFields) ? list.GetItemById(itemId) : list.GetItemByIdSelectedFields(itemId, fieldNames); var dataItem = new SPGENRepositoryDataItem(fieldNames); ConvertToDataItem(listItem, dataItem, fileOperationParams); return dataItem; }
/// <summary> /// Sets the item security. /// </summary> /// <param name="web">The web.</param> /// <param name="list">The list.</param> /// <param name="listElement">The list element.</param> private static void SetItemSecurity(SPWeb web, SPList list, XmlElement listElement) { foreach (XmlElement itemElement in listElement.SelectNodes("Item")) { int itemId = int.Parse(itemElement.GetAttribute("Id")); SPListItem item = null; try { item = list.GetItemById(itemId); } catch (ArgumentException) { // no-op } if (item == null) { Logger.WriteWarning("Progress: Unable to locate item '{0}'.", itemId.ToString()); continue; } SetObjectSecurity(web, item, "Item " + itemId, itemElement); } }
protected void Page_Load(object sender, EventArgs e) { ListId = Request.QueryString["List"]; TaskList = Web.Lists[new Guid(ListId)]; TaskItem = TaskList.GetItemById((Convert.ToInt32(Request.Params["ID"]))); WorkflowInstanceId = new Guid((string)TaskItem["WorkflowInstanceID"]); WorkflowInstance = new SPWorkflow(Web, WorkflowInstanceId); ItemList = WorkflowInstance.ParentList; Item = ItemList.GetItemById(WorkflowInstance.ItemId); string urlToItem = Web.Site.MakeFullUrl(string.Format("{0}?ID={1}", ItemList.DefaultDisplayFormUrl, Item.ID.ToString())); string ItemName; if (Item.File != null) { ItemName = Item.File.Name; } else { ItemName = Item.Title; } lnkItem.Text = ItemName; lnkItem.NavigateUrl = urlToItem; lblListName.Text = ItemList.Title; lblSiteUrl.Text = Web.Url; if (TaskItem[SPBuiltInFieldId.TaskStatus].ToString() .Equals(SPUtility.GetLocalizedString("$Resources:Completed;", "core", SPContext.Current.Web.Language))) { btnApprove.Visible = false; btnReject.Visible = false; txtComments.Text = TaskItem["Comments"].ToString(); txtComments.Enabled = false; } }
private void CopyCat(int vnCatID, int enCatID, SPList vnCatList, SPList enCatList, SPList vnNewsList, SPList enNewsList) { var enParentCat = new SPFieldLookupValue(enCatID, enCatList.GetItemById(enCatID).Title); string camlQuery = string.Format("<Where><Eq><FieldRef Name='{0}' LookupId='TRUE'/><Value Type='Lookup'>{1}</Value></Eq></Where>", FieldsName.NewsCategory.English.ParentName, vnCatID); var query = new SPQuery(); query.Query = camlQuery; var vnListItems = vnCatList.GetItems(query); foreach (SPListItem item in vnListItems) { var enItem = enCatList.Items.Add(); enItem["Title"] = item["Title"]; enItem[FieldsName.NewsCategory.English.ParentName] = enParentCat; enItem[FieldsName.NewsCategory.English.Status] = item[FieldsName.NewsCategory.English.Status]; enItem[FieldsName.NewsCategory.English.TypeCategory] = item[FieldsName.NewsCategory.English.TypeCategory]; enItem.Update(); CopyNews(item.ID, enItem.ID, enCatList, vnNewsList, enNewsList); CopyCat(item.ID, enItem.ID, vnCatList, enCatList, vnNewsList, enNewsList); } }
public virtual void DeleteListItem(SPList list, int itemId) { var item = list.GetItemById(itemId); item.Delete(); }
public void UpdateListItem(SPList list, IDictionary dic , int id ) { SPListItem item = list.GetItemById(id); foreach (string fieldName in dic.Keys) { item[fieldName] = dic[fieldName]; } item.Update(); }
public static void CopyListItemsRoleAssignments(SPList sourceList, SPList destinationList) { foreach (SPListItem sourceListitem in sourceList.Items) { CopyListItemRoleAssignments(sourceListitem, destinationList.GetItemById(sourceListitem.ID)); } }
void NewCompress(string sZipFileFullPathName,SPList sList) { SPSecurity.RunWithElevatedPrivileges(delegate { ZipOutputStream zs = new ZipOutputStream(File.Create(sZipFileFullPathName));//D:/project/Dowload/DownLoadFile/1-2-3.zip zs.SetLevel(0); foreach (string sId in sIDS.Split('-')) { SPListItem item = sList.GetItemById(int.Parse(sId)); iParentFolderLength=item.Url.LastIndexOf('/')+1; NewCreateZip(item, zs); } zs.Finish(); zs.Close(); GC.Collect(); }); }
public SPListItem GetItem(SPList list, int id) { SPListItem item = list.GetItemById(id); return item; }
public MoveListItemCommand(int itemId, SPList sourceList, SPList targetList, List<string> siteColumnGroups, List<string> additionalFields, SPWeb web) : base(web) { _SiteColumnGroups = siteColumnGroups; _AdditionalFields = additionalFields; _CopyItem = sourceList.GetItemById(itemId); _List = targetList; }
private void CopyNews(int vnCatID, int enCatID, SPList enCatList, SPList vnNewsList, SPList enNewsList) { var enParentCat = new SPFieldLookupValue(enCatID, enCatList.GetItemById(enCatID).Title); string camlQuery = string.Format("<Where><Eq><FieldRef Name='{0}' LookupId='TRUE'/><Value Type='Lookup'>{1}</Value></Eq></Where>", FieldsName.NewsRecord.English.CategoryName, vnCatID); var query = new SPQuery(); query.Query = camlQuery; var vnListItems = vnNewsList.GetItems(query); foreach (SPListItem item in vnListItems) { var enItem = enNewsList.Items.Add(); enItem["Title"] = item["Title"]; enItem[FieldsName.NewsRecord.English.CategoryName] = enParentCat; enItem[FieldsName.NewsRecord.English.PublishingPageContent] = item[FieldsName.NewsRecord.English.PublishingPageContent]; enItem[FieldsName.NewsRecord.English.FocusNews] = item[FieldsName.NewsRecord.English.FocusNews]; enItem[FieldsName.NewsRecord.English.LinkAdv] = item[FieldsName.NewsRecord.English.LinkAdv]; enItem[FieldsName.NewsRecord.English.PublishingPageImage] = item[FieldsName.NewsRecord.English.PublishingPageImage]; if (!string.IsNullOrEmpty(Convert.ToString(item[FieldsName.NewsRecord.English.PublishingPageContent]))) { enItem[FieldsName.NewsRecord.English.PublishingPageContent] = item[FieldsName.NewsRecord.English.PublishingPageContent]; } else { enItem[FieldsName.NewsRecord.English.PublishingPageContent] = item[FieldsName.NewsRecord.English.PublishingPageContent]; item[FieldsName.NewsRecord.English.PublishingPageContent] = item[FieldsName.NewsRecord.English.PublishingPageContent]; item.Update(); } enItem[FieldsName.NewsRecord.English.ShortContent] = item[FieldsName.NewsRecord.English.ShortContent]; enItem[FieldsName.NewsRecord.English.ShowInHomePage] = item[FieldsName.NewsRecord.English.ShowInHomePage]; enItem[FieldsName.NewsRecord.English.Status] = item[FieldsName.NewsRecord.English.Status]; enItem[FieldsName.NewsRecord.English.ThumbnailImage] = item[FieldsName.NewsRecord.English.ThumbnailImage]; enItem.Update(); } }