SharePointCommunity
Die deutschsprachige Community für SharePoint, Microsoft 365, Teams, Yammer und mit Azure

Sponsored by

Willkommen im Forum Archiv.
Einträge sind hier nicht mehr möglich, aber der Bestand von 12 Jahren SharePoint-Wissen ist hier recherchierbar.




CreateDocumentSet und CreateLookupField dauert Ewigkeiten

Unbeantwortet Dieser Beitrag hat 16 Antworten

Ohne Rang
11 Beiträge
Vronsch erstellt 7 Aug. 2013 11:28
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Hallo alle zusammen!

Habe ein kleines Problem mit SharePoint 2013. Ich möchte 5 Dokumente anlegen mit folgendem Code:

Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp1", "Projekt GmbH");

Das Ganze dauert für die besagten 5 Dokumente zwischen 38 und 42 Sekunden.

Auch die folgenden beiden Zeilen benötigen zwischen 18 und 19 Sekunden.

Utils.CreateLookupField(tbProjectNumber.Text, "xx", "Bereich", "Dokumente Bereich", "Titel");
Utils.CreateLookupField(tbProjectNumber.Text, "xx", "Bereich", "Dokumente Kategorie", "Titel");

Das kann doch unmöglich normal sein oder?

Bin dankbar für jede Antwort

L.G. Vrosch

Alle Antworten

Ohne Rang
634 Beiträge
Olaf Didszun Als Antwort am 7 Aug. 2013 14:51
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Du hast recht, die Dauer scheint sehr lang zu sein, aber das kann auch mit der Umgebung zusammenhängen auf der der Code ausgeführt wird (bzw. beim Client Object Model die Performance vom Server und der Netzwerkverbindung.

Auch wenn ich mich jetzt oute, aber was ist bei Dir Utils?

Grüße

Olaf

Ohne Rang
11 Beiträge
Vronsch Als Antwort am 7 Aug. 2013 15:25
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Das kann natürlich auch sein. Nur die Umgebung kann ich in diesem Fall leider nur sehr umständlich beeinflussen. Die Frage ist, ob es Möglichkeiten gibt das Ganze rein codetechnisch noch zu optimieren. Bzw. wenn nicht erst dann zu überlegen, wie und ob ich die Umgebung hier verändern kann.
Stimmt, tut mir Leid, das hätte ich vielleicht erklären sollen. Utils ist eine selbstgeschriebene statische Klasse welche die Berechtigungen für SharePoint-Gruppen auf der Seite setzt.

L.G. Vronsch

Ohne Rang
634 Beiträge
Olaf Didszun Als Antwort am 7 Aug. 2013 15:53
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Wenn Utils etwas selbstgeschriebenes ist, dann können natürlich auch da Code-Fragmente enthalten sein, die nicht optimal sind. Nur aufgrund des Einzeilers, den Du in Deinem ersten Posting geschrieben hattest, ist da kaum eine sinnvolle Aussage zu treffen.

Beste Grüße

Olaf

Ohne Rang
11 Beiträge
Vronsch Als Antwort am 8 Aug. 2013 10:30
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Navigation;

using Microsoft.SharePoint.Publishing;

using Microsoft.SharePoint.Publishing.Navigation;

using Microsoft.Office.DocumentManagement.DocumentSets;

using System.Collections;

using System.Data.SqlClient;

using Microsoft.SharePoint.Utilities;

 

namespace ForRelation.SP.ProjectPortal.AddOns

{

    public static class Utils

    {

        /// <summary>

        /// set permissons for sharepoint groups on site

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(SPWeb theWeb, SPPrincipal spgroupName, string permissionLevel)

        {

            theWeb.AllowUnsafeUpdates = true;

 

            SPRoleAssignment roleAssignment = new SPRoleAssignment(spgroupName);

            SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

            if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

            //Check inheritance

            if (!theWeb.HasUniqueRoleAssignments)

            {

                theWeb.BreakRoleInheritance(false);

            }

 

            theWeb.RoleAssignments.Add(roleAssignment);

 

            theWeb.Update();

 

            if (theWeb != null)

                theWeb.Dispose();           

        }

 

        /// <summary>

        /// set permissons for sharepoint groups on lists

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="List"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(SPWeb theWeb, SPList List, SPPrincipal spgroupName, string permissionLevel)

        {

            theWeb.AllowUnsafeUpdates = true;

 

            SPRoleAssignment roleAssignment = new SPRoleAssignment(spgroupName);

            SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

            if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

            //Check inheritance

            if (!List.HasUniqueRoleAssignments)

            {

                List.BreakRoleInheritance(false);

            }

 

            List.RoleAssignments.Add(roleAssignment);

 

            List.Update();

 

            if (theWeb != null)

                theWeb.Dispose();

        }

 

        /// <summary>

        /// set permissons for sharepoint groups on lists V2

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="list"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(string siteURL, string list, string spgroupName, string permissionLevel)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList List = theWeb.Lists[list];

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                //Check inheritance

                if (!List.HasUniqueRoleAssignments)

                {

                    List.BreakRoleInheritance(false);

                }

 

                List.RoleAssignments.Add(roleAssignment);

 

                List.Update();

                //try

                //{

 

                //}

                //catch (Exception exc)

                //{

                //    System.Diagnostics.EventLog.WriteEntry("NewProject", exc.ToString(), EventLogEntryType.Error);

                //    throw;

                //}

            }

 

           

        }

 

        /// <summary>

        /// set permission to an item of a given list/library and identify item on the "Name" field

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="list"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        /// <param name="itemname"></param>

        public static void CreatePermissions(string siteURL, string list, string spgroupName, string permissionLevel, string itemname)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {               

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList List = theWeb.Lists[list];

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                SPListItemCollection items = List.Items;

                foreach (SPListItem item in items)

                {

                    if (item["Name"].ToString().Equals(itemname))

                    {

                        item.BreakRoleInheritance(false);

                        item.RoleAssignments.Add(roleAssignment);

                        item.Update();

                    }

                }

            }

           

        }

 

        /// <summary>

        /// set permission to an item of a given list/library and identify item on a specific field

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="list"></param>

        /// <param name="itemname"></param>

        /// <param name="searchfield"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(string siteURL, string list, string itemname, string searchfield, string spgroupName, string permissionLevel)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList List = theWeb.Lists[list];

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                SPListItemCollection items = List.Items;

                foreach (SPListItem item in items)

                {

                    if (item[searchfield].ToString().Equals(itemname))

                    {

                        item.BreakRoleInheritance(false);

                        item.RoleAssignments.Add(roleAssignment);

                        item.Update();

                    }

                }

            }

           

        }

 

        /// <summary>

        /// set permissons for sharepoint groups V2

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(string siteURL, string spgroupName, string permissionLevel)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                //Check inheritance

                if (!theWeb.HasUniqueRoleAssignments)

                {

                    theWeb.BreakRoleInheritance(false);

                }

 

                theWeb.RoleAssignments.Add(roleAssignment);

 

                theWeb.Update();               

            }           

        }

 

        /// <summary>

        /// add new navigation entry WSS Quicklaunch

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="url"></param>

        /// <param name="external"></param>

        public static void CreateNavigationEntry(string siteURL, string title, string url, bool external)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPNavigationNodeCollection quickLaunchNodes = theWeb.Navigation.QuickLaunch;

                SPNavigationNode navigationentry = new SPNavigationNode(title, url, external);

 

                quickLaunchNodes.AddAsLast(navigationentry);

 

                theWeb.Update();               

            }

        }

 

        /// <summary>

        /// modify url on publishing site navigation entry

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="url"></param>

        /// <param name="external"></param>

        public static void ModifyNavigationEntryURL(string siteURL, string title, string url, bool OpenInNewWindow)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                theWeb.AllowUnsafeUpdates = true;

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                PublishingWeb thePubWeb = PublishingWeb.GetPublishingWeb(theWeb);               

 

                foreach (SPNavigationNode navNodes in thePubWeb.Navigation.CurrentNavigationNodes)

                {

                    if (navNodes.Title == title)

                    {

                        navNodes.Url = url;

                        if (OpenInNewWindow == true)

                        {

                            navNodes.Properties["Target"] = "_blank";

                        }

                        navNodes.Update();

                        thePubWeb.Update();

                    }

                }

            }           

        }

 

        /// <summary>

        /// modify url on publishing site navigation entry children

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="url"></param>

        /// <param name="external"></param>

        public static void ModifyNavigationEntryURL(string siteURL, string title, string subtitle, string url, bool OpenInNewWindow)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                PublishingWeb thePubWeb = PublishingWeb.GetPublishingWeb(theWeb);               

 

                foreach (SPNavigationNode navNodes in thePubWeb.Navigation.CurrentNavigationNodes)

                {

                    if (navNodes.Title == title)

                    {

                        foreach (SPNavigationNode navNodeChildren in navNodes.Children)

                        {

                            if (navNodeChildren.Title == subtitle)

                            {

                                navNodeChildren.Url = url;

                                if (OpenInNewWindow == true)

                                {

                                    navNodeChildren.Properties["Target"] = "_blank";

                                }

                                navNodeChildren.Update();

                                thePubWeb.Update();

                            }

                        }

                    }

                }               

            }

        }

 

        /// <summary>

        /// modify audience on publishing site navigation entry

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="audience"></param>

        public static void ModifyNavigationEntryAudience(string siteURL, string title, string audience)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                PublishingWeb thePubWeb = PublishingWeb.GetPublishingWeb(theWeb);               

 

                foreach (SPNavigationNode navNodes in thePubWeb.Navigation.CurrentNavigationNodes)

                {

                    if (navNodes.Title == title)

                    {

                        navNodes.Properties.Add("Audience", ";;;;" + audience);

                        navNodes.Update();

                        thePubWeb.Update();

                    }

                }               

            }           

        }

 

        /// <summary>

        /// add new sharepoint group

        /// </summary>

        /// <param name="groupName"></param>

        /// <param name="groupDescription"></param>

        public static void CreateSharepointGroup(string groupName, string groupDescription)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs["/"])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs["/"];

                theWeb.SiteGroups.Add(groupName, theWeb.AssociatedOwnerGroup, null, groupDescription);               

            }

        }

 

        /// <summary>

        /// create document set

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibName"></param>

        /// <param name="setName"></param>

        /// <param name="documentSetCt"></param>

        public static void CreateDocumentSet(string siteURL, string doclibName, string setName, string documentSetCt)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.Lists[doclibName] as SPDocumentLibrary;

                SPFolder folderToInsert = doclib.RootFolder;

                SPContentTypeId dsCtID = new SPContentTypeId();

 

                dsCtID = doclib.ContentTypes[documentSetCt].Id;

 

                // Create the Document Set Properties HashTable

 

                Hashtable properties = new Hashtable();

                properties.Add("Name", setName);

                //properties.Add("Project Client", "AdventureWorks");

 

                DocumentSet docSet = DocumentSet.Create(folderToInsert, setName, dsCtID, properties);

               

                docSet.Provision();

                //doclib.Folders.Add();               

            }          

        }

 

        /// <summary>

        /// delete folder from document library

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibName"></param>

        /// <param name="folderName"></param>

        public static void DeleteDoclibFolder(string siteURL, string doclibName, string folderName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                theWeb.Folders[doclibName].SubFolders.Delete(folderName);               

            }

        }

 

        /// <summary>

        /// add new lookup field to document library and on all content types

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibName"></param>

        /// <param name="lookupFieldName"></param>

        /// <param name="lookupFieldTargetList"></param>

        /// <param name="lookupFieldTargetListField"></param>

        public static void CreateLookupField(string siteURL, string doclibName, string lookupFieldName, string lookupFieldTargetList, string lookupFieldTargetListField)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.Lists[doclibName] as SPDocumentLibrary;               

 

                SPList targetList = theWeb.Lists[lookupFieldTargetList];

                SPField targetField = targetList.Fields[lookupFieldTargetListField];

 

                doclib.Fields.AddLookup(lookupFieldName, targetList.ID, false);

                SPFieldLookup lkp = (SPFieldLookup)doclib.Fields[lookupFieldName];

                lkp.LookupField = targetField.InternalName;

                lkp.Update();

 

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(new SPFieldLink(lkp));

                    ct.Update();

                }

 

                doclib.Update();               

            }           

        }

 

        /// <summary>

        /// delete field from content type

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibName"></param>

        /// <param name="ctName"></param>

        /// <param name="fieldName"></param>

        public static void DeleteCtField(string siteURL, string doclibName, string ctName, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                theWeb.AllowUnsafeUpdates = true;

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPDocumentLibrary doclib = theWeb.Lists[doclibName] as SPDocumentLibrary;               

 

                SPContentTypeCollection ctcoll = doclib.ContentTypes;

                SPContentType ct = ctcoll[ctName];

                ct.FieldLinks.Delete(fieldName);

                ct.Update();               

            }

        }

 

        /// <summary>

        /// add field to a specific content type in document library

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibName"></param>

        /// <param name="ctName"></param>

        /// <param name="fieldName"></param>

        public static void AddCtField(string siteURL, string doclibName, string ctName, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.Lists[doclibName] as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);               

 

                SPContentTypeCollection ctcoll = doclib.ContentTypes;

                SPContentType ct = ctcoll[ctName];

                ct.FieldLinks.Add(fieldLink);

                ct.Update();               

            }

        }

 

        /// <summary>

        /// add field to all content types in document library

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibName"></param>

        /// <param name="fieldName"></param>

        public static void AddCtField(string siteURL, string doclibName, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.Lists[doclibName] as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);               

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(fieldLink);

                    ct.Update();

                }               

            }

        }

 

        /// <summary>

        /// add field to all content types in document library in current web

        /// </summary>

        /// <param name="doclibName"></param>

        /// <param name="fieldName"></param>

        public static void AddCtFieldCurr(string doclibName, string fieldName)

        {

            SPDocumentLibrary doclib = SPContext.Current.Web.Lists[doclibName] as SPDocumentLibrary;

            SPField field = doclib.Fields[fieldName];

            SPFieldLink fieldLink = new SPFieldLink(field);          

 

            foreach (SPContentType ct in doclib.ContentTypes)

            {

                ct.FieldLinks.Add(fieldLink);

                ct.Update();

            }           

        }

 

        /// <summary>

        /// add field to a specific content type in document library in current web

        /// </summary>

        /// <param name="doclibName"></param>

        /// <param name="ctName"></param>

        /// <param name="fieldName"></param>

        public static void AddCtFieldCurr(string doclibName, string ctName, string fieldName)

        {

            SPDocumentLibrary doclib = SPContext.Current.Web.Lists[doclibName] as SPDocumentLibrary;

            SPField field = doclib.Fields[fieldName];

            SPFieldLink fieldLink = new SPFieldLink(field);

 

            SPContentTypeCollection ctcoll = doclib.ContentTypes;

            SPContentType ct = ctcoll[ctName];

            ct.FieldLinks.Add(fieldLink);

            ct.Update();           

        }

 

 

 

        /// <summary>

        /// create new parameter entry in configuration list

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listName"></param>

        /// <param name="entryName"></param>

        /// <param name="entryValue"></param>

        public static void AddConfigurationEntry(string siteURL, string listName, string entryName, string entryValue)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.Lists[listName];

                SPListItem newItem = list.Items.Add();               

 

                newItem["Parameter"] = entryName;

                newItem["Value"] = entryValue;

                newItem.Update();              

            }

        }

 

        /// <summary>

        /// delete column from view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listName"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void DeleteColumnFromView(string siteURL, string listName, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.Lists[listName];

                SPView view = list.Views[viewName];

 

                if (view.ViewFields.Exists(columnName))

                {

                    theWeb.AllowUnsafeUpdates = true;

                    view.ViewFields.Delete(columnName);

                    view.Update();

                }               

            }

        }

 

        /// <summary>

        /// add column to view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listName"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void AddColumnToView(string siteURL, string listName, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.Lists[listName];

                SPView view = list.Views[viewName];

 

                theWeb.AllowUnsafeUpdates = true;

                view.ViewFields.Add(columnName);

                view.Update();               

            }

        }

 

        public static void ChangeViewQuery(string siteURL, string listName, string viewName, string viewQuery)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.Lists[listName];

                SPView view = list.Views[viewName];               

 

                view.Query = viewQuery;

                view.Update();               

            }          

        }

 

        /// <summary>

        /// Create Permisson on specific item

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="ListItem"></param>

        /// <param name="loginName"></param>

        /// <param name="roleName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(SPWeb theWeb, SPListItem ListItem, string loginName, string roleName, string permissionLevel)

        {

            using (theWeb = new SPSite(theWeb.Site.ID).OpenWeb(theWeb.ID))

            {

                //theWeb = new SPSite(theWeb.Site.ID).OpenWeb(theWeb.ID);

                theWeb.AllowUnsafeUpdates = true;

 

                ListItem = theWeb.Lists[ListItem.ParentList.ID].GetItemById(ListItem.ID);

 

                SPRoleAssignment roleAssignment = new SPRoleAssignment(loginName, "", roleName, "");

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                //Check inheritance

                if (!ListItem.HasUniqueRoleAssignments)

                {

                    ListItem.BreakRoleInheritance(false);

                }

 

                ListItem.RoleAssignments.Add(roleAssignment);

 

                ListItem.Update();               

            }

        }

 

        /// <summary>

        /// Add User to specific group on specific site

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="groupName"></param>

        /// <param name="userName"></param>

        public static void AddUserToGroup(string siteURL, string groupName, string userName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

 

                SPUser spUser = theWeb.EnsureUser(userName);

 

                if (spUser != null)

                {

                    SPGroup spGroup = theWeb.Groups[groupName];

 

                    if (spGroup != null)

                        spGroup.AddUser(spUser);

                }               

            }          

        }

    }

}

 

 

