protected virtual void ValidateProperties(SPListItem item, ListItemDefinition definition) { var assert = ServiceFactory.AssertService .NewAssert(definition, item) .ShouldNotBeNull(item) .ShouldBeEqual(m => m.Title, o => o.Title); }
public void HandleSecurityRules(SPListItem listItem, SPEventReceiverType eventType) { SPSecurity.RunWithElevatedPrivileges(delegate() { SecuritySettings settings = listItem.ParentList.GetCustomSettings<SecuritySettings>(TVMCORPFeatures.TVS); if (settings == null) return; settings.Rules.Sort(delegate(Rule rule1, Rule rule2) { return rule1.Order.CompareTo(rule2.Order); }); foreach (Rule r in settings.Rules) { bool ruleQualified = ValidateRule(r, listItem, eventType); if (ruleQualified) { bool itemQuailfied = ValidateItem(listItem, r); if (itemQuailfied) { ApplySecuritySettings(listItem, r); break; } } } }); }
private static void setPerrmissionToListItem(SPListItem listItem, PermissionAssigment pa) { List<string> members = new List<string>(); if (pa.Members != null && pa.Members.Count > 0) { members.AddRange(pa.Members); } if (pa.FieldIds != null && pa.FieldIds.Count > 0) { foreach (string fieldId in pa.FieldIds) { if (listItem.Fields.ContainFieldId(new Guid(fieldId)) && listItem[new Guid(fieldId)] != null) { SPFieldUserValueCollection users = new SPFieldUserValueCollection(listItem.Web, listItem[new Guid(fieldId)].ToString()); foreach (SPFieldUserValue user in users) { if (user.User != null) members.Add(user.LookupId + ";#" + user.User.LoginName); else members.Add(user.ToString()); } } } } listItem.SetPermissions(pa.PermissionLevel, members); }
public UpdateCommand(SPListItem item, SPWeb web, Dictionary<string, object> values) : base(item, web) { _NewValues = values; _OldValues = new Dictionary<string, object>(); LoadOldValues(); }
private static void Create_Forms(SPListItem item, Array klienci) { SPList list = BLL.admProcesy.GetList(item.Web); string mask = BLL.Tools.Get_Text(item, "colMaskaSerwisu"); foreach (SPListItem k in klienci) { if (string.IsNullOrEmpty(mask)) { if (BLL.Tools.Has_SerwisAssigned(k, "selSewisy", "ZUS-*")) Create_New_GFR_K(item, "ZUS-*", list, k); if (BLL.Tools.Has_SerwisAssigned(k, "selSewisy", "PD-*")) Create_New_GFR_K(item, "PD-*", list, k); if (BLL.Tools.Has_SerwisAssigned(k, "selSewisy", "PDS-*")) Create_New_GFR_K(item, "PDS-*", list, k); if (BLL.Tools.Has_SerwisAssigned(k, "selSewisy", "VAT-*")) Create_New_GFR_K(item, "VAT-*", list, k); if (BLL.Tools.Has_SerwisAssigned(k, "selSewisy", "RBR")) Create_New_GFR_K(item, "RBR", list, k); if (BLL.Tools.Has_SerwisAssigned(k, "selSewisy", "RB")) Create_New_GFR_K(item, "RB", list, k); } else { if (BLL.Tools.Has_SerwisAssigned(k, "selSewisy", mask)) Create_New_GFR_K(item, mask, list, k); } } }
/// <summary> /// Метод, возвращающий права для группы по умолчанию, в зависимости от карточки и её статуса /// </summary> /// <param name="Group">Группа</param> /// <returns></returns> private static AccessData GetGroupAccessData(SPWeb Web, SPGroup Group, SPListItem Item, CardState State, List<string> Companies) { AccessData result = new AccessData(); switch (Item.ParentList.Title) { default: break; case GlobalConstants.ListNames.ControlMeasures: { } break; case GlobalConstants.ListNames.Request: { } break; case GlobalConstants.ListNames.Inbox: { } break; case GlobalConstants.ListNames.Outbox: { } break; } return result; }
public void GetSPLibItemData(SPListItem spItem) { base.GetSPListItemData(spItem); FileName = spItem.File.Name; FileSize = spItem.File.Length; FileUrl = spItem.File.ServerRelativeUrl; //FileRelUrl = spItem.File.Url; FileAbsUrl = Convert.ToString(spItem[LibraryItemDefaultFields.EncodedAbsUrl]); if (string.IsNullOrEmpty(Title)) { Title = this.FileName; } CheckOutStatus = spItem.File.CheckOutStatus; if ((int)CheckOutStatus != 0) { CheckoutUser = new UserData(spItem.File.CheckedOutByUser); CheckoutDate = spItem.File.CheckedOutDate; } CheckinComment = spItem.File.CheckInComment; //DocumentIcon = SPUtility.MapToIcon(spItem.Web, this.FileName, string.Empty); //FileRef = spItem.File.Url;// spItem.GetFieldStringValue(LibraryItemDefaultFields.FileRef); //FileSize = spItem.File.Length;//.GetFieldStringValue(LibraryItemDefaultFields.FileSize); //FileName = spItem.File.Name;// spItem.GetFieldStringValue(LibraryItemDefaultFields.LinkFilename); //EncodedAbsUrl = Convert.ToString(spItem[LibraryItemDefaultFields.EncodedAbsUrl]); //ServerUrl = spItem.GetFieldStringValue(LibraryItemDefaultFields.ServerUrl); //DocIcon = spItem.GetFieldStringValue(LibraryItemDefaultFields.DocIcon); //FileInfo = spItem.File;//.GetFieldUserValueOrEmpty(LibraryItemDefaultFields.CheckoutUser); //CheckinComment = spItem.GetFieldStringValue(LibraryItemDefaultFields.CheckinComment); }
public static void Create_ctRB_Form(SPWeb web, int klientId, int okresId, string key, SPListItem klientItem, Models.Klient iok) { Logger.LogEvent("Create_ctRB_Form", klientId.ToString()); SPList list = web.Lists.TryGetList(targetList); SPListItem newItem = list.AddItem(); BLL.Tools.Set_Value(newItem, "selKlient", klientId); BLL.Tools.Set_Value(newItem, "selOkres", okresId); BLL.Tools.Set_Text(newItem, "KEY", key); Models.Okres o = new Models.Okres(web, okresId); BLL.Tools.Set_Text(newItem, "Title", string.Format("Opłata za obsługę {0}", o.Nazwa)); double om = BLL.tabStawki.Get_OplataMiesieczna(web, klientId); if (om > 0) { BLL.Tools.Set_Value(newItem, "colDoZaplaty", om); } else { BLL.tabStawki.Ensure_KlientExist(web, klientId); } newItem.SystemUpdate(); }
public string GetFieldValueUserCollectionEmails(SPListItem item, string fieldName) { string emails = ""; if (item != null && item.Fields.ContainsField(fieldName) && item[fieldName] != null) { string fieldVal = item[fieldName].ToString(); SPFieldUserValueCollection usersV = new SPFieldUserValueCollection(item.Web, fieldVal); foreach (SPFieldUserValue uv in usersV) { emails += uv.User.Email + "; "; } return emails; } else { return string.Empty; } }
public MoveListItemCommand(SPListItem copyItem, SPList targetList, List<string> siteColumnGroups, SPWeb web) : base(web) { _CopyItem = copyItem; _SiteColumnGroups = siteColumnGroups; _List = targetList; }
public static void Get_TemplateByKod(SPListItem item, string kod, out string temat, out string trescHTML, string nadawcaEmail) { switch (item.ParentList.Title) { case "Zadania": //zobacz czy operator jest przypisany do zadania string temp = string.Empty; string footerTR = string.Empty; Get_TemplateByKod(item.Web, "EMAIL_FOOTER_TR", out temp, out footerTR, false); if (string.IsNullOrEmpty(nadawcaEmail)) { int operatorId = Get_LookupId(item, "selOperator"); footerTR = Format_FooterTR(item, footerTR, operatorId); } else { int operatorId = BLL.dicOperatorzy.Get_OperatorIdByEmail(item.Web, nadawcaEmail); footerTR = Format_FooterTR(item, footerTR, operatorId); } Get_TemplateByKod(item.Web, kod, out temat, out trescHTML, true); trescHTML = trescHTML.Replace("___FOOTER___", footerTR); break; default: Get_TemplateByKod(item.Web, kod, out temat, out trescHTML, true); break; } }
public override void OnExpiration(SPListItem item, XmlNode parametersData, DateTime expiredDate) { item["Status"] = "Expired"; item["ExpiredDate"] = expiredDate; item.Update(); }
public static XmlCDataSection CreateCDataSection(XmlDocument parentDoc, XmlElement parentElement,SPListItem item, string fieldName) { string valString = GetListItemValue(item, fieldName); XmlCDataSection newSection = parentDoc.CreateCDataSection(valString); parentElement.AppendChild(newSection); return newSection; }
public static IEnumerable<SPUser> GetSPUsers(SPListItem listItem, string key) { object obj = null; try { obj = listItem[key]; } catch (Exception) { var index = -1; switch (key) { case "Author": index = GetFieldIndex(listItem, key); obj = listItem[index]; //Ошибка шарепоинта - иногда не ищет поле Author break; case "Editor": index = GetFieldIndex(listItem, key); obj = listItem[index]; //Ошибка шарепоинта - иногда не ищет поле Editor break; } } if (obj == null) return null; try { var value = new SPFieldUserValueCollection(listItem.Web, obj.ToString()); return value.Select(item => item.User); } catch (Exception) { return null; } }
private void RenderDonorPanel(SPListItem item) { if (item["Donor"] != null) { var donor = new SPFieldLookupValue(item["Donor"].ToString()); try { var linkField = SPContext.Current.Web.Lists["Donors"].GetItemById(donor.LookupId); DonorLink.Text = donor.LookupValue; if (linkField["Website"] != null) { var link = new SPFieldUrlValue(linkField["Website"].ToString()); DonorLink.NavigateUrl = link.Url; DonorLink.Target = "_blank"; } DonorPanel.Visible = true; } catch (ArgumentException) { //throw new Exception(string.Format("The requested Donor \"{0}\" was not found for the item titled \"{1}\".", donor, item.Title)); DonorPanel.Visible = false; } } else { DonorPanel.Visible = false; } }
private void RenderNumberOfBids(SPListItem item) { if (item["NumberOfBids"] != null) { var bids = item["NumberOfBids"].ToString(); NumberOfBidsLabel.Text = string.Format("{0} - <a href=\"#\" onclick=\"javascript:$('#auction-bid-history').slideToggle()\">Bid History</a>", bids); // build list of bids for this item var query = new SPQuery { Query = "<Where><Eq><FieldRef Name=\"Item\" LookupId=\"TRUE\"/><Value Type=\"Lookup\">" + item.ID + "</Value></Eq></Where><OrderBy><FieldRef Name=\"Modified\" Ascending=\"FALSE\"/></OrderBy></Query>" }; var bidHistory = SPContext.Current.Web.Lists[Constants.BidderListName].GetItems(query); BidHistory.Text = "<table cellpadding=\"4\" cellspacing=\"4\"><tr>"; BidHistory.Text += "<th>Bidder</th><th>Bid Amount</th><th>Bid Time</th>"; foreach (SPListItem bidItem in bidHistory) { var bidderColumn = (SPFieldUser)bidItem.Fields.GetField("Bidder"); var bidder = (SPFieldUserValue)bidderColumn.GetFieldValue(bidItem["Bidder"].ToString()); BidHistory.Text += string.Format("<tr><td>{0}</td><td>{1:c}</td><td>{2}</td></tr>", bidder.User.Name, bidItem["Amount"], bidItem["Modified"]); } BidHistory.Text += "</tr></table>"; } else { NumberOfBidsLabel.Text = "0"; } }
private void UnLockWorkflowTasks(SPListItem wfItem) { bool isNeedUnlock = false; foreach (SPWorkflow workflow in wfItem.Workflows) { foreach (SPWorkflowTask task in workflow.Tasks) { if (task[SPBuiltInFieldId.WorkflowVersion].AsString() != "1") { isNeedUnlock = true; task[SPBuiltInFieldId.WorkflowVersion] = "1"; task.SystemUpdate(); } } } if (isNeedUnlock) { DisplayMessage(string.Format("The workflow {0} is unlocked now.", wfItem["Title"].AsString())); } else { DisplayMessage(string.Format("The workflow {0} was not locked before.", wfItem["Title"].AsString())); } }
public void GetSPListItemData(SPListItem spItem) { //base.Init(spItem, AttachmentsLoadMode.Short); ID = spItem.GetFieldIntValue(ListItemDefaultFields.ID); Title = spItem.GetFieldStringValue(ListItemDefaultFields.Title); GUID = spItem.GetFieldGuidValue(ListItemDefaultFields.GUID); Created = spItem.GetFieldDateTimeValue(ListItemDefaultFields.Created); CreatedBy = spItem.GetFieldUserValueOrEmpty(ListItemDefaultFields.CreatedBy); Modified = spItem.GetFieldDateTimeValue(ListItemDefaultFields.Modified); ModifiedBy = spItem.GetFieldUserValueOrEmpty(ListItemDefaultFields.ModifiedBy); ContentTypeId = Convert.ToString(spItem.ContentTypeId); ContentType = spItem.ContentType.Name; SPContentTypeCollection ctsParentList = spItem.ParentList.ContentTypes; foreach (SPContentType ct in ctsParentList) { UlsLogging.LogInformation("SPContentType Name: {0} Id: {1}", ct.Name, Convert.ToString(ct.Id)); //ContentTypes.Add(ct.Name, Convert.ToString(ct.Id)); } if (spItem.ModerationInformation != null) { ModerationStatus = spItem.ModerationInformation.Status; ModerationComments = Convert.ToString(spItem.ModerationInformation.Comment); } //ListID = spItem.ParentList.ID; //ListTitle = spItem.ParentList.Title; //WebID = spItem.Web.ID; //WebUrl = spItem.Web.Url; UIVersionString = spItem[ListItemDefaultFields.UIVersionString]; OriginInfo OriginInfo = new OriginInfo(); OriginInfo.GetData(spItem.ParentList); }
private static void Copy_Attachement(SPListItem newItem, SPFile file) { int bufferSize = 20480; byte[] byteBuffer = new byte[bufferSize]; byteBuffer = file.OpenBinary(); newItem.Attachments.Add(file.Name, byteBuffer); }
public TestCondition(SPListItem listItem, string fieldName, string op, object val) { this.listItem = listItem; this.fieldName = fieldName; this.op = op; this.val = val; }
private void ProcessItem(SPListItem item) { string title = item["Title"].ToString(); string description = item["Description"].ToString(); table.Rows.Add(title, description); }
private static void Update_msg(StringBuilder msg, string procName, SPListItem task) { msg.AppendFormat("<li>zadanie# {0} klient: {1} procedura: {2}</li>", task.ID.ToString(), BLL.Tools.Get_LookupValue(task, "selKlient"), procName); }
public static void StartWorkflow(SPListItem listItem, string workflowName) { try { SPWorkflowManager manager = listItem.Web.Site.WorkflowManager; SPWorkflowAssociationCollection objWorkflowAssociationCollection = listItem.ParentList.WorkflowAssociations; foreach (SPWorkflowAssociation objWorkflowAssociation in objWorkflowAssociationCollection) { if (String.Compare(objWorkflowAssociation.Name, workflowName, true) == 0) { //We found our workflow association that we want to trigger. //Replace the workflow_GUID with the GUID of the workflow feature that you //have deployed. try { manager.StartWorkflow(listItem, objWorkflowAssociation, objWorkflowAssociation.AssociationData, true); //The above line will start the workflow... } catch (Exception) { } break; } } } catch (Exception) { } }
public static void SendMailWithAttachment(SPListItem item, MailMessage message) { SmtpClient client = new SmtpClient(); client.Host = item.Web.Site.WebApplication.OutboundMailServiceInstance.Server.Address; //nazwa witryny if (string.IsNullOrEmpty(message.From.Address)) { message.From = new MailAddress(BLL.admSetup.GetValue(item.Web, "EMAIL_BIURA"), item.Web.Title != null ? item.Web.Title : BLL.admSetup.GetValue(item.Web, "EMAIL_NAZWA_FIRMY")); } else { message.From = new MailAddress(message.From.Address, Format_SenderDisplayName(item.Web,message.From.Address)); } //ustaw adres zwrotny message.ReplyTo = message.From; for (int attachmentIndex = 0; attachmentIndex < item.Attachments.Count; attachmentIndex++) { string url = item.Attachments.UrlPrefix + item.Attachments[attachmentIndex]; SPFile file = item.ParentList.ParentWeb.GetFile(url); message.Attachments.Add(new Attachment(file.OpenBinaryStream(), file.Name)); } client.Send(message); }
private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e) { Debug.WriteLine("admProcessRequestsWF:{" + workflowProperties.WorkflowId + "} initiated"); item = workflowProperties.Item; startTime = DateTime.Now; }
public static string AddCompanyName(string temat, SPListItem item) { if (item != null) { if (item.ContentType.Name == "KPiR" || item.ContentType.Name == "KSH") { int klientId = Get_LookupId(item, "selKlient"); if (klientId > 0) { BLL.Models.Klient k = new Klient(item.Web, klientId); return string.Format("{0} {1}", temat, k.PelnaNazwaFirmy); } } if (item.ContentType.Name == "Prośba o dokumenty" || item.ContentType.Name == "Prośba o przesłanie wyciągu bankowego" || item.ContentType.Name == "Rozliczenie podatku dochodowego" || item.ContentType.Name == "Rozliczenie podatku dochodowego spółki" || item.ContentType.Name == "Rozliczenie podatku VAT" || item.ContentType.Name == "Rozliczenie z biurem rachunkowym" || item.ContentType.Name == "Rozliczenie ZUS") { int klientId = Get_LookupId(item, "selKlient"); if (klientId > 0) { BLL.Models.Klient k = new Klient(item.Web, klientId); return string.Format("{0} {1}", temat, k.PelnaNazwaFirmy); } } } return temat; }
public MoveCommand(SPListItem item, SPWeb web, string targetUrl) : base(item, web) { _TargetUrl = targetUrl; _ContentTypeId = item.ContentTypeId; _SourceUrl = string.Format("{0}/{1}", web.Url, item.Url); }
public PrzeterminowanaFaktura(SPListItem record) { if (record!=null) { if (record["Title"]!=null) { NazwaDluznika = record["Title"].ToString(); } if (record["colNumerFaktury"] != null) { NumerFaktury = record["colNumerFaktury"].ToString(); } if (record["Title"] != null) { NazwaDluznika = record["Title"].ToString(); } if (record["Title"] != null) { NazwaDluznika = record["Title"].ToString(); } if (record["Title"] != null) { NazwaDluznika = record["Title"].ToString(); } if (record["Title"] != null) { NazwaDluznika = record["Title"].ToString(); } } }
public MoveListItemCommand(SPListItem copyItem, string targetListName, List<string> siteColumnGroups, SPWeb web) : base(web) { _CopyItem = copyItem; _SiteColumnGroups = siteColumnGroups; _List = _SPWeb.Lists.TryGetList(targetListName); }
protected void assign_roles(SPWeb web, SPListItem item, SPListItem project, string field_name, string field_guid, SPRoleDefinition definition) { try { string value = project[field_name].ToString(); SPFieldUserValueCollection field_user_value = (SPFieldUserValueCollection)project.Fields[new Guid(field_guid)].GetFieldValue(value); foreach (SPFieldUserValue user_value in field_user_value) { if (user_value.User == null) { SPGroup group = web.SiteGroups.GetByID(user_value.LookupId); bind_role(item, group, definition); } else { bind_role(item, user_value.User, definition); } } } catch (Exception ex) { log(web.Site, "为项目【" + project["Title"] + "】的【" + field_name + "】的文档授权时发生错误", "错误", ex.ToString()); } }
protected void Page_Load(object sender, EventArgs e) { LocalizeControls(); if (!Page.IsPostBack) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID)) { // Load all webs in drop down foreach (SPWeb web in currentSite.AllWebs) { ddlWebs.Items.Add(new ListItem(web.Url, web.ID.ToString())); web.Dispose(); } // Select the good web site if (fieldProperties != null) { ListItem item = ddlWebs.Items.FindByValue(fieldProperties.WebId); if (item != null) { item.Selected = true; } } else { ddlWebs.Items.FindByValue(SPContext.Current.Web.ID.ToString()).Selected = true; } // Load picture libraries of the site web LoadPictureLibraries(currentSite); // Init controls with field properties if (fieldProperties != null) { ListItem item = ddlPictureLibrary.Items.FindByValue(fieldProperties.PictureLibraryId); if (item != null) { item.Selected = true; } cbOverwrite.Checked = fieldProperties.Overwrite; tbFormatName.Text = fieldProperties.FormatName; } // Load the default picture if (fieldProperties != null && fieldProperties.DefaultPictureId != -1) { try { using (SPWeb spWeb = currentSite.OpenWeb(new Guid(fieldProperties.WebId))) { SPList pictureLibrary = spWeb.Lists[new Guid(fieldProperties.PictureLibraryId)]; SPListItem picture = pictureLibrary.GetItemById(fieldProperties.DefaultPictureId); // Display the thumbnail in the picture imgDefaultPicture.ImageUrl = Utility.GetRelativeUrl(picture["EncodedAbsThumbnailUrl"].ToString()); } imgDefaultPicture.Visible = true; } catch { /* ignore incase picture library or default picture is not found */ } } } }); } }
private static DateTime Get_Date(SPListItem item, string col) { return(item[col] != null?DateTime.Parse(item[col].ToString()) : new DateTime()); }
public static DateTime Get_TerminPlatnosciByOkresId(SPWeb web, string nazwaKolumny, int okresId) { SPListItem item = Get_ItemById(web, okresId); return(item[nazwaKolumny] != null?DateTime.Parse(item[nazwaKolumny].ToString()) : new DateTime()); }
const string targetList = "Okresy"; //"tabOkresy"; private static void Get_ZUS_Terminy(bool isPracownicy, ref DateTime terminPlatnosci, ref DateTime terminPrzekazania, SPListItem item) { if (isPracownicy) { terminPlatnosci = DateTime.Parse(item["colZUS_TerminPlatnosciSkladek_ZP"].ToString()); } else { terminPlatnosci = DateTime.Parse(item["colZUS_TerminPlatnosciSkladek_Be"].ToString()); } int offset = int.Parse(item["ZUS_TerminPrzekazaniaWynikow_Ofs"].ToString()); terminPrzekazania = terminPlatnosci.AddDays(offset); }
protected override void RenderContents(HtmlTextWriter writer) { SPWeb mySite = SPContext.Current.Web; SPList lst = findList(mySite); if (lst != null) { try { string titleItem = ""; SPListItem li = null; if (!String.IsNullOrEmpty(Page.Request.QueryString["RootFolder"])) { li = this.findDiscussion(lst, Page.Request.QueryString["RootFolder"]); } else { if (lst.BaseTemplate == SPListTemplateType.WebPageLibrary) { li = this.findWikiPage(lst); if (li.Fields.ContainsField("Title0")) { titleItem = li.Fields[li.Fields.GetFieldByInternalName("Title0").ToString()].ToString(); } else { titleItem = nameWikiPage(li); } } else { li = lst.GetItemById(Convert.ToInt32(Page.Request.QueryString["ID"])); if (li.Fields.ContainsField("Title") && li["Title"] != null) { titleItem = li["Title"].ToString(); } else { titleItem = ""; } } } if (li != null && li.Fields.ContainsField(tagColumnName)) { tags = getTags(li); XmlDocument xdoc = new XmlDocument(); XmlDocument xsld = new XmlDocument(); xdoc.LoadXml("<rows></rows>"); if (tags.Length > 0) { DataTable hsItems = this.GetItems(); XmlNode xn; XmlAttribute xa; string weburl; string ct; foreach (DataRow row in hsItems.Rows) { if ((row["TipoContenuto"].ToString().Contains("Pagina") && !row["Path"].ToString().Contains(li.Url)) || (!row["TipoContenuto"].ToString().Contains("Pagina") && HttpUtility.HtmlDecode(row["Title"].ToString()) != HttpUtility.HtmlDecode(titleItem))) { xn = xdoc.CreateElement("row"); xdoc.DocumentElement.AppendChild(xn); xa = xdoc.CreateAttribute("title"); xn.Attributes.Append(xa); if (row["TipoContenuto"].ToString().Contains("Pagina")) { if (row["Path"].ToString().Contains(".aspx")) { xa.Value = row["Path"].ToString().Substring(row["Path"].ToString().LastIndexOf('/') + 1); xa.Value = xa.Value.Substring(0, xa.Value.Length - 5); } else { xa.Value = "Sito"; } } else { xa.Value = row["Title"].ToString(); } xa = xdoc.CreateAttribute("created"); xn.Attributes.Append(xa); xa.Value = row["Created"].ToString(); xa = xdoc.CreateAttribute("site"); xn.Attributes.Append(xa); xa.Value = row["SiteTitle"].ToString(); xa = xdoc.CreateAttribute("siteurl"); xn.Attributes.Append(xa); xa.Value = row["SiteName"].ToString(); xa = xdoc.CreateAttribute("url"); xn.Attributes.Append(xa); xa.Value = row["Path"].ToString(); xa = xdoc.CreateAttribute("contenttype"); xn.Attributes.Append(xa); xa.Value = row["TipoContenuto"].ToString(); xa = xdoc.CreateAttribute("tags"); xn.Attributes.Append(xa); string resultTags = ""; if (row["Tags"].GetType() == typeof(System.String[])) { for (int i = 0; i < ((string[])row["Tags"]).Length; i++) { resultTags += ((string[])row["Tags"])[i] + "; "; } } else { resultTags = row["Tags"].ToString(); } xa.Value = resultTags; } } } if (xsltFlag) { xsld.LoadXml(XSLT); writer.Write(Transform(xdoc, xsld)); } else { writer.Write("<pre>" + xdoc.OuterXml + "</pre>"); } } else { writer.Write("<span style=\"display:none\"> elemento senza correlazioni <span>"); } } catch (Exception ex) { writer.Write("<pre>"); writer.Write(ex.ToString()); writer.Write("</pre>"); } } }
private float iInstallNavigationItem(SPNavigationNodeCollection navNode, XmlNodeList ndParentItems, int ParentMessageId, XmlNode docFiles, float counter, float max, string navField, SPListItem oParentListItem, ref ArrayList arrNavNodes) { var iArrNodes = new ArrayList(); foreach (XmlNode nd in ndParentItems) { var sParentName = ApplicationInstallerHelpers.getAttribute(nd, "Name"); var sParentUrl = GetCleanUrl(ApplicationInstallerHelpers.getAttribute(nd, "Url")); var bParentExternal = false; bool.TryParse(ApplicationInstallerHelpers.getAttribute(nd, "External"), out bParentExternal); var bAppend = false; bool.TryParse(ApplicationInstallerHelpers.getAttribute(nd, "Append"), out bAppend); if (bParentExternal || DoesLocationExist(sParentUrl, ApplicationInstallerHelpers.getAttribute(nd, "Url"), ApplicationInstallerHelpers.getAttribute(nd, "List"), docFiles)) { var ndChildItems = nd.SelectNodes("Item"); try { SPNavigationNode oNewNav = null; if (!bVerifyOnly) { oNewNav = ApplicationInstallerHelpers.GetNavNode(navNode, navField, sParentName, oParentListItem); } if (!bVerifyOnly && oNewNav == null) { oNewNav = new SPNavigationNode(sParentName, sParentUrl, bParentExternal); navNode.AddAsLast(oNewNav); iArrNodes.Add(oNewNav.Id.ToString()); arrNavNodes.Add(oNewNav.Id + (iCommunity != 0 ? ":" + appDef.Id : string.Empty)); } var ParentNavMessageId = addMessage(ErrorLevels.NoError, sParentName, string.Empty, ParentMessageId); foreach (XmlNode ndChild in nd.SelectNodes("Item")) { var sChildName = ApplicationInstallerHelpers.getAttribute(ndChild, "Name"); try { var sChildUrl = GetCleanUrl(ApplicationInstallerHelpers.getAttribute(ndChild, "Url")); var bChildExternal = false; bool.TryParse(ApplicationInstallerHelpers.getAttribute(ndChild, "External"), out bChildExternal); if (bChildExternal || DoesLocationExist(sChildUrl, ApplicationInstallerHelpers.getAttribute(ndChild, "Url"), ApplicationInstallerHelpers.getAttribute(ndChild, "List"), docFiles)) { if (oNewNav != null) { var oNewChildNav = new SPNavigationNode(sChildName, GetCleanUrl(sChildUrl), bChildExternal); oNewNav.Children.AddAsLast(oNewChildNav); arrNavNodes.Add(oNewChildNav.Id + (iCommunity != 0 ? ":" + appDef.Id : string.Empty)); iArrNodes.Add(oNewChildNav.Id.ToString()); } addMessage(ErrorLevels.NoError, sChildName, string.Empty, ParentNavMessageId); } else { addMessage(ErrorLevels.Warning, sChildName, "Url Doesn't Exist (" + sChildUrl + ")", ParentNavMessageId); } } catch (Exception ex2) { Trace.WriteLine(ex2.ToString()); addMessage(ErrorLevels.Warning, sChildName, "Error: " + ex2.Message, ParentNavMessageId); } } if (oNewNav != null) { oNewNav.Update(); } } catch (Exception ex1) { Trace.WriteLine(ex1.ToString()); addMessage(ErrorLevels.Warning, sParentName, "Error: " + ex1.Message, ParentMessageId); } } else { addMessage(ErrorLevels.Warning, sParentName, "Url Doesn't Exist (" + sParentUrl + ")", ParentMessageId); } counter++; var percent = counter / max; updateLIPercent(percent); } if (!bVerifyOnly && oParentListItem != null) { try { if (oParentListItem[navField].ToString() != string.Empty) { var Navs = oParentListItem[navField].ToString().Split(','); iArrNodes.AddRange(Navs); } } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } oParentListItem[navField] = string.Join(",", (string[])iArrNodes.ToArray(typeof(string))); oParentListItem.Update(); } return(counter); }
private void PullResourceFromTopSite(SPWeb web) { SPList rList = null; SPList tList = null; web.Site.AllowUnsafeUpdates = true; web.Site.RootWeb.AllowUnsafeUpdates = true; web.AllowUnsafeUpdates = true; tList = web.Lists.TryGetList("Team"); string resWebUrl = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveResourceURL", true, true); if (!string.IsNullOrEmpty(resWebUrl)) { using (SPWeb rWeb = web.Site.AllWebs[resWebUrl]) { rList = rWeb.Lists.TryGetList("Resources"); if ((rList != null) && (rList.Items.Count > 0) && (tList != null)) { foreach (SPListItem item in rList.Items) { SPField userValueFld = null; string spAccounts = null; try { userValueFld = item.Fields[item.Fields.GetFieldByInternalName("SharePointAccount").Id]; } catch { } if ((userValueFld != null) && (item[rList.Fields.GetFieldByInternalName("SharePointAccount").Id] != null)) { spAccounts = item[rList.Fields.GetFieldByInternalName("SharePointAccount").Id].ToString(); string[] valPair = spAccounts.Split(new string[] { ";#" }, StringSplitOptions.None); if (int.Parse(valPair[0]) != SPContext.Current.Web.CurrentUser.ID) { continue; } SPQuery q = new SPQuery(); q.Query = "<Where><Eq><FieldRef Name=\"ResID\" /><Value Type=\"Number\">" + SPContext.Current.Web.CurrentUser.ID.ToString() + "</Value></Eq></Where>"; SPListItemCollection tListItems = tList.GetItems(q); if (tListItems.Count.Equals(0)) { SPListItem newTeamItem = tList.Items.Add(); newTeamItem[tList.Fields.GetFieldByInternalName("Title").Id] = item["Title"]; newTeamItem[tList.Fields.GetFieldByInternalName("ResID").Id] = item.ID; newTeamItem.Update(); tList.Update(); web.Update(); break; } } } } } } }
public static SPFieldLookupValue GetLookup(this SPListItem item) { return(item != null ? new SPFieldLookupValue(item.ID, String.Empty) : null); }
public static object GetValue(this SPListItem item, string internalName) { SPField field = item.Fields.GetFieldByInternalName(internalName); return(item[field.Id]); }
public static void SetValue(this SPListItem item, string internalName, object value) { SPField field = item.Fields.GetFieldByInternalName(internalName); item[field.Id] = value; }
/// <summary> /// Maps metadata from a SPListItem to the metadata update message to be sent to the Guidewire metadata update service /// </summary> /// <param name="item">The SPListItem to get metadata from</param> /// <returns></returns> private static List <GuidewireWS.trg_MetadataPair> CreateMetadata(SPListItem item) { List <GuidewireWS.trg_MetadataPair> metadata = new List <GuidewireWS.trg_MetadataPair>(); CreateMetadataPair(metadata, "name", "Title", item); if (item.Fields.ContainsField(Resource.FieldWorkMatter)) { CreateMetadataPair(metadata, "workmatter", Resource.FieldWorkMatter, item); } else { CreateMetadataPair(metadata, "trg_ContactID", Resource.FieldVendor, item); } CreateMetadataPair(metadata, "author", "Created By", item); if (item.Fields.ContainsField(Resource.FieldCategory) && item[Resource.FieldCategory] != null) { CreateMetadataPair(metadata, "trg_Category", Resource.FieldCategory, item); } else if (item.Fields.ContainsField(Resource.FieldBCSWorkMatterDocument + ": Category") && item[Resource.FieldBCSWorkMatterDocument + ": Category"] != null) { CreateMetadataPair(metadata, "trg_Category", Resource.FieldBCSWorkMatterDocument + ": Category", item); } else if (item.Fields.ContainsField(Resource.FieldBCSVendorDocument + ": Category") && item[Resource.FieldBCSVendorDocument + ": Category"] != null) { CreateMetadataPair(metadata, "trg_Category", Resource.FieldBCSVendorDocument + ": Category", item); } if (item.Fields.ContainsField(Resource.FieldSubCategory) && item[Resource.FieldSubCategory] != null) { CreateMetadataPair(metadata, "trg_SubCategory", Resource.FieldSubCategory, item); } else if (item.Fields.ContainsField(Resource.FieldBCSWorkMatterDocument + ": Sub Category") && item[Resource.FieldBCSWorkMatterDocument + ": Sub Category"] != null) { CreateMetadataPair(metadata, "trg_SubCategory", Resource.FieldBCSWorkMatterDocument + ": Sub Category", item); } else if (item.Fields.ContainsField(Resource.FieldBCSVendorDocument + ": Sub Category") && item[Resource.FieldBCSVendorDocument + ": Sub Category"] != null) { CreateMetadataPair(metadata, "trg_SubCategory", Resource.FieldBCSVendorDocument + ": Sub Category", item); } if (item.Fields.ContainsField(Resource.FieldDocumentStatus) && item[Resource.FieldDocumentStatus] != null) { CreateMetadataPair(metadata, "status", Resource.FieldDocumentStatus, item); } else if (item.Fields.ContainsField(Resource.FieldBCSWorkMatterDocument + ": Status") && item[Resource.FieldBCSWorkMatterDocument + ": Status"] != null) { CreateMetadataPair(metadata, "status", Resource.FieldBCSWorkMatterDocument + ": Status", item); } else if (item.Fields.ContainsField(Resource.FieldBCSVendorDocument + ": Status") && item[Resource.FieldBCSVendorDocument + ": Status"] != null) { CreateMetadataPair(metadata, "status", Resource.FieldBCSVendorDocument + ": Status", item); } if (item.Fields.ContainsField(Resource.FieldDescription) && item[Resource.FieldDescription] != null) { CreateMetadataPair(metadata, "description", Resource.FieldDescription, item); } else if (item.Fields.ContainsField(Resource.FieldBCSWorkMatterDocument + ": Description") && item[Resource.FieldBCSWorkMatterDocument + ": Description"] != null) { CreateMetadataPair(metadata, "description", Resource.FieldBCSWorkMatterDocument + ": Description", item); } else if (item.Fields.ContainsField(Resource.FieldBCSVendorDocument + ": Description") && item[Resource.FieldBCSVendorDocument + ": Description"] != null) { CreateMetadataPair(metadata, "description", Resource.FieldBCSVendorDocument + ": Description", item); } CreateMetadataPair(metadata, "mimetype", "File Type", item); CreateMetadataPair(metadata, "dateModified", Resource.FieldModifiedDate, item); CreateMetadataPair(metadata, "dateCreated", Resource.FieldCreatedDate, item); return(metadata); }
/// <summary> /// Fixes the SP field type lookup. /// </summary> /// <param name="fileSpListItem">The file sp list item.</param> /// <param name="sourceValue">The source value.</param> /// <returns>Fixes the SPField type Lookup.</returns> private string FixSPFieldTypeLookup(SPListItem fileSpListItem, string sourceValue) { string s = "\t\tLookup(" + sourceValue + ")\tIsThisLookup? " + this.SPFieldTypeIsLookup + "\n"; s += "\t\twas:" + fileSpListItem[this.ContextSPField.Id] + "\n"; // process lookup columns (including multi-valued ones) List <string> lookupValueList = new List <string>(); if (this.SPFieldTypeIsLookup) { s += "\t\tIsThisLookupupMulti? " + this.SPFieldLookupIsMultiValue + "\n"; if (this.SPFieldLookupIsMultiValue) { foreach (SPFieldLookupValue spFieldLookupValue in (fileSpListItem[this.FileSPField.Id] as SPFieldLookupValueCollection)) { lookupValueList.Add(spFieldLookupValue.LookupValue); } } else { lookupValueList.Add(new SPFieldLookupValue(sourceValue).LookupValue); } } else { string[] strList = sourceValue.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string str in strList) { lookupValueList.Add(str); } s += "\t\tLookupElse ListCount:\t" + lookupValueList.Count + "\n"; } // construct an SPFieldLookup object in the image of our field SPFieldLookup spFieldLookup = this.ContextSPField as SPFieldLookup; s += "\t\tspfield as spfield lookup multi? " + spFieldLookup.AllowMultipleValues + "\n"; s += "\t\tlookupvaluelistcount:\t" + lookupValueList.Count + "\n"; if (spFieldLookup.AllowMultipleValues) { SPFieldLookupValueCollection spFieldLookupValues = new SPFieldLookupValueCollection(); foreach (string value in lookupValueList) { // obtain the lookup value and its corresponding ID SPFieldLookupValue lookupValue = this.GetLookupValue(fileSpListItem.Web.Site.ID, spFieldLookup, value); // lookup value found in the lookup list if (lookupValue != null) { spFieldLookupValues.Add(lookupValue); } } fileSpListItem[this.ContextSPField.Id] = spFieldLookupValues; s += "\t\tis_:" + spFieldLookupValues + "\n"; } else if (lookupValueList.Count > 0) { // empty column values are "copied" as well if (String.IsNullOrEmpty(lookupValueList[0])) { fileSpListItem[this.ContextSPField.Id] = String.Empty; // continue; } // obtain the lookup value and its corresponding ID SPFieldLookupValue spFieldLookupValue = this.GetLookupValue(fileSpListItem.Web.Site.ID, spFieldLookup, lookupValueList[0]); // lookup value found in the lookup list if (spFieldLookupValue != null) { fileSpListItem[this.ContextSPField.Id] = spFieldLookupValue.ToString(); } s += "\t\tis_:" + fileSpListItem[this.ContextSPField.Id] + "\n"; } return(s); }
public override bool Perform() { try { using (var spSite = new SPSite(Web.Site.ID)) { using (SPWeb spWeb = spSite.OpenWeb()) { LogTitle(GetWebInfo(spWeb), 1); SPList spList = spWeb.Lists.TryGetList("Installed Applications"); if (spList != null) { var qry = new SPQuery { Query = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>My Workplace</Value></Eq></Where>", ViewFields = @"<FieldRef Name='ID' />" }; SPListItemCollection listItems = spList.GetItems(qry); if (listItems.Count != 0) { try { LogTitle("Changing My Workplace to Global My Workplace", 2); SPListItem item = spList.GetItemById(listItems[0].ID); item["Title"] = "Global My Workplace"; item["HomePage"] = new SPFieldUrlValue { Url = spWeb.Url + "/SitePages/GlobalMyWorkplace.aspx", Description = "Global My Workplace" }; item.SystemUpdate(); LogTitle("Updating links", 2); string[] nodes = ((item["QuickLaunch"] ?? string.Empty).ToString()).Split(','); if (nodes.Any()) { foreach (string nodeId in nodes) { try { string message; MessageKind messageKind; int id = Convert.ToInt32(nodeId.Split(':')[0]); SPNavigationNode node = spWeb.Navigation.GetNodeById(id); if (node == null) { continue; } if (node.Title.Equals("My Work")) { string url = spWeb.ServerRelativeUrl + "/_layouts/15/epmlive/MyWork.aspx"; if (url.ToLower().Equals(node.Url.ToLower())) { continue; } UpgradeUtilities.UpdateNodeLink(url, item.ID, node, spWeb, out message, out messageKind); LogMessage(message, messageKind, 3); } else if (node.Title.Equals("Timesheet")) { string url = spWeb.ServerRelativeUrl + "/_layouts/15/epmlive/MyTimesheet.aspx"; if (url.ToLower().Equals(node.Url.ToLower())) { continue; } UpgradeUtilities.UpdateNodeLink(url, item.ID, node, spWeb, out message, out messageKind); LogMessage(message, messageKind, 3); } } catch (Exception e) { LogMessage(e.Message, MessageKind.FAILURE, 3); } } } else { LogMessage("No navigation nodes were found.", MessageKind.FAILURE, 3); } CacheStore.Current.RemoveSafely(spWeb.Url, new CacheStoreCategory(spWeb).Navigation); } catch (Exception e) { LogMessage(e.Message, MessageKind.FAILURE, 3); } } else { LogMessage("The My Workplace community was not found.", MessageKind.SKIPPED, 2); } } else { LogMessage("The list Installed Applications does not exists.", MessageKind.FAILURE, 2); } } } } catch (Exception e) { LogMessage(e.Message, MessageKind.FAILURE, 2); } return(true); }
public override bool Perform() { try { SPSecurity.RunWithElevatedPrivileges(() => { using (var spSite = new SPSite(Web.Site.ID)) { using (SPWeb spWeb = spSite.OpenWeb()) { LogTitle(GetWebInfo(spWeb), 1); SPList spList = spWeb.Lists.TryGetList(LIST_NAME); if (spList == null) { LogMessage("Downloading new " + LIST_NAME + " list", 2); var catalog = (SPDocumentLibrary)Web.Site.GetCatalog(SPListTemplateType.ListTemplateCatalog); const string TEMPLATE_NAME = LIST_NAME + " [5.5]"; using (var webClient = new WebClient()) { byte[] bytes = webClient.DownloadData(_storeUrl + "/Upgrade/" + LIST_NAME.ToLower() + ".stp"); SPFile file = catalog.RootFolder.Files.Add(LIST_NAME + "_55.stp", bytes, true); SPListItem li = file.GetListItem(); li["Title"] = TEMPLATE_NAME; li.SystemUpdate(); } LogMessage("Creating the " + LIST_NAME + " list", 2); SPListTemplateCollection listTemplates = spSite.GetCustomListTemplates(spWeb); SPListTemplate template = listTemplates[TEMPLATE_NAME]; spWeb.Lists.Add(LIST_NAME, string.Empty, template); SPList list = spWeb.Lists[LIST_NAME]; list.Title = LIST_NAME; list.Hidden = true; list.Update(); LogMessage("Adding reporting groups", 2); SPGroup owner = spWeb.SiteGroups["Administrators"]; SPUser user = spWeb.CurrentUser; AddGroup(spWeb, owner, user, "Report Viewers"); AddGroup(spWeb, owner, user, "Report Writers"); LogMessage("Processing reports", 2); string error; Reporting.ProcessIzendaReportsFromList(list, out error); if (!string.IsNullOrEmpty(error)) { LogMessage(error, MessageKind.FAILURE, 3); } else { LogMessage(null, MessageKind.SUCCESS, 3); } LogMessage("Updating Navigation link", 2); string relativeUrl = spWeb.ServerRelativeUrl.ToLower(); string newUrl = relativeUrl + "/_layouts/15/epmlive/reporting/landing.aspx"; SPList lst = spWeb.Lists.TryGetList("Installed Applications"); if (lst != null) { var qry = new SPQuery { Query = @"<Where><IsNotNull><FieldRef Name='QuickLaunch' /></IsNotNull></Where>", ViewFields = @"<FieldRef Name='QuickLaunch' />" }; SPListItemCollection listItems = lst.GetItems(qry); foreach (SPListItem item in listItems) { foreach (SPNavigationNode navNode in from node in item["QuickLaunch"].ToString().Split(',') select Convert.ToInt32(node.Split(':')[0]) into i select spWeb.Navigation.GetNodeById(i) into navNode where navNode != null let url = navNode.Url.ToLower() where url.EndsWith(relativeUrl + "/reports.aspx") || url.EndsWith(relativeUrl + "/sitepages/report.aspx") select navNode) { string message; MessageKind messageKind; UpgradeUtilities.UpdateNodeLink(newUrl, item.ID, navNode, spWeb, out message, out messageKind); LogMessage(message, messageKind, 3); } } } else { LogMessage("The list Installed Applications does not exists.", MessageKind.FAILURE, 3); } CacheStore.Current.RemoveSafely(spWeb.Url, new CacheStoreCategory(spWeb).Navigation); } else { LogMessage("Advance reporting is already configured.", MessageKind.SKIPPED, 2); } } } }); } catch (Exception e) { LogMessage(e.Message, MessageKind.FAILURE, 2); } return(true); }
public static string GetWikiPageContent(this SPListItem pageItem) { return(pageItem[SPBuiltInFieldId.WikiField] as string); }
protected override void RenderWebPart(HtmlTextWriter output) { EPMLiveCore.Act act = new EPMLiveCore.Act(SPContext.Current.Web); int activation = act.CheckFeatureLicense(EPMLiveCore.ActFeature.WebParts); if (activation != 0) { output.Write(act.translateStatus(activation)); return; } SPWeb cWeb = SPContext.Current.Web; SPSite cSite = SPContext.Current.Site; var sPubComTxt = string.Empty; try { sPubComTxt = CoreFunctions.getConfigSetting(cWeb, "EPMLivePublicCommentText"); sPubComTxt = HttpUtility.JavaScriptStringEncode(sPubComTxt); } catch { } if (string.IsNullOrEmpty(sPubComTxt)) { sPubComTxt = "What are you working on?"; } SPUser user = cWeb.CurrentUser; //get user picture from user id SPList userInfoList = cWeb.SiteUserInfoList; SPListItem userItem = userInfoList.GetItemById(user.ID); string userPictureUrl = cSite.MakeFullUrl(cWeb.ServerRelativeUrl) + "/_layouts/epmlive/images/O14_person_placeHolder_32.png"; SPField fldPicture = null; try { fldPicture = userItem.Fields.GetFieldByInternalName("Picture"); } catch (ArgumentException x) { fldPicture = null; } if (fldPicture != null) { try { string[] picUrls = userItem[userItem.Fields.GetFieldByInternalName("Picture").Id].ToString().Split(','); userPictureUrl = picUrls[0]; } catch { userPictureUrl = cSite.MakeFullUrl(cSite.ServerRelativeUrl) + "/_layouts/epmlive/images/O14_person_placeHolder_32.png"; } } string userProfileUrl = cSite.MakeFullUrl(cWeb.ServerRelativeUrl) + "/_layouts/userdisp.aspx?Force=True&ID=" + user.ID + "&source=" + HttpContext.Current.Request.UrlReferrer; var defaultHeight = 500; output.Write("<script>" + "curWebUrl = '" + cWeb.Url + "';" + "curWebTitle = '" + HttpUtility.JavaScriptStringEncode(cWeb.Title) + "';" + "userProfileUrl = '" + userProfileUrl + "';" + "userEmail = '" + user.Email + "';" + "userPicUrl = '" + userPictureUrl + "';" + "userName = '******';" + "numThreads = '" + this.NumThreads.ToString() + "';" + "maxComments = '" + this.MaxComments.ToString() + "';" + "sPubComTxt = '" + sPubComTxt + "';" + "defaultHeight = '" + (int.TryParse(this.DefaultHeight, out defaultHeight) ? defaultHeight : 500) + "px';" + "</script>"); output.Write("<link rel=\"STYLESHEET\" type=\"text/css\" href=\"" + (cWeb.ServerRelativeUrl == "/" ? "" : cWeb.ServerRelativeUrl) + "/_layouts/epmlive/Comments.UI.css\"/>"); output.Write("<link rel=\"STYLESHEET\" type=\"text/css\" href=\"" + (cWeb.ServerRelativeUrl == "/" ? "" : cWeb.ServerRelativeUrl) + "/_layouts/epmlive/CommentsWebPartStyle.css\"/>"); output.Write(@"<div id='wrapper' class='divPublicCommentContainer'> <table> <tbody> <tr> <td valign='middle' align='left' id='commentTblc1'> <div id='comment-photo'> <img src='" + userPictureUrl + @"' class='circleborder' /> </div> </td> <td valign='middle' align='left' style='padding-left:8px;padding-right:5px;' id='commentTblc2'> <div id='whatsup'> <div class='comment-box'> <div id='inputPublicComment' class='comment-paragraph' contenteditable='true'> </div> </div> </div> </td> <td valign='middle' align='left' id='commentTblc3'> <div class='general-button-wrapper'><a id='btnGeneralPost' href='#' class='btn-primary btn btn-small' style='text-decoration:none;'>Share</a></div> </td> </tr> </tbody> </table> </div>"); output.Write("<div style=\"clear:both;\"></div>"); output.Write("<div id=\"commentsWebPartMainContainer\" class=\"commentsWPMainContainer\">"); output.Write("<div style=\"clear:both;\"></div>"); output.Write(_loadingHtml); output.Write("<div style=\"clear:both;height:5px\"></div>"); output.Write(_noCommentHtml); output.Write("</div>"); }
/// <summary> /// Archives the project. /// </summary> /// <param name="listItem">The list item.</param> public void ArchiveProject(SPListItem listItem) { UpdateProjectStatus(listItem, true); }
/// <summary> /// Restores the project. /// </summary> /// <param name="listItem">The list item.</param> public void RestoreProject(SPListItem listItem) { UpdateProjectStatus(listItem, false); }
public void Translate(ImagesModel model, SPListItem item) { throw new NotImplementedException(); }
/// <summary> /// Updates the project status. /// </summary> /// <param name="projectListItem">The project list item.</param> /// <param name="status">if set to <c>true</c> project will be archived, otherwise restored.</param> private void UpdateProjectStatus(SPListItem projectListItem, bool status) { if (projectListItem == null) { throw new ArgumentNullException(); } var web = projectListItem.Web; web.AllowUnsafeUpdates = true; try { var action = status ? ArchiveProjectAction : RestoreProjectAction; LogMessage(web, $"Updating project '{projectListItem.ID}' - Action: '{action}'", LogKind.Info); projectListItem[ArchivedColumn] = status; if (projectListItem.Fields.ContainsFieldWithInternalName(TimesheetColumn)) { projectListItem[TimesheetColumn] = !status; } projectListItem.Update(); // when associated lists configured - move to archive all of them SPSecurity.RunWithElevatedPrivileges( () => { using (var elevatedSite = new SPSite(web.Site.ID)) { using (var elevatedWeb = elevatedSite.OpenWeb(web.ID)) { elevatedWeb.AllowUnsafeUpdates = true; if (ConnectionProvider.AllowDatabaseConnections(elevatedWeb)) { var pfeProjectRepository = new ProjectRepository(); pfeProjectRepository.UpdateArchivedStatus(web, projectListItem.ParentList.ID, projectListItem.ID, status); } try { var elevatedProjectList = elevatedWeb.Lists.GetList( projectListItem.ParentList.ID, false); var settings = ListCommands.GetGridGanttSettings(elevatedProjectList); if (settings.AssociatedItems) { var associated = ListCommands.GetAssociatedLists(elevatedProjectList) .Cast <AssociatedListInfo>().ToArray(); UpdateAssociatedLists(elevatedWeb, projectListItem.ID, status, associated); } } finally { elevatedWeb.AllowUnsafeUpdates = false; } } } }); } catch (Exception ex) { LogError(web, ex); throw; } finally { web.AllowUnsafeUpdates = false; } }
SPListItem AddReplyToItem(SPListItem relatedItem) { return(m_TextStartegy.CreateReply(relatedItem, m_message)); }
public void Process() { m_user = m_list.ParentWeb.SiteUsers.GetByEmail(m_message.Sender); if (m_user != null) { using (var site = new SPSite(m_list.ParentWeb.Site.ID, m_user.UserToken)) { using (var web = site.OpenWeb(m_list.ParentWeb.ID)) { m_list = web.Lists.GetList(m_list.ID, false, true); SPListItem relatedItem = GetRelatedListItem(); SPListItem newItem = null; if (relatedItem != null) { m_Logger.WriteTrace("Related item was found", SeverityEnum.Trace); if (relatedItem.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Discussion) || relatedItem.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Message)) { newItem = AddReplyToItem(relatedItem); } else { m_Logger.WriteTrace("Related item has some wrong content type " + relatedItem.ContentTypeId, SeverityEnum.CriticalError); } } else { m_Logger.WriteTrace("Related item was not found", SeverityEnum.Trace); if (m_itemIdPresented) { m_Logger.WriteTrace("Item id was present", SeverityEnum.Trace); } else { m_Logger.WriteTrace("Item id was not present", SeverityEnum.Trace); newItem = AddNewDiscussion(); } } if (newItem != null) { if (SaveOriginalMessage) { AddEmail(newItem); } if (SaveAttachments) { AddAttachments(newItem); } newItem.Update(); m_Logger.WriteTrace("Item SUCCESSFULY added", SeverityEnum.Trace); } else { m_Logger.WriteTrace("No new item", SeverityEnum.Warning); } } } } else { m_Logger.WriteTrace("No user with email=" + m_message.Sender, SeverityEnum.Warning); } }
static void Main(string[] args) { bool listOnly = false; Console.ForegroundColor = ConsoleColor.White; if (args.Length == 2 && args[1].ToLower() == "/list") { listOnly = true; } if (args.Length != 2) { Console.WriteLine("Deletes a web part from the web part gallary."); Console.ResetColor(); Console.WriteLine( string.Format( "Usage: {0} {1} {2}", System.AppDomain.CurrentDomain.FriendlyName, "http://localhost:51001", "name.webpart" ) ); Console.WriteLine( string.Format( "Usage: {0} {1} {2}", System.AppDomain.CurrentDomain.FriendlyName, "http://localhost:51001", "webpartID" ) ); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\nTo show all installed web parts."); Console.ResetColor(); Console.WriteLine(string.Format("{0} {1} {2}", System.AppDomain.CurrentDomain.FriendlyName, "http://localhost:51001", "/list")); return; } string siteUrl = args[0]; string webpartName = listOnly ? string.Empty : args[1].ToLower(); int webpartID = 0; int.TryParse(webpartName, out webpartID); using (SPSite parentSite = new SPSite(siteUrl)) { List <int> toDelete = new List <int>(); SPList list = parentSite.GetCatalog(SPListTemplateType.WebPartCatalog); Console.WriteLine("Searching..."); Console.ResetColor(); foreach (SPListItem item in list.Items) { if (listOnly) { Console.WriteLine("Found: " + item.ID + ", " + item.Name); continue; } if (webpartID > 0) { if (item.ID == webpartID) { Console.WriteLine("Found: " + item.Name + " with ID " + item.ID); toDelete.Add(item.ID); } } else { if (item["Web Part"].ToString().ToLower() == webpartName) { Console.WriteLine("Found: " + webpartName + " with ID " + item.ID); toDelete.Add(item.ID); } } } if (listOnly) { return; } if (toDelete.Count() == 0) { Console.WriteLine("Found nothing matching."); } foreach (int i in toDelete) { SPListItem item = list.GetItemById(i); item.Delete(); Console.WriteLine("Deleted ID: " + i); } Console.WriteLine("Updating list..."); list.Update(); Console.WriteLine("Done."); } }
private void ExecuteMain(SPItemEventProperties properties) { this.EventFiringEnabled = false; SPListItem item = properties.ListItem; bool isSent = false; if (item["colWyslany"] != null) { Boolean.TryParse(item["colWyslany"].ToString(), out isSent); } if (!isSent) { if (item.ContentType.Name == "Ogłoszenie") { SPFieldLookupValueCollection searchCriteriaCollection = (SPFieldLookupValueCollection)item["colGrupyOdbiorcow"]; GetTargetList(searchCriteriaCollection, properties); if (MatchedCustomers.Count > 0) { StringBuilder sb = new StringBuilder(); //nagłówek sb.AppendLine(String.Format(@"<div>{0}</div>", DateTime.Now.ToString())); sb.AppendLine(String.Format(@"<div>kryteria: ({0})</div>", searchCriteriaCollection.Count.ToString())); sb.AppendLine(String.Format(@"<ul>")); foreach (SPFieldLookupValue cItem in searchCriteriaCollection) { sb.AppendLine(String.Format(@"<li>{0}</li>", cItem.LookupValue.ToString())); } sb.AppendLine(String.Format(@"</ul>")); sb.AppendLine(String.Format(@"<div>odbiorcy ({0})</div>", MatchedCustomers.Count.ToString())); sb.AppendLine(String.Format(@"<ul>")); foreach (Customer cust in MatchedCustomers) { if ((bool)item["colGotoweDoWysylki"]) { //SendEmailWithAttachements(cust, properties); CreateMailRequest(cust, properties); } //treść sb.AppendLine(String.Format(@"<li>{0} {1}</li>", cust.Name.ToString(), cust.Email.ToString())); } sb.AppendLine(String.Format(@"</ul>")); item["colTarget"] = sb.ToString(); if ((bool)item["colGotoweDoWysylki"]) { item["colWyslany"] = true; } item.Update(); } else { item["colTarget"] = String.Format(@"Żaden klient nie spełnia zadanych kryteriów ({0})" , searchCriteriaCollection.ToString()); item.Update(); } } } this.EventFiringEnabled = true; }
public override void Execute(Guid targetInstanceId) { ////SPWebApplication webApp = this.Parent as SPWebApplication; ////string var1 = webApp.Sites[0].RootWeb.Url.ToString(); ////string var2 = webApp.Sites[0].Url.ToString(); SPSecurity.RunWithElevatedPrivileges(delegate() { SPWebApplication webApp = this.Parent as SPWebApplication; SPList logList = webApp.Sites[0].RootWeb.Lists["TimerLogList"]; SPListItem logListItems = logList.Items.Add(); logListItems["Title"] = var1 + "......." + var2; logListItems.Update(); }); GetSiteNames1(); LogAction_SQLDataInsert("Before starting foreach of SQL function"); CopySQLTableData(); LogAction_SQLDataInsert("After starting foreach of SQL function"); /* * TimerLogList_SQLDataInsert */ #region commented region // SPSecurity.RunWithElevatedPrivileges(delegate() // { // using (SPSite site = new SPSite("http://win-njfp7te48bn/sites/HVEDev")) // { // using (SPWeb web = site.OpenWeb()) // { // SPList list = web.Lists["TopViewedDocs"]; // SPQuery myQuery = new SPQuery(); // myQuery.ViewXml = @"<View> // <Query> // <OrderBy> // <FieldRef Name='DocViewCount' Ascending='False' /> // </OrderBy> // <FieldRef Name='DocName' /> // <FieldRef Name='DocViewCount' /> // </Query> // </View>"; // SPListItemCollection myItems = list.GetItems(myQuery); // foreach (SPListItem item in myItems) // { // //DocViewCounts(item["SiteName"].ToString(), item["DocLibName"].ToString()); // //htmlStr.Append(li["DocName"].ToString() + "--" + li["DocViewCount"].ToString() + "<br>"); // } // //Literal1.Text = htmlStr1.ToString(); // } // } // }); //TopViewedDocs ////SPWebApplication webapp = this.Parent as SPWebApplication; ////SPList tasklist = webapp.Sites[0].RootWeb.Lists["Tasks1"]; // SPSite site1 = new SPSite("http://win-njfp7te48bn/sites/HVEDev"); // SPWeb web1 = site1.OpenWeb(); // SPList tasklist = web1.Lists["Tasks1"]; // SPListItem li = tasklist.Items.Add(); // li["Title"] = "New Task :- " + DateTime.Now.ToString(); // li.Update(); #endregion }
public void InstallAndConfigureApp(bool verifyonly, SPWeb web, int iCommunityId) { bVerifyOnly = verifyonly; oWeb = web; iCommunity = iCommunityId; appDef = Applications.GetApplicationInfo(_id); CheckInstalledRoot(); oAppList = oWeb.Lists.TryGetList("Installed Applications"); if (oAppList == null) { addMessage(ErrorLevels.Error, "Application List", "You do not have the application list installed", 0); } else { var query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='EXTID' /><Value Type='Number'>" + appDef.Id + "</Value></Eq></Where>"; var lic = oAppList.GetItems(query); if (lic.Count > 0) { oListItem = lic[0]; } else { addMessage(ErrorLevels.Error, "Open Application Item", "Could not find item in list", 0); return; } if (appDef.loadErrorMessage == string.Empty) { if (CheckPermissions()) { if (CheckForApplicationList()) { if (CheckForPreReqs()) { if (CheckForKeys()) { InstallAndConfigureApp(); if (!bVerifyOnly) { ReportToAppReporting(web); } } } } } } else { addMessage(ErrorLevels.Error, "Check Applications", appDef.loadErrorMessage, 0); } if (oListItem != null) { reportResults(); } } }
/// <summary> /// 签到按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void SigninBtn_Click(object sender, ImageClickEventArgs e) { Random rd = new Random(); int rdScore = rd.Next(1, 5);//生成1~5之间的一个随机数,作为签到获得随机积分 SPWeb web = SPContext.Current.Web; SPList list = web.Lists["SignIn"]; string url = SPContext.Current.Site.Url; string[] userName = GetUserInfo(web); DateTime LastTime; int LastDays = 0; int AllDays = 0; int AllScore = 0; SPSecurity.RunWithElevatedPrivileges(delegate() { SPListItem listItem = GetListData(web, list, userName[0]); if (listItem != null)//已有签到记录 { AllScore = int.Parse(listItem["AllScore"].ToString()); LastTime = DateTime.Parse(listItem["LastTime"].ToString()); LastDays = int.Parse(listItem["LastDays"].ToString()); if (LastTime.Date.Equals(DateTime.Now.Date))//当日已签到 { return; } else if (LastTime.Date.Equals(DateTime.Now.AddDays(-1))) //昨日有签到 { listItem["LastDays"] = LastDays + 1; //连续签到天数+1 } else//昨日无签到,漏签,持续签到从第1天重新开始 { listItem["LastDays"] = 1; } listItem["LastScore"] = rdScore.ToString();//本次签到随机积分 AllDays = int.Parse(listItem["AllDays"].ToString()); listItem["AllDays"] = AllDays + 1; //总计签到天数 listItem["Degree"] = GetDegreeByDays(AllDays + 1); //签到等级 listItem["AllScore"] = (AllScore + rdScore).ToString(); //签到总积分 listItem["LastTime"] = DateTime.Now; //上次签到时间 listItem["LastOrder"] = GetRank(web, list, userName[0], 0, DateTime.Now); listItem["LastIP"] = GetIP(); //本次签到IP地址 listItem.Update(); } else//未有任何签到记录,即本次为第一次签到 { web.AllowUnsafeUpdates = true; listItem = list.Items.Add(); //list.AddItem(); listItem["Title"] = userName[0]; //签到账号 listItem["DisplayName"] = userName[1]; //签到姓名 listItem["Degree"] = "★"; //签到等级1 listItem["LastScore"] = rdScore.ToString(); //本次签到随机积分 listItem["AllScore"] = rdScore.ToString(); //签到总积分 listItem["LastTime"] = DateTime.Now; //上次签到时间 listItem["LastOrder"] = GetRank(web, list, userName[0], 0, DateTime.Now); listItem["LastDays"] = "1"; //连续签到天数 listItem["AllDays"] = "1"; //总计签到天数 listItem["LastIP"] = GetIP(); //本次签到IP地址 listItem.Update(); } } ); }
public XElement GetElement(SPListItem listItem) { if (listItem != null && (listItem.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Message) || listItem.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Discussion))) { var element = new XElement(L("DiscussionBoard")); List <SPListItem> chain = new List <SPListItem>(); if (listItem.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Message)) { chain.AddRange(GetDescedantsForMessage(listItem)); } else { chain.Add(listItem); } XElement parent = null; XElement curent = null; foreach (SPListItem item in chain)//first item in chain should be Discussion, last current message { if (item.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Discussion)) { curent = new XElement(L("Discussion")); element.Add(curent); var subjElement = new XElement(L("Subject")); var bodyElement = new XElement(L("Body")); var subjText = new XElement(L("Value")) { Value = item.GetFieldValue <string>(SPBuiltInFieldId.Title, string.Empty) }; var clearSubjText = new XElement(L("ClearValue")) { Value = GetClearDiscussionSubjText(subjText.Value) }; var bodyText = new XElement(L("Value")) { Value = item.GetFieldValue <string>(SPBuiltInFieldId.Body, string.Empty) }; var clearBodyText = new XElement(L("ClearValue")) { Value = GetClearDiscussionBodyText(bodyText.Value) }; subjElement.Add(subjText, clearSubjText); bodyElement.Add(bodyText, clearBodyText); curent.Add(subjElement, bodyElement); } else { curent = new XElement(L("Message")); var bodyElement = new XElement(L("Body")); var bodyText = new XElement(L("Value")) { Value = item.GetFieldValue <string>(SPBuiltInFieldId.Body, string.Empty) }; var clearBodyText = new XElement(L("ClearValue")) { Value = GetClearMessageBodyText(bodyText.Value) }; bodyElement.Add(bodyText, clearBodyText); curent.Add(bodyElement); } if (item.UniqueId == listItem.UniqueId) { curent.SetAttributeValue("Current", true); } if (item.Fields.Contains(SPBuiltInFieldId.Created)) { curent.SetAttributeValue("Created", item.GetFieldValue <DateTime>(SPBuiltInFieldId.Created).ToUniversalTime()); } if (item.ParentList != null && item.ParentList.ParentWeb != null) { var createdBy = new SPFieldUserValue(item.ParentList.ParentWeb, item[SPBuiltInFieldId.Author].ToString()); curent.SetAttributeValue("User", createdBy.User.LoginName); curent.SetAttributeValue("UserName", createdBy.User.Name); curent.SetAttributeValue("UserProfileUrl", "/_layouts/userdisp.aspx?ID=" + createdBy.User.ID); curent.SetAttributeValue("UserProfileUrl", "a"); } if (parent != null) { parent.Add(curent); } parent = curent; } return(element); } return(null); }
/// <summary> /// Creates a metadata mapping for an individual property on a SPListItem /// </summary> /// <param name="metadata">The metadata collection to assemble</param> /// <param name="key">The key to use to send up to Guidewire</param> /// <param name="propertyName">The name of the property in SharePoint</param> /// <param name="item">The SPListItem to retrieve the property from</param> private static void CreateMetadataPair(List <GuidewireWS.trg_MetadataPair> metadata, string key, string propertyName, SPListItem item) { try { // Set up a new metadata pair GuidewireWS.trg_MetadataPair metadataPair = new GuidewireWS.trg_MetadataPair(); SPListItem listItem = item; // Make sure the list item contains the field in question if (listItem.Fields.ContainsField(propertyName)) { metadataPair.key = key; SPField propertyField = listItem.Fields[propertyName]; // Each field type in SharePoint requires slightly different handling to retrieve strings or inner properties switch (propertyField.Type) { case SPFieldType.User: { SPFieldUser userField = propertyField as SPFieldUser; SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(listItem[propertyName].ToString()); if (userFieldValue != null && userFieldValue.User != null) { metadataPair.value = userFieldValue.User.Name; } else { metadataPair.value = (string)listItem[propertyName]; } } break; case SPFieldType.Lookup: { SPFieldLookup lookupField = propertyField as SPFieldLookup; SPFieldLookupValue lookupFieldValue = (SPFieldLookupValue)lookupField.GetFieldValue(listItem[propertyName].ToString()); if (lookupFieldValue != null && lookupFieldValue.LookupValue != null) { metadataPair.value = lookupFieldValue.LookupValue; } } break; // Bamboo selectors have type of invalid but work like lookup case SPFieldType.Invalid: { if (listItem[propertyName] != null) { if (propertyField.TypeAsString == "BusinessData") { metadataPair.value = (string)listItem[propertyName]; } else { SPFieldLookup lookupField = propertyField as SPFieldLookup; SPFieldLookupValue lookupFieldValue = (SPFieldLookupValue)lookupField.GetFieldValue(listItem[propertyName].ToString()); if (lookupFieldValue != null && lookupFieldValue.LookupValue != null) { metadataPair.value = lookupFieldValue.LookupValue; } } } } break; case SPFieldType.DateTime: { metadataPair.value = listItem[propertyName].ToString(); } break; default: if (listItem[propertyName] != null) { if (propertyName == "Name") { String fileName = (string)listItem[propertyName]; if (fileName.Length > 80) { String extension = fileName.Substring(fileName.LastIndexOf(".")); String name = fileName.Substring(0, fileName.Length - extension.Length); fileName = name.Substring(0, 80 - extension.Length) + extension; } metadataPair.value = fileName; } else { metadataPair.value = (string)listItem[propertyName]; } } break; } metadata.Add(metadataPair); } } catch (Exception e) { LogError("CreateMetadataPair failed with exception: " + e.Message); } }
private void RenderAdminArea(SPListItem item) { StartingBid.Text = string.Format("{0:c}", item["StartingBid"]); MinimumBidIncrement.Text = string.Format("{0:c}", item["MinimumBidIncrement"]); }