Esempio n. 1
0
        /// <summary>
        /// First attempts to locate an OOTB role definition from the SPRoleType enumeration.  If no role matches the
        /// provided name, it iterates over all roles in the SPWeb until it finds the matching definition.
        /// </summary>
        /// <param name="web">the web containing role definitions</param>
        /// <param name="roleName">the name of the role desired</param>
        /// <param name="roleDef"></param>
        /// <returns>returns True if a match is found, otherwise false</returns>
        public static bool TryGetRoleDefinition(this SPWeb web, string roleName, out SPRoleDefinition roleDef)
        {
            bool retVal = false;

            SPRoleDefinitionCollection roles = web.RoleDefinitions;

            try
            {
                // Try to get the definition based on the OOTB RoleTypes (Reader, Contributor, etc), ignoring case
                roleDef = roles.GetByType((SPRoleType)Enum.Parse(typeof(SPRoleType), roleName, true));
            }
            catch (Exception x)
            {
                Logger.Instance.Info("Error in TryGetRoleDefinition", x, DiagnosticsCategories.eCaseExtensions);
                roleDef = null;
            }

            if (roleDef == null)
            {
                foreach (SPRoleDefinition role in roles)
                {
                    // Case insensitive comparison
                    if (string.Compare(role.Name, roleName, true) == 0)
                    {
                        roleDef = role;
                        break;
                    }
                }
            }
            return(retVal);
        }
        public SPRoleDefinitionInstance GetByType(string roleType)
        {
            SPRoleType eRoleType;

            if (!roleType.TryParseEnum(true, out eRoleType))
            {
                return(null);
            }

            var result = m_roleDefinitionCollection.GetByType(eRoleType);

            return(result == null
        ? null
        : new SPRoleDefinitionInstance(Engine.Object.InstancePrototype, result));
        }
