コード例 #1
0
ファイル: tabProceduryER.cs プロジェクト: fraczo/Animus
        private void Execute(SPItemEventProperties properties)
        {
            this.EventFiringEnabled = false;

            try
            {
                BLL.Logger.LogEvent(properties.WebUrl, properties.ListItem.Title + ".OnUpdate");

                SPListItem item = properties.ListItem;

                if (item.Title.StartsWith(":"))
                {
                    item["_DISPLAY"] = item.Title;
                }
                else
                {
                    item["_DISPLAY"] = string.Format("{0}::{1}",
                     item["selGrupaProcedury"] != null ? new SPFieldLookupValue(item["selGrupaProcedury"].ToString()).LookupValue : string.Empty,
                     item.Title);
                }

                item.SystemUpdate();

            }
            catch (Exception ex)
            {
                BLL.Logger.LogEvent(properties.WebUrl, ex.ToString());
                var result = ElasticEmail.EmailGenerator.ReportError(ex, properties.WebUrl.ToString());
            }
            finally
            {
                this.EventFiringEnabled = true;
            }
        }
コード例 #2
0
        private void AddFileInfo(SPItemEventProperties properties)
        {
            try
            {
                var url = properties.WebUrl + "/" + properties.AfterUrl;
                var fileName = properties.AfterUrl;

                using (var site = new SPSite(properties.Web.Site.ID))
                using (var web = site.RootWeb)
                {
                    var list = web.Lists[LogList.ListName];
                    var listItems = list.Items;

                    var item = listItems.Add();
                    item["Title"] = fileName;
                    item["URL"] = url;
                    item.Update();
                }

                ULSLog.LogDebug(String.Format("Added {0} to {1} list", url, LogList.ListName));
            }
            catch (Exception ex)
            {
                ULSLog.LogError(ex);
            }
        }
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            SPWeb spWeb = properties.Web;
            SPPushNotificationSubscriberCollection pushSubscribers = spWeb.PushNotificationSubscribers;
            PushNotification pushNotification = new PushNotification();

            SPListItem listItem = properties.ListItem;

            string jobAssignment = "[Unassigned]";

            // This event receiver is intended to be associated with a specific list,
            // but the list may not have an "AssignedTo" field, so using try/catch here.
            try
            {
                jobAssignment = listItem["AssignedTo"].ToString();
            }
            catch { }

            PushNotificationResponse pushResponse = null;

            foreach (SPPushNotificationSubscriber ps in pushSubscribers)
            {
                // Send a toast notification to be displayed on subscribed phones on which the app is not running.
                pushResponse = pushNotification.PushToast(ps, "New job for:", jobAssignment, string.Empty, ToastIntervalValuesEnum.ImmediateToast);
                UpdateNotificationResultsList(spWeb, ps.User.Name, pushResponse);

                // Also send a raw notification to be displayed on subscribed phones on which the app is running when the item is added.
                pushResponse = pushNotification.PushRaw(ps, string.Format("New job for: {0}", jobAssignment), RawIntervalValuesEnum.ImmediateRaw);
                UpdateNotificationResultsList(spWeb, ps.User.Name, pushResponse);
            }

            base.ItemAdded(properties);
        }
コード例 #4
0
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties) {
            base.ItemAdded(properties);

            try {
                _dbg = "butik";
                object oButik = properties.ListItem[new Guid("a209aa87-f7e4-46cf-8865-37ea0002294b")];
                string strButik = oButik as string;

                if (strButik != null) {
                    SPFieldLookupValue butik = new SPFieldLookupValue(strButik);
                    _dbg = "ct";
                    string contenttype = properties.ListItem.ContentType.Name;
                    _dbg = "id";
                    int id = properties.ListItemId;
                    _dbg = "set";
                    properties.ListItem["Title"] = contenttype + " #" + id.ToString() + " - " + butik.LookupValue;
                    _dbg = "klar";
                    properties.ListItem.Update();
                    _dbg = "upd";
                    WriteLog("ItemAdded", EventLogEntryType.Information, 1002);
                }
            }
            catch (Exception ex) {
                WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace + "\r\n\r\nDebug:\r\n" + _dbg, EventLogEntryType.Error, 2002);
            }
        }
コード例 #5
0
        private int GetLatestItemOrderNo(SPItemEventProperties properties)
        {
            int orderNo = 0;

            string caml = string.Empty;
            var expressionsAnd = new List<Expression<Func<SPListItem, bool>>>();

            if (expressionsAnd.Count > 0)
                caml = Camlex.Query().WhereAll(expressionsAnd).OrderBy(x => x[Constants.ORDER_NUMBER_COLUMN] as Camlex.Desc).ToString();
            else
                caml = Camlex.Query().OrderBy(x => x[Constants.ORDER_NUMBER_COLUMN] as Camlex.Desc).ToString();

            SPQuery spQuery = new SPQuery();
            spQuery.Query = caml;

            spQuery.RowLimit = 1;

            SPList currentList = properties.List;
            SPListItemCollection items = currentList.GetItems(spQuery);

            if (items != null && items.Count > 0)
            {
                SPListItem item = items[0];

                if (item != null)
                {
                    orderNo = Convert.ToInt32(item[Constants.ORDER_NUMBER_COLUMN]);
                }
            }

            return orderNo;
        }
コード例 #6
0
ファイル: EventReceiver1.cs プロジェクト: vijaymca/SharePoint
        /// <summary>
        /// An item is being updated.
        /// </summary>
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            bool allowed = true;

            if (properties.ListTitle == "Open Positions")
            {
                allowed = checkItem(properties);
            }

            try
            {

                if (!allowed)
                {
                    properties.Status = SPEventReceiverStatus.CancelWithError;
                    properties.ErrorMessage = "The job you have entered is not defined in the Job Definitions List";
                    properties.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage = ex.Message;
                properties.Cancel = true;
            }
        }
コード例 #7
0
 public EventReceiverContext(SPItemEventProperties properties)
 {
     Site = new SPSite(properties.SiteId);
     Web = Site.OpenWeb(properties.RelativeWebUrl);
     List = Web.Lists[properties.ListId];
     Item = List.GetItemByIdAllFields(properties.ListItemId);
 }
コード例 #8
0
        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);

                SPListItem item = properties.ListItem;
                var createdByLeaveRequest = new SPFieldUserValue(properties.Web,item["Created By"].ToString());

                if (item["Status"].ToString() == "Approved")

                {
                    SPSite myDestinationSite = new SPSite(properties.WebUrl);
                    SPWeb myDestinationWeb = myDestinationSite.OpenWeb();
                    SPList myDestinationList = myDestinationWeb.Lists["LeaveDays"];
                    SPListItem myDestinationListItem = myDestinationList.Items[0];

                    var EmpNameLeavedays = new SPFieldUserValue(properties.Web, myDestinationListItem["Employee Name"].ToString());
                    myDestinationListItem["PaidLeaveBalance"] = item["Dup Paid Leave Balance"];//SourceEmpId;
                    myDestinationListItem["PaidLeaveUtilized"] = item["Dup Paidleaveutilize"];// SourceEmpName;
                    myDestinationWeb.AllowUnsafeUpdates = true;
                    if(createdByLeaveRequest.User.ID  == EmpNameLeavedays.User.ID)
                   {
                    myDestinationListItem.Update();
                    myDestinationWeb.AllowUnsafeUpdates = false;
                   }

                }
        }
コード例 #9
0
ファイル: StopItemDelete.cs プロジェクト: vijaymca/SharePoint
        protected void updateConformDate(SPItemEventProperties properties)
        {
            try
            {
                properties.Web.AllowUnsafeUpdates = true;
                //               DisableEventFiring();

                SPListItem listItem = properties.ListItem;
                string strDateJoin = listItem["Date of joining"].ToString();
                DateTime dojDate = Convert.ToDateTime(strDateJoin);
                //DateTime cnfDate = dojDate.AddMonths(6);

                listItem["Date of Conformation"] = dojDate.AddMonths(6);
                //listItem["StudentName"]="Changed";
                //properties.ListItem.SystemUpdate();
                listItem.SystemUpdate();
                //  listItem.Update();

                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage = "Item Updated..";
            }
            catch (Exception ex)
            {

            }
            finally
            {
                properties.Web.AllowUnsafeUpdates = false;
            }
        }
