コード例 #1
0
        public static string GetSettingsUrl(this SPClient.ContentType ct, TreeNode selectedNode)
        {
            // Link: <sitecollection|web>/_layouts/ManageContentType.aspx?ctype=0x0101009148F5A04DDD49CBA7127AADA5FB792B006973ACD696DC4858A76371B2FB2F439A
            // Link: <sitecollection|web>/_layouts/ManageContentType.aspx?List=%7BF798C4D9%2DEF29%2D4F8D%2DA1F1%2D4C70CFBAECE4%7D&ctype=0x010100A204AFB24228A94AB2D6195EB1705291

            if (selectedNode.Parent.Parent.Tag is SPClient.Site)
            {
                SPClient.Site site = selectedNode.Parent.Parent.Tag as SPClient.Site;
                return(string.Format("{0}/_layouts/ManageContentType.aspx?ctype={1}", site.RootWeb.GetUrl(), ct.Id));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.Web)
            {
                // <sitecollection>/<web>/_layouts/15/ManageContentType.aspx?ctype=0x00A7470EADF4194E2E9ED1031B61DA088403000BE6CEFFF1ACA6429D14B2B7E0A03FE2
                // <sitecollection>/<web>/_layouts/15/start.aspx#/_layouts/15/ManageContentType.aspx?ctype=0x00A7470EADF4194E2E9ED1031B61DA088403000BE6CEFFF1ACA6429D14B2B7E0A03FE2&Source=https%3A%2F%2Fbramdejager%2Esharepoint%2Ecom%2Fsub%2F%5Flayouts%2F15%2Fmngctype%2Easpx

                SPClient.Web web = selectedNode.Parent.Parent.Tag as SPClient.Web;
                return(string.Format("{0}/_layouts/ManageContentType.aspx?ctype={1}", web.GetUrl(), ct.Id));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.List)
            {
                SPClient.List list = selectedNode.Parent.Parent.Tag as SPClient.List;
                return(string.Format("{0}/_layouts/ManageContentType.aspx?list={1}&ctype={2}", list.ParentWeb.GetUrl(), list.Id, ct.Id));
            }
            else
            {
                return(string.Empty);
            }
        }
コード例 #2
0
        /// <summary>
        /// Initializes the ClientContext.
        /// </summary>
        public void InitClientContext()
        {
            this.IsLoaded = true;
            this.LoadDate = DateTime.Now;

            switch (this.Authentication)
            {
            case AuthN.Default:
                this.ClientContext = new SPClient.ClientContext(this.Url);
                if (!string.IsNullOrEmpty(this.Username))
                {
                    this.ClientContext.Credentials = new NetworkCredential(this.Username, this.Password);
                }
                break;

            case AuthN.SharePointOnline:
                this.ClientContext = MSDN.Samples.ClaimsAuth.ClaimClientContext.GetAuthenticatedContext(this.Url.OriginalString, 0, 0);
                break;
            }

            // Try connection, to ensure site is available
            SPClient.Site site = this.ClientContext.Site;
            this.ClientContext.Load(site);
            this.ClientContext.ExecuteQuery();
        }
コード例 #3
0
        public override BaseNode GenerateRootNode()
        {
            if (Context.Url.Contains("-admin"))
            {
                // We're connected to the Admin URL. Load the Tenant object
                Tenant tenant = new Tenant(Context);
                tenant.EnsureProperties(t => t.RootSiteUrl);

                BaseNode rootNode = new TenantNode(tenant);
                rootNode.Title         = "Tenant " + rootNode.Title;
                rootNode.NodeConnector = this;
                rootNode.OMType        = ObjectModelType.REMOTE;
                rootNode.SPObject      = tenant;
                DoTenant(tenant, rootNode, rootNode);


                return(rootNode);
            }
            else
            {
                Microsoft.SharePoint.Client.Site site = Context.Site;
                Context.Load(site);
                Context.ExecuteQuery();
                BaseNode rootNode = new SiteNode(site);
                rootNode.Title         = RootNodeTitle + rootNode.Title;
                rootNode.NodeConnector = this;
                rootNode.OMType        = ObjectModelType.REMOTE;
                rootNode.SPObject      = site;
                rootNode.LoadedData    = true;
                DoSPWeb(site.RootWeb, rootNode, rootNode);
                return(rootNode);
            }
        }
