Distribute Permission Instance (EventHandler)

13717 단어 Permission
SharePoint의 EventHandler는 주로 Web Level, List Level, List Item Level, Email 몇 가지가 있습니다.SharePoint의 이벤트 핸들러는 주로 SP Web Event Receiver, SP Email Event Receiver, SP List Event Receiver와 SP Item Event Receiver 클래스를 계승하여 그 중의 상응하는 방법을 실현하여 우리의 수요를 완성하는 것이다.
ModifiedPermissions:
using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

using System.IO;



namespace Anson.EventReceiver

{

    public class ModifiedPermission:SPItemEventReceiver

    {



        string strGroupName = "Home Owners";

        public override void ItemAdded(SPItemEventProperties properties)

        {

            SPWeb myWeb = null;

            SPSite mySite = null;            

            try

            {

                SPSecurity.RunWithElevatedPrivileges(delegate()

                {

                    mySite = new SPSite(properties.ListItem.Web.Site.ID);

                    myWeb = mySite.AllWebs[properties.ListItem.Web.ID];

                    string currentUser = properties.ListItem.Web.CurrentUser.LoginName;

                    SPListItem myListItem = myWeb.Lists[properties.ListId].GetItemById(properties.ListItemId);

                    myWeb.AllowUnsafeUpdates = true;

                    myListItem.BreakRoleInheritance(true);



                    //Clear new listItem all the RoleAssignment 

                    while (myListItem.RoleAssignments.Count>0)

                    {

                        myListItem.RoleAssignments.Remove(0);

                    }



                    //Add Home Owner Group RoleAssignment

                    SPGroup oOwnerGroup=myWeb.SiteGroups[strGroupName];

                    if (oOwnerGroup!=null)

                    {

                        SPRoleAssignment oRoleGroup = new SPRoleAssignment(oOwnerGroup);

                        oRoleGroup.RoleDefinitionBindings.Add(myWeb.RoleDefinitions["Full Control"]);

                        myListItem.RoleAssignments.Add(oRoleGroup);

                    }

                    //Add  Author RoleAssignment

                    SPRoleAssignment authorRoleAssignment = new SPRoleAssignment(myWeb.SiteUsers[currentUser]);

                    authorRoleAssignment.RoleDefinitionBindings.Add(myWeb.RoleDefinitions["Full Control"]);

                    myListItem.RoleAssignments.Add(authorRoleAssignment);



                    myWeb.Update();

                    myWeb.AllowUnsafeUpdates = false;

                    

                });

            }

            catch (Exception ex)

            {



                log(ex.Message);

            }

            

        }

        public override void ItemDeleting(SPItemEventProperties properties)

        {

       

            try

            {

                

                string oCurrentUser = properties.ListItem.Web.CurrentUser.Name;



                string authorName = properties.ListItem["Created By"].ToString();

                authorName = authorName.Substring(authorName.IndexOf(";#") + 2);

                if (oCurrentUser != authorName)

                {

                    properties.Cancel = true;

                    properties.ErrorMessage = "You have not enough permission to delete!";

                }

            }

            catch (Exception ex)

            {

                log("ItemDeleting Method Error Message:"+ex.Message+DateTime.Now.ToString());

            }

        }

        private  void log(string ErrorMessage)