コード例 #10
0
ファイル: EventReceiver1.cs プロジェクト: vijaymca/SharePoint
 bool checkItem(SPItemEventProperties properties)
 {
     string jobTitle = properties.AfterProperties["Title"].ToString();
        bool allowed = false;
        SPWeb jobDefWeb = null;
        SPList jobDefList;
        SPUser privilegedAccount = properties.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
        SPUserToken privilegedToken = privilegedAccount.UserToken;
        try
        {
        using (SPSite elevatedSite = new SPSite(properties.Web.Url, privilegedToken))
        {
            using (SPWeb elevatedWeb = elevatedSite.OpenWeb())
            {
                jobDefWeb = elevatedWeb.Webs["JobDefinitions"];
                jobDefList = jobDefWeb.Lists["Job Definitions"];
                foreach (SPListItem item in jobDefList.Items)
                {
                    if (item["Title"].ToString() == jobTitle)
                    {
                        allowed = true;
                        break;
                    }
                }
            }
        }
        return (allowed);
        }
        finally
        {
        jobDefWeb.Dispose();
        }
 }
コード例 #11
0
 public override void ItemUpdating(SPItemEventProperties properties) {
   string title = properties.AfterProperties["Title"].ToString();
   if (title.ToLower().Contains("lobster") || title.ToLower().Contains("clam")) {
     properties.Status = SPEventReceiverStatus.CancelWithError;
     properties.ErrorMessage = "Do not use inflamitory terms such as 'lobster' or'clam'.";
   }
 }
コード例 #12
0
 /// <summary>
 /// An item is being updated.
 /// </summary>
 public override void ItemUpdating(SPItemEventProperties properties)
 {
     EventFiringEnabled = false;
     base.ItemUpdating(properties);
     DelegationApprovalCycle.RespondToDelegationUpdating(properties);
     EventFiringEnabled = true;
 }
 /// <summary>
 /// 已更新项.
 /// </summary>
 public override void ItemUpdated(SPItemEventProperties properties)
 {
     this.EventFiringEnabled = false;
        base.ItemAdded(properties);
        update_permission(properties);
        update_folders_time(properties);
 }
コード例 #14
0
 private void AssignDelegation(SPItemEventProperties properties, Delegation validDelegation)
 {
     properties.AfterProperties["OriginalAssignee"] = GetSPUserValue(properties, "AssignedTo");
     properties.AfterProperties["AssignedTo"] = ConvertStringToUser(properties, validDelegation.AssignedTo);
     properties.AfterProperties["IsDelegated"] = true;
     properties.AfterProperties["DelegationType"] = validDelegation.DelegationType.ToString();
 }
コード例 #15
0
        /// <summary>
        /// Asynchronous After event that occurs after an existing item is changed, for example, when the user changes data in one or more fields.
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPItemEventProperties" /> object that represents properties of the event handler.</param>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            this.EventFiringEnabled = false;

            using (var childScope = SearchContainerProxy.BeginWebLifetimeScope(properties.Web))
            {
                this.EventFiringEnabled = false;
                var logger = childScope.Resolve<ILogger>();

                try
                {
                    var browserTitleService = childScope.Resolve<IBrowserTitleBuilderService>();

                    // Set slugs
                    browserTitleService.SetBrowserTitle(properties.Web, properties.ListItem);
                }
                catch (Exception e)
                {
                    logger.Exception(e);
                }
                finally
                {
                    this.EventFiringEnabled = true;
                }
            }
        }
コード例 #16
0
       private void Execute(SPItemEventProperties properties)
       {
           this.EventFiringEnabled = false;

           try
           {
               Update_KEY(properties);

               SPListItem item = properties.ListItem;
               BLL.Tools.Ensure_LinkColumn(item, "selKlient");
           }
           catch (Exception ex)
           {
#if DEBUG
                throw ex;
#else
               BLL.Logger.LogEvent(properties.WebUrl, ex.ToString());
               var result = ElasticEmail.EmailGenerator.ReportError(ex, properties.WebUrl.ToString());
#endif

           }
           finally
           {
               this.EventFiringEnabled = true;
           }

       }
コード例 #17
0
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            SPListItem listItem = properties.ListItem;

            HandleSecurityRules(listItem, properties.EventType);
        }
コード例 #18
0
ファイル: dicUrzedySkarbowe.cs プロジェクト: fraczo/Animus
        private void Execute(SPItemEventProperties properties)
        {
            this.EventFiringEnabled = false;
            SPListItem item = properties.ListItem;
            BLL.Logger.LogEvent_EventReceiverInitiated(item);

            try
            {
                // aktualizuje pole opisowe _konta

                item["_Konta"] = String.Format(@"{0}{1}{2}",
                    item["colPIT_Konto"] != null ? item["colPIT_Konto"] + " - PIT<br>" : string.Empty,
                    item["colCIT_Konto"] != null ? item["colCIT_Konto"] + " - CIT<br>" : string.Empty,
                    item["colVAT_Konto"] != null ? item["colVAT_Konto"] + " - VAT" : string.Empty);
                item.SystemUpdate();
            }
            catch (Exception ex)
            {
                BLL.Logger.LogEvent(properties.WebUrl, ex.ToString());
                var result = ElasticEmail.EmailGenerator.ReportError(ex, properties.WebUrl.ToString());
            }
            finally
            {
                BLL.Logger.LogEvent_EventReceiverCompleted(item);
                this.EventFiringEnabled = true;
            }
        }
コード例 #19
0
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            this.EventFiringEnabled = false;

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (var site = new SPSite(properties.Web.Site.ID))
                {
                    using (var web = site.OpenWeb(properties.Web.ID))
                    {
                        //var list = web.Lists.GetList(properties.ListId, true);
                        //var item = list.GetItemById(properties.ListItemId);
                        //try
                        //{
                        //    SetPermission(web, item);
                        //}
                        //finally
                        //{
                        //    this.EventFiringEnabled = true;
                        //}
                    }

                }
            });
        }
コード例 #20
0
        /// <summary>
        /// Asynchronous After event that occurs after an existing item is changed, for example, when the user changes data in one or more fields.
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPItemEventProperties" /> object that represents properties of the event handler.</param>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);

            using (var childScope = NavigationContainerProxy.BeginWebLifetimeScope(properties.Web))
            {
                this.EventFiringEnabled = false;
                var logger = childScope.Resolve<ILogger>();

                try
                {
                    var navigationTermService = childScope.Resolve<INavigationTermBuilderService>();
                    var variationHelper = childScope.Resolve<IVariationHelper>();

                    var item = properties.ListItem;

                    // If the content is created at the source label, sync the term
                    if (variationHelper.IsCurrentWebSourceLabel(item.Web))
                    {
                        // Create term in other term sets
                        navigationTermService.SyncNavigationTerm(properties.ListItem);
                    }
                }
                catch (Exception e)
                {
                    logger.Exception(e);
                }
                finally
                {
                    this.EventFiringEnabled = true;
                }
            }
        }