コード例 #4
0
        public static string GetSettingsUrl(this SPClient.Field field, TreeNode selectedNode)
        {
            // <sitecollection|web>/_layouts/FldEditEx.aspx?field=Instructie
            // <sitecollection|web>/_layouts/FldEdit.aspx?List=%7BCEBB8CB0%2DC088%2D4BEE%2DBF17%2DE6A8CD5F6C9F%7D&Field=Title

            if (selectedNode.Parent.Parent.Tag is SPClient.Site)
            {
                // <sitecollection>/_layouts/15/fldedit.aspx?field=%5FEndDate&Source=%2F%5Flayouts%2F15%2Fmngfield%2Easpx%3FFilter%3DAll%2520Groups

                SPClient.Site site = selectedNode.Parent.Parent.Tag as SPClient.Site;
                return(string.Format("{0}/_layouts/fldedit.aspx?field={1}", site.RootWeb.GetUrl(), field.InternalName));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.Web)
            {
                // <sitecollection>/<web>/_layouts/15/fldedit.aspx?field=Sub%5Fx0020%5FSite%5Fx0020%5FColumn&Source=%2Fsub%2F%5Flayouts%2F15%2Fmngfield%2Easpx%3FFilter%3DAll%2520Groups

                SPClient.Web web = selectedNode.Parent.Parent.Tag as SPClient.Web;
                return(string.Format("{0}/_layouts/fldedit.aspx?field={1}", web.GetUrl(), field.InternalName));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.List)
            {
                // <sitecollection>/<web>/_layouts/15/FldEditEx.aspx?List=%7B051E4502%2D504E%2D49C8%2DA815%2DF46BFD61911D%7D&Field=Modified

                SPClient.List list = selectedNode.Parent.Parent.Tag as SPClient.List;
                return(string.Format("{0}/_layouts/FldEditEx.aspx?list={1}&field={2}", list.ParentWeb.GetUrl(), list.Id, field.InternalName));
            }
            else
            {
                return(string.Empty);
            }
        }
コード例 #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (ClientContext clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Get user profile
                ProfileLoader loader =
                    Microsoft.SharePoint.Client.UserProfiles.ProfileLoader.GetProfileLoader(clientContext);
                UserProfile profile = loader.GetUserProfile();
                Microsoft.SharePoint.Client.Site personalSite = profile.PersonalSite;

                clientContext.Load(personalSite);
                clientContext.ExecuteQuery();

                // Let's check if the site already exists
                if (personalSite.ServerObjectIsNull.Value)
                {
                    profile.CreatePersonalSiteEnque(true);
                    clientContext.ExecuteQuery();
                }
                else
                {
                    Web rootWeb = personalSite.RootWeb;
                    clientContext.Load(rootWeb);
                    clientContext.ExecuteQuery();

                    // Setting the custom theme to host web
                    SetThemeBasedOnName(clientContext, rootWeb, "Orange");
                }
            }
        }
コード例 #6
0
 public SitePipeBind(Microsoft.SharePoint.Client.Site site)
 {
     site.EnsureProperties(s => s.Url, s => s.Id);
     _url  = site.Url;
     _site = site;
     _id   = site.Id;
 }
コード例 #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (ClientContext clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Get user profile
                ProfileLoader loader  = Microsoft.SharePoint.Client.UserProfiles.ProfileLoader.GetProfileLoader(clientContext);
                UserProfile   profile = loader.GetUserProfile();
                Microsoft.SharePoint.Client.Site personalSite = profile.PersonalSite;

                clientContext.Load(personalSite);
                clientContext.ExecuteQuery();

                // Let's check if the site already exists The following code uses a timer job-based approach to schedule the creation of a OneDrive for Business site if it has not yet been created for a particular user.
                if (personalSite.ServerObjectIsNull.Value)
                {
                    // Let's queue the personal site creation using an approach based on the out-of-the-box timer job.
                    // Using async mode, since end user could go away from browser, you also could do this using an out-of-the-box web part.
                    profile.CreatePersonalSiteEnque(true);
                    clientContext.ExecuteQuery();
                }
                else
                {
                    Web rootWeb = personalSite.RootWeb;
                    clientContext.Load(rootWeb);
                    clientContext.ExecuteQuery();

                    // Setting the custom theme to host web
                    SetThemeBasedOnName(clientContext, rootWeb, "Orange");
                }
            }
        }
コード例 #8
0
 public HubSitePipeBind(Microsoft.SharePoint.Client.Site site)
 {
     site.EnsureProperties(s => s.Url, s => s.Id);
     Id   = site.Id;
     Url  = site.Url;
     Site = site;
 }
コード例 #9
0
        /// <summary>
        /// Gets or sets a Boolean value that specifies whether the user is a site collection administrator.
        /// </summary>
        /// <param name="site"></param>
        /// <returns>true if the user is a site collection administrator; otherwise, false.</returns>
        public static bool IsCurrentUserAdmin(this SPClient.Site site)
        {
            bool isAdmin = false;

            site.Context.Load(site.RootWeb.CurrentUser);
            site.Context.ExecuteQuery();

            isAdmin = site.RootWeb.CurrentUser.IsSiteAdmin;

            return(isAdmin);
        }
コード例 #10
0
        public RoleDefinition GetRoleDefinition(Microsoft.SharePoint.Client.Site site)
        {
            if (_roleDefinition != null)
            {
                return(_roleDefinition);
            }
            var roleDefinition = site.RootWeb.RoleDefinitions.GetByName(_name);

            site.Context.Load(roleDefinition);
            site.Context.ExecuteQueryRetry();
            return(roleDefinition);
        }