Ohne Rang
929 Beiträge
Thomas Östreich Als Antwort am 8 Aug. 2013 10:50
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

[quote user="Vronsch"]           using (SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL])[/quote]

Nicht über Arrays/Collections arbeiten im SharePoint wenn es andere Methoden gibt. AllWebs ruft alle SPWeb Objekte aus der DB ab rufe das Web lieber immer über die Url ab:

SPContext.Current.Site.OpenWeb("...").

Listen und Bibliotheken am besten über die URL ermitteln web.GetList("[ServerRelativeUrl]"), bei einer Liste/DokLib ist das immer die RootUrl.

 

Ohne Rang
11 Beiträge
Vronsch Als Antwort am 8 Aug. 2013 11:04
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Das würde auch erklären, warum das Ganze immer langsamer wird, ja öfter ich den Code ausführe, denn dann gibt es ja immer mehr Objekte, die auch mitaufgerufen werden. Das macht ja direkt Sinn.
Dankeschön. Werde mir das heute noch anschauen, sobald ich dazukomme.

Vielen Danke für den Hinweis
Vronsch

Ohne Rang
11 Beiträge
Vronsch Als Antwort am 9 Aug. 2013 14:05
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

using System;

using System.ComponentModel;

using System.Threading;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using System.Data;

using System.Xml;

using System.Xml.Linq;

using System.Diagnostics;

using System.Collections;

using System.Collections.Generic;

using Microsoft.SharePoint.Navigation;

using ForRelation.SP.ProjectPortal.AddOns;

 

namespace ForRelation.SP.ProjectPortal.NewProjectWebPart

{           

    [ToolboxItemAttribute(false)]

    public class NewProjectWebPart : WebPart

    {

        #region controls

        //Test

        private TextBox tbProjectNumber = new TextBox();

        private TextBox tbProjectName = new TextBox();

        private TextBox tbProjectDesc = new TextBox();

        private DropDownList ddTemplate = new DropDownList();

        private Label lbStatusMessage = new Label();

        //private UpdatePanel _updatePanel;

        //private UpdateProgress _updateProgress;

        //private static readonly object EventSubmitKey = new object();

        #endregion

 

        #region properties, fields and constants

        string mPermissionSettings =

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

        <permissionconfig>

          <sharepointgroups>

            <group id='_Intern_PL' desc='Interner Projektleiter' />

            <group id='_Intern_MA' desc='Interner Mitarbeiter' />

            <group id='_Kunde_PL' desc='Kundenprojektleiter' />

            <group id='_Kunde_MA' desc='Kundenmitarbeiter' />

            <group id='_Besucher' desc='Besucher (nur lesen)' />

          </sharepointgroups>

 

          <permissions>

            <!-- global rights for the site -->

            <object id='root' group='_Intern_PL' permission='Teilnehmen' />

            <object id='root' group='_Intern_MA' permission='Perm_CRU' />

            <object id='root' group='_Kunde_PL' permission='Lesen_Kunde' />

            <object id='root' group='_Kunde_MA' permission='Lesen_Kunde' />

           

            <!-- document libraries-->

            <object id='Links' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Links' group='_Intern_MA' permission='Perm_CRU' />   

 

            <object id='Projektdokumentation' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdokumentation' group='_Intern_MA' permission='Perm_CRU' />

 

            <object id='Projektdokumente' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdokumente' group='_Intern_MA' permission='Perm_CRU' />

            <object id='Projektdokumente' group='_Kunde_PL' permission='Perm_CRU_Kunde' />

            <object id='Projektdokumente' group='_Kunde_MA' permission='Perm_CRU_Kunde' />

 

            <!-- items in doclibs -->

            <!-- <object id='Seiten' item='Projektdokumente.aspx' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Seiten' item='Konf_Ticket.aspx' group='_Intern_PL' permission='Teilnehmen' /> -->

 

            <object id='Sicherheitsstufen' item='Intern' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='Intern' field='Titel' group='_Intern_MA' permission='Lesen' />                       

            <object id='Sicherheitsstufen' item='Keine' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='Keine' field='Titel' group='_Intern_MA' permission='Lesen' />           

            <object id='Sicherheitsstufen' item='Keine' field='Titel' group='_Kunde_PL' permission='Lesen_Kunde' />

            <object id='Sicherheitsstufen' item='Keine' field='Titel' group='_Kunde_MA' permission='Lesen_Kunde' />

            <object id='Sicherheitsstufen' item='PL Intern' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='PL Kunde' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='PL Kunde' field='Titel' group='_Intern_MA' permission='Lesen' />                        

            <object id='Sicherheitsstufen' item='PL Kunde' field='Titel' group='_Kunde_PL' permission='Lesen_Kunde' />    

            <object id='Sicherheitsstufen' item='Projektleiter' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='Projektleiter' field='Titel' group='_Kunde_PL' permission='Lesen_Kunde' /> 

 

            <!-- lists -->

            <object id='configuration' group='_Intern_PL' permission='Lesen' />

            <object id='configuration' group='_Intern_MA' permission='Lesen' />

            <object id='configuration' group='_Kunde_PL' permission='Lesen' />

            <object id='configuration' group='_Kunde_MA' permission='Lesen' />

            <object id='freigaben' group='_Intern_PL' permission='Teilnehmen' />

            <object id='freigaben' group='_Intern_MA' permission='Perm_CRU' />

            <object id='freigaben' group='_Kunde_PL' permission='Perm_CRU_Kunde' />

            <object id='freigaben' group='_Kunde_MA' permission='Perm_CRU_Kunde' />

            <object id='Projektdaten' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdaten' group='_Intern_MA' permission='Perm_CRU' />

            <object id='Projektdokumente Bereich' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdokumente Bereich' group='_Intern_MA' permission='Lesen' />

            <object id='Projektdokumente Bereich' group='_Kunde_PL' permission='Lesen_Kunde' />

            <object id='Projektdokumente Bereich' group='_Kunde_MA' permission='Lesen_Kunde' />

            <object id='Projektdokumente Kategorie' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdokumente Kategorie' group='_Intern_MA' permission='Lesen' />

            <object id='Projektdokumente Kategorie' group='_Kunde_PL' permission='Lesen_Kunde' />

            <object id='Projektdokumente Kategorie' group='_Kunde_MA' permission='Lesen_Kunde' />

            <object id='projekttagebuch' group='_Intern_PL' permission='Teilnehmen' />

            <object id='projekttagebuch' group='_Intern_MA' permission='Perm_CRU' />

                    

          </permissions>  

        </permissionconfig>";

        [Personalizable(PersonalizationScope.Shared),

        WebBrowsable(true),

        WebDisplayName("Security Settings"),

        WebDescription("The xml definition containing the permission assignments to users and wss objects."),

        Category("Portal Security")]

        public string PermissionSettings

        {

            get { return mPermissionSettings; }

            set { mPermissionSettings = value; }

        }

 

        private string mSiteTemplate =

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

        <templates>

            <template id='1' name='de_navax4relation_project.wsp' lcid='1031' />

            <!--template id='2' name='en_navax4relation_project.wsp' lcid='1033' /-->

        </templates>";

        [Personalizable(PersonalizationScope.Shared),

        WebBrowsable(true),

        WebDisplayName("Project template definition"),

        WebDescription("The name of the site template (stp file) including the lcid information"),

        Category("Portal Settings")]

        public string SiteTemplate

        {

            get { return mSiteTemplate; }

            set { mSiteTemplate = value; }

        }

 

        private string mQuickLaunchHeading = "Projekte";

        [Personalizable(PersonalizationScope.Shared),

        WebBrowsable(true),

        WebDisplayName("Navigation heading"),

        WebDescription("The heading caption where the new site link must be placed."),

        Category("Portal Settings")]

        public string QuickLaunchHeading

        {

            get { return mQuickLaunchHeading; }

            set { mQuickLaunchHeading = value; }

        }

 

        private bool mEnableDebugMode = false;

        [Personalizable(PersonalizationScope.Shared),

        WebBrowsable(true),

        WebDisplayName("Enable Debug mode"),

        WebDescription("Shows detailed information of the project portal creation."),

        Category("Portal Settings")]

        public bool EnableDebugMode

        {

            get { return mEnableDebugMode; }

            set { mEnableDebugMode = value; }

        }

 

        private const string ILLEGALCHARS = "/\\:*?\"<>|#\t{}%~&][,@+=;'";

        #endregion

 

        #region constructors

        /// <summary>

        /// constructs the NewProjectWebPart instance

        /// </summary>

        public NewProjectWebPart()

        {

            ExportMode = WebPartExportMode.All;

        }

        #endregion

       

 

        [WebBrowsable(true), Personalizable(PersonalizationScope.Shared), Category("AbdHaq Property")]

        //[WebBrowsable(true), WebDisplayName("Image URL"), WebDescription("Image URL"), Personalizable(PersonalizationScope.Shared)]

        public string LoadingImageURL{

        get {

            object _obj = ViewState["LoadingImageURL"];

            if (_obj == null) {

                //return "/_layouts/images/GEARS_AN.GIF";

                return "/_layouts/ProjectPortal/LoadingImage.gif";

            }

            else {

                return (string)ViewState["LoadingImageURL"];

 

            }

        }

        set { ViewState["LoadingImageURL"] = value; }

    }

    //public event EventHandler Submit {

    //    add { Events.AddHandler(EventSubmitKey, value); }

    //    remove { Events.RemoveHandler(EventSubmitKey, value); }

    //}

 

 

 

        #region methods

        /// <summary>

        /// creates the controls for the webpart

        /// </summary>

        protected override void CreateChildControls()

        {

            Controls.Clear();

 

            //_updatePanel = new UpdatePanel();

            //{

            //    _updatePanel.ID = "UpdatePanel1";

            //    _updatePanel.ChildrenAsTriggers = true;

            //    _updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;

            //}

 

            //_updateProgress = new UpdateProgress();

            //_updateProgress.ID = "UpdateProgress1";

            //string _templateHTML = null;

            //if (LoadingImageURL == null || LoadingImageURL == string.Empty)

            //{

            //    _templateHTML = "<span>Loading ...</span>";

            //}

            //else

            //{

            //    _templateHTML = "<div><img alt='Loading...' src='" + LoadingImageURL.Trim() + "'/></div>";

            //}

            //_updateProgress.ProgressTemplate = new ProgressTemplate(_templateHTML);

            //_updateProgress.AssociatedUpdatePanelID = _updatePanel.ClientID;

 

            //this.Controls.Add(_updatePanel);

 

            base.CreateChildControls();

 

            Table table = new Table();

            table.Style.Add(HtmlTextWriterStyle.Width, "100%");

 

            TableRow row = new TableRow();

            TableCell cellDesc = new TableCell();

            TableCell cellValue = new TableCell();

 

            #region textboxes

            // project number

            //

            cellDesc.Text = "Project key (Service Portal Schlüssel): ";

            cellDesc.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            cellDesc.Style.Add(HtmlTextWriterStyle.Width, "300px");

            tbProjectNumber.Width = 250;

            tbProjectNumber.ID = "projectNumber";

            cellValue.Controls.Add(tbProjectNumber);

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

 

            // project name

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            cellDesc.Text = "Project name (Service Portal Projekt):";

            cellDesc.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            tbProjectName.ID = "projectName";

            tbProjectName.Width = 250;

            cellValue.Controls.Add(tbProjectName);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

 

            // project description

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            cellDesc.Text = "Project description (Optionale Beschreibung):";

            cellDesc.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            tbProjectDesc.ID = "projectDescription";

            tbProjectDesc.Width = 250;

            cellValue.Controls.Add(tbProjectDesc);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

            #endregion

 

            #region DropDownLists

            // project template

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            cellDesc.Text = "Site template";

            cellDesc.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            FillDropDown();

            ddTemplate.ID = "projectTemplate";

            tbProjectDesc.Width = 250;

            cellValue.Controls.Add(ddTemplate);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

            #endregion

 

            // insert empty row

            //

            row = new TableRow();

            table.Rows.Add(row);

 

            #region buttons

            // button create

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            Button btnCreateSite = new Button();

            btnCreateSite.Text = "Create project portal";

            btnCreateSite.Click += new EventHandler(btnCreateSite_Click);

            cellValue.Controls.Add(btnCreateSite);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

            #endregion

 

            // insert empty row

            //

            row = new TableRow();

            //row.Height = 15;

            table.Rows.Add(row);

 

            // update progress

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            //cellValue.Style.Add(HtmlTextWriterStyle.TextAlign, "center");

            //cellValue.Controls.Add(_updateProgress);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

 

            // insert empty row

            //

            row = new TableRow();

            table.Rows.Add(row);

 

            #region labels

            // add status message label

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();           

            lbStatusMessage.ID = "statusMessage";

            lbStatusMessage.Text = String.Empty;

            lbStatusMessage.Style.Add(HtmlTextWriterStyle.Color, "red");

            cellValue.Controls.Add(lbStatusMessage);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

            #endregion

 

            //_updatePanel.ContentTemplateContainer.Controls.Add(table);

            this.Controls.Add(table);

        }

 

       /// <summary>

        /// shows the given site template xml to the dropdownbox

        /// </summary>

        private void FillDropDown()

        {

            DataSet data = new DataSet();

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(mSiteTemplate);

            data.ReadXml(new XmlNodeReader(xmlDocument));

 

            ddTemplate.DataValueField = "id";

            ddTemplate.DataTextField = "name";

            ddTemplate.DataSource = data;

            ddTemplate.DataBind();

        }

 

        /// <summary>

        /// eventhandler that handles the click event of the create project portal button

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnCreateSite_Click(object sender, EventArgs e)