コード例 #21
0
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties) {
            base.ItemAdded(properties);

            try {
                string lopnummerStr = properties.Web.Properties["lopnummer"];
                int lopnummer;
                if (int.TryParse(lopnummerStr, out lopnummer)) {
                    string nyttLopnummer = (lopnummer + 1).ToString();
                    string code = properties.Web.Properties["municipalAreaCode"];
                    string letter = properties.Web.Properties["municipalRegionLetter"];
                    string kundnummer = letter + code + "-" + nyttLopnummer;
                    string strAdress = (string)properties.ListItem[new Guid("b5c833ef-df4e-44f3-9ed5-316ed61a59c9")];
                    if (!string.IsNullOrEmpty(strAdress)) {
                        SPFieldLookupValue adress = new SPFieldLookupValue(strAdress);
                        properties.ListItem[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")] = adress.LookupValue;
                    }
                    else {
                        properties.ListItem[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")] = kundnummer;
                    }
                    properties.ListItem[new Guid("353eabaa-f0d3-40cc-acc3-4c6b23d3a64f")] = kundnummer;
                    
                    properties.ListItem.Update();
                    properties.Web.Properties["lopnummer"] = nyttLopnummer;
                    properties.Web.Properties.Update();
                }
                WriteLog("Success", EventLogEntryType.Information, 1000);
            }
            catch (Exception ex) {
                WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2000);
            }
        }
コード例 #22
0
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            bool IsAssignmentComplete = Convert.ToBoolean(properties.AfterProperties[properties.ListItem.Fields[SiteColumns.IsAssignmentComplete].InternalName]);
            int HomeworkPointsReceived = Convert.ToInt16(properties.AfterProperties[properties.ListItem.Fields[SiteColumns.HomeworkAssignmentPointsRecievied].InternalName]);
            int HomeworkPointsAllowed = Convert.ToInt16(properties.AfterProperties[properties.ListItem.Fields[SiteColumns.HomeworkAssignmentPointsAllowed].InternalName]);

            if (IsAssignmentComplete)
            {
                int ClassID = Convert.ToInt16(properties.AfterProperties[properties.List.Fields[SiteColumns.Class].InternalName].ToString());
                int StudentID = Convert.ToInt16(properties.AfterProperties[properties.List.Fields[SiteColumns.Student].InternalName].ToString());

                /* Determine the letter grade for the assignment. */
                int RawGradeValue = (HomeworkPointsReceived / HomeworkPointsAllowed) * 100;
                string LetterGrade = Utility.GetLetterGrade(RawGradeValue);

                using(DisabledEventsScope scope = new DisabledEventsScope())
                {
                    SPListItem item = properties.ListItem;
                    item[SiteColumns.LetterGrade] = LetterGrade;
                    item.Update();
                }

                /* Get an instance of the ClassGrades list and update the students class grade. */
            }
        }
コード例 #23
0
        public override void ItemAdded(SPItemEventProperties properties)
        {
            this.DisableEventFiring();
            try
            {
                string _mimeType = GetMimeType(properties.ListItem.File.Name);
                if (_mimeType != null)
                {
                    this.DisableEventFiring();
                    properties.ListItem["Content MimeType"] = _mimeType;
                    properties.ListItem["Document Author(s)"] = properties.ListItem.File.Properties["vti_author"];
                    properties.ListItem["Publishable Status"] = "Draft";

                    SPFieldUrlValue value = new SPFieldUrlValue();
                    value.Description = "Private";
                    value.Url = SPHelper.GetRootUrl(SPContext.Current.Web.Url) + "_layouts/IMAGES/bizdataactionicon.gif";
                    properties.ListItem["Access Level"] = value;
                    properties.ListItem.Update();
                }
            }
            catch (Exception ex)
            {
                properties.Cancel = true;
                properties.ErrorMessage = "Unable attach metadata to this item " + ex.Message;
            }
            finally
            {
                this.EnableEventFiring();
                base.ItemAdded(properties);
            }
        }
コード例 #24
0
ファイル: tabKlienciER.cs プロジェクト: fraczo/Biuromagda
        private void Execute(SPItemEventProperties properties)
        {
            this.EventFiringEnabled = false;

            try
            {
                BLL.Logger.LogEvent(properties.WebUrl, properties.ListItem.Title + ".OnChange");

                SPListItem item = properties.ListItem;
                SPWeb web = properties.Web;

                Update_LookupRefFields(item);

                Update_FolderInLibrary(item, web);
            }
            catch (Exception ex)
            {
                BLL.Logger.LogEvent(properties.WebUrl, ex.ToString());
                var result = ElasticEmail.EmailGenerator.ReportError(ex, properties.WebUrl.ToString());
            }
            finally
            {
                this.EventFiringEnabled = true;
            }
        }
コード例 #25
0
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            SPListItem item1 = properties.ListItem;
            var delemans = item1["Delegates"].AsString();
            if (delemans.AsString().IsNullOrWhitespace())
            {
                return;
            }
            char[] split = { '#' };
            string[] deles = delemans.Split(split);
            List<SPPrincipal> principals = new List<SPPrincipal>();
            for (int i = 0; i < deles.Length; i++)
            {
                if (deles[i].IsNullOrWhitespace())
                {
                    continue;
                }
                principals.Add(item1.Web.Users[deles[i]]);
            }

            if (principals.Count > 0)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite site = new SPSite(properties.SiteId))
                    {
                        using (SPWeb web = site.OpenWeb("WorkFlowCenter"))
                        {
                            try
                            {
                                SPListItem item = web.Lists["Travel Request Workflow2"].GetItemById(item1.ID);
                                if (!item.HasUniqueRoleAssignments)
                                {
                                    item.BreakRoleInheritance(true);
                                }

                                SPRoleDefinition AdminRoleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Administrator);
                                SPRoleDefinition GuestRoleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Guest);
                                foreach (SPPrincipal principal in principals)
                                {
                                    SPRoleAssignment RoleAssignment = new SPRoleAssignment(principal);
                                    RoleAssignment.RoleDefinitionBindings.Add(AdminRoleDefinition);
                                    RoleAssignment.RoleDefinitionBindings.Remove(GuestRoleDefinition);
                                    item.RoleAssignments.Remove(principal);
                                    item.RoleAssignments.Add(RoleAssignment);
                                }
                                item["Delegates"] = string.Empty;
                                base.DisableEventFiring();
                                item.Update();
                                base.EnableEventFiring();
                            }
                            catch (Exception ex)
                            {
                                //TO-DO
                            }
                        }
                    }
                });
            }
        }
コード例 #26
0
        private void GiveUserPrivelegesToWorkspace(SPUser user, SPItemEventProperties properties)
        {
            InitializeWebAppProperties(properties);
            string workspaceURL = properties.Web.ServerRelativeUrl;
            //workspaceURL = workspaceURL.Remove(0, emisSiteURL.Length);
            workspaceURL = workspaceURL.Substring(workspaceURL.IndexOf("Agenda-"));

            using (SPSite emisSite = new SPSite(emisSiteURL))
            {
                using (SPWeb currentWorkspace = emisSite.OpenWeb(workspaceURL))
                {
                    currentWorkspace.AllowUnsafeUpdates = true;

                    SPRoleAssignment role;

                    role = new SPRoleAssignment(currentWorkspace.EnsureUser(user.LoginName));

                    role.RoleDefinitionBindings.Add(currentWorkspace.RoleDefinitions["Restricted Contribute"]);

                    currentWorkspace.RoleAssignments.Add(role);
                    currentWorkspace.AllowUnsafeUpdates = false;
                    currentWorkspace.Update();
                }
            }
        }
コード例 #27
0
        public override void ItemAdded(SPItemEventProperties properties)
        {
            if (properties.ListItem == null)
                return;
            using (DisableItemEvent disableItemEvent = new DisableItemEvent())
            {
                foreach (SPField field in properties.ListItem.Fields)
                {
                    var item = properties.ListItem;

                    if (field.TypeAsString == "LinkViewItem")
                    {
                        // Edit form full url
                        //string.Format("{0}{1}?ID={2}", item.Web.Url, item.ParentList.Forms[PAGETYPE.PAGE_EDITFORM].ServerRelativeUrl, item.ID);

                        // Edit form relative url
                        //string.Format("{0}?ID={1}", item.ParentList.Forms[PAGETYPE.PAGE_EDITFORM].ServerRelativeUrl, item.ID);

                        // Display form full url
                        //string url = string.Format("{0}{1}?ID={2}", item.Web.Site.RootWeb.Url, item.ParentList.DefaultDisplayFormUrl, item.ID);
                        //should use this instead: PageType=4
                        string url = string.Format("{0}/_layouts/listform.aspx?PageType=4&ListId={1}&ID={2}", item.Web.Url, item.ParentList.ID.ToString(), item.ID);

                        // Display form relative url
                        //string.Format("{0}?ID={1}", item.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].ServerRelativeUrl, item.ID);
                        properties.ListItem[field.Id] = url;
                        properties.ListItem.SystemUpdate();
                    }
                }
                //base.ItemAdded(properties);
            }
        }