コード例 #11
0
        protected override void ExecuteCmdlet()
        {
            Microsoft.SharePoint.Client.Site site = ClientContext.Site;
            ClientContext.Load(site);
            ClientContext.ExecuteQuery();
            var sub = new Microsoft.SharePoint.Client.Taxonomy.ContentTypeSync.ContentTypeSubscriber(ClientContext);

            ClientContext.Load(sub);
            ClientContext.ExecuteQuery();
            var res = sub.SyncContentTypesFromHubSite2(site.Url, ContentTypes);

            ClientContext.ExecuteQuery();
            WriteObject(res);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);

            // Notice that we use direct client context, not using SP App auth pattern. This is so that we execute the code
            // only in the context of the particular user and ignoring app permissions completely.
            using (ClientContext clientContext = new ClientContext(hostWeb))
            {
                // Get user profile
                ProfileLoader loader  = Microsoft.SharePoint.Client.UserProfiles.ProfileLoader.GetProfileLoader(clientContext);
                UserProfile   profile = loader.GetUserProfile();;
                Microsoft.SharePoint.Client.Site personalSite = profile.PersonalSite;

                clientContext.Load(personalSite);
                clientContext.ExecuteQuery();

                // Let's check if the site already exists
                if (personalSite.ServerObjectIsNull.Value)
                {
                    // Let's queue the personal site creation using oob timer job based approach
                    // Using async mode, since end user could go away from browser, you could do this using oob web part as well
                    profile.CreatePersonalSiteEnque(true);
                    clientContext.ExecuteQuery();
                    Response.Write("No my site exists. Currently provisioning...");
                }
                else
                {
                    // Site already exists, let's modify the branding by applyign a theme... just as well you could upload
                    // master page and set that to be shown. Notice that you can also modify this code to change the branding
                    // later and updates would be reflected whenever user visits my site host... or any other location where this
                    // app part is located. You could place this also to front page of the intranet for ensuring that it's applied.
                    using (ClientContext subContext = new ClientContext(personalSite.Url))
                    {
                        // Let's update the theme colors of the my site
                        Microsoft.SharePoint.Client.Web rootWeb = subContext.Web;
                        subContext.Load(rootWeb);
                        subContext.ExecuteQuery();

                        rootWeb.ApplyTheme(URLCombine(rootWeb.ServerRelativeUrl, "/_catalogs/theme/15/palette008.spcolor"),
                                           URLCombine(rootWeb.ServerRelativeUrl, "/_catalogs/theme/15/fontscheme003.spfont"),
                                           null, false);
                        subContext.ExecuteQuery();

                        // Just to output status
                        Response.Write("My site exists: " + personalSite.Url + " - web title - " + subContext.Web.Title);
                    }
                }
            }
        }
コード例 #13
0
        public static string GetSettingsUrl(this SPClient.Feature feature, TreeNode selectedNode)
        {
            // Link: <sitecollection|web>/_layouts/ManageFeatures.aspx
            // Link: <sitecollection>/_layouts/ManageFeatures.aspx?Scope=Site

            if (selectedNode.Parent.Parent.Tag is SPClient.Site)
            {
                SPClient.Site site = selectedNode.Parent.Parent.Tag as SPClient.Site;
                return(string.Format("{0}/_layouts/ManageFeatures.aspx?Scope=Site", site.RootWeb.GetWebUrl()));
            }
            else
            {
                SPClient.Web web = selectedNode.Parent.Parent.Tag as SPClient.Web;
                return(string.Format("{0}/_layouts/ManageFeatures.aspx", web.GetWebUrl()));
            }
        }
コード例 #14
0
        internal RecycleBinItem GetRecycleBinItem(Microsoft.SharePoint.Client.Site site)
        {
            if (Item != null)
            {
                return(Item);
            }
            if (!_id.HasValue)
            {
                return(null);
            }

            _item = site.RecycleBin.GetById(_id.Value);
            site.Context.Load(_item);
            site.Context.ExecuteQueryRetry();
            return(Item);
        }
コード例 #15
0
        private static string Tokenize(string input, Web web, SPSite site)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(input);
            }

            input = input.ReplaceCaseInsensitive(web.Url, "{site}");
            input = input.ReplaceCaseInsensitive(web.ServerRelativeUrl, "{site}");
            input = input.ReplaceCaseInsensitive(web.Id.ToString(), "{siteid}");
            input = input.ReplaceCaseInsensitive(site.ServerRelativeUrl, "{sitecollection}");
            input = input.ReplaceCaseInsensitive(site.Id.ToString(), "{sitecollectionid}");
            input = input.ReplaceCaseInsensitive(site.Url, "{sitecollection}");

            return(input);
        }
コード例 #16
0
        internal EventReceiverDefinition GetEventReceiverOnSite(Microsoft.SharePoint.Client.Site site)
        {
            if (_eventReceiverDefinition != null)
            {
                return(_eventReceiverDefinition);
            }

            if (_id != Guid.Empty)
            {
                return(site.GetEventReceiverById(_id));
            }
            else if (!string.IsNullOrEmpty(Name))
            {
                return(site.GetEventReceiverByName(Name));
            }
            return(null);
        }
コード例 #17
0
 public void Dispose()
 {
     if (_site != null)
     {
         _site = null;
     }
     if (_web != null)
     {
         _web = null;
     }
     if (_clientContext != null)
     {
         _clientContext.Dispose();
         _clientContext = null;
     }
     Credentials = null;
 }