        {

            DateTime preTime;

            TimeSpan duration;

 

            try

            {

                uint lcid = 1031;

                string templateName = string.Empty;

 

                #region check fields

                if (!IsValidProjectNumber())

                {

                    lbStatusMessage.Text = string.Format("The project key is part of the url. It contains illegal characters or is an empty string." +

                        "Invalid characters are: {0}.", ILLEGALCHARS);

                    return;

                }

 

                if (String.IsNullOrEmpty(tbProjectName.Text))

                {

                    lbStatusMessage.Text = "The project name must not be empty.";

                    return;

                }

                #endregion

 

                // get templatename and language

                //

                DataRow row;

                if ((row = GetSelectedTemplate()) != null)

                {

                    lcid = UInt32.Parse(row["lcid"] as string);

                    templateName = row["name"] as string;

                }

 

                // create subsite

                //

                preTime = DateTime.Now;

                string url = String.Empty;

                if (!String.IsNullOrEmpty(url = CreateSite(tbProjectNumber.Text, tbProjectName.Text, tbProjectDesc.Text, templateName, lcid)))

                {

                    if (EnableDebugMode)

                    {

                        duration = DateTime.Now.Subtract(preTime);

                        lbStatusMessage.Text = string.Format("<span style='color: green;'>Das !neue! Projektportal <a href='{0}' style='color: green;'>{1}</a> wurde erfolgreich angelegt." + " - Duration: " + duration.TotalSeconds.ToString() + "s</span><br><br>",

                        url,

                        tbProjectName.Text);

                    }

                    else

                    {

                        lbStatusMessage.Text = string.Format("<span style='color: green;'>Das Projektportal <a href='{0}' style='color: green;'>{1}</a> wurde erfolgreich angelegt.</span>",

                        url,

                        tbProjectName.Text);

                    }

                }

 

                // assign the permissions...

                //

                preTime = DateTime.Now;

                AssignPermission();     

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Assign Permissions" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

             

                //create temporary documents sets

                //

                bool success = false;

                int count = 0, max = 3;

                TimeSpan Createspeed = new TimeSpan();

                TimeSpan Deletespeed = new TimeSpan();

 

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp1", "Projekt 4relation Consulting GmbH");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp1");

                        count++;

                    }

                }

                lbStatusMessage.Text += "First DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() +  "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() +"s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Projekt 4relation Consulting GmbH' failed!!!<br>";

                }

 

                count = 0;

                success = false;

                Createspeed = new TimeSpan();

                Deletespeed = new TimeSpan();

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp2", "Projekt NAVAX Consulting GmbH");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp2");

                        count++;

                    }

                }

                lbStatusMessage.Text += "Second DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() + "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() + "s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Projekt NAVAX Consulting GmbH' failed!!!<br>";

                }

 

                count = 0;

                success = false;

                Createspeed = new TimeSpan();

                Deletespeed = new TimeSpan();

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp3", "Projekt NAVAX Projekt GmbH");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp3");

                        count++;

                    }

                }

                lbStatusMessage.Text += "Third DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() + "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() + "s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Projekt NAVAX Projekt GmbH' failed!!!<br>";

                }

 

                count = 0;

                success = false;

                Createspeed = new TimeSpan();

                Deletespeed = new TimeSpan();

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp4", "Vertrieb 4relation");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp4");

                        count++;

                    }

                }

                lbStatusMessage.Text += "Fourth DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() + "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() + "s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Vertrieb 4relation' failed!!!<br>";

                }

 

                count = 0;

                success = false;

                Createspeed = new TimeSpan();

                Deletespeed = new TimeSpan();

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp5", "Vertrieb NAVAX");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp5");

                        count++;

                    }

                }

                lbStatusMessage.Text += "Fifth DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() + "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() + "s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Vertrieb NAVAX' failed!!!<br>";

                }

 

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Create Temporary Document Sets" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

 

                //delete temporary documents sets

                //

                preTime = DateTime.Now;

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp1");

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp2");

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp3");

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp4");

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp5");

 

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Delete Temporary Document Sets" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }               

 

                // create lookup fields

                //

                preTime = DateTime.Now;

                Utils.CreateLookupField(tbProjectNumber.Text, "Projektdokumente", "Bereich", "Projektdokumente Bereich", "Titel");

                Utils.CreateLookupField(tbProjectNumber.Text, "Projektdokumente", "Kategorie", "Projektdokumente Kategorie", "Titel");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Create Lookup Fields" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

 

                // add fields to ct's

                //

                preTime = DateTime.Now;

                Utils.AddCtField(tbProjectNumber.Text, "Projektdokumente", "Sicherheitsstufe");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Add Fields to Content Types" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

 

                // delete lookup fields from document sets

                //

                preTime = DateTime.Now;

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt 4relation Consulting GmbH", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Consulting GmbH", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Projekt GmbH", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb 4relation", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb NAVAX", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt 4relation Consulting GmbH", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Consulting GmbH", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Projekt GmbH", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb 4relation", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb NAVAX", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt 4relation Consulting GmbH", "Sicherheitsstufe");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Consulting GmbH", "Sicherheitsstufe");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Projekt GmbH", "Sicherheitsstufe");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb 4relation", "Sicherheitsstufe");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb NAVAX", "Sicherheitsstufe");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Delete Lookup Fields" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }               

 

                // create configuration parameters

                //

                preTime = DateTime.Now;

                Utils.AddConfigurationEntry(tbProjectNumber.Text, "configuration", "ProjectNumber", tbProjectNumber.Text);

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Create Configuration Parameters" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

 

                //modify views

                //

                preTime = DateTime.Now;

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Bereich");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Kategorie");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Geändert");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Geändert von");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Inhaltstyp");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Sicherheitsstufe");

                Utils.DeleteColumnFromView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "setpermi");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Bereich");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Kategorie");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Geändert");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Geändert von");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Sicherheitsstufe");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Bereich");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Kategorie");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Geändert");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Geändert von");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Inhaltstyp");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Sicherheitsstufe");

                Utils.ChangeViewQuery(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "<GroupBy Collapse='FALSE' GroupLimit='30'><FieldRef Name='Bereich' /></GroupBy><OrderBy><FieldRef Name='FileLeafRef' /></OrderBy>");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Bereich");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Kategorie");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Geändert");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Geändert von");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Inhaltstyp");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Sicherheitsstufe");

                Utils.ChangeViewQuery(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "<GroupBy Collapse='FALSE' GroupLimit='30'><FieldRef Name='Kategorie' /></GroupBy><OrderBy><FieldRef Name='FileLeafRef' /></OrderBy>");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Modify Views" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }               

 

                //modify navigation entries

                //

                preTime = DateTime.Now;

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Allgemeines", "#", false);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Dokumente", "#", false);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Service Portal", "#", false);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Service Portal", "Projektaufgaben", "https://service.navax.at/browse/" + tbProjectNumber.Text, true);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Einrichtung", "#", false);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Administration", "#", false);

                Utils.ModifyNavigationEntryAudience(tbProjectNumber.Text, "Allgemeines", "Projektportal Administratoren," + tbProjectNumber.Text + "_Intern_PL," + tbProjectNumber.Text + "_Intern_MA");

                Utils.ModifyNavigationEntryAudience(tbProjectNumber.Text, "Einrichtung", "Projektportal Administratoren," + tbProjectNumber.Text + "_Intern_PL");

                Utils.ModifyNavigationEntryAudience(tbProjectNumber.Text, "Administration", "Projektportal Administratoren");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Modify Navigation Entries" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }                             

            }

            catch (Exception exc)

            {

                lbStatusMessage.Text += "An exception occured: " + HttpUtility.HtmlEncode(exc.Message);

            }

        }

 

 

        //protected override void OnInit(EventArgs e)

        //{

        //    base.OnInit(e);

 

        //    ScriptManager _AjaxManager = ScriptManager.GetCurrent(this.Page);

        //    if (_AjaxManager == null)

        //    {

        //        //create new ScriptManager and EnablePartialRendering

        //        _AjaxManager = new ScriptManager();

        //        _AjaxManager.EnablePartialRendering = true;

        //        _AjaxManager.AsyncPostBackTimeout = 300;

        //        //Fix problem with postbacks and form actions (DevDiv 55525)

 

        //        Page.ClientScript.RegisterStartupScript(this.GetType(), this.ID, "_spOriginalFormAction = document.forms[0].action;", true);

 

        //        if ((this.Page.Form != null))

        //        {

        //            string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];

        //            if (!string.IsNullOrEmpty(formOnSubmitAtt) & formOnSubmitAtt == "return _spFormOnSubmitWrapper();")

        //            {

        //                this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";

        //            }

        //            //add the ScriptManager as the first control in the Page.Form

        //            this.Page.Form.Controls.AddAt(0, _AjaxManager);

        //        }

        //    }

        //}

 

        //protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)

        //{

        //    _updatePanel.RenderControl(writer);

        //}

 

 

        //public class ProgressTemplate : ITemplate

        //{

        //    private string template;

 

        //    public ProgressTemplate(string temp)

        //    {

        //        template = temp;

        //    }

           

        //    public void InstantiateIn(Control container)

        //    {

        //        LiteralControl ltr = new LiteralControl(this.template);

        //        container.Controls.Add(ltr);

        //    }

        //}

 

        /// <summary>

        /// assigns permission defined by the permissionsettings xml

        /// </summary>

        private void AssignPermission()

        {

            XDocument xdoc = XDocument.Parse(mPermissionSettings);

 

            // create wss groups

            //

            var groupresult = xdoc.Descendants("group");

            foreach (var group in groupresult)

            {

                Debug.WriteLine(group.Attribute("id").Value + " " + group.Attribute("desc").Value);

                Utils.CreateSharepointGroup(string.Format("{0}{1}", tbProjectNumber.Text, group.Attribute("id").Value),

                    string.Format("{0} {1}", group.Attribute("desc").Value, tbProjectName.Text));

            }

 

            // assign permissions per ojbect and group

            //

            var permissionresult = xdoc.Descendants("object");

            string objectid = string.Empty;

            string groupid = string.Empty;

            string permissionvalue = string.Empty;

            string item = string.Empty;

            string field = string.Empty;

 

            foreach (var permission in permissionresult)

            {

                // check attribute count...

                //

               

                List<XAttribute> permissions = new List<XAttribute>();

                permissions.AddRange(permission.Attributes());

                

                if (permissions.Count < 3 || permissions.Count > 5)

                {

                    throw new NotSupportedException("Illegal count of attributes for element 'object'.");

                }

 

                // construct the parameters for the permission setting

                objectid = permission.Attribute("id").Value;

                groupid = string.Format("{0}{1}", tbProjectNumber.Text, permission.Attribute("group").Value);

                permissionvalue = permission.Attribute("permission").Value;

                if (permission.Attribute("item") != null)

                {

                    item = permission.Attribute("item").Value;

                }

                if (permission.Attribute("field") != null)

                {

                    field = permission.Attribute("field").Value;

                }

 

                // special case if the objectid equals to "root" than the root of the site is meant

                //

                if (objectid.Equals("root"))

                {

                    Utils.CreatePermissions(tbProjectNumber.Text, groupid, permissionvalue);

                }

                else // in all other cases

                {

                    if (permissions.Count == 3) // '3 attributes' means permissionassignemnts to lists or libraries

                    {

                        Utils.CreatePermissions(tbProjectNumber.Text, objectid, groupid, permissionvalue);

                    }

                    else if (permissions.Count == 4) // '4 attributes' means permissionassignments to pages or items within lists or libraries

                    {

                        Utils.CreatePermissions(tbProjectNumber.Text, objectid, groupid, permissionvalue, item);

                    }

                    else if (permissions.Count == 5) // '5 attributes' means permissionassignments to pages or items within lists or libraries on a specific field

                    {

                        Utils.CreatePermissions(tbProjectNumber.Text, objectid, item, field, groupid, permissionvalue);

                        //Utils.CreatePermissions(tbProjectNumber.Text, "Sicherheitsstufen", "Intern", "Titel",tbProjectNumber.Text + "_Intern_PL", "Teilnehmen");

                    }

                }

 

                #region debuginformation

                if (permissions.Count == 3)

                {

                    Debug.WriteLine(permission.Attribute("id").Value + " " + permission.Attribute("group").Value + " " + permission.Attribute("permission").Value);

 

                }

                else if (permissions.Count == 4)

                {

                    Debug.WriteLine(permission.Attribute("id").Value + " " + permission.Attribute("group").Value + " " + permission.Attribute("permission").Value + " " + permission.Attribute("item").Value);

                }

                else if (permissions.Count == 5)

                {

                    Debug.WriteLine(permission.Attribute("id").Value + " " + permission.Attribute("group").Value + " " + permission.Attribute("permission").Value + " " + permission.Attribute("item").Value + " " + permission.Attribute("field").Value);

                }

                #endregion

            }

        }

 

        /// <summary>

        /// create a subsite with the given projectnumber, name, description and template for the given language id

        /// </summary>

        /// <param name="projectNumber"></param>

        /// <param name="projectName"></param>

        /// <param name="projectDescription"></param>

        /// <param name="solutionName"></param>

        /// <param name="lcid"></param>

        /// <returns>the url of the newly created subsite</returns>

        private string CreateSite(string projectNumber, string projectName, string projectDescription, string solutionName, uint lcid)

        {

            //Get templateName from solutionName (Example: de_navax4relation_project.wsp)

            string templateName = string.Empty;

            foreach (SPUserSolution solution in SPContext.Current.Site.Solutions)

            {

                lbStatusMessage.Text += solution.Name + " ";

                if (solution.Name == solutionName)

                {

                    //Solution exists

                    foreach (SPFeature feature in SPContext.Current.Site.Features)

                    {

                        if (feature.Definition != null)

                        {

                            if ((feature.Definition.SolutionId == solution.SolutionId) & (feature.Definition.DisplayName.EndsWith("WebTemplate", StringComparison.OrdinalIgnoreCase)))

                            {

                                //Web Template feature exists so calculate the internal template name

                                string featureID = feature.DefinitionId.ToString();

                                if (!featureID.StartsWith("{")) featureID = String.Format("{{{0}}}", featureID);

                                int pos = feature.Definition.DisplayName.LastIndexOf("WebTemplate", StringComparison.OrdinalIgnoreCase);

                                templateName = String.Format("{0}#{1}", featureID, feature.Definition.DisplayName.Substring(0, pos));

                            }

                        }

                    }

                }

            }

 

            SPWeb newWeb = SPContext.Current.Web.Webs.Add(projectNumber, projectName, projectDescription, lcid, templateName, false, false);

            SPNavigationNodeCollection quickLaunch = SPContext.Current.Web.Navigation.QuickLaunch;

 

            if (newWeb != null)

            {

                foreach (SPNavigationNode node in quickLaunch)

                {

                    if (node.Title.Equals(mQuickLaunchHeading))

                    {

                        node.Children.AddAsLast(new SPNavigationNode(newWeb.Title, newWeb.Url.Replace(newWeb.Site.Url, "")));

                    }

                }

            }

            return newWeb.Url;

        }

 

        /// <summary>

        /// returns the name of the selected template of the dropdownbox

        /// </summary>

        private DataRow GetSelectedTemplate()

        {

            DataSet data = ddTemplate.DataSource as DataSet;

            if (data == null || data.Tables.Count == 0)

            {

                throw new ArgumentOutOfRangeException("DataSet is null or empty.");

            }

 

            if (data.Tables[0] == null || data.Tables[0].Rows.Count == 0)

            {

                throw new ArgumentOutOfRangeException("DataTable is null or empty.");

            }

 

            string selectedId = ddTemplate.SelectedValue;

            foreach (DataRow row in data.Tables[0].Rows)

            {

                if (row["id"].ToString() == selectedId)

                {

                    return row;

                }

            }

            return null;

        }

 

        /// <summary>

        /// checks if the project number has illegal characters

        /// </summary>

        /// <returns>returns true if all characters are legal otherwise false</returns>

        private bool IsValidProjectNumber()

        {

            if (tbProjectNumber.Text.Trim().Length < 1)

                return false;

            if (tbProjectNumber.Text.IndexOfAny(ILLEGALCHARS.ToCharArray()) > -1)

                return false;

            return true;

        }

        #endregion

    }

}