Esempio n. 3
0
        /// <summary>
        /// 创建子项目按钮事件
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnCreateSite_Click(object sender, EventArgs e)
        {
            try
            {
                SPSite site = SPContext.Current.Web.Site;
                //string spwt = SPWebTemplate.WebTemplateSTS;//默认选择工作组网站模板

                SPWeb web = site.OpenWeb("/");
                web.AllowUnsafeUpdates = true;
                SPMember memUser = web.Users[0];
                SPUser   suser   = web.Users[0];


                //新建组
                //web.SiteGroups.Add("skyteam3", memUser, suser, "new skyteam");
                //web.SiteGroups["skyteam3"].AddUser("adr\\administrator", "[email protected]", "蔡", "系统维修人员");
                //web.Groups["skyteam2"].AddUser("adr\\pccai", "[email protected]", "蔡", "系统维修人员");


                //新建子站点
                string currentTemplate = web.WebTemplate;
                //web.Webs.Add("Test2", "站点名称2", "站点描述2", 2052, "_GLOBAL_#0", true, false);


                //打开子站点
                SPWeb web2 = site.OpenWeb("Projects/Test2");
                web2.AllowUnsafeUpdates = true;
                // web2.SiteGroups.Add("skyteam6", memUser, suser, "new skyteam");//新建组
                // web2.SiteGroups["skyteam6"].AddUser("adr\\administrator", "[email protected]", "边", "系统维修人员");


                //改变站点继承权
                if (!web2.HasUniqueRoleDefinitions)
                {
                    web2.RoleDefinitions.BreakInheritance(true, true);
                }

                //站点继承权改变后重新设置状态
                web2.AllowUnsafeUpdates = true;



                //添加权限级别 (Role)
                //SPRoleDefinition roleDefinition = new SPRoleDefinition();
                //roleDefinition.Name = "项目角色";
                //roleDefinition.Description = "项目角色可以批准所有项目情况.";
                //roleDefinition.BasePermissions = SPBasePermissions.FullMask ^ SPBasePermissions.ManagePermissions;
                //web2.RoleDefinitions.Add(roleDefinition);


                //更改权限级别 (Permissions)
                SPRoleDefinitionCollection roles           = web2.RoleDefinitions;
                SPRoleDefinition           roleDefinition1 = roles["读取"];
                roleDefinition1.BasePermissions = SPBasePermissions.AddListItems |
                                                  SPBasePermissions.BrowseDirectories |
                                                  SPBasePermissions.EditListItems |
                                                  SPBasePermissions.DeleteListItems |
                                                  SPBasePermissions.AddDelPrivateWebParts;
                roleDefinition1.Update();


                //用户权限分配与定义(New)
                SPRoleDefinitionCollection        roleDefinitions = web2.RoleDefinitions;
                SPRoleAssignmentCollection        roleAssignments = web2.RoleAssignments;
                SPRoleAssignment                  roleAssignment  = new SPRoleAssignment("adr\\administrator", "*****@*****.**", "Display_Name", "Notes");
                SPRoleDefinitionBindingCollection roleDefBindings = roleAssignment.RoleDefinitionBindings;
                roleDefBindings.Add(roleDefinitions["项目角色"]);
                roleAssignments.Add(roleAssignment);


                //权限定义(Old)
                //SPRoleCollection siteGroups = web2.Roles;
                //siteGroups.Add("skyteam6", "Description", SPRights.ManageWeb | SPRights.ManageSubwebs);


                //获得权限定义
                SPRoleDefinition sprole = roleDefinitions.GetByType(SPRoleType.Reader);
                string           spname = sprole.Name;


                //组权限分配与定义(New)
                SPRoleDefinitionCollection roleDefinitions1 = web2.RoleDefinitions;
                SPRoleAssignmentCollection roleAssignments1 = web2.RoleAssignments;
                SPMember         memCrossSiteGroup          = web2.SiteGroups["skyteam6"];
                SPPrincipal      myssp   = (SPPrincipal)memCrossSiteGroup;
                SPRoleAssignment myroles = new SPRoleAssignment(myssp);
                SPRoleDefinitionBindingCollection roleDefBindings1 = myroles.RoleDefinitionBindings;
                roleDefBindings1.Add(roleDefinitions1["设计"]);
                roleDefBindings1.Add(roleDefinitions1["读取"]);
                roleAssignments1.Add(myroles);


                //组权限分配与定义(Old)
                //SPMember member = web2.Roles["skyteam"];
                //web2.Permissions[member].PermissionMask =
                //    SPRights.ManageLists | SPRights.ManageListPermissions;



                //更改列表权限(Old)
                //SPList list = site.Lists["通知"];
                //SPPermissionCollection perms = list.Permissions;
                //SPUserCollection users = site.Users;
                //SPMember member = users["ADR\\pccai"];
                //list.Permissions[member].PermissionMask = SPRights.AddListItems | SPRights.EditListItems;



                //  PermissionCollection perc = web.Permissions;
                //perc.AddUser("adr\\administrator", "[email protected]", "title", "Notes", PortalRight.AllSiteRights);
                // SecurityManager.AddRole(context, "title", "descriptions", PortalRight.ManageSite);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 4
0
        protected override long SaveDocument(string LocalFilePath, DocumentStorage Storage, DocumentStorageArea StorageArea, Document Document, BindingList <DocumentAttributeValue> attributeValue)
        {
            SPSite site = null;
            SPWeb  web  = null;

            byte[]            data            = null;
            SPFile            fileUploaded    = null;
            string            RootLibraryName = String.Empty;
            SPDocumentLibrary doclib          = null;

            //Pick up the file in binary stream
            data = Document.Content.Blob;

            using (site = new SPSite(Storage.MainPath))
            {
                using (web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;

                    //SPFolder Folder = web.GetFolder(StorageArea.Path);
                    doclib = web.Lists[Storage.Name] as SPDocumentLibrary;
                    if (doclib == null)
                    {
                        web.Lists.Add(Storage.Name, string.Empty, SPListTemplateType.DocumentLibrary);
                    }

                    /// **REMOVE**: 20090818
                    /// viene impostato l'override, altrimenti il documento resterebbe nel transito
                    /// TODO : da sistemare con la gestione delle versioni in sharepoint
                    try
                    {
                        SPFolder foolder = null;
                        if (data != null)
                        {
                            if (!string.IsNullOrEmpty(StorageArea.Path))
                            {
                                try
                                {
                                    if (doclib.RootFolder.SubFolders[StorageArea.Path] == null)
                                    {
                                        doclib.RootFolder.SubFolders.Add(StorageArea.Path);
                                    }
                                }
                                catch (Exception)
                                {
                                    doclib.RootFolder.SubFolders.Add(StorageArea.Path);
                                }
                                foolder = doclib.RootFolder.SubFolders[StorageArea.Path];
                            }
                            else
                            {
                                foolder = doclib.RootFolder;
                            }

                            string fileName = GetIdDocuemnt(Document) + Path.GetExtension(Document.Name);
                            try
                            {
                                fileUploaded = foolder.Files[fileName];
                            }
                            catch { }
                            if (fileUploaded != null)
                            {
                                fileUploaded.CheckOut();
                                fileUploaded.SaveBinary(data);
                                fileUploaded.CheckIn("BiblosDS", SPCheckinType.MajorCheckIn);
                            }
                            else
                            {
                                fileUploaded = foolder.Files.Add(fileName, data, true);
                            }
                            //Set the file version
                            Document.StorageVersion = fileUploaded.MajorVersion;


                            if (ConfigurationManager.AppSettings["ForceSharePointSecurity"] != null && ConfigurationManager.AppSettings["ForceSharePointSecurity"].ToString().Equals("true", StringComparison.InvariantCultureIgnoreCase))
                            {
                                fileUploaded.Item.BreakRoleInheritance(false);
                                try
                                {
                                    for (int i = 0; i < fileUploaded.Item.RoleAssignments.Count; i++)
                                    {
                                        try
                                        {
                                            fileUploaded.Item.RoleAssignments.Remove((SPPrincipal)fileUploaded.Item.RoleAssignments[i].Member);
                                        }
                                        catch (Exception)
                                        {
                                        }
                                        //
                                    }
                                    string SiteGroupsName = ConfigurationManager.AppSettings["SiteGroupsName"] == null ? string.Empty : ConfigurationManager.AppSettings["SiteGroupsName"].ToString();
                                    //foreach (var item in Document.Permissions)
                                    //{
                                    SPRoleDefinitionCollection webroledefinition = web.RoleDefinitions;

                                    SPGroup group = null;
                                    try
                                    {
                                        group = web.SiteGroups[SiteGroupsName];
                                    }
                                    catch (Exception)
                                    {
                                        web.SiteGroups.Add(SiteGroupsName, web.AssociatedOwnerGroup, null, "");
                                        group = web.SiteGroups[SiteGroupsName];
                                    }

                                    //Add user to the group of viewer
                                    //try
                                    //{
                                    //    group.AddUser()
                                    //}
                                    //catch (Exception)
                                    //{

                                    //    throw;
                                    //}
                                    SPRoleAssignment assignment = new SPRoleAssignment(group);
                                    assignment.RoleDefinitionBindings.Add(webroledefinition.GetByType(SPRoleType.Reader));
                                    fileUploaded.Item.RoleAssignments.Add(assignment);
                                    //}
                                }
                                catch (Exception)
                                {
                                }
                                finally
                                {
                                    fileUploaded.Item.BreakRoleInheritance(true);
                                }
                            }

                            //In questo caso forse conviene salvare gli attributi al momento dell'upload del file.
                            //SPListItem MyListItem = fileUploaded.Item;
                            foreach (var item in Document.AttributeValues)
                            {
                                try
                                {
                                    fileUploaded.Item[item.Attribute.Name] = item.Value;
                                }
                                catch (Exception)
                                {
                                    doclib.Fields.Add(item.Attribute.Name, ParseSPFieldType(item.Attribute.AttributeType), item.Attribute.IsRequired);
                                    doclib.Update();
                                }
                            }
                            fileUploaded.Item.SystemUpdate();
                        }
                    }
                    catch (Exception ex)
                    {
                        //Write the log
                        Logging.WriteLogEvent(BiblosDS.Library.Common.Enums.LoggingSource.BiblosDS_Sharepoint,
                                              "SaveDocument",
                                              ex.ToString(),
                                              BiblosDS.Library.Common.Enums.LoggingOperationType.BiblosDS_General,
                                              BiblosDS.Library.Common.Enums.LoggingLevel.BiblosDS_Errors);
                        throw new FileNotUploaded_Exception("File not uploaded" + Environment.NewLine + ex.ToString());
                    }
                    web.AllowUnsafeUpdates = false;
                }
            }
            return(data.Length);
        }
        private void AddSecuritySettings(SPFeatureReceiverProperties properties)
        {
            SPGroup authenticatedGroup = null;
            SPGroup designersGroup     = null;
            SPGroup approversGroup     = null;
            SPGroup viewersGroup       = null;
            //SPGroup guestGroup = null;

            SPSite site    = properties.Feature.Parent as SPSite;
            SPWeb  rootWeb = site.RootWeb;

            try
            {
                SPGroupCollection siteGroups  = rootWeb.SiteGroups;
                SPUser            currentUser = rootWeb.CurrentUser;
                bool addOwnerToGroup          = true;
                if (rootWeb.Site.SystemAccount.ID == currentUser.ID)
                {
                    addOwnerToGroup = false;
                }

                authenticatedGroup = AddSecurityGroup(siteGroups, "All Authenticated Users", "All Authenticated Users", currentUser, addOwnerToGroup);
                designersGroup     = AddSecurityGroup(siteGroups, "Designers", "Designers", currentUser, addOwnerToGroup);
                approversGroup     = AddSecurityGroup(siteGroups, "Approvers", "Approvers", currentUser, addOwnerToGroup);
                viewersGroup       = AddSecurityGroup(siteGroups, "Viewers", "Viewers", currentUser, addOwnerToGroup);
                //guestGroup = AddSecurityGroup(siteGroups, "Guests", "Guests", currentUser, addOwnerToGroup);
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
            }

            SPRoleDefinition contributerRole   = null;
            SPRoleDefinition readerRole        = null;
            SPRoleDefinition designerRole      = null;
            SPRoleDefinition administratorRole = null;
            SPRoleDefinition guestRole         = null;

            SPRoleDefinition approverRole = null;
            SPRoleDefinition viewerRole   = null;

            try
            {
                SPRoleDefinitionCollection roleDefinitions = rootWeb.RoleDefinitions;
                bool flag2 = false;
                foreach (SPRoleDefinition definition7 in roleDefinitions)
                {
                    if ((definition7.Order != 0x7fffffff) && (definition7.Order != 0))
                    {
                        flag2 = true;
                        break;
                    }
                }
                if (!flag2)
                {
                    contributerRole   = SetRoleDefinitionOrder(rootWeb, SPRoleType.Contributor, 5);
                    readerRole        = SetRoleDefinitionOrder(rootWeb, SPRoleType.Reader, 6);
                    designerRole      = SetRoleDefinitionOrder(rootWeb, SPRoleType.WebDesigner, 2);
                    administratorRole = SetRoleDefinitionOrder(rootWeb, SPRoleType.Administrator, 1);
                    guestRole         = SetRoleDefinitionOrder(rootWeb, SPRoleType.Guest, 8);
                }
                else
                {
                    contributerRole   = roleDefinitions.GetByType(SPRoleType.Contributor);
                    readerRole        = roleDefinitions.GetByType(SPRoleType.Reader);
                    designerRole      = roleDefinitions.GetByType(SPRoleType.WebDesigner);
                    administratorRole = roleDefinitions.GetByType(SPRoleType.Administrator);
                    guestRole         = roleDefinitions.GetByType(SPRoleType.Guest);
                }

                approverRole = AddRoleDefinition(roleDefinitions, "Approver", "Approver", SPBasePermissions.BrowseDirectories | SPBasePermissions.AddDelPrivateWebParts | SPBasePermissions.BrowseUserInfo | SPBasePermissions.CreateSSCSite | SPBasePermissions.EditMyUserInfo | SPBasePermissions.CreateAlerts | SPBasePermissions.UpdatePersonalWebParts | SPBasePermissions.UseRemoteAPIs | SPBasePermissions.UseClientIntegration | SPBasePermissions.ApproveItems | SPBasePermissions.DeleteListItems | SPBasePermissions.ViewVersions | SPBasePermissions.OpenItems | SPBasePermissions.EditListItems | SPBasePermissions.AddListItems | SPBasePermissions.ViewListItems | SPBasePermissions.ViewPages | SPBasePermissions.Open | SPBasePermissions.ViewFormPages | SPBasePermissions.CancelCheckout | SPBasePermissions.DeleteVersions | SPBasePermissions.ManagePersonalViews, flag2 ? 0x7fffffff : 4);
                viewerRole   = AddRoleDefinition(roleDefinitions, "Viewer", "Viewer", SPBasePermissions.OpenItems | SPBasePermissions.ViewListItems | SPBasePermissions.ViewPages | SPBasePermissions.Open, flag2 ? 0x7fffffff : 7);
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
            }

            SPUser authenticatedUser = null;

            try
            {
                string logonName = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null).Translate(typeof(NTAccount)).Value;
                authenticatedUser = rootWeb.EnsureUser(logonName);
                authenticatedGroup.AddUser(authenticatedUser);
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                authenticatedUser = null;
            }

            /*
             * SPUser anonymousUser = null;
             * try
             * {
             *  string logonName = new SecurityIdentifier(WellKnownSidType.AnonymousSid, null).Translate(typeof(NTAccount)).Value;
             *  anonymousUser = rootWeb.EnsureUser(logonName);
             *  guestGroup.AddUser(anonymousUser);
             * }
             * catch (Exception ex)
             * {
             *  SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
             *  anonymousUser = null;
             * }
             */

            try
            {
                SPClaim claim = SPAllUserClaimProvider.CreateAuthenticatedUserClaim(true);
                string  str4  = SPClaimProviderManager.Local.EncodeClaim(claim);
                authenticatedUser = rootWeb.EnsureUser(str4);
                authenticatedGroup.AddUser(authenticatedUser);
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                authenticatedUser = null;
            }


            try
            {
                /*
                 * SPList catalog = rootWeb.GetCatalog(SPListTemplateType.MasterPageCatalog);
                 * SPList styleLibrary = rootWeb.Lists["Style Library"];
                 *
                 * catalog.BreakRoleInheritance(true);
                 * styleLibrary.BreakRoleInheritance(true);
                 */
                SPRoleAssignmentCollection roleAssignments = rootWeb.RoleAssignments;
                //SPRoleAssignmentCollection catalogRoles = catalog.RoleAssignments;
                //SPRoleAssignmentCollection styleRoles = styleLibrary.RoleAssignments;

                SPRoleAssignment DesignerAssignment = new SPRoleAssignment(designersGroup);
                DesignerAssignment.RoleDefinitionBindings.Add(designerRole);

                //SPRoleAssignment GuestAssignment = new SPRoleAssignment(guestGroup);
                //GuestAssignment.RoleDefinitionBindings.Add(guestRole);

                roleAssignments.Add(DesignerAssignment);
                //roleAssignments.Add(GuestAssignment);
                //catalogRoles.Add(DesignerAssignment);
                //catalogRoles.Add(GuestAssignment);
                //styleRoles.Add(DesignerAssignment);
                //styleRoles.Add(GuestAssignment);

                AddRoleAssignment(roleAssignments, approversGroup, approverRole, true);
                AddRoleAssignment(roleAssignments, viewersGroup, viewerRole, true);

                //AddRoleAssignment(roleAssignments, guestGroup, guestRole, true);

                /*
                 * AddRoleAssignment(catalogRoles, approversGroup, readerRole, true);
                 * AddRoleAssignment(catalogRoles, viewersGroup, readerRole, true);
                 * AddRoleAssignment(catalogRoles, authenticatedGroup, readerRole, false);
                 *
                 * AddRoleAssignment(catalogRoles, guestGroup, guestRole, false);
                 *
                 * AddRoleAssignment(catalogRoles, approversGroup, viewerRole, true);
                 * AddRoleAssignment(catalogRoles, viewersGroup, viewerRole, true);
                 * AddRoleAssignment(catalogRoles, authenticatedGroup, viewerRole, true);
                 *
                 * AddRoleAssignment(styleRoles, approversGroup, viewerRole, true);
                 * AddRoleAssignment(styleRoles, viewersGroup, viewerRole, true);
                 * AddRoleAssignment(styleRoles, authenticatedGroup, viewerRole, true);
                 *
                 * AddRoleAssignment(styleRoles, guestGroup, guestRole, true);
                 */
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
            }
        }