コード例 #18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Check if we should skip this check. We do this only once per hour to avoid
            // perf issues and there's really no point even hitting the user profile
            // in every request.
            if (CookieCheckSkip())
            {
                return;
            }

            var spContext =
                SharePointContextProvider.Current.GetSharePointContext(Context);

            using (ClientContext clientContext =
                       spContext.CreateUserClientContextForSPHost())
            {
                // Get user profile
                ProfileLoader loader  = ProfileLoader.GetProfileLoader(clientContext);
                UserProfile   profile = loader.GetUserProfile();
                Microsoft.SharePoint.Client.Site personalSite = profile.PersonalSite;

                clientContext.Load(profile, prof => prof.AccountName);
                clientContext.Load(personalSite);
                clientContext.ExecuteQuery();

                // Let's check if the site already exists
                if (personalSite.ServerObjectIsNull.Value)
                {
                    // Let's queue the personal site creation using oob timer job based
                    // approach using async mode, since end user could go away from
                    // browser, you could do this using oob web part as well
                    profile.CreatePersonalSiteEnque(true);
                    clientContext.ExecuteQuery();
                    WriteDebugInformationIfNeeded("OneDrive for Business site was not present, queued for provisioning now.");
                }
                else
                {
                    // Site already exists, let's create a task to the Azure queue for web job to start processing these requests...
                    // Notice that we bypass the site collection URL as the parameter to the queue, so that web job knows which site collection to process
                    AddConfigurationRequestToQueue(profile.AccountName, profile.PersonalSite.Url);

                    // Let's add taks to the queueu for configuration check up.
                    WriteDebugInformationIfNeeded(string.Format("OneDrive for Business site existed at {0}. Configuration check up task created.", personalSite.Url));
                }
            }
        }
コード例 #19
0
        protected void btnScenarioRemove_Click(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                Microsoft.SharePoint.Client.Site site = clientContext.Site;
                Audit audit = site.Audit;
                clientContext.Load(site);
                clientContext.Load(audit);
                clientContext.ExecuteQuery();
                // Set remove any auditing from site colelction level
                site.Audit.AuditFlags = Microsoft.SharePoint.Client.AuditMaskType.None;
                site.Audit.Update();
                site.TrimAuditLog = false;
                clientContext.ExecuteQuery();
            }
        }