Habe den Code jetzt folgendermaßen abgeändert. So funktioniert er. Habe allerdings mit //boese Kommentare geschrieben wie ich was noch geändert hätte. Diese Änderungen sind allerdings hier nur Kommentare, da sie mir eine FileNotFound-Exception zurückgeben, was ich allerdings nicht verstehen kann.

V.a. warum funktioniert folgende Zeile:

SPDocumentLibrary

 

 

 

aber folgende Zeile funktioniert nicht:

doclib = theWeb.GetList("/" + siteURL + "/" + doclibName) as SPDocumentLibrary;

SPList

list = theWeb.GetList("/" + siteURL + "/" +listName);

 

list = theWeb.GetList("/" + siteURL + "/" +listName);

 

list = theWeb.GetList("/" + siteURL + "/" +listName);

 

list = theWeb.GetList("/" + siteURL + "/" +listName);

 

 

 

 

 

Für mich vollkommen unverständlich...

Bin wie immer sehr dankbar für alle Hilfestellungen

Liebe Grüße

Vronsch

 

 

 

 

 


Ohne Rang
11 Beiträge
Vronsch Als Antwort am 9 Aug. 2013 14:05
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

using System;

using System.ComponentModel;

using System.Threading;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using System.Data;

using System.Xml;

using System.Xml.Linq;

using System.Diagnostics;

using System.Collections;

using System.Collections.Generic;

using Microsoft.SharePoint.Navigation;

using ForRelation.SP.ProjectPortal.AddOns;

 

namespace ForRelation.SP.ProjectPortal.NewProjectWebPart

{           

    [ToolboxItemAttribute(false)]

    public class NewProjectWebPart : WebPart

    {

        #region controls

        //Test

        private TextBox tbProjectNumber = new TextBox();

        private TextBox tbProjectName = new TextBox();

        private TextBox tbProjectDesc = new TextBox();

        private DropDownList ddTemplate = new DropDownList();

        private Label lbStatusMessage = new Label();

        //private UpdatePanel _updatePanel;

        //private UpdateProgress _updateProgress;

        //private static readonly object EventSubmitKey = new object();

        #endregion

 

        #region properties, fields and constants

        string mPermissionSettings =

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

        <permissionconfig>

          <sharepointgroups>

            <group id='_Intern_PL' desc='Interner Projektleiter' />

            <group id='_Intern_MA' desc='Interner Mitarbeiter' />

            <group id='_Kunde_PL' desc='Kundenprojektleiter' />

            <group id='_Kunde_MA' desc='Kundenmitarbeiter' />

            <group id='_Besucher' desc='Besucher (nur lesen)' />

          </sharepointgroups>

 

          <permissions>

            <!-- global rights for the site -->

            <object id='root' group='_Intern_PL' permission='Teilnehmen' />

            <object id='root' group='_Intern_MA' permission='Perm_CRU' />

            <object id='root' group='_Kunde_PL' permission='Lesen_Kunde' />

            <object id='root' group='_Kunde_MA' permission='Lesen_Kunde' />

           

            <!-- document libraries-->

            <object id='Links' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Links' group='_Intern_MA' permission='Perm_CRU' />   

 

            <object id='Projektdokumentation' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdokumentation' group='_Intern_MA' permission='Perm_CRU' />

 

            <object id='Projektdokumente' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdokumente' group='_Intern_MA' permission='Perm_CRU' />

            <object id='Projektdokumente' group='_Kunde_PL' permission='Perm_CRU_Kunde' />

            <object id='Projektdokumente' group='_Kunde_MA' permission='Perm_CRU_Kunde' />

 

            <!-- items in doclibs -->

            <!-- <object id='Seiten' item='Projektdokumente.aspx' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Seiten' item='Konf_Ticket.aspx' group='_Intern_PL' permission='Teilnehmen' /> -->

 

            <object id='Sicherheitsstufen' item='Intern' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='Intern' field='Titel' group='_Intern_MA' permission='Lesen' />                       

            <object id='Sicherheitsstufen' item='Keine' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='Keine' field='Titel' group='_Intern_MA' permission='Lesen' />           

            <object id='Sicherheitsstufen' item='Keine' field='Titel' group='_Kunde_PL' permission='Lesen_Kunde' />

            <object id='Sicherheitsstufen' item='Keine' field='Titel' group='_Kunde_MA' permission='Lesen_Kunde' />

            <object id='Sicherheitsstufen' item='PL Intern' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='PL Kunde' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='PL Kunde' field='Titel' group='_Intern_MA' permission='Lesen' />                        

            <object id='Sicherheitsstufen' item='PL Kunde' field='Titel' group='_Kunde_PL' permission='Lesen_Kunde' />    

            <object id='Sicherheitsstufen' item='Projektleiter' field='Titel' group='_Intern_PL' permission='Lesen' />

            <object id='Sicherheitsstufen' item='Projektleiter' field='Titel' group='_Kunde_PL' permission='Lesen_Kunde' /> 

 

            <!-- lists -->

            <object id='configuration' group='_Intern_PL' permission='Lesen' />

            <object id='configuration' group='_Intern_MA' permission='Lesen' />

            <object id='configuration' group='_Kunde_PL' permission='Lesen' />

            <object id='configuration' group='_Kunde_MA' permission='Lesen' />

            <object id='freigaben' group='_Intern_PL' permission='Teilnehmen' />

            <object id='freigaben' group='_Intern_MA' permission='Perm_CRU' />

            <object id='freigaben' group='_Kunde_PL' permission='Perm_CRU_Kunde' />

            <object id='freigaben' group='_Kunde_MA' permission='Perm_CRU_Kunde' />

            <object id='Projektdaten' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdaten' group='_Intern_MA' permission='Perm_CRU' />

            <object id='Projektdokumente Bereich' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdokumente Bereich' group='_Intern_MA' permission='Lesen' />

            <object id='Projektdokumente Bereich' group='_Kunde_PL' permission='Lesen_Kunde' />

            <object id='Projektdokumente Bereich' group='_Kunde_MA' permission='Lesen_Kunde' />

            <object id='Projektdokumente Kategorie' group='_Intern_PL' permission='Teilnehmen' />

            <object id='Projektdokumente Kategorie' group='_Intern_MA' permission='Lesen' />

            <object id='Projektdokumente Kategorie' group='_Kunde_PL' permission='Lesen_Kunde' />

            <object id='Projektdokumente Kategorie' group='_Kunde_MA' permission='Lesen_Kunde' />

            <object id='projekttagebuch' group='_Intern_PL' permission='Teilnehmen' />

            <object id='projekttagebuch' group='_Intern_MA' permission='Perm_CRU' />

                    

          </permissions>  

        </permissionconfig>";

        [Personalizable(PersonalizationScope.Shared),

        WebBrowsable(true),

        WebDisplayName("Security Settings"),

        WebDescription("The xml definition containing the permission assignments to users and wss objects."),

        Category("Portal Security")]

        public string PermissionSettings

        {

            get { return mPermissionSettings; }

            set { mPermissionSettings = value; }

        }

 

        private string mSiteTemplate =

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

        <templates>

            <template id='1' name='de_navax4relation_project.wsp' lcid='1031' />

            <!--template id='2' name='en_navax4relation_project.wsp' lcid='1033' /-->

        </templates>";

        [Personalizable(PersonalizationScope.Shared),

        WebBrowsable(true),

        WebDisplayName("Project template definition"),

        WebDescription("The name of the site template (stp file) including the lcid information"),

        Category("Portal Settings")]

        public string SiteTemplate

        {

            get { return mSiteTemplate; }

            set { mSiteTemplate = value; }

        }

 

        private string mQuickLaunchHeading = "Projekte";

        [Personalizable(PersonalizationScope.Shared),

        WebBrowsable(true),

        WebDisplayName("Navigation heading"),

        WebDescription("The heading caption where the new site link must be placed."),

        Category("Portal Settings")]

        public string QuickLaunchHeading

        {

            get { return mQuickLaunchHeading; }

            set { mQuickLaunchHeading = value; }

        }

 

        private bool mEnableDebugMode = false;

        [Personalizable(PersonalizationScope.Shared),

        WebBrowsable(true),

        WebDisplayName("Enable Debug mode"),

        WebDescription("Shows detailed information of the project portal creation."),

        Category("Portal Settings")]

        public bool EnableDebugMode

        {

            get { return mEnableDebugMode; }

            set { mEnableDebugMode = value; }

        }

 

        private const string ILLEGALCHARS = "/\\:*?\"<>|#\t{}%~&][,@+=;'";

        #endregion

 

        #region constructors

        /// <summary>

        /// constructs the NewProjectWebPart instance

        /// </summary>

        public NewProjectWebPart()

        {

            ExportMode = WebPartExportMode.All;

        }

        #endregion

       

 

        [WebBrowsable(true), Personalizable(PersonalizationScope.Shared), Category("AbdHaq Property")]

        //[WebBrowsable(true), WebDisplayName("Image URL"), WebDescription("Image URL"), Personalizable(PersonalizationScope.Shared)]

        public string LoadingImageURL{

        get {

            object _obj = ViewState["LoadingImageURL"];

            if (_obj == null) {

                //return "/_layouts/images/GEARS_AN.GIF";

                return "/_layouts/ProjectPortal/LoadingImage.gif";

            }

            else {

                return (string)ViewState["LoadingImageURL"];

 

            }

        }

        set { ViewState["LoadingImageURL"] = value; }

    }

    //public event EventHandler Submit {

    //    add { Events.AddHandler(EventSubmitKey, value); }

    //    remove { Events.RemoveHandler(EventSubmitKey, value); }

    //}

 

 

 

        #region methods

        /// <summary>

        /// creates the controls for the webpart

        /// </summary>

        protected override void CreateChildControls()

        {

            Controls.Clear();

 

            //_updatePanel = new UpdatePanel();

            //{

            //    _updatePanel.ID = "UpdatePanel1";

            //    _updatePanel.ChildrenAsTriggers = true;

            //    _updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;

            //}

 

            //_updateProgress = new UpdateProgress();

            //_updateProgress.ID = "UpdateProgress1";

            //string _templateHTML = null;

            //if (LoadingImageURL == null || LoadingImageURL == string.Empty)

            //{

            //    _templateHTML = "<span>Loading ...</span>";

            //}

            //else

            //{

            //    _templateHTML = "<div><img alt='Loading...' src='" + LoadingImageURL.Trim() + "'/></div>";

            //}

            //_updateProgress.ProgressTemplate = new ProgressTemplate(_templateHTML);

            //_updateProgress.AssociatedUpdatePanelID = _updatePanel.ClientID;

 

            //this.Controls.Add(_updatePanel);

 

            base.CreateChildControls();

 

            Table table = new Table();

            table.Style.Add(HtmlTextWriterStyle.Width, "100%");

 

            TableRow row = new TableRow();

            TableCell cellDesc = new TableCell();

            TableCell cellValue = new TableCell();

 

            #region textboxes

            // project number

            //

            cellDesc.Text = "Project key (Service Portal Schlüssel): ";

            cellDesc.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            cellDesc.Style.Add(HtmlTextWriterStyle.Width, "300px");

            tbProjectNumber.Width = 250;

            tbProjectNumber.ID = "projectNumber";

            cellValue.Controls.Add(tbProjectNumber);

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

 

            // project name

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            cellDesc.Text = "Project name (Service Portal Projekt):";

            cellDesc.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            tbProjectName.ID = "projectName";

            tbProjectName.Width = 250;

            cellValue.Controls.Add(tbProjectName);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

 

            // project description

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            cellDesc.Text = "Project description (Optionale Beschreibung):";

            cellDesc.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            tbProjectDesc.ID = "projectDescription";

            tbProjectDesc.Width = 250;

            cellValue.Controls.Add(tbProjectDesc);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

            #endregion

 

            #region DropDownLists

            // project template

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            cellDesc.Text = "Site template";

            cellDesc.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            FillDropDown();

            ddTemplate.ID = "projectTemplate";

            tbProjectDesc.Width = 250;

            cellValue.Controls.Add(ddTemplate);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

            #endregion

 

            // insert empty row

            //

            row = new TableRow();

            table.Rows.Add(row);

 

            #region buttons

            // button create

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            Button btnCreateSite = new Button();

            btnCreateSite.Text = "Create project portal";

            btnCreateSite.Click += new EventHandler(btnCreateSite_Click);

            cellValue.Controls.Add(btnCreateSite);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

            #endregion

 

            // insert empty row

            //

            row = new TableRow();

            //row.Height = 15;

            table.Rows.Add(row);

 

            // update progress

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();

            //cellValue.Style.Add(HtmlTextWriterStyle.TextAlign, "center");

            //cellValue.Controls.Add(_updateProgress);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

 

            // insert empty row

            //

            row = new TableRow();

            table.Rows.Add(row);

 

            #region labels

            // add status message label

            //

            cellDesc = new TableCell();

            cellValue = new TableCell();           

            lbStatusMessage.ID = "statusMessage";

            lbStatusMessage.Text = String.Empty;

            lbStatusMessage.Style.Add(HtmlTextWriterStyle.Color, "red");

            cellValue.Controls.Add(lbStatusMessage);

            row = new TableRow();

            row.Cells.Add(cellDesc);

            row.Cells.Add(cellValue);

            table.Rows.Add(row);

            #endregion

 

            //_updatePanel.ContentTemplateContainer.Controls.Add(table);

            this.Controls.Add(table);

        }

 

       /// <summary>

        /// shows the given site template xml to the dropdownbox

        /// </summary>

        private void FillDropDown()

        {

            DataSet data = new DataSet();

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(mSiteTemplate);

            data.ReadXml(new XmlNodeReader(xmlDocument));

 

            ddTemplate.DataValueField = "id";

            ddTemplate.DataTextField = "name";

            ddTemplate.DataSource = data;

            ddTemplate.DataBind();

        }

 

        /// <summary>

        /// eventhandler that handles the click event of the create project portal button

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnCreateSite_Click(object sender, EventArgs e)

        {

            DateTime preTime;

            TimeSpan duration;

 

            try

            {

                uint lcid = 1031;

                string templateName = string.Empty;

 

                #region check fields

                if (!IsValidProjectNumber())

                {

                    lbStatusMessage.Text = string.Format("The project key is part of the url. It contains illegal characters or is an empty string." +

                        "Invalid characters are: {0}.", ILLEGALCHARS);

                    return;

                }

 

                if (String.IsNullOrEmpty(tbProjectName.Text))

                {

                    lbStatusMessage.Text = "The project name must not be empty.";

                    return;

                }

                #endregion

 

                // get templatename and language

                //

                DataRow row;

                if ((row = GetSelectedTemplate()) != null)

                {

                    lcid = UInt32.Parse(row["lcid"] as string);

                    templateName = row["name"] as string;

                }

 

                // create subsite

                //

                preTime = DateTime.Now;

                string url = String.Empty;

                if (!String.IsNullOrEmpty(url = CreateSite(tbProjectNumber.Text, tbProjectName.Text, tbProjectDesc.Text, templateName, lcid)))

                {

                    if (EnableDebugMode)

                    {

                        duration = DateTime.Now.Subtract(preTime);

                        lbStatusMessage.Text = string.Format("<span style='color: green;'>Das !neue! Projektportal <a href='{0}' style='color: green;'>{1}</a> wurde erfolgreich angelegt." + " - Duration: " + duration.TotalSeconds.ToString() + "s</span><br><br>",

                        url,

                        tbProjectName.Text);

                    }

                    else

                    {

                        lbStatusMessage.Text = string.Format("<span style='color: green;'>Das Projektportal <a href='{0}' style='color: green;'>{1}</a> wurde erfolgreich angelegt.</span>",

                        url,

                        tbProjectName.Text);

                    }

                }

 

                // assign the permissions...

                //

                preTime = DateTime.Now;

                AssignPermission();     

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Assign Permissions" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

             

                //create temporary documents sets

                //

                bool success = false;

                int count = 0, max = 3;

                TimeSpan Createspeed = new TimeSpan();

                TimeSpan Deletespeed = new TimeSpan();

 

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp1", "Projekt 4relation Consulting GmbH");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp1");

                        count++;

                    }

                }