        {

            FileStream FS = null;

            StreamWriter SW = null;

            try

            {

                SPSecurity.RunWithElevatedPrivileges

                    (

                    delegate

                    {

                        FS = File.Open("c:\\Error.txt", FileMode.Append);

                        SW = new StreamWriter(FS);

                        SW.Write(ErrorMessage+"\r
"); SW.Close(); SW.Dispose(); FS.Close(); FS.Dispose(); } ); } catch { } finally { SW = null; FS = null; } } } }

 
 
EventReceiveManger.cs---이것은 모바일 EventReceiver를 추가하는 관리 클래스입니다.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;

namespace Anson.EventReceiver
{
class EventReceiverManager
{

public static bool SetEventReceiver(SPList list,Type t,params SPEventReceiverType[] eventType)
{

try
{
string assembly = t.Assembly.FullName;
string className = t.FullName;
SPEventReceiverDefinitionCollection ERCollection = list.EventReceivers;
SPEventReceiverDefinition def = null;
for (int i = 0; i < ERCollection.Count; i++)
{
def = ERCollection[i];
if (def.Class==className)
{
def.Delete();
}
}

foreach (SPEventReceiverType ET in eventType)
{
list.EventReceivers.Add(ET, assembly, className);

}
list.Update();
return true;

}
catch (Exception ex)
{
log("SetEventReceiverError:" + ex.Message + "\r
");
return false;
}
}

public static bool RemoveEventReceivers(SPList list ,Type t)
{
try
{
string assembly = t.Assembly.FullName;
string className = t.FullName;
SPEventReceiverDefinitionCollection ERCollection = list.EventReceivers;
SPEventReceiverDefinition def = null;
for (int i = 0; i < ERCollection.Count; i++)
{
def = ERCollection[i];
if (def.Class==className)
{
def.Delete();
}
}
list.Update();
return true;
}
catch (Exception ex)
{

log("RemoveEventReceivrs Method Error:"+ex.Message+"\r
");
return false;
}

}


#region Log Method
public static void log(string ErrorMessage)
{
FileStream FS = null;
StreamWriter SW = null;
try
{
SPSecurity.RunWithElevatedPrivileges
(
delegate
{
FS = File.Open("c:\\Error.txt", FileMode.Append);
SW = new StreamWriter(FS);
SW.Write(ErrorMessage + "\r
");
SW.Close();
SW.Dispose();
FS.Close();
FS.Dispose();
}
);
}
catch
{
}
finally
{
SW = null;
FS = null;
}
}
#endregion
}

}

 
EventReceiverInstall.cs--이것은 Feature를 설치하는 클래스입니다.
using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;





namespace Anson.EventReceiver

{

    class EventReceiverInstall:SPFeatureReceiver

    {

        string CustomListName = "AnsonList";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)

        {

            SPSite mySite = properties.Feature.Parent as SPSite;

            SPList myList = mySite.RootWeb.Lists[CustomListName];

            SPEventReceiverType[] types={SPEventReceiverType.ItemDeleting,SPEventReceiverType.ItemAdded};

            if (myList!=null)

            {

                EventReceiverManager.SetEventReceiver(myList,

                    typeof(ModifiedPermission), types);

            }

            else

            {

                return;

            }

        }



        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

        {

            SPSite mySite = properties.Feature.Parent as SPSite;

            SPList myList = mySite.RootWeb.Lists[CustomListName];

            if (myList != null)

            {

                EventReceiverManager.RemoveEventReceivers(myList, typeof(ModifiedPermission));

            }

            else

            {

                return;

            }



        }



        public override void FeatureInstalled(SPFeatureReceiverProperties properties)

        {

            

        }



        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)

        {

            

        }

    }

}




 
 
Feature.xml-이것은 Feature와 유사한 구조이고 다른 구조 작성법도 있습니다. 저는 이런 것을 습관적으로 사용합니다.
<?xml version="1.0" encoding="utf-8"?>

<Feature Scope="Site"

  Title="Anson.EventReceiver ModifedPermission"

  Id="615208F2-85DD-42c5-9590-1F9B0BC725B0" Description="It is Created by Ansom ,Use in the list of AnsonList"

  xmlns="http://schemas.microsoft.com/sharepoint/"

 Hidden="FALSE"

 Version="1.0.0.0"

 ReceiverAssembly="Anson.EventReceiver, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5abfd538ff01cc7c"

 ReceiverClass="Anson.EventReceiver.EventReceiverInstall">

</Feature>


 
배포:
1. 강명한다.
2. DLL 파일을 GAC에 배치
3. IIS,command:iisreset 재부팅
3. 기능을 포함한다.xml 파일의 폴더 DistributePermission을 12\TEMPLATE\FEATURES 파일 부품에 넣습니다.
4. Feature, Stsadm Command: stsadm -o installfeature -name DistributePermission 설치
5. Feature 활성화

좋은 웹페이지 즐겨찾기