Example: I had create a column named "Store", it is the metadata column. the "store" column contains some value that is the groups you want to give to the new item. after adding a item, the item will break the Inheritance permission and the item had unquie permission.
Note : you should get the administrator permisison with the code SPSecurity.RunWithElevatedPrivileges(delegate(), or the genenal user won't add the item. and when you get login name of the user of the current web, you will get the administrator, so you should get the login name out of the code SPSecurity.RunWithElevatedPrivileges(delegate().
Here is the code:
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
int currentUserID = properties.Web.CurrentUser.ID;
//Break the list items Inheritance and the permission is none.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = new SPSite(properties.SiteId).OpenWeb(properties.RelativeWebUrl))
{
SPListItem item = web.Lists[properties.ListTitle].GetItemById(properties.ListItemId);
SPField field = web.Lists[properties.ListTitle].Fields["Store"];
object value = item["Store"];
string store = field.GetFieldValueAsText(value);
if (store == "")
{
properties.Cancel = true;
return;
}
web.AllowUnsafeUpdates = true;
if (!item.HasUniqueRoleAssignments)
{
item.BreakRoleInheritance(false);
item.Update();
}
web.AllowUnsafeUpdates = true;
int num = store.Length - store.Replace(";","").Length;
string[] a = store.Split(';');
SPRoleDefinition roleDefinition = web.RoleDefinitions["Contribute"];
SPGroup securityGroup;
SPRoleAssignment roleAssignment;
for (int i = 0; i < a.Length; i++)
{
securityGroup = web.SiteGroups[a[i].ToString()];
roleAssignment = new SPRoleAssignment(securityGroup);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
item.RoleAssignments.Add(roleAssignment);
item.Update();
}
}
});
properties.List.Update();
base.ItemAdded(properties);
}
catch
{
properties.Cancel = true;
}
}
Hope to help you.