コード例 #28
0
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            CreateMeetingWorkspace(properties);
               CopyToEmisSite(properties);

               base.ItemAdded(properties);
        }
コード例 #29
0
        private SPUser GetSPUser(SPItemEventProperties properties, string key)
        {
            string rawUserName = Convert.ToString(properties.AfterProperties["AssignedTo"]);

            int separatorIndex = rawUserName.IndexOf(";#");
            string claimsUserName = rawUserName.Substring(separatorIndex + 2);

            SPClaimProviderManager claimsManager = SPClaimProviderManager.Local;

            string userName = null;

            if (claimsManager != null)
            {
                userName = claimsManager.DecodeClaim(claimsUserName).Value;
            }

            return properties.Web.EnsureUser(userName);

            //SPContentType martaTaskCT = properties.Web.ContentTypes["MARTATask"];

            //SPFieldUser field = martaTaskCT.Fields[key] as SPFieldUser;

            //if (field != null)
            //{
            //    SPFieldUserValue fieldValue = field.GetFieldValue(Convert.ToString(properties.AfterProperties["AssignedTo"])) as SPFieldUserValue;
            //    if (fieldValue != null)
            //    {
            //        return fieldValue.User;
            //    }
            //}
            //return null;
        }
コード例 #30
0
        public static SPFieldUserValueCollection GetKeyPeopleForAgenda(string agendaType, string agmOffice, SPItemEventProperties eventProperties)
        {
            string masterKeyPeopleListName = null;
            //SPFolder defaultDocuments =rootWeb.RootWeb.Folders["Default Documents"];
            SPWebApplication webApplication = eventProperties.Web.Site.WebApplication;
            if (webApplication.Properties != null && webApplication.Properties.Count > 0)
            {
                masterKeyPeopleListName = webApplication.Properties["MasterKeyPeopleListName"].ToString();
            }

            SPList list = eventProperties.Web.Lists[masterKeyPeopleListName];

            SPFieldUserValueCollection authUsers = new SPFieldUserValueCollection();

            if (list != null)
            {
                foreach (SPListItem item in list.Items)
                {
                    if ((item["Agenda Type"].ToString() == agendaType) && (item["AGM Office"].ToString() == agmOffice) && (item["Position"].ToString() == "Agenda Coordinator"))
                    {
                        string authUsersFieldValue = item["KeyPerson"].ToString();

                        authUsers.Add(new SPFieldUserValue(item.Web, authUsersFieldValue));
                        //break;
                    }
                }
                return authUsers;
            }
            else
                return null;
        }
コード例 #31
0
        private void SendEmail(Customer cust, SPItemEventProperties properties, bool formatMessage)
        {
            string strBody = string.Empty;

            if (properties.ListItem["colBody"] != null)
            {
                strBody = properties.ListItem["colBody"].ToString();
            }

            bool mailSent = SendElasticEmail(
                SENDER_EMAIL,
                SENDER_NAME,
                cust.Email,
                properties.ListItem.Title,
                strBody,
                string.Empty, formatMessage);
        }
コード例 #32
0
        /// <summary>
        /// An item is being added.
        /// </summary>
        public override void ItemAdding(SPItemEventProperties properties)
        {
            // получаем контекст добавленного Айтема
            SPListItem item = properties.ListItem;

            // удаляем родительский файл в папке очереди



            // если папка очереди пуста, то удаляем папку и проверяем создан ли в отчет об архивации в папке архивации


            // если отчет существует - удаляем запись в списке главной библиотеки


            base.ItemAdding(properties);
        }
コード例 #33
0
 private void undoCheckOut(SPItemEventProperties properties)
 {
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         using (SPSite site = new SPSite(properties.WebUrl))
         {
             using (SPWeb web = site.OpenWeb())
             {
                 SPFile _currentFile = web.Lists[properties.ListId].GetItemById(properties.ListItemId).File;
                 if (_currentFile.CheckOutType != SPFile.SPCheckOutType.None)
                 {
                     _currentFile.UndoCheckOut();
                 }
             }
         }
     });
 }
コード例 #34
0
        // Public Methods (3) 

        /// <summary>
        ///     Asynchronous After event that occurs after a new item has been added to its containing object.
        /// </summary>
        /// <param name="properties"></param>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            try
            {
                if (Initialize(true, properties))
                {
                    InsertItem();
                }

                _myWorkReportData.Dispose();
            }
            catch (Exception exception)
            {
                SPSecurity.RunWithElevatedPrivileges(
                    () => LogEvent(exception, 6001, "EPMLive My Work Reporting Item Added"));
            }
        }
コード例 #35
0
        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            Logger.WriteLog(Logger.Category.Information, "ItemUpdated", "Started.");

            try
            {
                //Logger.WriteLog(Logger.Category.Information, "ItemUpdated AfterProperties['vti_sourcecontrolcheckedoutby'] :", properties.AfterProperties["vti_sourcecontrolcheckedoutby"].ToString());
                //Logger.WriteLog(Logger.Category.Information, "ItemUpdated BeforeProperties['vti_sourcecontrolcheckedoutby'] ", properties.BeforeProperties["vti_sourcecontrolcheckedoutby"].ToString());
                //if ((properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null) &&
                //    (properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] != null))
                //{
                Logger.WriteLog(Logger.Category.Information, "ItemUpdated", "Getting settings");
                SharprSettings settings = GetSharprSettingValues(properties);
                //Logger.WriteLog(Logger.Category.Information, "ItemUpdated", "Retrieved settings.");
                //if (properties.ListItem.Level == SPFileLevel.Published)
                //{
                Logger.WriteLog(Logger.Category.Information, "ItemUpdated", "Item is published");
                //Logger.WriteLog(Logger.Category.Information, "ItemAdded", "properties.List.Title is '" + properties.List.Title + "'");
                //Logger.WriteLog(Logger.Category.Information, "ItemAdded", "settings.DocumentListName is '" + settings.DocumentListName + "'");
                //Logger.WriteLog(Logger.Category.Information, "ItemAdded", "properties.List.ID is '" + properties.List.ID + "'");
                if (properties.List.ID.ToString().Equals(settings.DocumentListName))
                {
                    //Logger.WriteLog(Logger.Category.Information, "ItemUpdated", "Calling SendFile");
                    SendFile(properties);
                    //Logger.WriteLog(Logger.Category.Information, "ItemUpdated", "SendFile completed.");
                }
                //}

                //}

                Logger.WriteLog(Logger.Category.Information, "ItemUpdated", "Completed.");
            }
            catch (Exception ex)
            {
                string innerEx = "";
                if (ex.InnerException != null)
                {
                    innerEx = ex.InnerException.Message + Environment.NewLine + ex.InnerException.StackTrace;
                }
                Logger.WriteLog(Logger.Category.Unexpected, "ItemUpdated", ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + innerEx);
            }
            finally
            {
                base.ItemUpdated(properties);
            }
        }
コード例 #36
0
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            if (properties.ListTitle == "Registrations")
            {
                string classId = properties.AfterProperties["Title"].ToString();
                string id      = properties.ListItem["ID"].ToString();
                properties.ListItem["RegistrationId"] = classId + "-" + id;
                properties.ListItem.Update();

                SPList     classesList = properties.Web.Lists["Classes"];
                SPListItem row         = classesList.Items.GetItemById(Convert.ToInt32(classId));
                row["Registrations"] = Convert.ToInt32(row["Registrations"]) + 1;
                row.Update();
            }

            base.ItemAdded(properties);
        }