                lbStatusMessage.Text += "First DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() +  "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() +"s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Projekt 4relation Consulting GmbH' failed!!!<br>";

                }

 

                count = 0;

                success = false;

                Createspeed = new TimeSpan();

                Deletespeed = new TimeSpan();

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp2", "Projekt NAVAX Consulting GmbH");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp2");

                        count++;

                    }

                }

                lbStatusMessage.Text += "Second DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() + "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() + "s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Projekt NAVAX Consulting GmbH' failed!!!<br>";

                }

 

                count = 0;

                success = false;

                Createspeed = new TimeSpan();

                Deletespeed = new TimeSpan();

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp3", "Projekt NAVAX Projekt GmbH");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp3");

                        count++;

                    }

                }

                lbStatusMessage.Text += "Third DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() + "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() + "s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Projekt NAVAX Projekt GmbH' failed!!!<br>";

                }

 

                count = 0;

                success = false;

                Createspeed = new TimeSpan();

                Deletespeed = new TimeSpan();

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp4", "Vertrieb 4relation");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp4");

                        count++;

                    }

                }

                lbStatusMessage.Text += "Fourth DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() + "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() + "s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Vertrieb 4relation' failed!!!<br>";

                }

 

                count = 0;

                success = false;

                Createspeed = new TimeSpan();

                Deletespeed = new TimeSpan();

                while (!success && count < max)

                {

                    try

                    {

                        Createspeed += Utils.CreateDocumentSet(tbProjectNumber.Text, "Projektdokumente", "tmp5", "Vertrieb NAVAX");

                        success = true;

                    }

                    catch

                    {

                        Deletespeed += Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp5");

                        count++;

                    }

                }

                lbStatusMessage.Text += "Fifth DokumentSet created!" + " - count: " + count + " - speed to create all: " + Createspeed.TotalSeconds.ToString() + "s - speed to delete all: " + Deletespeed.TotalSeconds.ToString() + "s<br>";

                if (!success)

                {

                    lbStatusMessage.Text += "!!!Create DokumentSet 'Vertrieb NAVAX' failed!!!<br>";

                }

 

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Create Temporary Document Sets" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

 

                //delete temporary documents sets

                //

                preTime = DateTime.Now;

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp1");

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp2");

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp3");

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp4");

                Utils.DeleteDoclibFolder(tbProjectNumber.Text, "Projektdokumente", "tmp5");

 

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Delete Temporary Document Sets" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }               

 

                // create lookup fields

                //

                preTime = DateTime.Now;

                Utils.CreateLookupField(tbProjectNumber.Text, "Projektdokumente", "Bereich", "Projektdokumente Bereich", "Titel");

                Utils.CreateLookupField(tbProjectNumber.Text, "Projektdokumente", "Kategorie", "Projektdokumente Kategorie", "Titel");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Create Lookup Fields" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

 

                // add fields to ct's

                //

                preTime = DateTime.Now;

                Utils.AddCtField(tbProjectNumber.Text, "Projektdokumente", "Sicherheitsstufe");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Add Fields to Content Types" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

 

                // delete lookup fields from document sets

                //

                preTime = DateTime.Now;

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt 4relation Consulting GmbH", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Consulting GmbH", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Projekt GmbH", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb 4relation", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb NAVAX", "Bereich");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt 4relation Consulting GmbH", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Consulting GmbH", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Projekt GmbH", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb 4relation", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb NAVAX", "Kategorie");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt 4relation Consulting GmbH", "Sicherheitsstufe");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Consulting GmbH", "Sicherheitsstufe");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Projekt NAVAX Projekt GmbH", "Sicherheitsstufe");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb 4relation", "Sicherheitsstufe");

                Utils.DeleteCtField(tbProjectNumber.Text, "Projektdokumente", "Vertrieb NAVAX", "Sicherheitsstufe");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Delete Lookup Fields" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }               

 

                // create configuration parameters

                //

                preTime = DateTime.Now;

                Utils.AddConfigurationEntry(tbProjectNumber.Text, "configuration", "ProjectNumber", tbProjectNumber.Text);

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Create Configuration Parameters" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }

 

                //modify views

                //

                preTime = DateTime.Now;

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Bereich");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Kategorie");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Geändert");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Geändert von");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Inhaltstyp");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "Sicherheitsstufe");

                Utils.DeleteColumnFromView(tbProjectNumber.Text, "Projektdokumente", "Alle Dokumente", "setpermi");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Bereich");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Kategorie");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Geändert");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Geändert von");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Dokumentenmappen", "Sicherheitsstufe");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Bereich");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Kategorie");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Geändert");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Geändert von");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Inhaltstyp");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "Sicherheitsstufe");

                Utils.ChangeViewQuery(tbProjectNumber.Text, "Projektdokumente", "Nach Bereich", "<GroupBy Collapse='FALSE' GroupLimit='30'><FieldRef Name='Bereich' /></GroupBy><OrderBy><FieldRef Name='FileLeafRef' /></OrderBy>");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Bereich");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Kategorie");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Geändert");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Geändert von");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Inhaltstyp");

                Utils.AddColumnToView(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "Sicherheitsstufe");

                Utils.ChangeViewQuery(tbProjectNumber.Text, "Projektdokumente", "Nach Kategorie", "<GroupBy Collapse='FALSE' GroupLimit='30'><FieldRef Name='Kategorie' /></GroupBy><OrderBy><FieldRef Name='FileLeafRef' /></OrderBy>");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Modify Views" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }               

 

                //modify navigation entries

                //

                preTime = DateTime.Now;

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Allgemeines", "#", false);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Dokumente", "#", false);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Service Portal", "#", false);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Service Portal", "Projektaufgaben", "https://service.navax.at/browse/" + tbProjectNumber.Text, true);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Einrichtung", "#", false);

                Utils.ModifyNavigationEntryURL(tbProjectNumber.Text, "Administration", "#", false);

                Utils.ModifyNavigationEntryAudience(tbProjectNumber.Text, "Allgemeines", "Projektportal Administratoren," + tbProjectNumber.Text + "_Intern_PL," + tbProjectNumber.Text + "_Intern_MA");

                Utils.ModifyNavigationEntryAudience(tbProjectNumber.Text, "Einrichtung", "Projektportal Administratoren," + tbProjectNumber.Text + "_Intern_PL");

                Utils.ModifyNavigationEntryAudience(tbProjectNumber.Text, "Administration", "Projektportal Administratoren");

                if (EnableDebugMode)

                {

                    duration = DateTime.Now.Subtract(preTime);

                    lbStatusMessage.Text += "Modify Navigation Entries" + " - Duration: " + duration.TotalSeconds.ToString() + "s<br>";

                }                             

            }

            catch (Exception exc)

            {

                lbStatusMessage.Text += "An exception occured: " + HttpUtility.HtmlEncode(exc.Message);

            }

        }

 

 

        //protected override void OnInit(EventArgs e)

        //{

        //    base.OnInit(e);

 

        //    ScriptManager _AjaxManager = ScriptManager.GetCurrent(this.Page);

        //    if (_AjaxManager == null)

        //    {

        //        //create new ScriptManager and EnablePartialRendering

        //        _AjaxManager = new ScriptManager();

        //        _AjaxManager.EnablePartialRendering = true;

        //        _AjaxManager.AsyncPostBackTimeout = 300;

        //        //Fix problem with postbacks and form actions (DevDiv 55525)

 

        //        Page.ClientScript.RegisterStartupScript(this.GetType(), this.ID, "_spOriginalFormAction = document.forms[0].action;", true);

 

        //        if ((this.Page.Form != null))

        //        {

        //            string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];

        //            if (!string.IsNullOrEmpty(formOnSubmitAtt) & formOnSubmitAtt == "return _spFormOnSubmitWrapper();")

        //            {

        //                this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";

        //            }

        //            //add the ScriptManager as the first control in the Page.Form

        //            this.Page.Form.Controls.AddAt(0, _AjaxManager);

        //        }

        //    }

        //}

 

        //protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)

        //{

        //    _updatePanel.RenderControl(writer);

        //}

 

 

        //public class ProgressTemplate : ITemplate

        //{

        //    private string template;

 

        //    public ProgressTemplate(string temp)

        //    {

        //        template = temp;

        //    }

           

        //    public void InstantiateIn(Control container)

        //    {

        //        LiteralControl ltr = new LiteralControl(this.template);

        //        container.Controls.Add(ltr);

        //    }

        //}

 

        /// <summary>

        /// assigns permission defined by the permissionsettings xml

        /// </summary>

        private void AssignPermission()

        {

            XDocument xdoc = XDocument.Parse(mPermissionSettings);

 

            // create wss groups

            //

            var groupresult = xdoc.Descendants("group");

            foreach (var group in groupresult)

            {

                Debug.WriteLine(group.Attribute("id").Value + " " + group.Attribute("desc").Value);

                Utils.CreateSharepointGroup(string.Format("{0}{1}", tbProjectNumber.Text, group.Attribute("id").Value),

                    string.Format("{0} {1}", group.Attribute("desc").Value, tbProjectName.Text));

            }

 

            // assign permissions per ojbect and group

            //

            var permissionresult = xdoc.Descendants("object");

            string objectid = string.Empty;

            string groupid = string.Empty;

            string permissionvalue = string.Empty;

            string item = string.Empty;

            string field = string.Empty;

 

            foreach (var permission in permissionresult)

            {

                // check attribute count...

                //

               

                List<XAttribute> permissions = new List<XAttribute>();

                permissions.AddRange(permission.Attributes());

                

                if (permissions.Count < 3 || permissions.Count > 5)

                {

                    throw new NotSupportedException("Illegal count of attributes for element 'object'.");

                }

 

                // construct the parameters for the permission setting

                objectid = permission.Attribute("id").Value;

                groupid = string.Format("{0}{1}", tbProjectNumber.Text, permission.Attribute("group").Value);

                permissionvalue = permission.Attribute("permission").Value;

                if (permission.Attribute("item") != null)

                {

                    item = permission.Attribute("item").Value;

                }

                if (permission.Attribute("field") != null)

                {

                    field = permission.Attribute("field").Value;

                }

 

                // special case if the objectid equals to "root" than the root of the site is meant

                //

                if (objectid.Equals("root"))

                {

                    Utils.CreatePermissions(tbProjectNumber.Text, groupid, permissionvalue);

                }

                else // in all other cases

                {

                    if (permissions.Count == 3) // '3 attributes' means permissionassignemnts to lists or libraries

                    {

                        Utils.CreatePermissions(tbProjectNumber.Text, objectid, groupid, permissionvalue);

                    }

                    else if (permissions.Count == 4) // '4 attributes' means permissionassignments to pages or items within lists or libraries

                    {

                        Utils.CreatePermissions(tbProjectNumber.Text, objectid, groupid, permissionvalue, item);

                    }

                    else if (permissions.Count == 5) // '5 attributes' means permissionassignments to pages or items within lists or libraries on a specific field

                    {

                        Utils.CreatePermissions(tbProjectNumber.Text, objectid, item, field, groupid, permissionvalue);

                        //Utils.CreatePermissions(tbProjectNumber.Text, "Sicherheitsstufen", "Intern", "Titel",tbProjectNumber.Text + "_Intern_PL", "Teilnehmen");

                    }

                }

 

                #region debuginformation

                if (permissions.Count == 3)

                {

                    Debug.WriteLine(permission.Attribute("id").Value + " " + permission.Attribute("group").Value + " " + permission.Attribute("permission").Value);

 

                }

                else if (permissions.Count == 4)

                {

                    Debug.WriteLine(permission.Attribute("id").Value + " " + permission.Attribute("group").Value + " " + permission.Attribute("permission").Value + " " + permission.Attribute("item").Value);

                }

                else if (permissions.Count == 5)

                {

                    Debug.WriteLine(permission.Attribute("id").Value + " " + permission.Attribute("group").Value + " " + permission.Attribute("permission").Value + " " + permission.Attribute("item").Value + " " + permission.Attribute("field").Value);

                }

                #endregion

            }

        }

 

        /// <summary>

        /// create a subsite with the given projectnumber, name, description and template for the given language id

        /// </summary>

        /// <param name="projectNumber"></param>

        /// <param name="projectName"></param>

        /// <param name="projectDescription"></param>

        /// <param name="solutionName"></param>

        /// <param name="lcid"></param>

        /// <returns>the url of the newly created subsite</returns>

        private string CreateSite(string projectNumber, string projectName, string projectDescription, string solutionName, uint lcid)

        {

            //Get templateName from solutionName (Example: de_navax4relation_project.wsp)

            string templateName = string.Empty;

            foreach (SPUserSolution solution in SPContext.Current.Site.Solutions)

            {

                lbStatusMessage.Text += solution.Name + " ";

                if (solution.Name == solutionName)

                {

                    //Solution exists

                    foreach (SPFeature feature in SPContext.Current.Site.Features)

                    {

                        if (feature.Definition != null)

                        {

                            if ((feature.Definition.SolutionId == solution.SolutionId) & (feature.Definition.DisplayName.EndsWith("WebTemplate", StringComparison.OrdinalIgnoreCase)))

                            {

                                //Web Template feature exists so calculate the internal template name

                                string featureID = feature.DefinitionId.ToString();

                                if (!featureID.StartsWith("{")) featureID = String.Format("{{{0}}}", featureID);

                                int pos = feature.Definition.DisplayName.LastIndexOf("WebTemplate", StringComparison.OrdinalIgnoreCase);

                                templateName = String.Format("{0}#{1}", featureID, feature.Definition.DisplayName.Substring(0, pos));

                            }

                        }

                    }

                }

            }

 

            SPWeb newWeb = SPContext.Current.Web.Webs.Add(projectNumber, projectName, projectDescription, lcid, templateName, false, false);

            SPNavigationNodeCollection quickLaunch = SPContext.Current.Web.Navigation.QuickLaunch;

 

            if (newWeb != null)

            {

                foreach (SPNavigationNode node in quickLaunch)

                {

                    if (node.Title.Equals(mQuickLaunchHeading))

                    {

                        node.Children.AddAsLast(new SPNavigationNode(newWeb.Title, newWeb.Url.Replace(newWeb.Site.Url, "")));

                    }

                }

            }

            return newWeb.Url;

        }

 

        /// <summary>

        /// returns the name of the selected template of the dropdownbox

        /// </summary>

        private DataRow GetSelectedTemplate()

        {

            DataSet data = ddTemplate.DataSource as DataSet;

            if (data == null || data.Tables.Count == 0)

            {

                throw new ArgumentOutOfRangeException("DataSet is null or empty.");

            }

 

            if (data.Tables[0] == null || data.Tables[0].Rows.Count == 0)

            {

                throw new ArgumentOutOfRangeException("DataTable is null or empty.");

            }

 

            string selectedId = ddTemplate.SelectedValue;

            foreach (DataRow row in data.Tables[0].Rows)

            {

                if (row["id"].ToString() == selectedId)

                {

                    return row;

                }

            }

            return null;

        }

 

        /// <summary>

        /// checks if the project number has illegal characters

        /// </summary>

        /// <returns>returns true if all characters are legal otherwise false</returns>

        private bool IsValidProjectNumber()

        {

            if (tbProjectNumber.Text.Trim().Length < 1)

                return false;

            if (tbProjectNumber.Text.IndexOfAny(ILLEGALCHARS.ToCharArray()) > -1)

                return false;

            return true;

        }

        #endregion

    }

}