コード例 #20
0
        public static void LoadSite(TreeNode parentNode, SiteAuth siteAuth, MainBrowser form)
        {
            try
            {
                SPClient.ClientContext ctx  = siteAuth.ClientContext;
                SPClient.Site          site = ctx.Site;
                ctx.Load(site);
                ctx.ExecuteQuery();

                TreeNode siteNode = parentNode.Nodes.Add(site.Url);
                siteNode.ImageKey         = Constants.IMAGE_SITE;
                siteNode.SelectedImageKey = Constants.IMAGE_SITE;
                siteNode.Tag = site;
                siteNode.ContextMenuStrip = form.mnContextSite;
                siteNode.Expand();

                SPClient.Web rootWeb = site.RootWeb;

                TreeNode rootWebNode = LoadWeb(siteNode, rootWeb, form);
                //rootWebNode.Expand();

                foreach (string webUrl in siteAuth.Webs)
                {
                    LoadWeb(siteNode, site.OpenWeb(webUrl), form);
                }

                AddLoadingNode(siteNode, "Site Columns", Constants.IMAGE_SITE_COLUMN, LoadType.SiteFields);
                AddLoadingNode(siteNode, "Content Types", Constants.IMAGE_CONTENT_TYPE, LoadType.SiteContentTypes);
                AddLoadingNode(siteNode, "Site Features", "Gets a value that specifies the collection of the site collection features for the site collection that contains the site.", Constants.IMAGE_FEATURE, LoadType.SiteFeatures);
                AddLoadingNode(siteNode, "Recycle Bin", Constants.IMAGE_RECYCLE_BIN, LoadType.SiteRecycleBin);

                if (!site.Context.IsMinimalServerVersion(ServerVersion.SharePoint2010))
                {
                    siteNode.ImageKey         = Constants.IMAGE_SITE_WARNING;
                    siteNode.SelectedImageKey = Constants.IMAGE_SITE_WARNING;

                    MessageBox.Show(string.Format("You are NOT connecting to a SharePoint 2010 site ({0}), this could result in errors. Please be aware! The application will continue loading the site as normal.", rootWeb.GetWebUrl()), form.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #21
0
        public IEnumerable <TEntity> GetDocumentsByQuery(string ListName, ICamlQuery Query)
        {
            try
            {
                List <TEntity> entityItems = new List <TEntity>();
                SP.Site        site        = context.Site;
                context.Load(site);
                SP.Web       web   = context.Web;
                SP.List      list  = web.Lists.GetByTitle(ListName);
                SP.CamlQuery query = (SP.CamlQuery)Query.ExecuteQuery();

                SP.ListItemCollection items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQuery();

                foreach (SP.ListItem item in items)
                {
                    var     properties = typeof(TEntity).GetProperties();
                    TEntity entry      = new TEntity();

                    foreach (var property in properties)
                    {
                        if (item[property.Name] != null)
                        {
                            property.SetValue(entry, item[property.Name]);
                        }
                    }

                    entityItems.Add(entry);
                }

                return(entityItems);
            }
            catch (InvalidCastException ex)
            {
                throw new Exception(ex.Message + ". Data model types are invalid, please verify that models are strongly typed and match the SharePoint list column types.", new InvalidCastException());
            }
            catch (Exception ex)
            {
                throw new Exception("Error updating SharePoint list data: " + ex.Message);
            }
        }
コード例 #22
0
        protected void btnScenario_Click(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                Microsoft.SharePoint.Client.Site site = clientContext.Site;
                Audit audit = site.Audit;
                clientContext.Load(site);
                clientContext.Load(audit);
                clientContext.ExecuteQuery();
                // Enable all auditing is site collection level
                site.Audit.AuditFlags = Microsoft.SharePoint.Client.AuditMaskType.All;
                site.Audit.Update();
                // Adjust retention time to be 7 days
                site.AuditLogTrimmingRetention = 7;
                site.TrimAuditLog = true;
                clientContext.ExecuteQuery();
            }
        }
コード例 #23
0
        private static string Tokenize(string input, Web web, SPSite site)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(input);
            }
            //foreach (var list in lists)
            //{
            //    input = input.ReplaceCaseInsensitive(web.Url.TrimEnd('/') + "/" + list.GetWebRelativeUrl(), "{listurl:" + Regex.Escape(list.Title) + "}");
            //    input = input.ReplaceCaseInsensitive(list.RootFolder.ServerRelativeUrl, "{listurl:" + Regex.Escape(list.Title)+ "}");
            //}
            input = input.ReplaceCaseInsensitive(web.Url, "{site}");
            input = input.ReplaceCaseInsensitive(web.ServerRelativeUrl, "{site}");
            input = input.ReplaceCaseInsensitive(web.Id.ToString(), "{siteid}");
            input = input.ReplaceCaseInsensitive(site.ServerRelativeUrl, "{sitecollection}");
            input = input.ReplaceCaseInsensitive(site.Id.ToString(), "{sitecollectionid}");
            input = input.ReplaceCaseInsensitive(site.Url, "{sitecollection}");

            return(input);
        }
コード例 #24
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParamSet_ById)
            {
                HubSiteProperties sourceProperties = Tenant.GetHubSitePropertiesById(Source);
                ClientContext.Load(sourceProperties);
                sourceProperties.ParentHubSiteId = Target;
                sourceProperties.Update();
                ClientContext.ExecuteQueryRetry();
            }
            else
            {
                SiteProperties sourceSiteProperties = Tenant.GetSitePropertiesByUrl(SourceUrl, true);
                ClientContext.Load(sourceSiteProperties);
                ClientContext.ExecuteQueryRetry();

                SiteProperties destSiteProperties = Tenant.GetSitePropertiesByUrl(TargetUrl, true);
                ClientContext.Load(destSiteProperties);
                ClientContext.ExecuteQueryRetry();

                if (!sourceSiteProperties.IsHubSite)
                {
                    throw new PSInvalidOperationException("Source site collection needs to be a Hub site.");
                }

                if (!destSiteProperties.IsHubSite)
                {
                    throw new PSInvalidOperationException("Destination site collection needs to be a Hub site.");
                }

                HubSiteProperties sourceProperties = Tenant.GetHubSitePropertiesByUrl(SourceUrl);
                ClientContext.Load(sourceProperties);
                Microsoft.SharePoint.Client.Site targetSite = Tenant.GetSiteByUrl(TargetUrl);
                ClientContext.Load(targetSite);
                ClientContext.ExecuteQueryRetry();
                sourceProperties.ParentHubSiteId = targetSite.HubSiteId;
                sourceProperties.Update();
                ClientContext.ExecuteQueryRetry();
            }
        }
コード例 #25
0
 /// <summary>
 /// Returns the REST endpoint for current field.
 /// </summary>
 /// <param name="field"></param>
 /// <example>http://server/site/_api/web/Fields</example>
 /// <example>http://server/site/_api/web/AvailableFields</example>
 /// <example>http://server/site/_api/web/AvailableFields(guid'56747800-d36e-4625-abe3-b1bc74a7d5f8')</example>
 /// <example>http://server/site/_api/web/lists(guid'81c57897-96ad-4b39-94d4-092be56d562d')/fields(guid'1d22ea11-1e32-424e-89ab-9fedbadb6ce1')</example>
 /// <returns></returns>
 public static Uri GetRestUrl(this SPClient.Field field, TreeNode selectedNode)
 {
     if (selectedNode.Parent.Parent.Tag is SPClient.Site)
     {
         SPClient.Site site = selectedNode.Parent.Parent.Tag as SPClient.Site;
         return(new Uri(string.Format("{0}/_api/Web/AvailableFields(guid'{1}')", site.RootWeb.GetUrl(), field.Id)));
     }
     else if (selectedNode.Parent.Parent.Tag is SPClient.Web)
     {
         SPClient.Web web = selectedNode.Parent.Parent.Tag as SPClient.Web;
         return(new Uri(string.Format("{0}/_api/Web/AvailableFields(guid'{1}')", web.GetUrl(), field.Id)));
     }
     else if (selectedNode.Parent.Parent.Tag is SPClient.List)
     {
         SPClient.List list = selectedNode.Parent.Parent.Tag as SPClient.List;
         return(new Uri(string.Format("{0}/_api/Web/Lists(guid'{1}')/Fields(guid'{2}')", list.ParentWeb.GetUrl(), list.Id, field.Id)));
     }
     else
     {
         return(null);
     }
 }