コード例 #37
0
        }   // cierre WriteFileAgain

        // ----------------------------------------------------------------------------------


        private void DocumentNotSigned(SPItemEventProperties properties)
        {
            properties.ListItem.ParentList.ParentWeb.AllowUnsafeUpdates = true;
            SPFile currentFile = properties.ListItem.File;

            if (currentFile.CheckOutStatus == SPFile.SPCheckOutStatus.None)
            {
                currentFile.CheckOut();
            }

            this.DisableEventFiring();
            currentFile.CheckIn(string.Empty);
            currentFile.Publish(string.Empty);
            currentFile.Deny(string.Empty);
            properties.ListItem.ParentList.ParentWeb.AllowUnsafeUpdates = false;
            this.EnableEventFiring();
        }   // cierre DocumentNotSigned
コード例 #38
0
        public void HandleListItemEventExceptionCanSwapMessage()
        {
            SharePointServiceLocator.ReplaceCurrentServiceLocator(new ActivatingServiceLocator()
                                                                  .RegisterTypeMapping <ILogger, MockLogger>(InstantiationType.AsSingleton));
            MockLogger logger = SharePointServiceLocator.Current.GetInstance <ILogger>() as MockLogger;

            SPItemEventProperties mockSpItemEventProperties = Isolate.Fake.Instance <SPItemEventProperties>(Members.ReturnRecursiveFakes);
            Exception             exception = new Exception("Unhandled Exception Occured.");

            ListExceptionHandler exceptionHandler = new ListExceptionHandler();

            exceptionHandler.HandleListItemEventException(exception, mockSpItemEventProperties, "New Message");

            Assert.AreEqual("New Message", mockSpItemEventProperties.ErrorMessage);
            Assert.IsTrue(mockSpItemEventProperties.Cancel);
            Assert.AreEqual("Unhandled Exception Occured.", logger.ErrorMessage);
        }
コード例 #39
0
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            if (properties.ListTitle == "Registration")
            {
                string classId = properties.ListItem["RegistrationID"].ToString();
                string id      = properties.ListItem["ID"].ToString();
                properties.ListItem["ID"] = classId + "-" + id;
                properties.ListItem.Update();

                SPWeb      web   = properties.Web;
                SPList     clist = web.Lists["Classes"];
                SPListItem item  = clist.GetItemById(Convert.ToInt32(classId));
                item["Registrations"] = Convert.ToInt32(item["Registrations"].ToString()) + 1;
                item.Update();
            }
            base.ItemAdded(properties);
        }