Habe den Code jetzt folgendermaßen abgeändert. So funktioniert er. Habe allerdings mit //boese Kommentare geschrieben wie ich was noch geändert hätte. Diese Änderungen sind allerdings hier nur Kommentare, da sie mir eine FileNotFound-Exception zurückgeben, was ich allerdings nicht verstehen kann.

V.a. warum funktioniert folgende Zeile:

SPDocumentLibrary

 

 

 doclib = theWeb.GetList("/" + siteURL + "/" + doclibName) as SPDocumentLibrary;

aber folgende Zeile funktioniert nicht:

SPList

 

 

list = theWeb.GetList("/" + siteURL + "/" +listName);

 

Für mich vollkommen unverständlich...

Bin wie immer sehr dankbar für alle Hilfestellungen

Liebe Grüße

Vronsch

 

Für mich vollkommen unverständlich...

Bin wie immer sehr dankbar für alle Hilfestellungen

Liebe Grüße

Vronsch

 

Für mich vollkommen unverständlich...

Bin wie immer sehr dankbar für alle Hilfestellungen

Liebe Grüße

Vronsch

Für mich vollkommen unverständlich...

Bin wie immer sehr dankbar für alle Hilfestellungen

Liebe Grüße

Vronsch

 

 

 

 

 


Ohne Rang
19231 Beiträge
Andi Fandrich Als Antwort am 9 Aug. 2013 14:55
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

[quote user="Vronsch"]aber folgende Zeile funktioniert nicht:

SPList list = theWeb.GetList("/" + siteURL + "/" +listName);[/quote]

Das liegt daran, daß Listen normalerweise alle in einem Ordner "Lists" liegen, also z.B.
/Sites/Site1/Lists/Listname

Viele Grüße
Andi
af @ evocom de
Blog
Ohne Rang
929 Beiträge
Thomas Östreich Als Antwort am 9 Aug. 2013 15:50
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Die URL zu Liste hat nichts mit den Namen zu tun (nur Zufall wenn Sie keine Sonderzeichen enthält), da der Name einer Liste zum einen geändert und zum anderem Sonderzeichen enthalten kann. Die URL kann normalerweise direkt nicht geändert werden und kann auch keine Sonderzeichen enthalten. Es ist immer die RootFolder URL.

Ohne Rang
11 Beiträge
Vronsch Als Antwort am 12 Aug. 2013 13:23
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Ahhh natürlich, Dankeschön. So funktioniert es jetzt:

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Navigation;

using Microsoft.SharePoint.Publishing;

using Microsoft.SharePoint.Publishing.Navigation;

using Microsoft.Office.DocumentManagement.DocumentSets;

using System.Collections;

using System.Data.SqlClient;

using Microsoft.SharePoint.Utilities;

 

namespace ForRelation.SP.ProjectPortal.AddOns

{

    public static class Utils

    {

        /// <summary>

        /// set permissons for sharepoint groups on site

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(SPWeb theWeb, SPPrincipal spgroupName, string permissionLevel)

        {

            theWeb.AllowUnsafeUpdates = true;

 

            SPRoleAssignment roleAssignment = new SPRoleAssignment(spgroupName);

            SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

            if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

            //Check inheritance

            if (!theWeb.HasUniqueRoleAssignments)

            {

                theWeb.BreakRoleInheritance(false);

            }

 

            theWeb.RoleAssignments.Add(roleAssignment);

 

            theWeb.Update();

 

            if (theWeb != null)

                theWeb.Dispose();           

        }

 

        /// <summary>

        /// set permissons for sharepoint groups on lists

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="List"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(SPWeb theWeb, SPList List, SPPrincipal spgroupName, string permissionLevel)

        {

            theWeb.AllowUnsafeUpdates = true;

 

            SPRoleAssignment roleAssignment = new SPRoleAssignment(spgroupName);

            SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

            if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

            //Check inheritance

            if (!List.HasUniqueRoleAssignments)

            {

                List.BreakRoleInheritance(false);

            }

 

            List.RoleAssignments.Add(roleAssignment);

 

            List.Update();

 

            if (theWeb != null)

                theWeb.Dispose();

        }

 

        /// <summary>

        /// set permissons for sharepoint groups on lists V2

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="list"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(string siteURL, string list, string spgroupName, string permissionLevel)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList List = theWeb.Lists[list];//loginName stammt aus einem xml. Somit ist es schwer festzustellen, ob es sich um eine Liste oder Doclib handelt.

 

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                //Check inheritance

                if (!List.HasUniqueRoleAssignments)

                {

                    List.BreakRoleInheritance(false);

                }

 

                List.RoleAssignments.Add(roleAssignment);

 

                List.Update();

                //try

                //{

 

                //}

                //catch (Exception exc)

                //{

                //    System.Diagnostics.EventLog.WriteEntry("NewProject", exc.ToString(), EventLogEntryType.Error);

                //    throw;

                //}

            }

 

           

        }

 

        /// <summary>

        /// set permission to an item of a given list/library and identify item on the "Name" field

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="list"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        /// <param name="itemname"></param>

        public static void CreatePermissions(string siteURL, string list, string spgroupName, string permissionLevel, string itemname)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {               

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList List = theWeb.Lists[list];//loginName stammt aus einem xml. Somit ist es schwer festzustellen, ob es sich um eine Liste oder Doclib handelt.

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                SPListItemCollection items = List.Items;

                foreach (SPListItem item in items)

                {

                    if (item["Name"].ToString().Equals(itemname))

                    {

                        item.BreakRoleInheritance(false);

                        item.RoleAssignments.Add(roleAssignment);

                        item.Update();

                    }

                }

            }

           

        }

 

        /// <summary>

        /// set permission to an item of a given list/library and identify item on a specific field

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="list"></param>

        /// <param name="itemname"></param>

        /// <param name="searchfield"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(string siteURL, string list, string itemname, string searchfield, string spgroupName, string permissionLevel)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList List = theWeb.Lists[list];//loginName stammt aus einem xml. Somit ist es schwer festzustellen, ob es sich um eine Liste oder Doclib handelt.

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                SPListItemCollection items = List.Items;

                foreach (SPListItem item in items)

                {

                    if (item[searchfield].ToString().Equals(itemname))

                    {

                        item.BreakRoleInheritance(false);

                        item.RoleAssignments.Add(roleAssignment);

                        item.Update();

                    }

                }

            }

           

        }

 

        /// <summary>

        /// set permissons for sharepoint groups V2

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(string siteURL, string spgroupName, string permissionLevel)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                //Check inheritance

                if (!theWeb.HasUniqueRoleAssignments)

                {

                    theWeb.BreakRoleInheritance(false);

                }

 

                theWeb.RoleAssignments.Add(roleAssignment);

 

                theWeb.Update();               

            }           

        }

 

        /// <summary>

        /// add new navigation entry WSS Quicklaunch

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="url"></param>

        /// <param name="external"></param>

        public static void CreateNavigationEntry(string siteURL, string title, string url, bool external)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPNavigationNodeCollection quickLaunchNodes = theWeb.Navigation.QuickLaunch;

                SPNavigationNode navigationentry = new SPNavigationNode(title, url, external);

 

                quickLaunchNodes.AddAsLast(navigationentry);

 

                theWeb.Update();               

            }

        }

 

        /// <summary>

        /// modify url on publishing site navigation entry

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="url"></param>

        /// <param name="external"></param>

        public static void ModifyNavigationEntryURL(string siteURL, string title, string url, bool OpenInNewWindow)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                theWeb.AllowUnsafeUpdates = true;

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                PublishingWeb thePubWeb = PublishingWeb.GetPublishingWeb(theWeb);               

 

                foreach (SPNavigationNode navNodes in thePubWeb.Navigation.CurrentNavigationNodes)

                {

                    if (navNodes.Title == title)

                    {

                        navNodes.Url = url;

                        if (OpenInNewWindow == true)

                        {

                            navNodes.Properties["Target"] = "_blank";

                        }

                        navNodes.Update();

                        thePubWeb.Update();

                    }

                }

            }           

        }

 

        /// <summary>

        /// modify url on publishing site navigation entry children

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="url"></param>

        /// <param name="external"></param>

        public static void ModifyNavigationEntryURL(string siteURL, string title, string subtitle, string url, bool OpenInNewWindow)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                PublishingWeb thePubWeb = PublishingWeb.GetPublishingWeb(theWeb);               

 

                foreach (SPNavigationNode navNodes in thePubWeb.Navigation.CurrentNavigationNodes)

                {

                    if (navNodes.Title == title)

                    {

                        foreach (SPNavigationNode navNodeChildren in navNodes.Children)

                        {

                            if (navNodeChildren.Title == subtitle)

                            {

                                navNodeChildren.Url = url;

                                if (OpenInNewWindow == true)

                                {

                                    navNodeChildren.Properties["Target"] = "_blank";

                                }

                                navNodeChildren.Update();

                                thePubWeb.Update();

                            }

                        }

                    }

                }               

            }

        }

 

        /// <summary>

        /// modify audience on publishing site navigation entry

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="audience"></param>

        public static void ModifyNavigationEntryAudience(string siteURL, string title, string audience)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                PublishingWeb thePubWeb = PublishingWeb.GetPublishingWeb(theWeb);               

 

                foreach (SPNavigationNode navNodes in thePubWeb.Navigation.CurrentNavigationNodes)

                {

                    if (navNodes.Title == title)

                    {

                        navNodes.Properties.Add("Audience", ";;;;" + audience);

                        navNodes.Update();

                        thePubWeb.Update();

                    }

                }               

            }           

        }

 

        /// <summary>

        /// add new sharepoint group

        /// </summary>

        /// <param name="groupName"></param>

        /// <param name="groupDescription"></param>

        public static void CreateSharepointGroup(string groupName, string groupDescription)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb("/"))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs["/"];

                theWeb.SiteGroups.Add(groupName, theWeb.AssociatedOwnerGroup, null, groupDescription);               

            }

        }

 

        /// <summary>

        /// create document set

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="setName"></param>

        /// <param name="documentSetCt"></param>

        public static TimeSpan CreateDocumentSet(string siteURL, string doclibNameURL, string setName, string documentSetCt)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                DateTime preTime = DateTime.Now;

                TimeSpan duration;

 

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

 

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;

                SPFolder folderToInsert = doclib.RootFolder;

                SPContentTypeId dsCtID = new SPContentTypeId();

 

                dsCtID = doclib.ContentTypes[documentSetCt].Id;

 

                // Create the Document Set Properties HashTable

 

                Hashtable properties = new Hashtable();

                properties.Add("Name", setName);

                //properties.Add("Project Client", "AdventureWorks");

 

                DocumentSet docSet = DocumentSet.Create(folderToInsert, setName, dsCtID, properties);

               

                docSet.Provision();

                //doclib.Folders.Add();

 

                duration = DateTime.Now.Subtract(preTime);

                return duration;

            }          

        }

 

        /// <summary>

        /// delete folder from document library

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="folderName"></param>

        public static TimeSpan DeleteDoclibFolder(string siteURL, string doclibNameURL, string folderName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                DateTime preTime = DateTime.Now;

                TimeSpan duration;

 

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                theWeb.Folders[doclibNameURL].SubFolders.Delete(folderName);

 

                duration = DateTime.Now.Subtract(preTime);

                return duration;

            }

        }

 

        /// <summary>

        /// add new lookup field to document library and on all content types

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="lookupFieldName"></param>

        /// <param name="lookupFieldTargetList"></param>

        /// <param name="lookupFieldTargetListField"></param>

        public static void CreateLookupField(string siteURL, string doclibNameURL, string lookupFieldName, string lookupFieldTargetList, string lookupFieldTargetListField)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;               

 

                SPList targetList = theWeb.Lists[lookupFieldTargetList];

               

                SPField targetField = targetList.Fields[lookupFieldTargetListField];

 

                doclib.Fields.AddLookup(lookupFieldName, targetList.ID, false);

                SPFieldLookup lkp = (SPFieldLookup)doclib.Fields[lookupFieldName];

                lkp.LookupField = targetField.InternalName;

                lkp.Update();

 

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(new SPFieldLink(lkp));

                    ct.Update();

                }

 

                doclib.Update();               

            }           

        }

 

        /// <summary>

        /// add new lookup field to document library and on all content types

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="lookupFieldName"></param>

        /// <param name="lookupFieldTargetList"></param>

        /// <param name="lookupFieldTargetListField"></param>

        public static void CreateListLookupField(string siteURL, string listNameURL, string lookupFieldName, string lookupFieldTargetList, string lookupFieldTargetListField)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL) as SPDocumentLibrary;

 

                SPList targetList = theWeb.GetList("/" + siteURL + "/Lists/" + lookupFieldTargetList);

                //ALT:SPList targetList = theWeb.Lists[lookupFieldTargetList];

               

                SPField targetField = targetList.Fields[lookupFieldTargetListField];

 

                doclib.Fields.AddLookup(lookupFieldName, targetList.ID, false);

                SPFieldLookup lkp = (SPFieldLookup)doclib.Fields[lookupFieldName];

                lkp.LookupField = targetField.InternalName;

                lkp.Update();

 

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(new SPFieldLink(lkp));

                    ct.Update();

                }

 

                doclib.Update();

            }

        }

 

        /// <summary>

        /// add new lookup field to document library and on all content types

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="lookupFieldName"></param>

        /// <param name="lookupFieldTargetListURL"></param>

        /// <param name="lookupFieldTargetListField"></param>

        public static void CreateDoclibLookupField(string siteURL, string doclibNameURL, string lookupFieldName, string lookupFieldTargetListURL, string lookupFieldTargetListField)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;

 

                SPList targetList = theWeb.GetList("/" + siteURL + "/Lists/" + lookupFieldTargetListURL);

               

                SPField targetField = targetList.Fields[lookupFieldTargetListField];

 

                doclib.Fields.AddLookup(lookupFieldName, targetList.ID, false);

                SPFieldLookup lkp = (SPFieldLookup)doclib.Fields[lookupFieldName];

                lkp.LookupField = targetField.InternalName;

                lkp.Update();

 

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(new SPFieldLink(lkp));

                    ct.Update();

                }

 

                doclib.Update();

            }

        }

 

        /// <summary>

        /// delete field from content type

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="ctName"></param>

        /// <param name="fieldName"></param>

        public static void DeleteDoclibCtField(string siteURL, string doclibNameURL, string ctName, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                theWeb.AllowUnsafeUpdates = true;

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;               

 

                SPContentTypeCollection ctcoll = doclib.ContentTypes;

                SPContentType ct = ctcoll[ctName];

                ct.FieldLinks.Delete(fieldName);

                ct.Update();                

            }

        }

 

        /// <summary>

        /// add field to a specific content type in document library

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="ctName"></param>

        /// <param name="fieldName"></param>

        public static void AddDoclibCtField(string siteURL, string doclibNameURL, string ctName, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);               

 

                SPContentTypeCollection ctcoll = doclib.ContentTypes;

                SPContentType ct = ctcoll[ctName];

                ct.FieldLinks.Add(fieldLink);

                ct.Update();               

            }

        }

 

        /// <summary>

        /// add field to all content types in document library

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="fieldName"></param>

        public static void AddDoclibCtField(string siteURL, string doclibNameURL, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);               

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(fieldLink);

                    ct.Update();

                }               

            }

        }

 

        /// <summary>

        /// add field to all content types in document library in current web

        /// </summary>

        /// <param name="doclibNameURL"></param>

        /// <param name="fieldName"></param>

        public static void AddDoclibCtFieldCurr(string doclibNameURL, string fieldName)

        {

           

            //using (SPDocumentLibrary doclib = SPContext.Current.Web.Lists[doclibName] as SPDocumentLibrary)

            using (SPWeb theWeb = SPContext.Current.Web)

            {

                SPDocumentLibrary doclib = theWeb.GetList("/" + theWeb.ServerRelativeUrl + "/" + doclibNameURL) as SPDocumentLibrary;

                //ALT: SPDocumentLibrary doclib = theWeb.Lists[doclibName] as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(fieldLink);

                    ct.Update();

                }

            }       

        }

 

        /// <summary>

        /// add field to a specific content type in document library in current web

        /// </summary>

        /// <param name="doclibNameURL"></param>

        /// <param name="ctName"></param>

        /// <param name="fieldName"></param>

        public static void AddDoclibCtFieldCurr(string doclibNameURL, string ctName, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Web)

            {

                SPDocumentLibrary doclib = theWeb.GetList("/" + theWeb.ServerRelativeUrl + "/" + doclibNameURL) as SPDocumentLibrary;

                //ALT: SPDocumentLibrary doclib = theWeb.Lists[doclibName] as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);

 

                SPContentTypeCollection ctcoll = doclib.ContentTypes;

                SPContentType ct = ctcoll[ctName];

                ct.FieldLinks.Add(fieldLink);

                ct.Update();

            }          

        }

 

 

 

        /// <summary>

        /// create new parameter entry in configuration list

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="entryName"></param>

        /// <param name="entryValue"></param>

        public static void AddConfigurationEntry(string siteURL, string listNameURL, string entryName, string entryValue)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL);

                //ALT: SPList list = theWeb.Lists[listName];

                SPListItem newItem = list.Items.Add();               

 

                newItem["Parameter"] = entryName;

                newItem["Value"] = entryValue;

                newItem.Update();              

            }

        }

 

        /// <summary>

        /// delete column from view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void DeleteColumnFromView(string siteURL, string listNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.Lists[listNameURL];

                SPView view = list.Views[viewName];

 

                if (view.ViewFields.Exists(columnName))

                {

                    theWeb.AllowUnsafeUpdates = true;

                    view.ViewFields.Delete(columnName);

                    view.Update();

                }               

            }

        }

 

        /// <summary>

        /// delete column from view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void DeleteColumnFromListView(string siteURL, string listNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                SPList list = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL);

                SPView view = list.Views[viewName];

 

                if (view.ViewFields.Exists(columnName))

                {

                    theWeb.AllowUnsafeUpdates = true;

                    view.ViewFields.Delete(columnName);

                    view.Update();

                }

            }

        }

 

        /// <summary>

        /// delete column from view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void DeleteColumnFromDoclibView(string siteURL, string doclibNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                SPList list = theWeb.GetList("/" + siteURL + "/" + doclibNameURL);

                SPView view = list.Views[viewName];

 

                if (view.ViewFields.Exists(columnName))

                {

                    theWeb.AllowUnsafeUpdates = true;

                    view.ViewFields.Delete(columnName);

                    view.Update();

                }

            }

        }

 

        /// <summary>

        /// add column to view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void AddColumnToView(string siteURL, string listNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.Lists[listNameURL];

                SPView view = list.Views[viewName];

 

                theWeb.AllowUnsafeUpdates = true;

                view.ViewFields.Add(columnName);

                view.Update();               

            }

        }

 

        /// <summary>

        /// add column to view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void AddColumnToListView(string siteURL, string listNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL);

                //ALT: SPList list = theWeb.Lists[listName];

                SPView view = list.Views[viewName];

 

                theWeb.AllowUnsafeUpdates = true;

                view.ViewFields.Add(columnName);

                view.Update();

            }

        }

 

        /// <summary>

        /// add column to view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void AddColumnToDoclibView(string siteURL, string doclibNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.GetList("/" + siteURL + "/" + doclibNameURL);

                //ALT: SPList list = theWeb.Lists[doclibName];

                SPView view = list.Views[viewName];

 

                theWeb.AllowUnsafeUpdates = true;

                view.ViewFields.Add(columnName);

                view.Update();

            }

        }

 

 

        public static void ChangeViewQuery(string siteURL, string listNameURL, string viewName, string viewQuery)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.Lists[listNameURL];

                SPView view = list.Views[viewName];               

 

                view.Query = viewQuery;

                view.Update();               

            }          

        }

 

        public static void ChangeDoclibViewQuery(string siteURL, string doclibNameURL, string viewName, string viewQuery)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.GetList("/" + siteURL + "/" + doclibNameURL);

                //ALT: SPList list = theWeb.Lists[doclibName];

                SPView view = list.Views[viewName];

 

                view.Query = viewQuery;

                view.Update();

            }

        }

 

        public static void ChangeListViewQuery(string siteURL, string listNameURL, string viewName, string viewQuery)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL);

                //ALT: SPList list = theWeb.Lists[listName];

                SPView view = list.Views[viewName];

 

                view.Query = viewQuery;

                view.Update();

            }

        }

 

        /// <summary>

        /// Create Permisson on specific item

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="ListItem"></param>

        /// <param name="loginName"></param>

        /// <param name="roleName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(SPWeb theWeb, SPListItem ListItem, string loginName, string roleName, string permissionLevel)

        {

            using (theWeb = new SPSite(theWeb.Site.ID).OpenWeb(theWeb.ID))

            {

                //theWeb = new SPSite(theWeb.Site.ID).OpenWeb(theWeb.ID);

                theWeb.AllowUnsafeUpdates = true;

 

                ListItem = theWeb.Lists[ListItem.ParentList.ID].GetItemById(ListItem.ID);

                //loginName stammt aus einem xml. Somit ist es schwer festzustellen, ob es sich um eine Liste oder Doclib handelt.

 

                SPRoleAssignment roleAssignment = new SPRoleAssignment(loginName, "", roleName, "");

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                //Check inheritance

                if (!ListItem.HasUniqueRoleAssignments)

                {

                    ListItem.BreakRoleInheritance(false);

                }

 

                ListItem.RoleAssignments.Add(roleAssignment);

 

                ListItem.Update();                

            }

        }

 

        /// <summary>

        /// Add User to specific group on specific site

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="groupName"></param>

        /// <param name="userName"></param>

        public static void AddUserToGroup(string siteURL, string groupName, string userName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

 

                SPUser spUser = theWeb.EnsureUser(userName);

 

                if (spUser != null)

                {

                    SPGroup spGroup = theWeb.Groups[groupName];

 

                    if (spGroup != null)

                        spGroup.AddUser(spUser);

                }               

            }          

        }

    }

}

 

