public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); SPWeb web = properties.OpenWeb(); string _listName = "Resource_Allocation"; if (properties.ListTitle == "Resource_Allocation") { try { if (SPUtility.IsEmailServerSet(web)) { string body = GetParameter("UserContent", properties); StringDictionary headers = new StringDictionary(); headers.Add("To", GetSPUserEmailID(_listName, properties, "Owner")); headers.Add("Subject", GetParameter("UserSubject", properties)); headers.Add("Content-Type", "text/html; charset=\"UTF-8\""); SPUtility.SendEmail(web, headers, body); } } catch (Exception ex) { throw ex; } } }
private SPItemEventProperties CreateMockSpItemEventProperties(string title, string code, DateTime enrollmentDate, DateTime startDate, DateTime endDate, float courseCost) { //Create any mock objects we'll need here SPItemEventProperties spItemEventProperties = RecorderManager.CreateMockedObject <SPItemEventProperties>(); SPWeb web = RecorderManager.CreateMockedObject <SPWeb>(); SPItemEventDataCollection afterProperties = RecorderManager.CreateMockedObject <SPItemEventDataCollection>(); //record our main expectations using (RecordExpectations recorder = RecorderManager.StartRecording()) { object obj = spItemEventProperties.AfterProperties; recorder.Return(afterProperties).RepeatAlways(); afterProperties["Title"] = string.Empty; afterProperties["TrainingCourseCode"] = string.Empty; spItemEventProperties.OpenWeb(); recorder.Return(web); obj = spItemEventProperties.ListItem[new Guid(Fields.TrainingCourseCode)]; recorder.Return("12345678").RepeatAlways(); } //Record our expectations for our AfterProperties collection MockHelper.RecordSPItemEventDataCollection(afterProperties, "Title", title); MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseCode", code); MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseEnrollmentDate", enrollmentDate); MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseStartDate", startDate); MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseEndDate", endDate); MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseCost", courseCost); return(spItemEventProperties); }
/// <summary> /// Public Methods /// </summary> /// <param name="listName"></param> /// <param name="properties"></param> /// <param name="fieldName"></param> /// <returns></returns> public string GetSPUserEmailID(string listName, SPItemEventProperties properties, string fieldName) { SPFieldUser userField = (SPFieldUser)properties.OpenWeb().Lists[listName].Fields.GetField(fieldName); SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(properties.ListItem[fieldName] + ""); SPUser user = fieldValue.User; return user.Email; }
/// <summary> /// An item is being deleted /// </summary> public override void ItemDeleting(SPItemEventProperties properties) { base.ItemDeleting(properties); SPListItem currentItem = properties.ListItem; SPList currentList = properties.List; using (SPWeb web = properties.OpenWeb()) { if (currentList.Title == Constants.WebRegistry.ListTitle) { SPWeb chWeb = FindSubSite(web, currentItem[Constants.WebRegistry.SiteRelativeUrl].ToString()); if (chWeb == null) { properties.Status = SPEventReceiverStatus.Continue; Logger.WriteLog(Logger.Category.Medium, "Devyatkin.TracingCreationSites", "Deleted item with not existin site url in WebRegistry"); } else { properties.Status = SPEventReceiverStatus.CancelWithError; properties.ErrorMessage = "You can't delete record of subsite with existing URL"; Logger.WriteLog(Logger.Category.Information, "Devyatkin.TracingCreationSites", "Detected deleted item, stoped in WebRegistry"); } } else { Logger.WriteLog(Logger.Category.Information, "Devyatkin.TracingCreationSites", "Wrong list"); } } }
/// <summary> /// An item was added /// </summary> public override void ItemAdding(SPItemEventProperties properties) { base.ItemAdded(properties); //SPListItem currentItem = properties.AfterProperties; SPList currentList = properties.List; using (SPWeb web = properties.OpenWeb()) { if (currentList.Title == Constants.WebRegistry.ListTitle) { SPWeb chWeb = FindSubSite(web, properties.AfterProperties[Constants.WebRegistry.SiteRelativeUrl].ToString()); if (chWeb == null) { properties.Status = SPEventReceiverStatus.CancelWithError; properties.ErrorMessage = "You can't create record with non existing subsite URL"; Logger.WriteLog(Logger.Category.Information, "Devyatkin.TracingCreationSites", "Blocked by adding with nonexistent address in WebRegistry"); } else { Logger.WriteLog(Logger.Category.Information, "Devyatkin.TracingCreationSites", "Added new record in WebRegistry"); } } } }
private void Notify(SPItemEventProperties properties) { SPWeb web = properties.OpenWeb(); item = properties.ListItem; notified = new List <SPUser>(); List <string> actions = new List <string>(); List <string> groups = new List <string>(); ReadConfig(web, actions, groups); if ((properties.EventType == SPEventReceiverType.ItemAdded && actions.Contains("insert")) || (properties.EventType == SPEventReceiverType.ItemUpdated && actions.Contains("update"))) { string Event = string.Empty; if (properties.EventType == SPEventReceiverType.ItemAdded) { Event = "hinzugefügt"; } else if (properties.EventType == SPEventReceiverType.ItemUpdated) { Event = "geändert"; } ExpandGroups(web, groups.ToArray(), Event); } }
public override void ItemUpdated(SPItemEventProperties properties) { base.ItemUpdated(properties); SPWeb web = properties.OpenWeb(); if (properties.ListTitle == "Resource_Allocation") { try { if (SPUtility.IsEmailServerSet(web)) { string body = GetParameter("SystemsContent", properties); StringDictionary headers = new StringDictionary(); headers.Add("To", GetParameter("SystemsEmail", properties)); headers.Add("Subject", GetParameter("SystemsSubject", properties)); headers.Add("Content-Type", "text/html; charset=\"UTF-8\""); SPUtility.SendEmail(web, headers, body); } } catch (Exception ex) { throw ex; } } }
/// <summary> /// An item is being updated. /// </summary> public override void ItemUpdating(SPItemEventProperties properties) { base.ItemUpdating(properties); if (properties.ListTitle == SOURCE_LIST) { try { SPListItem theItem = properties.ListItem; if (theItem.Title != properties.AfterProperties["Title"].ToString()) { SPWeb theSite = properties.OpenWeb(); SPList theList = theSite.Lists[CALENDAR_LIST]; SPViewCollection theViews = theList.Views; try { this.DeleteTheView(theViews, theItem.Title); } catch { } this.CreateTheView(theViews, properties.AfterProperties["Title"].ToString()); } } catch (Exception ex) { properties.ErrorMessage = ex.Message; properties.Status = SPEventReceiverStatus.CancelWithError; } } }
////// <summary> ////// The list received a context event. ////// </summary> //public override void ContextEvent(SPItemEventProperties properties) //{ // base.ContextEvent(properties); //} /// <summary> /// Executes the Barista Script in response to an item event. /// </summary> /// <param name="properties">The properties.</param> private static void ExecuteBaristaScript(SPItemEventProperties properties) { BrewRequest request; using (var web = properties.OpenWeb()) { var list = web.Lists[properties.ListId]; var item = list.GetItemById(properties.ListItemId); var headers = new Dictionary <string, IEnumerable <string> > { { "Content-Type", new[] { "application/json" } } }; request = new BrewRequest { Headers = new BrewRequestHeaders(headers), Code = properties.ReceiverData, ScriptEngineFactory = "Barista.SharePoint.SPBaristaJurassicScriptEngineFactory, Barista.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2d8064cb9226f52" }; request.SetExtendedPropertiesFromSPItemEventProperties(web, list, item, properties); } var serviceContext = SPServiceContext.Current ?? SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, new SPSiteSubscriptionIdentifier(Guid.Empty)); var client = new BaristaServiceClient(serviceContext); client.Exec(request); //TODO: Allow for Syncronous events that expect to return an object with which to update the properties object with. }
/// <summary> /// Public Methods /// </summary> /// <param name="listName"></param> /// <param name="properties"></param> /// <param name="fieldName"></param> /// <returns></returns> public string GetSPUserEmailID(string listName, SPItemEventProperties properties, string fieldName) { SPFieldUser userField = (SPFieldUser)properties.OpenWeb().Lists[listName].Fields.GetField(fieldName); SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(properties.ListItem[fieldName] + ""); SPUser user = fieldValue.User; return(user.Email); }
public override void ItemAdded(SPItemEventProperties properties) { try { if (properties.ListTitle == "Terms") { Guid siteID, webID, listID; int itemID; listID = properties.ListId; itemID = properties.ListItem.ID; using (SPWeb web = properties.OpenWeb()) { siteID = web.Site.ID; webID = web.ID; } //run this block as System Account SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(siteID)) { using (SPWeb web = site.OpenWeb(webID)) { web.AllowUnsafeUpdates = true; SPListItem item = web.Lists[listID].GetItemById(itemID); if (item != null) { if (item["Author"].ToString() == "-1;#") { //Impersonate the Author to be System Account item["Author"] = web.AllUsers[@"SHAREPOINT\system"]; item.SystemUpdate(); } //start the by add the item and workflow name StartWorkflow(item, "TERMS_Approval", properties.SiteId); } web.AllowUnsafeUpdates = false; } } }); } else { return; } } catch(Exception ex) { Common.LogError("TermsEventHandlerEventReceiver.ItemAdded", ex, properties.SiteId); } }
/// <summary> /// An item was added. /// </summary> //<snippet1> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); SPWeb web = properties.OpenWeb(); properties.ListItem["Due Date"] = "July 1, 2009"; properties.ListItem["Description"] = "This is a critical task."; properties.ListItem.Update(); }
private void ExecuteReceivedEvent(AlertEventType eventType, SPItemEventProperties properties) { LogManager.write("Entered in to ExecuteReceivedEvent with event type" + eventType); try { using (SPWeb web = properties.OpenWeb()) { //TODO we have to check is feature activated for this site or not AlertManager alertManager = new AlertManager(web.Site.Url); MailTemplateManager mailTemplateManager = new MailTemplateManager(web.Site.Url); IList <Alert> alerts = alertManager.GetAlertForList(properties.ListItem, eventType, mailTemplateManager); Notifications notifications = new Notifications(); foreach (Alert alert in alerts) { if (eventType != AlertEventType.DateColumn) { if (alert.IsValid(properties.ListItem, eventType, properties)) { try { if (alert.SendType == SendType.ImmediateAlways) { notifications.SendMail(alert, eventType, properties.ListItem, FinalBody); } else if (alert.SendType == SendType.ImmediateBusinessDays) { if (alert.ImmediateBusinessDays.Contains((WeekDays)DateTime.UtcNow.DayOfWeek)) { if (alert.BusinessStartHour <= Convert.ToInt32(DateTime.UtcNow.Hour) && alert.BusinessendtHour >= Convert.ToInt32(DateTime.UtcNow.Hour)) { notifications.SendMail(alert, eventType, properties.ListItem, FinalBody); } else { return; } } } else { CreateDelayedAlert(alert, eventType, properties, alertManager); } } catch { } } } } } } catch (System.Exception Ex) { LogManager.write("Error occured white excuting event receiver" + Ex.Message); } }
/// <summary> /// An item was updated. /// </summary> public override void ItemUpdated(SPItemEventProperties properties) { base.ItemUpdated(properties); using (SPWeb web = properties.OpenWeb()) { try { SPListItem currentItem = properties.ListItem; string EmailBody = currentItem["Anakoinoseis"].ToString(); var body1 = EmailBody.Split(new[] { ";" }, StringSplitOptions.None); var email = ""; currentItem["E_x002d_mail_x0020_Body"] = ""; for (int i = body1.Length; i > 1; i -= 2) { email = currentItem["E_x002d_mail_x0020_Body"].ToString(); var body = body1[i - 1].Split(new[] { "#" }, StringSplitOptions.None); currentItem["E_x002d_mail_x0020_Body"] = email + body[1] + "<br>"; } base.EventFiringEnabled = false; currentItem.Update(); base.EventFiringEnabled = true; } catch (Exception ex) { throw ex; } WriteLogFile(web, "Start sending emails"); SPList groups = web.GetList("/greek/test/Lists/Expand Groups"); SPListItemCollection items = groups.GetItems(); foreach (SPListItem item in items) { string name = item["User"].ToString(); name = name.Substring(3, name.Length - 3); string email = web.EnsureUser(name).Email; StringDictionary headers = new StringDictionary(); headers.Add("from", "*****@*****.**"); headers.Add("to", email); headers.Add("subject", properties.ListItem["E-mail Subject"].ToString()); headers.Add("fAppendHtmlTag", "True"); //To enable HTML format System.Text.StringBuilder strMessage = new System.Text.StringBuilder(); strMessage.Append(properties.ListItem["E-mail Body"].ToString()); SPUtility.SendEmail(web, headers, strMessage.ToString()); string message = "Email sent to " + name; WriteLogFile(web, message); } WriteLogFile(web, "End sending emails"); } }
/// <summary> /// 任务(操作和作品合成任务名称)和日程(人+操作+作品) /// </summary> /// <param name="properties"></param> public override void ItemAdding(SPItemEventProperties properties) { if (properties.List.Fields.ContainsField("操作") && properties.List.Fields.ContainsField("作品")) { SPItemEventDataCollection afterData = properties.AfterProperties; SPList myList = properties.OpenWeb().Lists[properties.ListId]; string nameFieldOper = myList.Fields.GetField("操作").InternalName; string nameFieldWorks = myList.Fields.GetField("作品").InternalName; string newValue = afterData[nameFieldOper].ToString() + afterData[nameFieldWorks]; properties.AfterProperties.ChangedProperties.Add("Title", newValue); } }
/// <summary> /// Posts to a specified url in response to an item event. /// </summary> /// <param name="properties">The properties.</param> private static void Post(SPItemEventProperties properties) { using (var web = properties.OpenWeb()) { var list = web.Lists[properties.ListId]; var postBodyObject = new PostData { Properties = properties, ListItem = BaristaRemoteItemEventReceiver.GetFieldValuesAsObject(list.GetItemById(properties.ListItemId)) }; var request = (HttpWebRequest)WebRequest.Create(properties.ReceiverData); request.Method = "POST"; request.ContentType = "application/json"; request.AllowAutoRedirect = true; request.UseDefaultCredentials = true; request.Proxy = WebRequest.GetSystemWebProxy(); var jsonProperties = JsonConvert.SerializeObject(postBodyObject, new JsonSerializerSettings { ContractResolver = new FilteredContractResolver("Web", "List", "Site", "ListItem") }); var data = Encoding.UTF8.GetBytes(jsonProperties); request.ContentLength = data.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } // now put the get response code in a new thread and immediately return ThreadPool.QueueUserWorkItem(x => { try { using (var objResponse = (HttpWebResponse)request.GetResponse()) { var responseStream = new MemoryStream(); objResponse.GetResponseStream().CopyTo(responseStream); responseStream.Seek(0, SeekOrigin.Begin); } } catch { //Do Nothing. } }); } }
private static void TranslateFields(SPItemEventProperties property) { using (SPWeb currentWeb = property.OpenWeb()) { currentWeb.AllowUnsafeUpdates = true; string listId = property.ListId.ToString(); string itemId = property.ListItem.ID.ToString(); const string Lang = "ALL"; string url = currentWeb.Url; try { SPList currentList = property.ListItem.ParentList; SPListItem currentItem = property.ListItem; bool discussionBoardEdition = ((property.EventType == SPEventReceiverType.ItemUpdated) && (currentList.BaseTemplate == SPListTemplateType.DiscussionBoard)); if (currentList.Fields.ContainsField("ItemsAutoCreation")) { if (currentItem["ItemsAutoCreation"] != null) { if ((currentItem["ItemsAutoCreation"].ToString() == "Create items for all languages") || (currentItem["ItemsAutoCreation"].ToString() == "Overwrite/Create items for all languages")) { TranslatorAutoTranslation.CreateClonedMultilingualItem( HttpRuntime.Cache[OceanikAutomaticTranslation] as IAutomaticTranslation, currentWeb, listId, url, itemId, Lang, false, discussionBoardEdition); if (currentList.BaseTemplate != SPListTemplateType.DiscussionBoard) { currentWeb.AllowUnsafeUpdates = true; currentItem["ItemsAutoCreation"] = "None"; if (currentItem["AutoTranslation"] != null) { currentItem["AutoTranslation"] = "No"; } currentItem.SystemUpdate(false); } } } } } catch (Exception ex) { Utilities.LogException("Error in UpdateItemAutoTranslation: " + ex.Message, ex, EventLogEntryType.Warning); } currentWeb.AllowUnsafeUpdates = false; } }
/// <summary> /// 已添加项. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); if (properties.ListTitle == "请假单审批任务") { Guid related_field_guid = new Guid("{58ddda52-c2a3-4650-9178-3bbc1f6e36da}"); string link = properties.ListItem[related_field_guid].ToString().Split(',')[0]; int id_index = link.IndexOf("ID="); int id = int.Parse(link.Substring(id_index + 3)); SPListItem ask_leave_item = properties.OpenWeb().Lists["请假单"].GetItemById(id); SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(properties.SiteId)) { using (SPWeb web = site.OpenWeb("/admin")) { SPListItem item = web.Lists[properties.ListId].Items.GetItemById(properties.ListItemId); item.BreakRoleInheritance(false); try { // 清理旧权限。 int role_index = 0; while (item.RoleAssignments.Count > 1) { SPRoleAssignment role = item.RoleAssignments[role_index]; if (role.Member.LoginName.ToLower() == "sharepoint\\system") { role_index++; } else { item.RoleAssignments.Remove(role_index); } } foreach (SPRoleAssignment ra in ask_leave_item.RoleAssignments) { item.RoleAssignments.Add(ra); } } catch (Exception ex) { log(site, "自动删除项目旧权限", "错误", ex.ToString()); } // 分别为各个角色赋予此项目的独特权限:。 log(web.Site, "更新项目权限", "消息", "为项目【" + item["Title"] + "】更新权限完成。"); } } }); } }
/// <summary> /// 已添加项. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); if (properties.ListTitle == "请假单审批任务") { Guid related_field_guid = new Guid("{58ddda52-c2a3-4650-9178-3bbc1f6e36da}"); string link = properties.ListItem[related_field_guid].ToString().Split(',')[0]; int id_index = link.IndexOf("ID="); int id = int.Parse(link.Substring(id_index + 3)); SPListItem ask_leave_item = properties.OpenWeb().Lists["请假单"].GetItemById(id); SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(properties.SiteId)) { using (SPWeb web = site.OpenWeb("/admin")) { SPListItem item = web.Lists[properties.ListId].Items.GetItemById(properties.ListItemId); item.BreakRoleInheritance(false); try { // 清理旧权限。 int role_index = 0; while (item.RoleAssignments.Count > 1) { SPRoleAssignment role = item.RoleAssignments[role_index]; if (role.Member.LoginName.ToLower() == "sharepoint\\system") { role_index++; } else { item.RoleAssignments.Remove(role_index); } } foreach (SPRoleAssignment ra in ask_leave_item.RoleAssignments) { item.RoleAssignments.Add(ra); } } catch (Exception ex) { log(site, "自动删除项目旧权限", "错误", ex.ToString()); } // 分别为各个角色赋予此项目的独特权限:。 log(web.Site, "更新项目权限", "消息", "为项目【" + item["Title"] + "】更新权限完成。"); } } }); } }
public static string GetParameter(string parameter, SPItemEventProperties properties) { string outValue = string.Empty; SPWeb web = properties.OpenWeb(); SPList list = web.Lists["PhrescoParams"]; SPQuery query = new SPQuery(); query.Query = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + parameter + "</Value></Eq></Where>"); var items = list.GetItems(query); if (items != null && items.Count > 0) { outValue = items[0][list.Fields["Value"].InternalName].ToString(); } return outValue; }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { // Get a reference to the site collection SPSite site = properties.OpenSite(); // Get a reference to the current site SPWeb currentWeb = properties.OpenWeb(); // Get a reference to the root site SPWeb rootWeb = site.RootWeb; // Skip if the root web is the same as the current web if (rootWeb.Url == currentWeb.Url) { return; } // Get the current list SPList currentList = properties.List; // Get the announcement list on the root site SPList rootList = rootWeb.Lists["Announcements"]; // Get the list item that got added SPListItem currentListItem = properties.ListItem; // Add the announcement item to the list on the root web SPListItem rootListItem = rootList.Items.Add(); foreach (SPField field in currentList.Fields) { if (!field.ReadOnlyField) { rootListItem[field.Id] = currentListItem[field.Id]; } } // Append user display name to title. rootListItem["Title"] += " - " + properties.UserDisplayName; // Append the web url to the Body rootListItem["Body"] += string.Format(" This announcements was made by {0} on subweb {1}", properties.UserLoginName, properties.WebUrl); rootListItem.Update(); }
private void CreateSnapshot(SPItemEventProperties properties) { using (var site = properties.OpenWeb()) { var item = properties.ListItem; var shadowLibrary = site.Lists[ShadowLibrary] as SPDocumentLibrary; var path = string.Format("Versions/{0}/{1}", item.ID, GetOfficialVersionLabel(item)); var shadowFolder = CreateFolderPath(shadowLibrary, path); foreach (string fileName in item.Attachments) { SPFile existingFile = item.ParentList.ParentWeb.GetFile(item.Attachments.UrlPrefix + fileName); SPFile newFile = shadowFolder.Files.Add(fileName, existingFile.OpenBinaryStream()); newFile.Item.Update(); } } }
/// <summary> /// 如果当前网站下不存在活动这个列表,则不进行操作 /// </summary> /// <param name="properties"></param> public override void ItemUpdated(SPItemEventProperties properties) { base.ItemUpdated(properties); SPList activ = properties.Web.Lists.TryGetList("活动1"); if (activ == null) { CreateActivityList(properties.SiteId, properties.Web.ID, "活动1", "计划生成活动", properties.List.Title); } return; //获取字段内部名 string nameField = properties.List.Fields.GetField("完成百分比").InternalName; string fType = properties.List.Fields.GetField("活动类型").InternalName; string fDiDian = properties.List.Fields.GetField("活动地点").InternalName; string fObject = properties.List.Fields.GetField("活动对象").InternalName; string fStart = properties.List.Fields.GetField("开始日期").InternalName; string fEnd = properties.List.Fields.GetField("截止日期").InternalName; string fAssigned = properties.List.Fields.GetField("分配对象").InternalName; string fDesc = properties.List.Fields.GetField("说明").InternalName; if (properties.ListItem["ParentID"] != null) {// sub level if (properties.ListItem[nameField].ToString() == "1") { string taskName = properties.ListItem["Title"].ToString(); //外键 SPFieldLookupValue taskID = new SPFieldLookupValue(properties.ListItem.ID, taskName); Activity myActivity = new Activity(); myActivity.name = taskName; myActivity.aType = properties.ListItem[fType].ToString(); myActivity.aPosition = properties.ListItem[fDiDian].ToString(); myActivity.aObject = properties.ListItem[fObject].ToString(); myActivity.start = DateTime.Parse(properties.ListItem[fStart].ToString()); DateTime end = DateTime.Parse(properties.ListItem[fEnd].ToString()); myActivity.during = GetDuring(myActivity.start, end); SPFieldUserValueCollection assignedTo = (SPFieldUserValueCollection)properties.ListItem[fAssigned]; myActivity.author = assignedTo; myActivity.task = taskID; myActivity.aDescption = properties.ListItem[fDesc].ToString(); WriteToList(properties.SiteId, properties.OpenWeb().ID, activ.Title, myActivity); } } }
public static string GetParameter(string parameter, SPItemEventProperties properties) { string outValue = string.Empty; SPWeb web = properties.OpenWeb(); SPList list = web.Lists["PhrescoParams"]; SPQuery query = new SPQuery(); query.Query = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + parameter + "</Value></Eq></Where>"); var items = list.GetItems(query); if (items != null && items.Count > 0) { outValue = items[0][list.Fields["Value"].InternalName].ToString(); } return(outValue); }
/// <summary> /// Valida si el tipo de contenido es el correcto /// </summary> /// <param name="properties"></param> /// <returns></returns> private bool EsTCCorrecto(SPItemEventProperties properties) { bool band = false; SPContentTypeCollection contentTypes = properties.OpenWeb().Lists[properties.ListId].ContentTypes; foreach (SPContentType contentType in contentTypes) { if (string.Equals(contentType.Name, TC_OBJETICO, StringComparison.CurrentCultureIgnoreCase)) { band = true; break; } } return(band); }
public override void ItemAdding(SPItemEventProperties properties) { base.ItemAdding(properties); //Cancel Event if title contain special character if (properties != null) { String sTitle = Convert.ToString(properties.AfterProperties["Title"]); if (!String.IsNullOrEmpty(sTitle)) { if (sTitle.HasSpecialCharacterForFileandFolder()) { properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl; SPWeb web = properties.OpenWeb(); properties.RedirectUrl = current.Request.Url.ToString(); CustomExceptions.SetErrorMessageforUI(current, web, "Special Character is not allowed"); } } } }
private void CreateDocumentWorkspace(SPItemEventProperties properties) { using (SPWeb web = properties.OpenWeb()) using (SPSite site = web.Site) { const Int32 LOCALE_ID_ENGLISH = 1033; SPWebTemplateCollection templates = site.GetWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH)); try { SPWebTemplate template = templates["STS#2"]; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite elevatedSite = new SPSite(site.ID)) using (SPWeb elevatedWeb = elevatedSite.OpenWeb()) { SPWeb documentWorkspace = elevatedWeb.Webs.Add( string.Format("{0}-{1}", properties.List.Title, Guid.NewGuid().ToString()), properties.ListItem["Title"].ToString(), string.Format("Document Workspace for {0}", properties.ListItem["Title"].ToString()), Convert.ToUInt32(LOCALE_ID_ENGLISH), template, false, //TODO: This will change to true. We will need custom permissions for each meeting workspace. false); properties.ListItem["DocumentWorkspace"] = string.Format("{0}, {1}", documentWorkspace.Url, "Document Workspace"); properties.ListItem.Update(); SetUpDocumentWorkspace(properties, elevatedSite, documentWorkspace); } }); } catch (Exception ex) { Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Exception – {0} – {1} – {2}", "Error in Agenda Reciever", ex.Message, ex.StackTrace); properties.Cancel = true; properties.ErrorMessage = ex.Message; } } }
/// <summary> /// An item is being deleted. /// </summary> public override void ItemDeleting(SPItemEventProperties properties) { //base.ItemDeleting(properties); using (SPWeb web = properties.OpenWeb()) { try { SPList list = web.Lists["EmployeeDocumentLog"]; SPListItem newItem = list.Items.Add(); newItem["Title"] = properties.ListItem.Name; newItem["DocumentAction"] = "Document Deleted"; newItem.Update(); } catch (Exception ex) { throw ex; } } }
/// <summary> /// Genera y asigna el codigo CITE correlativo correspondiente /// </summary> /// <param name="properties"></param> private void EventoGenerarCITE(SPItemEventProperties properties) { SPListItem itemActual = properties.ListItem; SPUser usuarioActual = properties.OpenWeb().SiteUsers[properties.UserLoginName]; string tipoSalida = itemActual["Tipo salida"].ToString().Trim(); List <string> arrayParametro = this.RecuperarValorParametroGlobal(PARAMETRO, tipoSalida, usuarioActual); string valorParametro = arrayParametro[1]; string sinLadoIzq = valorParametro.Substring(valorParametro.IndexOf('{') + 1); int numeroBase = Convert.ToInt16(sinLadoIzq.Remove(sinLadoIzq.IndexOf('}'))); //string formatoBase = valorParametro.Remove(valorParametro.LastIndexOf('-') + 1); int numeroSiguiente = numeroBase + 1; #region Actualizar la columna CITE de la lista try { //itemActual["CITE"] = formatoBase + numeroSiguiente.ToString(); itemActual["CITE"] = valorParametro.Replace("{" + numeroBase + "}", numeroSiguiente.ToString()); } catch { itemActual["Title"] = valorParametro.Replace("{" + numeroBase + "}", numeroSiguiente.ToString()); } using (DisabledItemEventsScope scope = new DisabledItemEventsScope()) { itemActual.SystemUpdate(); } #endregion #region Actualizar el valor del parametro correspondiente this.ActualizarParametroCITE(Convert.ToInt16(arrayParametro[0]), valorParametro.Replace("{" + numeroBase + "}", "{" + numeroSiguiente.ToString() + "}")); #endregion }
/// <summary> /// An item is being updated. /// </summary> public override void ItemUpdating(SPItemEventProperties properties) { using (SPWeb web = properties.OpenWeb()) { try { System.Diagnostics.Debugger.Break(); SPList list = web.Lists["DocumentLog"]; SPListItem newItem = list.Items.Add(); newItem["Title"] = properties.ListItem.Title; newItem["DateAndTime"] = System.DateTime.Now; newItem["Action"] = "Item Announcements Updated"; newItem.Update(); } catch (Exception ex) { throw ex; } } }
private void RestoreSnapshot(SPItemEventProperties properties) { var item = properties.ListItem; var restoreVersion = GetCustomVersionLabel(item); EventFiringEnabled = false; item.Attachments.Cast <string>().ToList().ForEach(attachment => item.Attachments.Delete(attachment)); using (var site = properties.OpenWeb()) { var path = string.Format("Versions/{0}/{1}", item.ID, restoreVersion); var shadowLibrary = site.Lists[ShadowLibrary] as SPDocumentLibrary; var source = CreateFolderPath(shadowLibrary, path); foreach (SPFile file in source.Files) { item.Attachments.Add(file.Name, file.OpenBinary()); } } item.SystemUpdate(false); EventFiringEnabled = true; }
public override void ItemUpdating(SPItemEventProperties properties) { bool isValid = true; StringBuilder errorMessage = new StringBuilder(); string title = string.Empty; string code = string.Empty; DateTime enrollmentDate = DateTime.MinValue; DateTime startDate = DateTime.MinValue; DateTime endDate = DateTime.MinValue; float cost = 0; using (SPWeb web = properties.OpenWeb()) { ITrainingCourseRepository repository = ServiceLocator.GetInstance().Get <ITrainingCourseRepository>(); Initalize(properties.AfterProperties, repository, web, out title, out code, out enrollmentDate, out startDate, out endDate, out cost); if (properties.ListItem[repository.GetFieldName(new Guid(Fields.TrainingCourseCode), web)].ToString() != code) { if (ValidateCourseCodeExists(repository, code, errorMessage, web)) { isValid = false; } } } isValid = isValid & ValidateCourseCode(code, errorMessage); isValid = isValid & ValidateStartDate(enrollmentDate, startDate, errorMessage); isValid = isValid & ValidateEndDate(startDate, endDate, errorMessage); isValid = isValid & ValidateCourseCost(cost, errorMessage); //if any of the rules fail, set an error message and set the //Cancel property to true to instruct SharePoint to redirect to //standard error page. if (!isValid) { properties.ErrorMessage = errorMessage.ToString(); properties.Cancel = true; } }
public override void ItemAdding(SPItemEventProperties properties) { bool isValid = true; StringBuilder errorMessage = new StringBuilder(); string title = string.Empty; string code = string.Empty; DateTime enrollmentDate = DateTime.MinValue; DateTime startDate = DateTime.MinValue; DateTime endDate = DateTime.MinValue; float cost = 0; //A web is required to retrieve Field names for iterating through ListItem collection //in the SPItemEventProperties as well as retrieveing existing items in the TrainingCourses list. using (SPWeb web = properties.OpenWeb()) { ITrainingCourseRepository repository = ServiceLocator.GetInstance().Get <ITrainingCourseRepository>(); Initalize(properties.AfterProperties, repository, web, out title, out code, out enrollmentDate, out startDate, out endDate, out cost); if (ValidateCourseCodeExists(repository, code, errorMessage, web)) { isValid = false; } } isValid = isValid & ValidateCourseCode(code, errorMessage); isValid = isValid & ValidateEnrollmentDate(enrollmentDate, errorMessage); isValid = isValid & ValidateStartDate(enrollmentDate, startDate, errorMessage); isValid = isValid & ValidateEndDate(startDate, endDate, errorMessage); isValid = isValid & ValidateCourseCost(cost, errorMessage); //if any of the rules fail, set an error message and set the //Cancel property to true to instruct SharePoint to redirect to //standard error page. if (!isValid) { properties.ErrorMessage = errorMessage.ToString(); properties.Cancel = true; } }
/// <summary> /// An item is being deleted. /// </summary> public override void ItemDeleting(SPItemEventProperties properties) { base.ItemDeleting(properties); if (properties.ListTitle == SOURCE_LIST) { try { SPListItem theItem = properties.ListItem; SPWeb theSite = properties.OpenWeb(); SPList theList = theSite.Lists[CALENDAR_LIST]; SPViewCollection theViews = theList.Views; this.DeleteTheView(theViews, theItem.Title); } catch (Exception ex) { properties.ErrorMessage = ex.Message; properties.Status = SPEventReceiverStatus.Continue; } } }
/// <summary> /// An item was added /// </summary> public override void ItemAdded(SPItemEventProperties properties) { // base.ItemAdded(properties); var currentWeb = properties.OpenWeb(); if (properties.ListTitle == "Proposals") { string ProposalID = RemoveNonAlphaAndSpaces(properties.ListItem["Title"].ToString()); string ProposalName = properties.ListItem["Title"].ToString(); properties.ListItem["ClientID"] = ClientID; properties.ListItem["ProposalID"] = ProposalID; properties.ListItem.Update(); var redirectToProposalUrl = this.CreateProposalSite(currentWeb, ClientID, ProposalID, ProposalName, properties.ListItem.ID); SPUtility.Redirect(redirectToProposalUrl, SPRedirectFlags.Default, ctx); } }
private void doit(SPItemEventProperties properties) { // This is our Context. We get files from it. SPWeb oWeb = properties.OpenWeb(); // Get the transform. Stream transformS = GetTransformStream(oWeb); XslCompiledTransform trans = new XslCompiledTransform(); trans.Load(new XmlTextReader(transformS)); // Create a Temp file to write the result to. // TODO: Probably could do this in memory with byte[] as they may // not be that large. string tempDoc = Path.GetTempFileName(); new FileInfo(tempDoc).Attributes = FileAttributes.Temporary; FileStream partStream = File.Open(tempDoc, FileMode.Create, FileAccess.Write); // Get the selected document. SPFile xml = properties.ListItem.File; XPathDocument doc = new XPathDocument(xml.OpenBinaryStream()); // Transform the selected document and close. trans.Transform(doc, null, partStream); partStream.Close(); // Store the result in the Results Folder SPFolder resultsfolder = oWeb.GetFolder(ResultsListName); string filename = getResultsItemNameFromName(xml.Name); FileStream inStream = File.Open(tempDoc, FileMode.Open, FileAccess.Read); // We will overwrite the item if it's updating. resultsfolder.Files.Add(filename, inStream); // Clean up, delete the temp file. File.Delete(tempDoc); }
/// <summary> /// An item is being deleted /// </summary> public override void ItemDeleting(SPItemEventProperties properties) { base.ItemDeleting(properties); if (properties.ListTitle == "Proposals") { if (properties.ListItem["ClientID"] != null && properties.ListItem["ProposalID"] != null) { var deletingClientID = properties.ListItem["ClientID"].ToString(); var deletingProposalID = properties.ListItem["ProposalID"].ToString(); if (deletingClientID != string.Empty && deletingProposalID != string.Empty) { SPSecurity.RunWithElevatedPrivileges(delegate() { var currentWeb = properties.OpenWeb(); SPWeb clientWeb = currentWeb.Webs[deletingClientID]; var deletingWeb = clientWeb.Webs[deletingProposalID]; if (deletingWeb.Exists) { clientWeb.Webs.Delete(deletingProposalID); } }); } } } }
/// <summary> /// An item is being updated /// </summary> public override void ItemUpdating(SPItemEventProperties properties) { base.ItemUpdating(properties); if (properties.ListTitle == "Proposals") { if (properties.ListItem["ClientID"] != null && properties.ListItem["ProposalID"] != null) { string afterValue = ""; string afterValueID = ""; var updatingClientID = properties.ListItem["ClientID"].ToString(); var ProposalName = properties.ListItem["Title"].ToString(); if (properties.AfterProperties["Title"] != null) { afterValue = properties.AfterProperties["Title"].ToString(); afterValueID = RemoveNonAlphaAndSpaces(afterValue); var updatingProposalID = RemoveNonAlphaAndSpaces(ProposalName); if (updatingClientID != string.Empty && updatingProposalID != string.Empty) { if (afterValueID != string.Empty) { SPSecurity.RunWithElevatedPrivileges(delegate() { var currentWeb = properties.OpenWeb(); SPWeb clientWeb = currentWeb.Webs[updatingClientID]; var updatingWeb = clientWeb.Webs[updatingProposalID]; if (updatingWeb.Exists) { updatingWeb.Name = afterValueID; updatingWeb.Title = afterValue; updatingWeb.Update(); } }); } } } } } }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); if (properties.ListTitle == SOURCE_LIST) { try { SPListItem theItem = properties.ListItem; SPWeb theSite = properties.OpenWeb(); SPList theRoomList = theSite.Lists[ROOM_LIST]; SPList theResourceList = theSite.Lists[RESOURCE_LIST]; string roomNotificationMail = this.CheckForRoomNotification(theRoomList, theItem["Sala reserva"]); List <string> resourceNotificationMails = this.CheckForResourceNotification(theResourceList, theItem["Recurso reserva"]); #region Room notification if (!string.IsNullOrWhiteSpace(roomNotificationMail)) { /*if (!SPUtility.IsEmailServerSet(properties.Web)) * { * throw new SPException("Outgoing E-Mail Settings are not configured!"); * } * else * {*/ string room = this.SubstringFormat(theItem["Sala reserva"]); string area = this.SubstringFormat(theItem["Área reserva"]); string user = theItem["Usuario reserva"].ToString(); string subject = theItem.Title; string begin = Convert.ToDateTime(theItem["Hora de inicio"].ToString()).ToString("dd/MM/yyyy HH:mm"); string end = Convert.ToDateTime(theItem["Hora de finalización"].ToString()).ToString("dd/MM/yyyy HH:mm"); string creator = this.SubstringFormat(theItem["Creado por"]); string created = Convert.ToDateTime(theItem["Creado"].ToString()).ToString("dd/MM/yyyy HH:mm"); System.Collections.Specialized.StringDictionary headers = new System.Collections.Specialized.StringDictionary(); headers.Add("to", roomNotificationMail); headers.Add("cc", ""); headers.Add("bcc", ""); headers.Add("from", "*****@*****.**"); headers.Add("subject", "Notificación automática, Sistema de Reserva de Salas BISA"); headers.Add("content-type", "text/html"); string bodyText = string.Format( "<table border='0' cellspacing='0' cellpadding='0' style='width:99%;border-collapse:collapse;'>" + "<tr><td style='border:solid #E8EAEC 1.0pt;background:#F8F8F9;padding:12.0pt 7.5pt 15.0pt 7.5pt'>" + "<p style='font-size:15.0pt;font-family:Verdana,sans-serif;'>" + "Sistema de Reserva de Salas: Reserva \"{0}\"</p></td></tr>" + "<tr><td style='border:none;border-bottom:solid #9CA3AD 1.0pt;padding:4.0pt 7.5pt 4.0pt 7.5pt'>" + "<p style='font-size:10.0pt;font-family:Tahoma,sans-serif'>" + "Esta es una notificación automática generada por el <b>Sistema de Reserva de Salas</b> " + "con el propósito de informar que se hizo la reserva siguiente:</p>" + "<p>- Sala reservada: <b>{0}</b></p>" + "<p>- Área solicitante: <b>{1}</b></p>" + "<p>- Usuario solicitante: <b>{2}</b></p>" + "<p>- Motivo: <b>{3}</b></p>" + "<p>- Periodo: desde <b>{4}</b> hasta <b>{5}</b></p>" + "<p style='font-size:8.0pt;font-family:Tahoma,sans-serif;'>" + "Reserva creada por {6} en fecha {7}</p></td></tr></table>", room, area, user, subject, begin, end, creator, created); SPUtility.SendEmail(properties.Web, headers, bodyText); /*}*/ } #endregion #region Resource notification if (resourceNotificationMails.Count > 0) { /*if (!SPUtility.IsEmailServerSet(properties.Web)) * { * throw new SPException("Outgoing E-Mail Settings are not configured!"); * } * else * {*/ string room = this.SubstringFormat(theItem["Sala reserva"]); string area = this.SubstringFormat(theItem["Área reserva"]); string user = theItem["Usuario reserva"].ToString(); string subject = theItem.Title; string begin = Convert.ToDateTime(theItem["Hora de inicio"].ToString()).ToString("dd/MM/yyyy HH:mm"); string end = Convert.ToDateTime(theItem["Hora de finalización"].ToString()).ToString("dd/MM/yyyy HH:mm"); string resources = this.GetFormatedResources(theItem["Recurso reserva"].ToString()); string creator = this.SubstringFormat(theItem["Creado por"]); string created = Convert.ToDateTime(theItem["Creado"].ToString()).ToString("dd/MM/yyyy HH:mm"); foreach (string resourceNotificationMail in resourceNotificationMails) { System.Collections.Specialized.StringDictionary headers = new System.Collections.Specialized.StringDictionary(); headers.Add("to", resourceNotificationMail); headers.Add("cc", ""); headers.Add("bcc", ""); headers.Add("from", "*****@*****.**"); headers.Add("subject", "Notificación automática, Sistema de Reserva de Salas BISA"); headers.Add("content-type", "text/html"); string bodyText = string.Format( "<table border='0' cellspacing='0' cellpadding='0' style='width:99%;border-collapse:collapse;'>" + "<tr><td style='border:solid #E8EAEC 1.0pt;background:#F8F8F9;padding:12.0pt 7.5pt 15.0pt 7.5pt'>" + "<p style='font-size:15.0pt;font-family:Verdana,sans-serif;'>" + "Sistema de Reserva de Salas: Reserva \"{0}\"</p></td></tr>" + "<tr><td style='border:none;border-bottom:solid #9CA3AD 1.0pt;padding:4.0pt 7.5pt 4.0pt 7.5pt'>" + "<p style='font-size:10.0pt;font-family:Tahoma,sans-serif'>" + "Esta es una notificación automática generada por el <b>Sistema de Reserva de Salas</b> " + "con el propósito de informar que se hizo la reserva siguiente:</p>" + "<p>- Sala reservada: <b>{0}</b></p>" + "<p>- Área solicitante: <b>{1}</b></p>" + "<p>- Usuario solicitante: <b>{2}</b></p>" + "<p>- Motivo: <b>{3}</b></p>" + "<p>- Periodo: desde <b>{4}</b> hasta <b>{5}</b></p>" + "<p>- Recursos a usar: <b>{6}</b></p>" + "<p style='font-size:8.0pt;font-family:Tahoma,sans-serif;'>" + "Reserva creada por {7} en fecha {8}</p></td></tr></table>", room, area, user, subject, begin, end, resources, creator, created); SPUtility.SendEmail(properties.Web, headers, bodyText); } /*}*/ } #endregion } catch (Exception ex) { properties.ErrorMessage = ex.Message; properties.Status = SPEventReceiverStatus.Continue; } } }
private void CreateMeetingWorkspace(SPItemEventProperties properties) { using (SPWeb web = properties.OpenWeb()) using (SPSite site = web.Site) { const Int32 LOCALE_ID_ENGLISH = 1033; SPWebTemplateCollection templates = site.GetWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH)); try { SPWebTemplate template = templates["MPS#0"]; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite elevatedSite = new SPSite(site.ID)) using (SPWeb elevatedWeb = elevatedSite.OpenWeb()) { SPWeb meetingWorkspace = elevatedWeb.Webs.Add( string.Format("{0}-{1}", properties.List.Title, Guid.NewGuid().ToString()), properties.ListItem["Title"].ToString(), properties.ListItem["Location"].ToString(), Convert.ToUInt32(LOCALE_ID_ENGLISH), template, false, //TODO: This will change to true. We will need custom permissions for each meeting workspace. false); SPMeeting meeting = SPMeeting.GetMeetingInformation(meetingWorkspace); meeting.LinkWithEvent(web, properties.ListId.ToString(), properties.ListItemId, "WorkspaceLink", "Workspace"); meetingWorkspace.AllowUnsafeUpdates = true; string currentTheme = web.Theme; meetingWorkspace.ApplyTheme(currentTheme); //Add the DocumentSet content Type to 'Document Library' SPList documentLibrary = meetingWorkspace.Lists["Document Library"]; documentLibrary.ContentTypes.Add(site.RootWeb.ContentTypes["Document Set"]); documentLibrary.Update(); //Remove the Objectives List and Attendees List from meeting workspace SPList objectivesList = meetingWorkspace.Lists["Objectives"]; SPList attendeesList = meetingWorkspace.Lists["Attendees"]; meetingWorkspace.Lists.Delete(objectivesList.ID); attendeesList.Hidden = true; attendeesList.Update(); //Hide the webpart SPLimitedWebPartManager webPartManager = meetingWorkspace.GetLimitedWebPartManager("Default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); for (int k = 0; k < webPartManager.WebParts.Count; k++) { //get reference to webpart WebPart wp = webPartManager.WebParts[k] as WebPart; webPartManager.DeleteWebPart(webPartManager.WebParts[k]); //update spWeb object meetingWorkspace.Update(); } //Add the extra fields to the Agenda List SPList meetingAgendaList = meetingWorkspace.Lists["Agenda"]; SPField ownerField = meetingAgendaList.Fields["Owner"]; SPField timeField = meetingAgendaList.Fields["Time"]; ownerField.Title = "Presenter"; timeField.Title = "Time (in minutes)"; ownerField.Update(); timeField.Update(); SPField fldSponsor = meetingAgendaList.Fields.CreateNewField(SPFieldType.User.ToString(), "Sponsor"); SPField fldItemNumber = meetingAgendaList.Fields.CreateNewField(SPFieldType.Number.ToString(), "Item Number"); SPField fldOffice = meetingAgendaList.Fields.CreateNewField(SPFieldType.Text.ToString(), "Office"); SPField fldAgendaID = meetingAgendaList.Fields.CreateNewField(SPFieldType.Number.ToString(), "AgendaID"); SPField fldDocuments = meetingAgendaList.Fields.CreateNewField(SPFieldType.URL.ToString(), "Documents"); meetingAgendaList.Fields.Add(fldSponsor); meetingAgendaList.Fields.Add(fldItemNumber); meetingAgendaList.Fields.Add(fldOffice); meetingAgendaList.Fields.Add(fldDocuments); meetingAgendaList.Fields.Add(fldAgendaID); meetingAgendaList.Update(); SPView defaultView = meetingAgendaList.Views["All Items"]; SPViewFieldCollection viewFields = defaultView.ViewFields; viewFields.Add(meetingAgendaList.Fields["Sponsor"]); viewFields.Add(meetingAgendaList.Fields["Item Number"]); viewFields.Add(meetingAgendaList.Fields["Office"]); viewFields.Add(meetingAgendaList.Fields["Documents"]); defaultView.Update(); meetingWorkspace.Update(); meetingWorkspace.AllowUnsafeUpdates = false; } }); } catch (Exception ex) { properties.Cancel = true; properties.ErrorMessage = ex.Message; } } }
private void ExecuteReceivedEvent(AlertEventType eventType, SPItemEventProperties properties) { LogManager.write("Entered in to ExecuteReceivedEvent with event type" + eventType); try { using (SPWeb web = properties.OpenWeb()) { //TODO we have to check is feature activated for this site or not AlertManager alertManager = new AlertManager(web.Site.Url); MailTemplateManager mailTemplateManager = new MailTemplateManager(web.Site.Url); IList<Alert> alerts = alertManager.GetAlertForList(properties.ListItem ,eventType, mailTemplateManager); Notifications notifications = new Notifications(); foreach (Alert alert in alerts) { if (eventType != AlertEventType.DateColumn) { if (alert.IsValid(properties.ListItem, eventType, properties)) { try { if (alert.SendType == SendType.ImmediateAlways) { notifications.SendMail(alert, eventType, properties.ListItem, FinalBody); } else if (alert.SendType == SendType.ImmediateBusinessDays) { if (alert.ImmediateBusinessDays.Contains((WeekDays)DateTime.UtcNow.DayOfWeek)) { if (alert.BusinessStartHour <= Convert.ToInt32(DateTime.UtcNow.Hour) && alert.BusinessendtHour >= Convert.ToInt32(DateTime.UtcNow.Hour)) { notifications.SendMail(alert, eventType, properties.ListItem, FinalBody); } else { return; } } } else { CreateDelayedAlert(alert, eventType, properties, alertManager); } } catch { } } } } } } catch (System.Exception Ex) { LogManager.write("Error occured white excuting event receiver" + Ex.Message); } }
/// <summary> /// 正在添加项. public override void ItemAdded(SPItemEventProperties properties) { //base.ItemAdded(properties); SPWeb web = properties.OpenWeb(); int authorID = 0; try { authorID = web.Author.ID; if (web.CurrentUser.ID == web.Author.ID) { return; } } catch { //未找到用户 if (authorID == 0) { foreach (SPUser sUser in web.Users) { if (web.CurrentUser.ID == sUser.ID && web.DoesUserHavePermissions(sUser.LoginName, SPBasePermissions.FullMask)) { return; } } } } SPListItem item = properties.ListItem; SPList lstNewPost = CheckList(web); string fieldRefName = "Title"; foreach (SPField fid in lstNewPost.Fields) { if (fid.Title == "文章ID") { fieldRefName = fid.InternalName;// +";" + fid.StaticName + ";"; break; } } SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb web1 = new SPSite(web.Site.ID).OpenWeb(web.ID)) { SPList lst = web1.Lists[lstNewPost.ID]; SPListItem lstItem = null; string id = item["文章 ID"].ToString(); id = id.Substring(0, id.IndexOf(";#")); SPQuery query = new SPQuery(); query.ViewAttributes = "Scope='RecursiveAll'"; query.Query = "<Where><Eq><FieldRef Name='" + fieldRefName + "'/><Value Type='Text'>" + id + "</Value></Eq></Where>"; SPListItemCollection items = lstNewPost.GetItems(query); if (items.Count == 0) { lstItem = lst.Items.Add(); lstItem["标题"] = item.ID; lstItem["文章ID"] = id; } else { lstItem = items[0]; } lstItem["新回复数"] = Convert.ToInt32(lstItem["新回复数"]) + 1; lstItem.Update(); } }); }
static List<LDwithID> findSimilarFiles(SPItemEventProperties properties) { SPWeb myWeb = properties.OpenWeb(); List<long> cFiles = new List<long>(); List<LDwithID> similarResults = new List<LDwithID>(); SPList currentList = properties.List; SPListItem currentItem = properties.ListItem; SPAttachmentCollection curFiles = currentItem.Attachments; try { foreach (String attachmentname in curFiles) { String attachmentAbsoluteURL = currentItem.Attachments.UrlPrefix + attachmentname; SPFile attachmentFile = myWeb.GetFile(attachmentAbsoluteURL); cFiles.Add(attachmentFile.Length); } if (cFiles.Count > 0) { SPListItemCollection items = properties.List.Items; foreach (SPListItem item in items) { if (item.ID != currentItem.ID) { SPAttachmentCollection files = item.Attachments; if (files.Count > 0) { foreach (String file in files) { try { String attachmentAbsoluteURL = currentItem.Attachments.UrlPrefix + file; SPFile attachmentFile = myWeb.GetFile(attachmentAbsoluteURL); foreach (long cFile in cFiles) { if (attachmentFile.Length == cFile) similarResults.Add(new LDwithID { recId = item.ID.ToString(), Distance = 99 }); if (similarResults.Count > 1) return similarResults; } } catch { } } } } } } } catch { } return similarResults; }