コード例 #40
0
        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            try {
                var requiresProcessing = false;
                if (properties.ListItem[SPBuiltInFieldId.File_x0020_Type].ToString().ToUpper() == "PDF")
                {
                    using (StreamReader sr = new StreamReader(properties.ListItem.File.OpenBinaryStream()))
                    {
                        string tempRead = sr.ReadLine();
                        if (tempRead == @"%PDF-1.3")
                        {
                            Util.LogError($"{properties.ListItem.File.Name} at {properties.WebUrl}/{properties.ListItem.Url} being updated because PDF version was ${tempRead}", Util.ErrorLevel.Info);
                            requiresProcessing = true;
                        }
                    }

                    if (requiresProcessing)
                    {
                        if (Util.InstantiateLicense(properties.Web))
                        {
                            // Read the entire file into a byte array
                            var binaryContent = properties.ListItem.File.OpenBinary();
                            // Increment the version number YAY Magic Numbers!!!
                            binaryContent[7]++;
                            // Read the bytes in as a stream to an Aspose PDF document
                            Aspose.Pdf.Document toBook = new Aspose.Pdf.Document(new MemoryStream(binaryContent));
                            // Reassess the metatable
                            toBook.ProcessParagraphs();
                            // Repair anything that the above line missed
                            toBook.Repair();
                            // Save out the new PDF to a stream
                            using (var ms = new MemoryStream())
                            {
                                toBook.Save(ms);
                                properties.ListItem.File.SaveBinary(ms);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Util.LogError($"PDF Version Correction for file {properties.WebUrl}/{properties.ListItem.Url}: {ex.Message}");
            }
        }
コード例 #41
0
        private void CallDynamicEventreceiver(SPItemEventProperties properties)
        {
            var dynEventReceiver = IronRuntime.GetDefaultIronRuntime(properties.Web.Site).CreateDynamicInstance(properties.ReceiverData) as SPItemEventReceiver;

            switch (properties.EventType)
            {
            case SPEventReceiverType.ItemAdded: dynEventReceiver.ItemAdded(properties); break;

            case SPEventReceiverType.ItemUpdated: dynEventReceiver.ItemUpdated(properties); break;

            case SPEventReceiverType.ItemDeleted: dynEventReceiver.ItemDeleted(properties); break;

            case SPEventReceiverType.ItemFileMoved: dynEventReceiver.ItemFileMoved(properties); break;

            case SPEventReceiverType.ItemCheckedIn: dynEventReceiver.ItemCheckedIn(properties); break;

            case SPEventReceiverType.ItemCheckedOut: dynEventReceiver.ItemCheckedOut(properties); break;

            case SPEventReceiverType.ItemAdding: dynEventReceiver.ItemAdding(properties); break;

            case SPEventReceiverType.ItemUpdating: dynEventReceiver.ItemUpdating(properties); break;

            case SPEventReceiverType.ItemDeleting: dynEventReceiver.ItemDeleting(properties); break;

            case SPEventReceiverType.ItemFileMoving: dynEventReceiver.ItemFileMoving(properties); break;

            case SPEventReceiverType.ItemCheckingIn: dynEventReceiver.ItemCheckingIn(properties); break;

            case SPEventReceiverType.ItemCheckingOut: dynEventReceiver.ItemCheckingOut(properties); break;

            case SPEventReceiverType.ItemUncheckedOut: dynEventReceiver.ItemUncheckedOut(properties); break;

            case SPEventReceiverType.ItemUncheckingOut: dynEventReceiver.ItemUncheckingOut(properties); break;

            case SPEventReceiverType.ItemAttachmentAdded: dynEventReceiver.ItemAttachmentAdded(properties); break;

            case SPEventReceiverType.ItemAttachmentAdding: dynEventReceiver.ItemAttachmentAdding(properties); break;

            case SPEventReceiverType.ItemAttachmentDeleted: dynEventReceiver.ItemAttachmentDeleted(properties); break;

            case SPEventReceiverType.ItemAttachmentDeleting: dynEventReceiver.ItemAttachmentDeleting(properties); break;

            case SPEventReceiverType.ItemFileConverted: dynEventReceiver.ItemFileConverted(properties); break;
            }
        }
コード例 #42
0
        /// <summary>
        ///     На самом деле это синхронный метод. Аналог ItemUpdating
        /// </summary>
        /// <param name="properties"></param>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            List <SyncType> syncTypes = SettingsProvider.Instance(properties.Web).CacheType(properties.List);

            using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
            {
                if (properties.ListItem.Fields.ContainsField(Fields.IsUpdated))
                {
                    bool   needSetIsUpdated = false;
                    object isUpdatedObj     = properties.ListItem.Properties[Fields.IsUpdated];
                    if (isUpdatedObj != null)
                    {
                        bool isUpdated;
                        if (bool.TryParse(isUpdatedObj.ToString(), out isUpdated))
                        {
                            if (!isUpdated)
                            {
                                needSetIsUpdated = true;
                            }
                        }
                    }
                    else
                    {
                        needSetIsUpdated = true;
                    }

                    if (needSetIsUpdated)
                    {
                        properties.ListItem[Fields.IsUpdated] = true;
                        properties.ListItem.Update();
                    }

                    //Если у элемента не проставлено значение в поле ItemUniqueID, то проставляем его.
                    //Такая ситуация может произойти со старыми элементами.
                    if (properties.ListItem[Constants.ItemUniqueIDFieldName] == null ||
                        string.IsNullOrEmpty(Convert.ToString(properties.ListItem[Constants.ItemUniqueIDFieldName])))
                    {
                        properties.ListItem[Constants.ItemUniqueIDFieldName] = properties.ListItem.UniqueId;
                        properties.ListItem.Update();
                    }
                }
            }
            this.Synchronize(properties, syncTypes, SyncActionType.Update);
        }
コード例 #43
0
        public override void ItemAdded(SPItemEventProperties properties)
        {
            this.EventFiringEnabled = false;

            SPWorkflow wf;

            try
            {
                switch (properties.ListItem.ContentType.Name)
                {
                case "Generowanie formatek rozliczeniowych":
                    wf = BLL.Workflows.StartWorkflow(properties.ListItem, "Generuj formatki rozliczeniowe");
                    Debug.WriteLine("StartWorkflow: Generuj formatki rozliczeniowe " + wf.InternalState.ToString());
                    break;

                case "Generowanie formatek rozliczeniowych dla klienta":
                    wf = BLL.Workflows.StartWorkflow(properties.ListItem, "Generuj formatki rozliczeniowe dla klienta");
                    Debug.WriteLine("StartWorkflow: Generuj formatki rozliczeniowe dla klienta " + wf.InternalState.ToString());
                    break;

                case "Obsługa wiadomości":
                    wf = BLL.Workflows.StartSiteWorkflow(properties.Web.Site, "Obsługa wiadomości oczekujących", properties.ListItemId.ToString());
                    //wf = BLL.Workflows.StartSiteWorkflow(properties.Web.Site, "Obsługa wiadomości oczekujących", null);
                    Debug.WriteLine("StartWorkflow: Generuj formatki rozliczeniowe dla klienta " + wf.InternalState.ToString());
                    break;

                case "Przygotuj wiadomości z kart kontrolnych":
                    wf = BLL.Workflows.StartSiteWorkflow(properties.Web.Site, "Obsługa kart kontrolnych", properties.ListItemId.ToString());
                    Debug.WriteLine("StartWorkflow: Generuj formatki rozliczeniowe dla klienta " + wf.InternalState.ToString());
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                BLL.Logger.LogEvent(properties.WebUrl, ex.ToString());
                var result = ElasticEmail.EmailGenerator.ReportError(ex, properties.WebUrl.ToString());
                BLL.Tools.Set_Text(properties.ListItem, "enumStatusZlecenia", _ANULOWANY);
                properties.ListItem.Update();
            }

            this.EventFiringEnabled = true;
        }
コード例 #44
0
        /// <summary>
        /// An item is being deleted.
        /// </summary>
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            base.ItemDeleting(properties);

            this.EventFiringEnabled = false;

            if (properties.ListTitle != "Skany")
            {
                try
                {
                    SPListItem item      = properties.ListItem;
                    string     tokenName = item["Nazwa"].ToString();

                    //update SkanDoAnalizy

                    using (SPSite site = new SPSite(properties.SiteId))
                    {
                        using (SPWeb web = site.AllWebs[properties.Web.ID])
                        {
                            SPList list = web.Lists["SkanDoAnalizy"];

                            StringBuilder sb = new StringBuilder(@"<OrderBy><FieldRef Name=""ID"" /></OrderBy><Where><And><And><Eq><FieldRef Name=""Token_x0020_zg_x0142_oszenia"" /><Value Type=""Text"">___TokenZgloszenia___</Value></Eq><Neq><FieldRef Name=""Batch_Completed"" /><Value Type=""Boolean"">1</Value></Neq></And><Neq><FieldRef Name=""IsDeleted"" /><Value Type=""Boolean"">1</Value></Neq></And></Where>");
                            sb.Replace("___TokenZgloszenia___", tokenName);
                            string camlQuery = sb.ToString();

                            SPQuery query = new SPQuery();
                            query.Query = camlQuery;

                            SPListItemCollection items = list.GetItems(query);
                            foreach (SPListItem myItem in items)
                            {
                                myItem["IsDeleted"] = true;
                                myItem.Update();
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                this.EventFiringEnabled = true;
            }
        }
コード例 #45
0
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            using (SPSite siteCollection = new SPSite("http://mysites.innotech.cloud/sites/edmonton"))
            {
                //Collection of lists fom the Site
                SPWeb  topSite = siteCollection.RootWeb;
                SPList list1   = topSite.Lists["NotificationEnabled"];
                SPListItemCollection items1 = list1.Items;
                int   c          = 0;
                int[] arrayitems = new int[list1.ItemCount];

                foreach (SPListItem item in items1) //Email recipients list
                {
                    arrayitems[c] = item.ID;
                    c++;
                }

                int maxValue = arrayitems.Max();
                var itemID   = maxValue;

                SPListItem notificationEnabled = list1.GetItemByIdSelectedFields(itemID, "EmailRecipient");
                var        list1EmailReceipt   = notificationEnabled["EmailRecipient"];

                SPList list2 = topSite.Lists["Email Recipients"];
                SPListItemCollection items = list2.Items;

                //Iterate through each list item on both lists to find matching list items!
                using (StreamWriter w = File.AppendText(@"C:\\Testing" + "\\" + "Log_File_Name.txt"))
                {
                    foreach (SPListItem item in items) //Email recipients list
                    {
                        SPListItem emailRecipient    = list2.GetItemByIdSelectedFields(item.ID, "EmailAddress");
                        var        list2EmailReceipt = emailRecipient["EmailAddress"];

                        if (list2EmailReceipt != null)
                        {
                            if (list1EmailReceipt.ToString().Trim().ToUpper() == (list2EmailReceipt.ToString().Trim().ToUpper()))
                            {
                                w.WriteLine("An email would have been sent to " + item["EmailAddress"].ToString() + " at {0} {1} ", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString());
                            }
                        }
                    }
                }
            }
        }
コード例 #46
0
        private void IncreaseItemOrderNo(SPItemEventProperties properties, bool isUpdate)
        {
            if (properties.AfterProperties[Constants.ORDER_NUMBER_COLUMN] != null && !string.IsNullOrEmpty(properties.AfterProperties[Constants.ORDER_NUMBER_COLUMN].ToString()))
            {
                int orderNo = 0;
                int.TryParse(properties.AfterProperties[Constants.ORDER_NUMBER_COLUMN].ToString(), out orderNo);

                if (orderNo != 0)
                {
                    string strItemId = properties.ListItem == null ? "0" : properties.ListItemId.ToString();

                    string caml           = string.Empty;
                    var    expressionsAnd = new List <Expression <Func <SPListItem, bool> > >();

                    expressionsAnd.Add(x => ((int)x[Constants.ORDER_NUMBER_COLUMN]) >= orderNo);
                    expressionsAnd.Add(x => (x["ID"]) != (DataTypes.Counter)strItemId);

                    caml = Camlex.Query().WhereAll(expressionsAnd).OrderBy(x => x[Constants.ORDER_NUMBER_COLUMN] as Camlex.Asc).ToString();

                    SPQuery spQuery = new SPQuery();
                    spQuery.Query = caml;

                    SPList currentList         = properties.List;
                    SPListItemCollection items = currentList.GetItems(spQuery);

                    foreach (SPListItem item in items)
                    {
                        orderNo++;

                        using (DisableItemEvent scope = new DisableItemEvent())
                        {
                            item[Constants.ORDER_NUMBER_COLUMN] = orderNo;
                            item.SystemUpdate(false);
                        }
                    }
                }
            }
            else
            {
                if (!isUpdate)
                {
                    properties.AfterProperties[Constants.ORDER_NUMBER_COLUMN] = GetLatestItemOrderNo(properties) + 1;
                }
            }
        }
コード例 #47
0
ファイル: WriteDept.cs プロジェクト: va-vs/VAProjects
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            base.ItemDeleting(properties);
            SPUser loginUser = properties.Web.CurrentUser;
            string loginInfo = loginUser.ID + ";#" + loginUser.Name;
            SPList lstNews   = properties.List;//
            bool   hasRight  = UserHaveApproveRight(properties.SiteId, properties.Web.Name, properties.List.Title, loginUser);
            string modeState = properties.ListItem["审批状态"].ToString();

            if (modeState == "0" && !hasRight)//审批通过
            {
                //properties.Status = SPEventReceiverStatus.CancelWithError;
                // properties.ErrorMessage = "此新闻已经审批,您无权删除!";
                properties.Status = SPEventReceiverStatus.CancelNoError;
                //properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
                //properties.RedirectUrl = "/_layouts/15/CustError/error.aspx?ErrMsg='文件不存在'";
            }
        }
コード例 #48
0
        private static void WriteSharprSettingValue(SPItemEventProperties properties, string title, string value)
        {
            //by convention, we're going to assume settings are stored in a list within the same site called "Sharpr Settings"
            using (SPWeb web = properties.Site.OpenWeb())
            {
                SPList   list   = web.Lists["Sharpr Settings"];
                string[] fields = { "Title", "Value" };

                foreach (SPListItem li in list.GetItems(fields))
                {
                    if (((string)li["Title"]) == title)
                    {
                        li["Value"] = value;
                        li.Update();
                    }
                }
            }
        }
コード例 #49
0
 public override void ItemUpdated(SPItemEventProperties properties)
 {
     if (properties.ListItem != null)
     {
         if (properties.List.BaseType == SPBaseType.DocumentLibrary && Boolean.TrueString.Equals(properties.ListItem.Properties[InitializeKey]))
         {
             HandleEvent(properties, SPModelEventType.Added);
         }
         else if (isPublishingEvent)
         {
             HandleEvent(properties, SPModelEventType.Published);
         }
         else
         {
             HandleEvent(properties, SPModelEventType.Updated);
         }
     }
 }
コード例 #50
0
        /// <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);
        }
コード例 #51
0
        public override void ItemAdded(SPItemEventProperties properties)
        {
            // add item to cache..
            //TODO:Remove
            //HttpRuntime runtime = new HttpRuntime();

            string category = properties.AfterProperties[SPSConfigurationManager.FIELD_CATEGORY] as string;
            string key      = properties.AfterProperties[SPSConfigurationManager.FIELD_KEY] as string;
            string cacheKey = SPSConfigurationManager.FormatKey(category, key);
            string value    = properties.AfterProperties[SPSConfigurationManager.FIELD_VALUE] as string;

            if (value != null)
            {
                HttpRuntime.Cache.Insert(cacheKey, value, null, DateTime.MaxValue, Cache.NoSlidingExpiration);
            }

            base.ItemAdded(properties);
        }
コード例 #52
0
ファイル: PerformList.cs プロジェクト: va-vs/VAProjects
        /// <summary>
        /// 正在删除项.
        /// </summary>
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            base.ItemDeleting(properties);
            if (!hasChildList(properties))
            {
                return;
            }
            SPUser loginUser          = properties.Web.CurrentUser;
            SPListItemCollection item = GetAppraiseRecord("审核", properties, 0, "通过");

            bool hasRight = UserHaveApproveRight(properties.SiteId, properties.Web.Name, properties.List.Title, loginUser); //具有网站级审批权限的用户保留删除的权限

            if (item != null && !hasRight)                                                                                  //审批通过
            {
                properties.Status       = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage = "该记录已通过审核,您无权删除!";
            }
        }
コード例 #53
0
ファイル: PerformList.cs プロジェクト: va-vs/VAProjects
        private bool hasChildList(SPItemEventProperties properties)
        {
            string siteUrl = properties.Site.Url;       // SPContext.Current.Site.Url;

            using (SPSite spSite = new SPSite(siteUrl)) //找到网站集
            {
                using (SPWeb spWeb = spSite.OpenWeb(properties.Web.ID))
                {
                    string childListName = properties.List.Title + "业绩";
                    SPList spList        = spWeb.Lists.TryGetList(childListName);
                    if (spList != null)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
コード例 #54
0
 /// <summary>
 /// An item is being added.
 /// </summary>
 public override void ItemAdding(SPItemEventProperties properties)
 {
     try
     {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             TaxonomySession session       = new TaxonomySession(properties.Web.Site);
             TermStore mainTermStore       = session.TermStores[0];
             Group siteGroup               = mainTermStore.GetSiteCollectionGroup(properties.Web.Site);
             TermSet issuingCompanyTermSet = GetTermSetByName("Issuing Company", siteGroup);
             if (issuingCompanyTermSet != null)
             {
                 string newTerm    = properties.AfterProperties["Title"].ToString();
                 Term matchingTerm = GetTermByName(newTerm, issuingCompanyTermSet);
                 if (matchingTerm != null)
                 {
                     if (matchingTerm.IsDeprecated)
                     {
                         matchingTerm.Deprecate(false);
                         mainTermStore.CommitAll();
                     }
                     else
                     {
                         throw new Exception(string.Format("Issuing Company with name {0} already exists.", newTerm));
                     }
                 }
                 else
                 {
                     issuingCompanyTermSet.CreateTerm(newTerm, 1033);
                     mainTermStore.CommitAll();
                 }
             }
             else
             {
                 throw new Exception("There was an error connecting to the SharePoint Managed Metadata Service");
             }
         });
     }
     catch (Exception taxonomyException)
     {
         properties.ErrorMessage = taxonomyException.Message;
         properties.Status       = SPEventReceiverStatus.CancelWithError;
     }
 }
コード例 #55
0
 protected void update_permission(SPItemEventProperties properties)
 {
     SPSecurity.RunWithElevatedPrivileges(delegate
     {
         using (SPSite site = new SPSite(properties.SiteId))
         {
             using (SPWeb web = site.OpenWeb("/projects"))
             {
                 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);
                         }
                     }
                     Guid field_guid = new Guid("{ef0a1009-f36d-46e2-bc7a-c66c258b69f6}");
                     SPFieldLookupValue project_lookup_value = item.Fields[field_guid].GetFieldValue(item[field_guid].ToString()) as SPFieldLookupValue;
                     SPListItem project = web.Lists[new Guid("{7ec93e5f-8fb7-4231-b0fe-9364a370d0e7}")].Items.GetItemById(project_lookup_value.LookupId);
                     // 分别为各个角色赋予此项目的独特权限:。
                     assign_role(site, item, project, "ProjectManager", "{3c3ac491-4910-4ddb-b28f-1e7328ff26d5}", web.RoleDefinitions["设计"]);
                     assign_roles(web, item, project, "ProjectMembers", "{7494dd0e-3c92-4556-b1cb-dd9e10b10d7f}", web.RoleDefinitions["读取"]);
                     assign_roles(web, item, project, "ProjectSupervisers", "{89ae4bfd-6243-4dce-aa79-c980aeff7584}", web.RoleDefinitions["参与讨论"]);
                     assign_roles(web, item, project, "ProjectVisitors", "{72bddba3-d5d3-465b-ac1b-331a1c403fe9}", web.RoleDefinitions["读取"]);
                     log(web.Site, "更新项目状态权限", "消息", "为项目【" + project["Title"] + "】更新权限完成。");
                 }
                 catch (Exception ex)
                 {
                     log(site, "自动删除项目状态旧权限", "错误", ex.ToString());
                 }
             }
         }
     });
 }
