Microsoft Cloud Authors: Elizabeth White, Yeshim Deniz, Serafima Al, Janakiram MSV, John Katrick

Related Topics: Microsoft Cloud, Cloud Security

Microsoft Cloud: Blog Feed Post

A Simple Way to Programmatically Create SharePoint Security Groups

I don’t like manual steps especially when it comes to setting up security

When it comes to SharePoint deployments, I try to automate everything I can.  I don’t like manual steps especially when it comes to setting up security.  A common task when deploying any sites is setting up security in some manner.  Today I am going to cover how to easily store definitions your SharePoint security groups in an XML file.  We’ll use LINQ to XML to make reading the file a breeze, and then we’ll use the SharePoint object model to create the groups and add users (or AD groups).   I’ve blogged on how to create a group before, but we’re going to take this a step further by giving you code that you can easily add to a feature receiver or console application.  First let’s take a look at the XML file we’re going to use.

<?xml version="1.0" encoding="utf-8" ?>


<Group Name="My Custom Read Group" Owner="SHAREPOINT\GroupOwner" Description="Readonly Permission Group" PermissionLevel="Readonly">

<User Name="SHAREPOINT\TestUser1" />

<User Name="SHAREPOINT\TestGroup1" />

<User Name="SHAREPOINT\TestGroup2" />


<Group Name="My Custom Contributors Group" Owner="SHAREPOINT\GroupOwner" Description="Contributors Permission Group" PermissionLevel="Contribute">

<User Name="SHAREPOINT\TestGroup3" />



In this file, I am defining two SharePoint groups.  One that will have readonly access and one that will have contribute access.  I store the required information needed by the Add method on the SPGroupCollection object.  I then have one or more User elements with the name of my Active Directory user or group.  I tried to keep my XML schema pretty simple.  You can customize it obviously how you want, you would just have to alter your LINQ queries.

Let’s take a look at the code we need to make this happen.  I won’t go into as much detail of the object model since I went into it pretty well on my last post.  We’ll just focus on how we use LINQ to XML to read the information we need and then have it create our groups.  My method is called CreateGroups and it takes an SPWeb object and a string with the filename of the XML document.

private void CreateGroups(SPWeb currentSite, string groupsFilename)


// get the xml document from the feature folder

XDocument groupsXml = XDocument.Load(groupsFilename);


// create a new anoynmous type with the group data

var groups = from sharePointGroup in groupsXml.Root.Elements("Group")

select new


Name = sharePointGroup.Attribute("Name").Value,

Owner = sharePointGroup.Attributes("Owner").Any() ? sharePointGroup.Attribute("Owner").Value : null,

Description = sharePointGroup.Attributes("Description").Any() ? sharePointGroup.Attribute("Description").Value : string.Empty,

PermissionLevel = sharePointGroup.Attributes("PermissionLevel").Any() ? sharePointGroup.Attribute("PermissionLevel").Value : null,

Users = sharePointGroup.Elements("User").Any() ? sharePointGroup.Elements("User") : null



// iterate through the groups and create the groups

foreach (var sharePointGroup in groups)


// only create the group if it does not exist

if (!ContainsGroup(currentSite.SiteGroups, sharePointGroup.Name))


// add the owner to the web site users



// add the group

currentSite.SiteGroups.Add(sharePointGroup.Name, currentSite.SiteUsers[sharePointGroup.Owner],

currentSite.SiteUsers[sharePointGroup.Owner], sharePointGroup.Description);



// add the users to the group

AddUsersToGroup(sharePointGroup.Name, sharePointGroup.Users, currentSite, sharePointGroup.PermissionLevel);



This seems like kind of a big method at first, but it’s really not that bad.  To keep things simple, I haven’t included any exception handling code.  We are really just querying the XML document, iterating through each group element inside of it, creating the groups, and then adding the users to the group.  The first line of code just creates an XDocument object.  We then construct a LINQ to XML query.  What we want is to return data from each Group element in the document.  The Add method doesn’t like nulls, so we check for them and use string.Empty if the value does not exist in the file.  The one case where I don’t do this is for the Name of the group.  If that is not present, I would rather the process throw an exception.  As for the Users assigned to the group, I grab all of them and add them to our anonymous type like this.

Users = sharePointGroup.Elements("User").Any() ? sharePointGroup.Elements("User") : null

This gives us an IEnumerable<XElement> that we can pass to a method later to add each Active Directory user (or group) to the SharePoint group.  Once we execute the query, we iterate through each group element.  The first thing we have to do is make sure that the group does not exist.  Of course there is no way to do that other than using the try/catch technique.  I will usually wrap this in an extension method, but for today’s purpose, we’ll just call a method to check.

private bool ContainsGroup(SPGroupCollection groupCollection, string index)




SPGroup testGroup = groupCollection[index];

return true;


catch (SPException e)


return false;



Lame I know.  I’m so happy there are ways to get around this in SharePoint 2010.  Then this starts to look like code from the previous post.  We call .EnsureUser to make sure the domain account of the group owner is registered with the site.  We then just call the Add method with the Name, Owner, default user, and description.  Again there is more info on the previous post about that method call.  Assuming the group is created, we can then add the users to the group.  We call a new method AddUsersToGroup which takes the groupName, the users element, an SPWeb, and the permission level.

The first thing we do is query the names of the Active Directory users (or groups).  Here we are just grabbing it from the Name attribute of the User element.  I probably could have condensed this query, but at least it’s easy to read.  We then add each user (or group) from the User elements to the group.  If you are curious about the empty parameters, take a look at the previous post.  If you are going to run into an exception, it’s going to be here.  If the group failed to be created or if the user does not exist (i.e.: you typed it in the XML file wrong), this line will throw an exception.

private void AddUsersToGroup(string groupName, IEnumerable<XElement> users, SPWeb currentSite)


// select the username from the xml document

var userList = from user in users

select new


Name = user.Attribute("Name").Value



// add the users to the sharepoint group

foreach (var user in userList)


currentSite.SiteGroups[groupName].AddUser(user.Name, string.Empty, user.Name, string.Empty);



Now, we’re almost done.  The last thing we need to do is set the permission level on the group.  This is where we specify whether the group has readonly, contribute, full control, etc access to the site.  Be sure and get the name on the permission level right otherwise you will get an exception.  I’ve also blogged about how to assign permission levels before.  Today’s post is really just a great practical use of putting together the things I have posted on before.

private void SetRoleDefinitionBinding(string groupName, SPWeb currentSite, string permissionLevel)


// add the read role definition to the site group

SPRoleAssignment roleAssignment = new SPRoleAssignment(currentSite.SiteGroups[groupName]);





Effectively you create a new SPRoleAssignment by passing it a SPGroup object.  You then add a binding using the existing RoleDefinitions on the site.  You then add the assignment to the site and of course call .Update() so things get saved.

That’s really all there is to it.  This is a great use of combining information from my previous posts into something that you can use everyday to set security on your sites.  How you execute this code is up to you.  I’ve used it in a feature receiver and in a console application before.  Setting up security through the UI is very slow and painful.  Once you create it on one server, there is no way to move it to another server and that’s not a lot of fun.  This should help you with that and eliminate those nasty manual steps in your deployment process.

Read the original blog entry...

More Stories By Corey Roth

Corey Roth, a SharePoint Server MVP, is an independent consultant specializing in Cloud technologies such as Azure and Office 365. He also specializes in mobile development. Corey serves as the product manager for two cloud-first mobile app platforms: BrewZap and HappenZap.

@ThingsExpo Stories
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...