コード例 #26
0
        private void DeploySiteModel(object modelHost, Microsoft.SharePoint.Client.Site site, SiteDefinition siteModel)
        {
            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = site,
                ObjectType       = typeof(Site),
                ObjectDefinition = siteModel,
                ModelHost        = modelHost
            });

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = site,
                ObjectType       = typeof(Site),
                ObjectDefinition = siteModel,
                ModelHost        = modelHost
            });
        }
コード例 #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (ClientContext clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Get user profile
                ProfileLoader loader  = Microsoft.SharePoint.Client.UserProfiles.ProfileLoader.GetProfileLoader(clientContext);
                UserProfile   profile = loader.GetUserProfile();
                Microsoft.SharePoint.Client.Site personalSite = profile.PersonalSite;

                clientContext.Load(personalSite);
                clientContext.ExecuteQuery();

                // Let's check if the site already exists
                if (personalSite.ServerObjectIsNull.Value)
                {
                    // Let's queue the personal site creation using oob timer job based approach
                    // Using async mode, since end user could go away from browser, you could do this using oob web part as well
                    profile.CreatePersonalSiteEnque(true);
                    clientContext.ExecuteQuery();
                    WriteDebugInformationIfNeeded("OneDrive for Business site was not present, queued for provisioning now.");
                }
                else
                {
                    // Site already exists, let's modify the branding by applying a theme... just as well you could upload
                    // master page and set that to be shown. Notice that you can also modify this code to change the branding
                    // later and updates would be reflected whenever user visits OneDrive host... or any other location where this
                    // app part is located. You could place this also to front page of the intranet for ensuring that it's applied.

                    Web rootWeb = personalSite.RootWeb;
                    clientContext.Load(rootWeb);
                    clientContext.ExecuteQuery();

                    //Let's set the theme only if needed, note that you can easily check for example specific version here as well
                    if (rootWeb.GetPropertyBagValueInt(OneDriveCustomizer.OneDriveMarkerBagID, 0) < 2)
                    {
                        // Let's first upload the contoso theme to host web, if it does not exist there
                        var colorFile      = rootWeb.UploadThemeFile(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/Themes/SPC/SPCTheme.spcolor")));
                        var backgroundFile = rootWeb.UploadThemeFile(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/Themes/SPC/SPCbg.jpg")));
                        rootWeb.CreateComposedLookByUrl("SPC", colorFile.ServerRelativeUrl, null, backgroundFile.ServerRelativeUrl, string.Empty);

                        // Setting the Contoos theme to host web
                        rootWeb.SetComposedLookByUrl("SPC");

                        // Add additional JS injection with the policy statement to the site
                        rootWeb.AddJsLink("OneDriveCustomJS", BuildJavaScriptUrl());

                        // Let's set the site processed, so that we don't update that all the time. Currently set as "version" 1 of branding
                        rootWeb.SetPropertyBagValue(OneDriveCustomizer.OneDriveMarkerBagID, 2);

                        // Write output if enabled
                        WriteDebugInformationIfNeeded(string.Format("OneDrive for Business site existed at {0}. Custom branding applied.", personalSite.Url));
                    }
                    else
                    {
                        // Just to output status if enabled in the app part
                        WriteDebugInformationIfNeeded(string.Format("OneDrive for Business site existed at {0} and had right branding.", personalSite.Url));
                    }
                }
            }
        }
コード例 #28
0
 public SitePipeBind()
 {
     _id   = Guid.Empty;
     _url  = string.Empty;
     _site = null;
 }