コード例 #56
0
        //private void SetUrlFieldMessage(SPItemEventProperties properties)
        //{
        //    EventFiringEnabled = false;

        //    SPSecurity.RunWithElevatedPrivileges(() =>
        //    {
        //        using (SPSite s = new SPSite(properties.SiteId))
        //        {
        //            using (SPWeb w = s.OpenWeb(properties.Web.ID))
        //            {
        //                SPList l = w.Lists[properties.ListId];
        //                SPListItem i = l.GetItemById(properties.ListItemId);
        //                if (!FieldExistsInList(l, "WorkspaceUrl"))
        //                {
        //                    string fldWorkspaceUrlIntName = l.Fields.Add("WorkspaceUrl", SPFieldType.URL, false);
        //                    SPFieldUrl fldWorkspaceUrl = l.Fields.GetFieldByInternalName(fldWorkspaceUrlIntName) as SPFieldUrl;
        //                    fldWorkspaceUrl.Update();
        //                }
        //                i["WorkspaceUrl"] = new SPFieldUrlValue() { Description = "Waiting for security to complete." };
        //                i.SystemUpdate();
        //            }
        //        }
        //    });

        //    EventFiringEnabled = true;
        //}

        private bool Initialize(SPItemEventProperties properties)
        {
            try
            {
                _siteId    = properties.SiteId.ToString();
                _webId     = properties.Web.ID.ToString();
                _listId    = properties.ListId.ToString();
                _itemTitle = properties.ListItem.Title;
                _itemId    = properties.ListItem.ID.ToString();
                _settings  = new GridGanttSettings(properties.List);

                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    using (var s = new SPSite(properties.SiteId))
                    {
                        using (var lockedWeb = s.OpenWeb(CoreFunctions.getLockedWeb(properties.Web)))
                        {
                            _createFromLiveTemp = CoreFunctions.getConfigSetting(lockedWeb, "EPMLiveUseLiveTemplates");
                        }
                    }
                });

                _creationParams = "<Data>" +
                                  "<Param key=\"IsStandAlone\">false</Param>" +
                                  "<Param key=\"TemplateSource\">downloaded</Param>" +
                                  "<Param key=\"TemplateItemId\">" + _settings.AutoCreationTemplateId + "</Param>" +
                                  "<Param key=\"IncludeContent\">True</Param>" +
                                  "<Param key=\"SiteTitle\">" + _itemTitle + "</Param>" +
                                  "<Param key=\"AttachedItemId\">" + _itemId + "</Param>" +
                                  "<Param key=\"AttachedItemListGuid\">" + _listId + "</Param>" +
                                  "<Param key=\"WebUrl\">" + properties.Web.Url + "</Param>" +
                                  "<Param key=\"WebId\">" + properties.Web.ID.ToString() + "</Param>" +
                                  "<Param key=\"SiteId\">" + _siteId.ToString() + "</Param>" +
                                  "<Param key=\"CreatorId\">" + properties.Web.CurrentUser.ID.ToString() + "</Param>" +
                                  "<Param key=\"CreateFromLiveTemp\">" + _createFromLiveTemp + "</Param>" +
                                  "<Param key=\"UniquePermission\">" + _settings.BuildTeamSecurity.ToString() + "</Param>" +
                                  "</Data>";
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #57
0
        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            SPListItem             item        = properties.List.GetItemById(properties.ListItemId);
            SPAttachmentCollection attachments = item.Attachments;
            SPList destinationList             = item.Web.Lists["Contract Documents"];

            for (int i = 0; i < attachments.Count; i++)
            {
                SPFile file = item.ParentList.ParentWeb.GetFile(item.Attachments.UrlPrefix + item.Attachments[i].ToString());
                string destinationLocation = destinationList.RootFolder.ServerRelativeUrl + "/" + file.Name;
                file.MoveTo(destinationLocation, true);
                SPFile     newFile = destinationList.ParentWeb.GetFile(destinationLocation);
                SPListItem newItem = newFile.Item;
                newItem["Contract"] = item.ID;
                newItem["Title"]    = newItem.File.Name;
                newItem.Update();
            }
        }
