how to create document set in document library programmatically in sharepoint server 2010?
If you want to use client object model for this:
{
ClientContext clientContext = new ClientContext("http://<<SERVER_NAME>>");
Web site = clientContext.Web;
// Create a list.
ListCreationInformation listCreationInfo =
new ListCreationInformation();
listCreationInfo.Title = "Document Library";
listCreationInfo.TemplateType = (int)ListTemplateType.DocumentLibrary;
List list = site.Lists.Add(listCreationInfo);
// Enable Content Types on list
list.ContentTypesEnabled = true;
// Update List Configuration
list.Update();
// Send it to SharePoint
clientContext.ExecuteQuery();
// Get Content Type Document Set ID = 0x0120D520
ContentType ctx = clientContext.Site.RootWeb.AvailableContentTypes.GetById("0x0120D520");
// Add Existing To List
list.ContentTypes.AddExistingContentType(ctx);
// Execute
clientContext.ExecuteQuery();
}
http://msdn.microsoft.com/en-us/library/gg581064.aspx
Afterwards add an item of that contenttype.
Related
I am not able to create a list content type using the below snippet. It throws a ServerException with additional information - "The site content type has already been added to this list."
var list = clientContext.Web.Lists.GetByTitle("sometitle");
var documentCT = clientContext.Web.ContentTypes.GetById("0x0101");
clientContext.Load(list,l=> l.ContentTypes);
clientContext.Load(documentCT);
clientContext.ExecuteQuery();
var test = new ContentTypeCreationInformation(){
Name = "TestCT", ParentContentType =documentCT };
list.ContentTypes.Add(test);
list.Update();
clientContext.ExecuteQuery();
Basically, I want to create a list content type whose parent is the "Document" CT.
I encountered this same problem.
What is happening here is that you have added the content type to the list successfully but you haven't turned on "allow management of content types" in Library settings > Advanced Settings > First setting. You will not see the content type via the UI.
Once you turn on this setting you will see your content type was in fact added.
Here's how I create a library
public static List CreateLibrary(ClientContext context, string title, bool allowContentTypes)
{
ListCreationInformation lci = new ListCreationInformation
{
Description = "Library used to hold Dynamics CRM documents",
Title = title,
TemplateType = 101,
};
List lib = context.Web.Lists.Add(lci);
lib.ContentTypesEnabled = allowContentTypes ? true : false;
lib.Update();
context.Load(lib);
context.ExecuteQuery();
return lib;
}
For your case just add in the line:
list.ContentTypesEnabled = true;
Don't forget the list.Update(), I see you have it in your code but for anyone else, this part is essential before you use ExecuteQuery()
I have to customize sharepoint 2013 document set welcome page(document set properties web part) and
I am not able to find the document set home aspx page
Can I use any client context model to fetch the data and display doc set properties.
Just create a new content type inheriting from Document Set, add the extra columns and set which ones need to be shown on the welcome page via the Document Set settings link when editing the Content Type. Also under the Document Set settings page you can click on 'Customize the Welcome Page' which allows you to edit the page just like any other web part page.
On the second point the client context will need to be connected to the web that contains the list and specific document set you're after, the identity used to connect will need permissions to the document set.
Edit:
To customize the look and feel by injecting JavaScript/CSS you'll need to make use of the ScriptLink custom action.
This lets you inject a custom piece of JavaScript into all pages. In the script you'll need logic to determine if the custom CSS should be applied, and if so Inject it.
The C# for injecting a script block via ScriptLink Custom Action:
public void AddJsLink(ClientContext ctx, Web web)
{
string scenarioUrl = String.Format("{0}://{1}:{2}/Scripts", this.Request.Url.Scheme,
this.Request.Url.DnsSafeHost, this.Request.Url.Port);
string revision = Guid.NewGuid().ToString().Replace("-", "");
string jsLink = string.Format("{0}/{1}?rev={2}", scenarioUrl, "injectStyles.js", revision);
StringBuilder scripts = new StringBuilder(#"
var headID = document.getElementsByTagName('head')[0];
var");
scripts.AppendFormat(#"
newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = '{0}';
headID.appendChild(newScript);", jsLink);
string scriptBlock = scripts.ToString();
var existingActions = web.UserCustomActions;
ctx.Load(existingActions);
ctx.ExecuteQuery();
var actions = existingActions.ToArray();
foreach (var action in actions)
{
if (action.Description == "injectnavigation" &&
action.Location == "ScriptLink")
{
action.DeleteObject();
ctx.ExecuteQuery();
}
}
var newAction = existingActions.Add();
newAction.Description = "injectnavigation";
newAction.Location = "ScriptLink";
newAction.ScriptBlock = scriptBlock;
newAction.Update();
ctx.Load(web, s => s.UserCustomActions);
ctx.ExecuteQuery();
}
Then your JavaScript would have something like:
if(window.location.href.indexOf(patternToMatchToDocSetpage)>-1) {
var link = document.createElement("link");
link.href = "http://example.com/mystyle.css";
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);
}
I'd advise you to take a look at the relevant PnP sample on script link injection
I have a requirement to create a new site collection from within an App in Office 365 programmatically. What I mean by a new site collection, is that after creation, it should appear on the list of site collections under the Admin --> Sharepoint tab of Office 365. I tried using a similar code below within a sharepoint hosted app that i had created,
//create sp context and get root
var clientContext = new SP.ClientContext.get_current();
var rootWeb = clientContext.site.rootWeb();
this.clientContext.load(rootWeb);
this.clientContext.executeQUery();
//set web info
var webInfo = new SP.WebCreationInformation();
webInfo.set_webTemplate('YourTemplateName');
webInfo.set_description('Your site description');
webInfo.set_title('Your site tittle');
webInfo.set_url(siteUrl);
webInfo.set_language(yourLangCode);
this.rootWeb.get_webs().add(webInfo);
this.rootWeb.update();
// save site and set callbacks
this.clientContext.load(this.rootWeb);
this.clientContext.executeQueryAsync(
Function.createDelegate(this, this.OnSiteCreationSuccess),
Function.createDelegate(this, this.Error));
However this just creates a sub site under the site collection that hosts my App.
Any suggestions on how i could implement this would be greatly appreciated.
It can be done with SharePoint Object Model 2013, the functions you need are inside the assembly: Microsoft.Online.SharePoint.Client.Tenant.dll, which is located at C:\Program Files\SharePoint Client Components\Assemblies after you install the SharePoint Client Object model 2013.
There's not much doc on this, but SharePoint Online Management Shell has the command to create the site collection, so I think it can be done with C# and figured it out. The code snippet shows how to do it.
using System;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using System.Security;
namespace SharePoint123
{
class Program
{
static void Main(string[] args)
{
//please change the value of user name, password, and admin portal URL
string username = "xxxx#xxxx.onmicrosoft.com";
String pwd = "xxxx";
ClientContext context = new ClientContext("https://xxxx-admin.sharepoint.com");
SecureString password = new SecureString();
foreach (char c in pwd.ToCharArray())
{
password.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, password);
Tenant t = new Tenant(context);
context.ExecuteQuery();//login into SharePoint online
//code to create a new site collection
var newsite = new SiteCreationProperties()
{
Url = "https://xxxxx.sharepoint.com/sites/createdbyProgram1",
Owner = "xxxxx#xxxxx.onmicrosoft.com",
Template = "STS#0", //using the team site template, check the MSDN if you want to use other template
StorageMaximumLevel = 100,
UserCodeMaximumLevel = 100,
UserCodeWarningLevel = 100,
StorageWarningLevel = 300,
Title = "CreatedbyPrgram",
CompatibilityLevel = 15, //15 means Shapoint online 2013, 14 means Sharepoint online 2010
};
t.CreateSite(newsite);
context.ExecuteQuery();
//end
}
}
}
How can I check that the current user is a SiteCollection Administrator using SharePoint CSOM?
How to determine whether current user is Site Administrator using CSOM
SharePoint 2013 CSOM
Use User.IsSiteAdmin property to get or set a Boolean value that specifies whether the user is a site collection administrator, for example:
using (var ctx = new ClientContext(webUri))
{
var currentUser = ctx.Web.CurrentUser;
ctx.Load(currentUser);
ctx.ExecuteQuery();
Console.WriteLine(currentUser.IsSiteAdmin);
}
SharePoint 2010 CSOM
Since User object does not expose IsSiteAdmin property in SharePoint 2010 CSOM, below is demonstrated how to determine whether current user is Site Administrator using User Information List:
using (var ctx = new ClientContext(url))
{
var currentUser = ctx.Web.CurrentUser;
ctx.Load(currentUser);
ctx.ExecuteQuery();
var isCurrentUserSiteAdmin = IsUserSiteAdmin(ctx, currentUser.Id);
}
public static bool IsUserSiteAdmin(ClientContext ctx,int userId)
{
var userInfoList = ctx.Site.RootWeb.SiteUserInfoList;
var item = userInfoList.GetItemById(userId);
ctx.Load(item);
ctx.ExecuteQuery();
return (bool)item["IsSiteAdmin"];
}
What about
spcontext.current.Site.RootWeb.CurrentUser.IsSiteAdmin
I tried searching on the net to programmatically insert a List as a webpart in a webpart page but was not lucky enough.
Any thoughts or ideas how i could Programmatically insert a List as a webpart in a webpart page
Many Thanks!
First add these using statements.
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
Then in your code
// First get the list
SPSite site = new SPSite("http://myserver");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["MyCustomlist"];
// Create a webpart
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Top"; // Replace this ith the correct zone on your page.
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();
// Get the web part collection
SPWebPartCollection coll =
web.GetWebPartCollection("default.aspx", // replace this with the correct page.
Storage.Shared);
// Add the web part
coll.Add(wp);
If you want to use a custom view, try playing with this:
SPView view = list.GetUncustomizedViewByBaseViewId(0);
wp.ListViewXml = view.HtmlSchemaXml;
Hope it helps,
W0ut
You need to perform two steps to add a web part to a page. First you have to create the list you want to show on the page. Therefore you can use the Add() method of the web site's list collection (SPListCollection).
To show the list on the web part page you have to add a ListViewWebPart to the web part page using the SPLimitedWebPartManager of the page.
To make this more re-usable as part of a feature receiver, you could pass in the splist and spview as part of a method:
static public void AddEventsListViewWebPart(PublishingPage page, string webPartZoneId, int zoneIndex, string webPartTitle, PartChromeType webPartChromeType, string listName, string viewname)
{
using (SPLimitedWebPartManager wpManager = page.ListItem.File.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
SPWeb web = page.PublishingWeb.Web;
SPList myList = web.Lists.TryGetList(listName);
using (XsltListViewWebPart lvwp = new XsltListViewWebPart())
{
lvwp.ListName = myList.ID.ToString("B").ToUpperInvariant();
lvwp.Title = webPartTitle;
// Specify the view
SPView view = myList.Views[viewname];
lvwp.ViewGuid = view.ID.ToString("B").ToUpperInvariant();
lvwp.TitleUrl = view.Url;
lvwp.Toolbar = "None";
lvwp.ChromeType = webPartChromeType;
wpManager.AddWebPart(lvwp, webPartZoneId, zoneIndex);
}
}
}
And then call it during feature activation:
AddEventsListViewWebPart(welcomePage, "Right", 1, "Events", PartChromeType.TitleOnly, "Events", "Calendar");