コード例 #29
0
        private void bkWorkerProcess_DoWorkAsync(object sender, DoWorkEventArgs e)
        {
            try
            {
                //
                string siteUrl   = txtSite.Text;
                string userName  = txtUser.Text;
                string password  = txtPassword.Text;
                string whiteList = txtWhiteList.Text;



                (sender as BackgroundWorker).ReportProgress(5, "The configuration process was started");

                //if (siteUrl.Substring(siteUrl.Length - 1) == "/")
                //{
                //    siteUrl = siteUrl.Substring(0, siteUrl.Length - 1);
                //}


                OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();



                using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteAdminUrl, userName, password))
                {
                    (sender as BackgroundWorker).ReportProgress(10, "Getting access to admin site");

                    Tenant adminSite = new Tenant(clientContext);

                    var siteName = txtSite.Text;



                    Regex pattern = new Regex("[&_,.;:/\"!@$%^+=\\|<>{}#~*? ]");
                    siteName = pattern.Replace(siteName, string.Empty);

                    Microsoft.SharePoint.Client.Site site = null;

                    if (adminSite.CheckIfSiteExists("https://jreckner.sharepoint.com/sites/" + siteName, "Active"))
                    {
                        throw new Exception("The site: " + txtSite.Text + ", already exists. Please choose another name.");
                    }

                    var siteCreationProperties = new SiteCreationProperties();

                    var sitedesign = new OfficeDevPnP.Core.Entities.SiteEntity();

                    string[] owners = { txtUser.Text };
                    (sender as BackgroundWorker).ReportProgress(15, "Creating site collection");
                    //CommunicationSiteCollectionCreationInformation modernteamSiteInfo = new CommunicationSiteCollectionCreationInformation
                    //{
                    //    Description = "",
                    //    Owner = txtUser.Text,
                    //    SiteDesignId = new Guid("6a3f7a23-031b-4072-bf24-4193c14af65f"),
                    //    Title = txtSite.Text,
                    //    Lcid = 1033,
                    //    AllowFileSharingForGuestUsers = false,
                    //    Url = "https://jreckner.sharepoint.com/sites/" + siteName

                    //};

                    TeamSiteCollectionCreationInformation modernteamSiteInfo = new TeamSiteCollectionCreationInformation()
                    {
                        DisplayName = txtSite.Text,
                        //Owners = owners,
                        //Alias = "https://jreckner.sharepoint.com/sites/" + siteName,
                        Alias       = siteName,
                        Lcid        = 1033,
                        IsPublic    = true,
                        Description = ""
                    };


                    var result = Task.Run(async() => { return(await clientContext.CreateSiteAsync(modernteamSiteInfo)); }).Result;


                    siteUrl = result.Url;

                    var properties = adminSite.GetSitePropertiesByUrl(siteUrl, true);

                    clientContext.Load(properties);
                    site = adminSite.GetSiteByUrl(siteUrl);
                    Web web = site.RootWeb;
                    clientContext.Load(web);
                    ListCreationInformation doclist = new ListCreationInformation()
                    {
                        Title        = "Document Library",
                        TemplateType = 101,
                    };
                    web.Lists.Add(doclist);
                    (sender as BackgroundWorker).ReportProgress(20, "Creating Document Library");
                    clientContext.ExecuteQuery();



                    (sender as BackgroundWorker).ReportProgress(30, "Configuring WhiteList");

                    properties.SharingDomainRestrictionMode = SharingDomainRestrictionModes.AllowList;
                    properties.SharingAllowedDomainList     = whiteList;

                    properties.SharingCapability = SharingCapabilities.ExternalUserSharingOnly;
                    properties.Update();
                    clientContext.ExecuteQuery();
                }



                using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                {
                    (sender as BackgroundWorker).ReportProgress(40, "Copy disclaimer file");
                    callResponseFlow(siteUrl, userName, userName);

                    (sender as BackgroundWorker).ReportProgress(50, "Getting access to site collection");



                    Web web = ctx.Web;
                    ctx.Load(web);

                    ctx.ExecuteQueryRetry();

                    var page2 = ctx.Web.AddClientSidePage("HomePageDisclaimer.aspx", true);
                    page2.AddSection(CanvasSectionTemplate.OneColumn, 5);

                    CanvasSection section = new CanvasSection(page2, CanvasSectionTemplate.OneColumn, page2.Sections.Count + 1);
                    page2.Sections.Add(section);
                    page2.PageTitle  = "Disclaimer";
                    page2.LayoutType = ClientSidePageLayoutType.Home;
                    page2.DisableComments();
                    page2.PromoteAsHomePage();
                    page2.PageHeader.LayoutType = ClientSidePageHeaderLayoutType.NoImage;
                    page2.Save();
                    (sender as BackgroundWorker).ReportProgress(60, "Generating disclaimer Page");

                    // Check if file exists
                    //Microsoft.SharePoint.Client.Folder folder = ctx.Web.GetFolderByServerRelativeUrl(ctx.Web.ServerRelativeUrl + "/" + library);
                    var documentFile = ctx.Web.GetFileByServerRelativeUrl(ctx.Web.ServerRelativeUrl + "/" + library + "/" + fileName);
                    web.Context.Load(documentFile, f => f.Exists); // Only load the Exists property
                    web.Context.ExecuteQuery();
                    if (documentFile.Exists)
                    {
                        Console.WriteLine("File exists!!!!");

                        //}

                        ctx.Load(documentFile);
                        ctx.Load(documentFile, w => w.SiteId);
                        ctx.Load(documentFile, w => w.WebId);
                        ctx.Load(documentFile, w => w.ListId);
                        ctx.Load(documentFile, w => w.UniqueId);
                        ctx.ExecuteQuery();

                        //if (documentFile != null)
                        //{ //si el documento existe
                        var pdfWebPart = page2.InstantiateDefaultWebPart(DefaultClientSideWebParts.DocumentEmbed);
                        var url        = new Uri(ctx.Web.Url + "/" + library + "/" + fileName);

                        pdfWebPart.Properties["siteId"]            = documentFile.SiteId;
                        pdfWebPart.Properties["webId"]             = documentFile.WebId;
                        pdfWebPart.Properties["listId"]            = documentFile.ListId;
                        pdfWebPart.Properties["uniqueId"]          = documentFile.UniqueId;
                        pdfWebPart.Properties["file"]              = url.AbsoluteUri;
                        pdfWebPart.Properties["serverRelativeUrl"] = documentFile.ServerRelativeUrl;
                        pdfWebPart.Properties["wopiurl"]           = String.Format("{0}/_layouts/15/{1}?sourcedoc=%7b{2}%7d&action=interactivepreview", web.Url, "WopiFrame.aspx", documentFile.UniqueId.ToString("D"));
                        pdfWebPart.Properties["startPage"]         = 1;
                        page2.AddControl(pdfWebPart, section.Columns[0]);
                        (sender as BackgroundWorker).ReportProgress(80, "Configuring webpart");
                        page2.Save();
                        page2.Publish();
                    }
                    else
                    {
                        throw (new Exception("We can't not find the disclaimer file, please upload it to the site at Document library as 'Disclaimer.pdf' and apply the configuration again."));
                    }
                }

                (sender as BackgroundWorker).ReportProgress(100, "All configuration was applied correctly!!!");
                //MessageBox.Show("All configuration was applied correctly!!!");
            }
            catch (Exception ex)
            {
                string errormessage = "";
                errormessage = ex.Message;
                if (ex.InnerException != null)
                {
                    errormessage = ex.InnerException.Message;
                }

                (sender as BackgroundWorker).ReportProgress(0, "Error: " + ex.Message);
            }
            finally {
                finishprocess = true;
            }
        }