Die Codestellen, welche ich nicht optimieren konnte sind durch Kommentare gekennzeichnet....
Gibt es noch weitere Optimierungen die ich vornehmen kann?

Ohne Rang
929 Beiträge
Thomas Östreich Als Antwort am 12 Aug. 2013 13:34
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

[quote user="Vronsch"]

               SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;               

 

[/quote]

Benutze lieber SPUrlUtility.CombineUrl(web.ServerRelativeUrl, docUrl) bzw. SPUrlUtility.CombineUrl(web.ServerRelativeUrl, "Lists/ListUrlName")

verhindert Probleme mit der RootSite "/" -> "///"

 

Ohne Rang
11 Beiträge
Vronsch Als Antwort am 14 Aug. 2013 15:38
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Werde ich machen. Dankeschön

Ohne Rang
11 Beiträge
Vronsch Als Antwort am 12 Aug. 2013 13:23
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Ahhh natürlich, Dankeschön. So funktioniert es jetzt:

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Navigation;

using Microsoft.SharePoint.Publishing;

using Microsoft.SharePoint.Publishing.Navigation;

using Microsoft.Office.DocumentManagement.DocumentSets;

using System.Collections;

using System.Data.SqlClient;

using Microsoft.SharePoint.Utilities;

 

namespace ForRelation.SP.ProjectPortal.AddOns

{

    public static class Utils

    {

        /// <summary>

        /// set permissons for sharepoint groups on site

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(SPWeb theWeb, SPPrincipal spgroupName, string permissionLevel)

        {

            theWeb.AllowUnsafeUpdates = true;

 

            SPRoleAssignment roleAssignment = new SPRoleAssignment(spgroupName);

            SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

            if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

            //Check inheritance

            if (!theWeb.HasUniqueRoleAssignments)

            {

                theWeb.BreakRoleInheritance(false);

            }

 

            theWeb.RoleAssignments.Add(roleAssignment);

 

            theWeb.Update();

 

            if (theWeb != null)

                theWeb.Dispose();           

        }

 

        /// <summary>

        /// set permissons for sharepoint groups on lists

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="List"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(SPWeb theWeb, SPList List, SPPrincipal spgroupName, string permissionLevel)

        {

            theWeb.AllowUnsafeUpdates = true;

 

            SPRoleAssignment roleAssignment = new SPRoleAssignment(spgroupName);

            SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

            if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

            //Check inheritance

            if (!List.HasUniqueRoleAssignments)

            {

                List.BreakRoleInheritance(false);

            }

 

            List.RoleAssignments.Add(roleAssignment);

 

            List.Update();

 

            if (theWeb != null)

                theWeb.Dispose();

        }

 

        /// <summary>

        /// set permissons for sharepoint groups on lists V2

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="list"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(string siteURL, string list, string spgroupName, string permissionLevel)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList List = theWeb.Lists[list];//loginName stammt aus einem xml. Somit ist es schwer festzustellen, ob es sich um eine Liste oder Doclib handelt.

 

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                //Check inheritance

                if (!List.HasUniqueRoleAssignments)

                {

                    List.BreakRoleInheritance(false);

                }

 

                List.RoleAssignments.Add(roleAssignment);

 

                List.Update();

                //try

                //{

 

                //}

                //catch (Exception exc)

                //{

                //    System.Diagnostics.EventLog.WriteEntry("NewProject", exc.ToString(), EventLogEntryType.Error);

                //    throw;