コード例 #58
0
        /// <summary>
        /// 获取当前用户的信息
        /// </summary>
        /// <param name="properties"></param>
        /// <param name="lgName"></param>
        /// <returns></returns>
        private List <string> GetUserInfo(SPItemEventProperties properties, string lgName)
        {
            //string listName = properties.ListTitle;
            string listTeachers           = "教师花名册";
            string siteUrl                = properties.Site.Url;
            SPListItemCollection retItems = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(siteUrl)) //找到网站集
                {
                    using (SPWeb spWeb = spSite.OpenWeb(""))
                    {
                        SPQuery qry = new SPQuery();
                        SPListItemCollection listItems;

                        #region teachers
                        SPList spTeacherList = spWeb.Lists.TryGetList(listTeachers);

                        qry       = new SPQuery();
                        qry.Query = @"<Where><Eq><FieldRef Name='EmpNO' /><Value Type='Text'>" + lgName + "</Value></Eq></Where>";
                        listItems = spTeacherList.GetItems(qry);
                        if (listItems.Count > 0)//获取系部下的教师
                        {
                            retItems = listItems;
                        }
                        #endregion
                    }
                }
            });
            List <string> userIDs = new List <string>();
            if (retItems != null)
            {
                foreach (SPListItem item in retItems)
                {
                    string dep = item["Department"].ToString();
                    userIDs.Add(dep.Substring(dep.IndexOf(";#") + 2));//查阅项需要解析
                    userIDs.Add(item["性别"] != null ? item["性别"].ToString() : "");
                    userIDs.Add(item["Duty"] != null ? item["Duty"].ToString() : "");
                }
            }
            return(userIDs);
        }
コード例 #59
0
        /// <summary>
        /// Asynchronous After event that occurs after a new item has been added to its containing object.
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPItemEventProperties"></see> object that represents properties of the event handler.</param>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            SPList                   currentList = properties.ListItem.ParentList;
            SiteCreationEngine       engine      = new SiteCreationEngine(currentList);
            SiteCreationEventActions actions     = new SiteCreationEventActions();

            string siteTitleValue    = properties.ListItem[engine.SiteField].ToString();
            string siteTemplateValue = properties.ListItem[engine.TemplateField].ToString();

            if (string.IsNullOrEmpty(siteTitleValue))
            {
                throw new ArgumentException(SiteCreationEngine.GetResourceString("ErrCantBeEmpty"));
            }

            Dictionary <string, string> templates = engine.GetTemplates();

            if (!templates.ContainsKey(siteTemplateValue))
            {
                throw new ArgumentException(SiteCreationEngine.GetResourceString("ErrBadTemplateDefinition"));
            }

            DebugData(engine, properties, siteTitleValue, templates[siteTemplateValue]);

            SPWeb web;

            web = actions.CreateWeb(properties.WebUrl,
                                    siteTitleValue,
                                    templates[siteTemplateValue],
                                    engine.OptUniquePermissions,
                                    engine.OptForceDup);

            properties.ListItem[engine.UrlField] = web.Url;
            properties.ListItem.Update();

            if (engine.OptOnQuickLaunch)
            {
                actions.AddOnQuickLaunchBar(web);
            }

            actions.SetUseSharedNavbar(web, engine.OptUseSharedNavBar);

            base.ItemAdded(properties);
        }
コード例 #60
0
ファイル: SetItemIdHandler.cs プロジェクト: renshan2/ecase2
        public static void HandleItemMoving(SPItemEventProperties properties)
        {
            string   destinationString = properties.AfterUrl.Substring(0, properties.AfterUrl.LastIndexOf("/"));
            SPFolder destinationFolder = properties.Web.GetFolder(destinationString);
            bool     updateRequired    = false;

            //if we are dealing with a document set, we need to do a few things
            int nextNumber = 1;

            if (properties.ListItem.File != null && SPFolderExtensions.IsDocumentSetFolder(destinationFolder))
            {
                // handle our SetItemID
                SPList  docSetList = properties.List;
                SPQuery query      = new SPQuery();
                query.RowLimit = 1;
                query.Folder   = destinationFolder;
                query.Query    = "<OrderBy><FieldRef Name='SetItemID' Ascending='FALSE' /></OrderBy>";
                SPListItemCollection Items = docSetList.GetItems(query);
                if (Items.Count > 0)
                {
                    SPListItem item = Items[0];
                    nextNumber = Convert.ToInt32(item["SetItemID"]) + 1;
                }

                properties.ListItem["SetItemID"] = nextNumber.ToString();
                updateRequired = true;
            }
            else
            {
                if (properties.ListItem["SetItemID"] != null && !string.IsNullOrEmpty(properties.ListItem["SetItemID"].ToString()))
                {
                    properties.ListItem["SetItemID"] = null;
                    updateRequired = true;
                }
            }

            if (updateRequired)
            {
                properties.ListItem.Update();
            }

            ReOrderSetItemID(properties, true);
        }