コード例 #30
0
        /// <summary>
        /// Initializes the ClientContext.
        /// </summary>
        public void InitClientContext()
        {
            try
            {
                LogUtil.LogMessage("Initializing site collection (ClientContext) for {0}.", this.Url);

                // Set client context
                this.ClientContext = new SPClient.ClientContext(this.Url);
                this.ClientContext.ApplicationName = ProductUtil.GetProductName();

                // Set authentication mode and credentials
                switch (this.Authentication)
                {
                case AuthenticationMode.Default:
                    this.ClientContext.AuthenticationMode = ClientAuthenticationMode.Default;
                    if (this.UseCurrentCredentials)
                    {
                        LogUtil.LogMessage("Using current user credentials for user '{0}\\{1}'.", Environment.UserDomainName, Environment.UserName);
                        this.ClientContext.Credentials = CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        LogUtil.LogMessage("Using custom credentials for user '{0}'.", this.UserName);
                        this.ClientContext.Credentials = new NetworkCredential(this.UserName, this.Password);
                    }
                    break;

                case AuthenticationMode.SharePointOnline:
                    LogUtil.LogMessage("Using SharePoint Online credentials for user '{0}'.", this.UserName);
                    this.ClientContext.AuthenticationMode = ClientAuthenticationMode.Default;
                    this.ClientContext.Credentials        = new SharePointOnlineCredentials(this.UserName, this.Password.GetSecureString());
                    break;

                case AuthenticationMode.Anonymous:
                    LogUtil.LogMessage("Using anonymous access.");
                    this.ClientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
                    break;

                case AuthenticationMode.Forms:
                    LogUtil.LogMessage("Using Forms Based authentication for user '{0}'.", this.UserName);
                    this.ClientContext.AuthenticationMode           = ClientAuthenticationMode.FormsAuthentication;
                    this.ClientContext.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo(this.UserName, this.Password);
                    break;

                case AuthenticationMode.Claims:
                    LogUtil.LogMessage("Using Claims authentication.");
                    bool isCancelled = false;
                    this.ClientContext = ClaimClientContext.GetAuthenticatedContext(this.Url.ToString(), out isCancelled);
                    if (isCancelled)
                    {
                        throw new Exception("Could not load site. Please retry.", new Exception("Loading site cancelled by user."));
                    }
                    break;

                default:
                    throw new NotImplementedException("Current authentication mode not supported.");
                }

                LogUtil.LogMessage("Valide (execute) the ClientContext.");

                // Try connection, to ensure site is available
                SPClient.Site site = this.ClientContext.Site;
                this.ClientContext.Load(site);
                this.ClientContext.ExecuteQuery();

                // After succes set variables
                this.IsLoaded = true;
                this.LoadDate = DateTime.Now;

                LogUtil.LogMessage("ClientContext successful loaded.");
                LogUtil.LogMessage("ClientContext technical data. ServerVersion: {0}. ServerSchemaVersion: {1}. ServerLibraryVersion: {2}. RequestSchemaVersion: {3}. TraceCorrelationId: {4}",
                                   this.ClientContext.ServerVersion,
                                   this.ClientContext.ServerSchemaVersion,
                                   this.ClientContext.ServerLibraryVersion,
                                   this.ClientContext.RequestSchemaVersion,
                                   this.ClientContext.TraceCorrelationId);

                //Try retrieving the SharePoint Server build version
                this.BuildVersion = TryGetServerVersion(site.Url);
            }
            catch (FileNotFoundException ex)
            {
                LogUtil.LogException(string.Format("File '{0}' not found, check log file {1} for detailed information.", ex.FileName, ex.FusionLog), ex);

                throw;
            }
        }