                //}

            }

 

           

        }

 

        /// <summary>

        /// set permission to an item of a given list/library and identify item on the "Name" field

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="list"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        /// <param name="itemname"></param>

        public static void CreatePermissions(string siteURL, string list, string spgroupName, string permissionLevel, string itemname)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {               

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList List = theWeb.Lists[list];//loginName stammt aus einem xml. Somit ist es schwer festzustellen, ob es sich um eine Liste oder Doclib handelt.

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                SPListItemCollection items = List.Items;

                foreach (SPListItem item in items)

                {

                    if (item["Name"].ToString().Equals(itemname))

                    {

                        item.BreakRoleInheritance(false);

                        item.RoleAssignments.Add(roleAssignment);

                        item.Update();

                    }

                }

            }

           

        }

 

        /// <summary>

        /// set permission to an item of a given list/library and identify item on a specific field

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="list"></param>

        /// <param name="itemname"></param>

        /// <param name="searchfield"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(string siteURL, string list, string itemname, string searchfield, string spgroupName, string permissionLevel)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList List = theWeb.Lists[list];//loginName stammt aus einem xml. Somit ist es schwer festzustellen, ob es sich um eine Liste oder Doclib handelt.

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                SPListItemCollection items = List.Items;

                foreach (SPListItem item in items)

                {

                    if (item[searchfield].ToString().Equals(itemname))

                    {

                        item.BreakRoleInheritance(false);

                        item.RoleAssignments.Add(roleAssignment);

                        item.Update();

                    }

                }

            }

           

        }

 

        /// <summary>

        /// set permissons for sharepoint groups V2

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="spgroupName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(string siteURL, string spgroupName, string permissionLevel)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPPrincipal principal = (SPPrincipal)theWeb.SiteGroups[spgroupName];

                SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                //Check inheritance

                if (!theWeb.HasUniqueRoleAssignments)

                {

                    theWeb.BreakRoleInheritance(false);

                }

 

                theWeb.RoleAssignments.Add(roleAssignment);

 

                theWeb.Update();               

            }           

        }

 

        /// <summary>

        /// add new navigation entry WSS Quicklaunch

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="url"></param>

        /// <param name="external"></param>

        public static void CreateNavigationEntry(string siteURL, string title, string url, bool external)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPNavigationNodeCollection quickLaunchNodes = theWeb.Navigation.QuickLaunch;

                SPNavigationNode navigationentry = new SPNavigationNode(title, url, external);

 

                quickLaunchNodes.AddAsLast(navigationentry);

 

                theWeb.Update();               

            }

        }

 

        /// <summary>

        /// modify url on publishing site navigation entry

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="url"></param>

        /// <param name="external"></param>

        public static void ModifyNavigationEntryURL(string siteURL, string title, string url, bool OpenInNewWindow)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                theWeb.AllowUnsafeUpdates = true;

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                PublishingWeb thePubWeb = PublishingWeb.GetPublishingWeb(theWeb);               

 

                foreach (SPNavigationNode navNodes in thePubWeb.Navigation.CurrentNavigationNodes)

                {

                    if (navNodes.Title == title)

                    {

                        navNodes.Url = url;

                        if (OpenInNewWindow == true)

                        {

                            navNodes.Properties["Target"] = "_blank";

                        }

                        navNodes.Update();

                        thePubWeb.Update();

                    }

                }

            }           

        }

 

        /// <summary>

        /// modify url on publishing site navigation entry children

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="url"></param>

        /// <param name="external"></param>

        public static void ModifyNavigationEntryURL(string siteURL, string title, string subtitle, string url, bool OpenInNewWindow)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                PublishingWeb thePubWeb = PublishingWeb.GetPublishingWeb(theWeb);               

 

                foreach (SPNavigationNode navNodes in thePubWeb.Navigation.CurrentNavigationNodes)

                {

                    if (navNodes.Title == title)

                    {

                        foreach (SPNavigationNode navNodeChildren in navNodes.Children)

                        {

                            if (navNodeChildren.Title == subtitle)

                            {

                                navNodeChildren.Url = url;

                                if (OpenInNewWindow == true)

                                {

                                    navNodeChildren.Properties["Target"] = "_blank";

                                }

                                navNodeChildren.Update();

                                thePubWeb.Update();

                            }

                        }

                    }

                }               

            }

        }

 

        /// <summary>

        /// modify audience on publishing site navigation entry

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="title"></param>

        /// <param name="audience"></param>

        public static void ModifyNavigationEntryAudience(string siteURL, string title, string audience)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                PublishingWeb thePubWeb = PublishingWeb.GetPublishingWeb(theWeb);               

 

                foreach (SPNavigationNode navNodes in thePubWeb.Navigation.CurrentNavigationNodes)

                {

                    if (navNodes.Title == title)

                    {

                        navNodes.Properties.Add("Audience", ";;;;" + audience);

                        navNodes.Update();

                        thePubWeb.Update();

                    }

                }               

            }           

        }

 

        /// <summary>

        /// add new sharepoint group

        /// </summary>

        /// <param name="groupName"></param>

        /// <param name="groupDescription"></param>

        public static void CreateSharepointGroup(string groupName, string groupDescription)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb("/"))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs["/"];

                theWeb.SiteGroups.Add(groupName, theWeb.AssociatedOwnerGroup, null, groupDescription);               

            }

        }

 

        /// <summary>

        /// create document set

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="setName"></param>

        /// <param name="documentSetCt"></param>

        public static TimeSpan CreateDocumentSet(string siteURL, string doclibNameURL, string setName, string documentSetCt)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                DateTime preTime = DateTime.Now;

                TimeSpan duration;

 

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

 

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;

                SPFolder folderToInsert = doclib.RootFolder;

                SPContentTypeId dsCtID = new SPContentTypeId();

 

                dsCtID = doclib.ContentTypes[documentSetCt].Id;

 

                // Create the Document Set Properties HashTable

 

                Hashtable properties = new Hashtable();

                properties.Add("Name", setName);

                //properties.Add("Project Client", "AdventureWorks");

 

                DocumentSet docSet = DocumentSet.Create(folderToInsert, setName, dsCtID, properties);

               

                docSet.Provision();

                //doclib.Folders.Add();

 

                duration = DateTime.Now.Subtract(preTime);

                return duration;

            }          

        }

 

        /// <summary>

        /// delete folder from document library

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="folderName"></param>

        public static TimeSpan DeleteDoclibFolder(string siteURL, string doclibNameURL, string folderName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                DateTime preTime = DateTime.Now;

                TimeSpan duration;

 

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                theWeb.Folders[doclibNameURL].SubFolders.Delete(folderName);

 

                duration = DateTime.Now.Subtract(preTime);

                return duration;

            }

        }

 

        /// <summary>

        /// add new lookup field to document library and on all content types

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="lookupFieldName"></param>

        /// <param name="lookupFieldTargetList"></param>

        /// <param name="lookupFieldTargetListField"></param>

        public static void CreateLookupField(string siteURL, string doclibNameURL, string lookupFieldName, string lookupFieldTargetList, string lookupFieldTargetListField)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;               

 

                SPList targetList = theWeb.Lists[lookupFieldTargetList];

               

                SPField targetField = targetList.Fields[lookupFieldTargetListField];

 

                doclib.Fields.AddLookup(lookupFieldName, targetList.ID, false);

                SPFieldLookup lkp = (SPFieldLookup)doclib.Fields[lookupFieldName];

                lkp.LookupField = targetField.InternalName;

                lkp.Update();

 

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(new SPFieldLink(lkp));

                    ct.Update();

                }

 

                doclib.Update();               

            }           

        }

 

        /// <summary>

        /// add new lookup field to document library and on all content types

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="lookupFieldName"></param>

        /// <param name="lookupFieldTargetList"></param>

        /// <param name="lookupFieldTargetListField"></param>

        public static void CreateListLookupField(string siteURL, string listNameURL, string lookupFieldName, string lookupFieldTargetList, string lookupFieldTargetListField)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL) as SPDocumentLibrary;

 

                SPList targetList = theWeb.GetList("/" + siteURL + "/Lists/" + lookupFieldTargetList);

                //ALT:SPList targetList = theWeb.Lists[lookupFieldTargetList];

               

                SPField targetField = targetList.Fields[lookupFieldTargetListField];

 

                doclib.Fields.AddLookup(lookupFieldName, targetList.ID, false);

                SPFieldLookup lkp = (SPFieldLookup)doclib.Fields[lookupFieldName];

                lkp.LookupField = targetField.InternalName;

                lkp.Update();

 

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(new SPFieldLink(lkp));

                    ct.Update();

                }

 

                doclib.Update();

            }

        }

 

        /// <summary>

        /// add new lookup field to document library and on all content types

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="lookupFieldName"></param>

        /// <param name="lookupFieldTargetListURL"></param>

        /// <param name="lookupFieldTargetListField"></param>

        public static void CreateDoclibLookupField(string siteURL, string doclibNameURL, string lookupFieldName, string lookupFieldTargetListURL, string lookupFieldTargetListField)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;

 

                SPList targetList = theWeb.GetList("/" + siteURL + "/Lists/" + lookupFieldTargetListURL);

               

                SPField targetField = targetList.Fields[lookupFieldTargetListField];

 

                doclib.Fields.AddLookup(lookupFieldName, targetList.ID, false);

                SPFieldLookup lkp = (SPFieldLookup)doclib.Fields[lookupFieldName];

                lkp.LookupField = targetField.InternalName;

                lkp.Update();

 

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(new SPFieldLink(lkp));

                    ct.Update();

                }

 

                doclib.Update();

            }

        }

 

        /// <summary>

        /// delete field from content type

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="ctName"></param>

        /// <param name="fieldName"></param>

        public static void DeleteDoclibCtField(string siteURL, string doclibNameURL, string ctName, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                theWeb.AllowUnsafeUpdates = true;

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;               

 

                SPContentTypeCollection ctcoll = doclib.ContentTypes;

                SPContentType ct = ctcoll[ctName];

                ct.FieldLinks.Delete(fieldName);

                ct.Update();                

            }

        }

 

        /// <summary>

        /// add field to a specific content type in document library

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="ctName"></param>

        /// <param name="fieldName"></param>

        public static void AddDoclibCtField(string siteURL, string doclibNameURL, string ctName, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);               

 

                SPContentTypeCollection ctcoll = doclib.ContentTypes;

                SPContentType ct = ctcoll[ctName];

                ct.FieldLinks.Add(fieldLink);

                ct.Update();               

            }

        }

 

        /// <summary>

        /// add field to all content types in document library

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="fieldName"></param>

        public static void AddDoclibCtField(string siteURL, string doclibNameURL, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPDocumentLibrary doclib = theWeb.GetList("/" + siteURL + "/" + doclibNameURL) as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);               

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(fieldLink);

                    ct.Update();

                }               

            }

        }

 

        /// <summary>

        /// add field to all content types in document library in current web

        /// </summary>

        /// <param name="doclibNameURL"></param>

        /// <param name="fieldName"></param>

        public static void AddDoclibCtFieldCurr(string doclibNameURL, string fieldName)

        {

           

            //using (SPDocumentLibrary doclib = SPContext.Current.Web.Lists[doclibName] as SPDocumentLibrary)

            using (SPWeb theWeb = SPContext.Current.Web)

            {

                SPDocumentLibrary doclib = theWeb.GetList("/" + theWeb.ServerRelativeUrl + "/" + doclibNameURL) as SPDocumentLibrary;

                //ALT: SPDocumentLibrary doclib = theWeb.Lists[doclibName] as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);

 

                foreach (SPContentType ct in doclib.ContentTypes)

                {

                    ct.FieldLinks.Add(fieldLink);

                    ct.Update();

                }

            }       

        }

 

        /// <summary>

        /// add field to a specific content type in document library in current web

        /// </summary>

        /// <param name="doclibNameURL"></param>

        /// <param name="ctName"></param>

        /// <param name="fieldName"></param>

        public static void AddDoclibCtFieldCurr(string doclibNameURL, string ctName, string fieldName)

        {

            using (SPWeb theWeb = SPContext.Current.Web)

            {

                SPDocumentLibrary doclib = theWeb.GetList("/" + theWeb.ServerRelativeUrl + "/" + doclibNameURL) as SPDocumentLibrary;

                //ALT: SPDocumentLibrary doclib = theWeb.Lists[doclibName] as SPDocumentLibrary;

                SPField field = doclib.Fields[fieldName];

                SPFieldLink fieldLink = new SPFieldLink(field);

 

                SPContentTypeCollection ctcoll = doclib.ContentTypes;

                SPContentType ct = ctcoll[ctName];

                ct.FieldLinks.Add(fieldLink);

                ct.Update();

            }          

        }

 

 

 

        /// <summary>

        /// create new parameter entry in configuration list

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="entryName"></param>

        /// <param name="entryValue"></param>

        public static void AddConfigurationEntry(string siteURL, string listNameURL, string entryName, string entryValue)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL);

                //ALT: SPList list = theWeb.Lists[listName];

                SPListItem newItem = list.Items.Add();               

 

                newItem["Parameter"] = entryName;

                newItem["Value"] = entryValue;

                newItem.Update();              

            }

        }

 

        /// <summary>

        /// delete column from view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void DeleteColumnFromView(string siteURL, string listNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.Lists[listNameURL];

                SPView view = list.Views[viewName];

 

                if (view.ViewFields.Exists(columnName))

                {

                    theWeb.AllowUnsafeUpdates = true;

                    view.ViewFields.Delete(columnName);

                    view.Update();

                }               

            }

        }

 

        /// <summary>

        /// delete column from view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void DeleteColumnFromListView(string siteURL, string listNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                SPList list = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL);

                SPView view = list.Views[viewName];

 

                if (view.ViewFields.Exists(columnName))

                {

                    theWeb.AllowUnsafeUpdates = true;

                    view.ViewFields.Delete(columnName);

                    view.Update();

                }

            }

        }

 

        /// <summary>

        /// delete column from view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void DeleteColumnFromDoclibView(string siteURL, string doclibNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                SPList list = theWeb.GetList("/" + siteURL + "/" + doclibNameURL);

                SPView view = list.Views[viewName];

 

                if (view.ViewFields.Exists(columnName))

                {

                    theWeb.AllowUnsafeUpdates = true;

                    view.ViewFields.Delete(columnName);

                    view.Update();

                }

            }

        }

 

        /// <summary>

        /// add column to view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void AddColumnToView(string siteURL, string listNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.Lists[listNameURL];

                SPView view = list.Views[viewName];

 

                theWeb.AllowUnsafeUpdates = true;

                view.ViewFields.Add(columnName);

                view.Update();               

            }

        }

 

        /// <summary>

        /// add column to view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="listNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void AddColumnToListView(string siteURL, string listNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL);

                //ALT: SPList list = theWeb.Lists[listName];

                SPView view = list.Views[viewName];

 

                theWeb.AllowUnsafeUpdates = true;

                view.ViewFields.Add(columnName);

                view.Update();

            }

        }

 

        /// <summary>

        /// add column to view

        /// </summary>

        /// <param name="siteURL"></param>

        /// <param name="doclibNameURL"></param>

        /// <param name="viewName"></param>

        /// <param name="columnName"></param>

        public static void AddColumnToDoclibView(string siteURL, string doclibNameURL, string viewName, string columnName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                SPList list = theWeb.GetList("/" + siteURL + "/" + doclibNameURL);

                //ALT: SPList list = theWeb.Lists[doclibName];

                SPView view = list.Views[viewName];

 

                theWeb.AllowUnsafeUpdates = true;

                view.ViewFields.Add(columnName);

                view.Update();

            }

        }

 

 

        public static void ChangeViewQuery(string siteURL, string listNameURL, string viewName, string viewQuery)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.Lists[listNameURL];

                SPView view = list.Views[viewName];               

 

                view.Query = viewQuery;

                view.Update();               

            }          

        }

 

        public static void ChangeDoclibViewQuery(string siteURL, string doclibNameURL, string viewName, string viewQuery)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.GetList("/" + siteURL + "/" + doclibNameURL);

                //ALT: SPList list = theWeb.Lists[doclibName];

                SPView view = list.Views[viewName];

 

                view.Query = viewQuery;

                view.Update();

            }

        }

 

        public static void ChangeListViewQuery(string siteURL, string listNameURL, string viewName, string viewQuery)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

                SPList list = theWeb.GetList("/" + siteURL + "/Lists/" + listNameURL);

                //ALT: SPList list = theWeb.Lists[listName];

                SPView view = list.Views[viewName];

 

                view.Query = viewQuery;

                view.Update();

            }

        }

 

        /// <summary>

        /// Create Permisson on specific item

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="ListItem"></param>

        /// <param name="loginName"></param>

        /// <param name="roleName"></param>

        /// <param name="permissionLevel"></param>

        public static void CreatePermissions(SPWeb theWeb, SPListItem ListItem, string loginName, string roleName, string permissionLevel)

        {

            using (theWeb = new SPSite(theWeb.Site.ID).OpenWeb(theWeb.ID))

            {

                //theWeb = new SPSite(theWeb.Site.ID).OpenWeb(theWeb.ID);

                theWeb.AllowUnsafeUpdates = true;

 

                ListItem = theWeb.Lists[ListItem.ParentList.ID].GetItemById(ListItem.ID);

                //loginName stammt aus einem xml. Somit ist es schwer festzustellen, ob es sich um eine Liste oder Doclib handelt.

 

                SPRoleAssignment roleAssignment = new SPRoleAssignment(loginName, "", roleName, "");

                SPRoleDefinition RoleDefinition = theWeb.RoleDefinitions[permissionLevel];

 

                if (!roleAssignment.RoleDefinitionBindings.Contains(RoleDefinition))

                    roleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

 

                //Check inheritance

                if (!ListItem.HasUniqueRoleAssignments)

                {

                    ListItem.BreakRoleInheritance(false);

                }

 

                ListItem.RoleAssignments.Add(roleAssignment);

 

                ListItem.Update();                

            }

        }

 

        /// <summary>

        /// Add User to specific group on specific site

        /// </summary>

        /// <param name="theWeb"></param>

        /// <param name="groupName"></param>

        /// <param name="userName"></param>

        public static void AddUserToGroup(string siteURL, string groupName, string userName)

        {

            using (SPWeb theWeb = SPContext.Current.Site.OpenWeb(siteURL))

            {

                //SPWeb theWeb = SPContext.Current.Site.AllWebs[siteURL];

                theWeb.AllowUnsafeUpdates = true;

 

                SPUser spUser = theWeb.EnsureUser(userName);

 

                if (spUser != null)

                {

                    SPGroup spGroup = theWeb.Groups[groupName];

 

                    if (spGroup != null)

                        spGroup.AddUser(spUser);

                }               

            }          

        }

    }

}

 

Die Codestellen, welche ich nicht optimieren konnte sind durch Kommentare gekennzeichnet....
Gibt es noch weitere Optimierungen die ich vornehmen kann?

Ohne Rang
19231 Beiträge
Andi Fandrich Als Antwort am 12 Aug. 2013 13:43
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

[quote user="Vronsch"]Gibt es noch weitere Optimierungen die ich vornehmen kann?[/quote]

Du erwartest aber nicht ernsthaft, daß jemand diese Menge Code für Dich analysiert, oder?

Nur eines, weil's direkt darüber steht:

SPGroup spGroup = theWeb.Groups[groupName];
if (spGroup != null)

Leider ist das Objektmodell sehr inkonsequent, wenn man per Indexer auf Collections zugreift. Manchmal liefert es null, wenn das gewünschte Element nicht existiert und manchmal wirft es eine Exception. Der Versuch eine Gruppe über ihren Namen zu bekommen, ist so ein Fall. D.h. also Dein Code wird mit einer Exception abgebrochen und die Prüfung spGroup != null ist hier sinnlos.

Also entweder die Exception fangen (nicht schön) oder per Schleife alle Groups durchgehen und schauen, ob es eine mit dem gesuchten Namen gibt (was man mit Linq vereinfachen kann).

Wie gesagt, das ist nur ein Beispiel, aber wahrscheinlich hast Du im Code noch mehr solche Stolperfallen. Und ebenfalls wie gesagt, es gibt hier in SharePoint keine Faustregel. Da hilft nur ausgiebig testen.

Viele Grüße
Andi
af @ evocom de
Blog
Ohne Rang
11 Beiträge
Vronsch Als Antwort am 14 Aug. 2013 15:37
SchlechtSchlechtIn OrdnungIn OrdnungDurchschnittDurchschnittGutGutSehr gutSehr gut

Nein natürlich nicht analysiert um Gottes Willen, aber eben so offensichtliche Sachen wie etwa dein Tipp. Dankeschön, den Rest werde ich jetzt wohl selber austesten müssen.

Liebe Grüße und nochmals vielen Dank
Vronsch