Programmatically add claim to a list - sharepoint-2010

I wrote a small piece of code which add a claim to a site in Sharepoint.
I proceed like that :
using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
SPClaimProviderManager claimMgr = SPClaimProviderManager.Local;
if (claimMgr != null)
{
SPClaim claim = new SPClaim(type, claim_name, Microsoft.IdentityModel.Claims.ClaimValueTypes.String, SPOriginalIssuers.Format(SPOriginalIssuerType.ClaimProvider, provider));
string userName = claimMgr.EncodeClaim(claim);
SPUserInfo info = new SPUserInfo
{ LoginName = userName,
Name = name };
SPRoleAssignment roleAssignment = new SPRoleAssignment(info.LoginName, info.Email, info.Name, info.Notes);
roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions["Read"]);
web.RoleAssignments.Add(roleAssignment);
web.Update();
}
}
}
Pretty easy but i would like to add the claim to a list that i created. By now, i'm using SPSite and SPWeb to access the site but i need to go deeper :) and i can't find the way to do ...
Thank you in advance!

Since both, SPWeb and SPList, inherit from SPSecurableObject all you have to do is load the SPList object for that list you want to alter the permissions.
A SPList can be loaded either by URL or by list title:
SPList listByTitle = web.Lists["Tasks"];
SPList listByUrl = web.GetList("/server/relative/Lists/Tasks");
In your example:
using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
SPClaimProviderManager claimMgr = SPClaimProviderManager.Local;
if (claimMgr != null)
{
SPClaim claim = new SPClaim(type, claim_name, Microsoft.IdentityModel.Claims.ClaimValueTypes.String, SPOriginalIssuers.Format(SPOriginalIssuerType.ClaimProvider, provider));
string userName = claimMgr.EncodeClaim(claim);
SPUserInfo info = new SPUserInfo
{ LoginName = userName,
Name = name };
SPRoleAssignment roleAssignment = new SPRoleAssignment(info.LoginName, info.Email, info.Name, info.Notes);
roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions["Read"]);
// web.RoleAssignments.Add(roleAssignment);
// web.Update();
SPList list = web.Lists["TheListTitle"];
list.RoleAssignments.Add(roleAssignment);
}
}
}
It is not required to update the web or list after the modification of the role assignments.

Related

How to fetch list of all distinguished names (DNs) from LDAP server using JNDI?

I wish to fetch the list of all distinguised names (DNs) from LDAP server using JNDI. I am able to fetch the base DN using following code:
Hashtable<String,String> env = new Hashtable<String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://" + ldapServer + ":" + ldapPort);
env.put(Context.REFERRAL, "follow");
if(sslEnabled) {
env.put("java.naming.ldap.factory.socket", TrustAllSSLSocketFactory.class.getName());
}
// Create the LDAP context
LdapContext context = new InitialLdapContext(env, null);
String base = "";
String filter = "(objectclass=*)";
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.OBJECT_SCOPE);
// Search the directory for retrieving namingContexts attribute
// which contains all the base DNs values
NamingEnumeration<SearchResult> results = context.search(base, filter, controls);
List<String> namingContextsList = new ArrayList<String>();
// Process attributes
if(results.hasMore()) {
Attributes attrs = results.next().getAttributes();
if (attrs != null) {
Attribute namingContexts = attrs.get("namingContexts");
NamingEnumeration enumeration = namingContexts.getAll();
while(enumeration.hasMore()) {
namingContextsList.add((String) enumeration.next());
}
}
}
System.out.println(namingContextsList);
Could you please help in fetching all the possible DNs in similar manner or other?
Just change OBJECT_SCOPE to SUBTREE_SCOPE.
This is all documented, you know.
Following code works for me: (Note that you need to provide credentials to perform this operation and the attribute name is "distinguishedName")
String ldapServer = "192.168.0.11";
String ldapPort = "389";
String principal = "CN=user";
String password = "password";
Hashtable<String,String> environment = new Hashtable<String,String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://" + ldapServer + ":" + ldapPort);
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, principal);
environment.put(Context.SECURITY_CREDENTIALS, password);
environment.put(Context.REFERRAL, "follow");
environment.put("com.sun.jndi.ldap.connect.pool", "true");
// Create the LDAP context
LdapContext context = new InitialLdapContext(environment, null);
String baseDN = "DC=domain,DC=com" // Put your base DN here
String filter = "(objectclass=*)";
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); // Use this for first level DNs only
NamingEnumeration<SearchResult> results = context.search(baseDN, filter, controls);
List<String> searchDNsList = new ArrayList<String>();
try {
// Process attributes
while(results.hasMore()) {
Attributes attrs = results.next().getAttributes();
if (attrs != null) {
Attribute distinguisedNames = attrs.get("distinguishedName");
if(distinguisedNames != null) {
NamingEnumeration enumeration = distinguisedNames.getAll();
while(enumeration.hasMore()) {
String searchDN = (String) enumeration.next();
searchDNsList.add(searchDN);
}
}
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println(searchDNsList);

Sharepoint 2010 DocumentSets - How to Manage Programatically?

I am new to Sharepoint 2010 but not new to .Net programming. Here is a my situation, i have a large set of files to be uploaded into Sharepoint 2010 with metadata. I have decided to write a C# class library to handle the documentsets programatically. I have to use to DocumentSets and i was able to successfully create a documentset. Now i am stuck with the following:
How do i check if a documentset already exists?
How do i remove a documentSet?
Here is my code to create the documentset:
using (SPSite site = new SPSite(spURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList docs = web.Lists["Documents"];
if (docs != null)
{
SPContentType docSetCT = docs.ContentTypes["Document Set"];
if (docSetCT != null)
{
Hashtable docsetProps = new Hashtable();
docsetProps.Add("New Docset", "New Docset");
DocumentSet docSet = DocumentSet.Create(docs.RootFolder, documentSetName, docSetCT.Id, docsetProps, true);
docs.Update();
}
}
}
}
The list of helper methods for working with Document Sets:
How do I check if a document set already exists?
private static bool IsDocumentSetExist(SPList list,string docSetName)
{
var folderUrl = SPUrlUtility.CombineUrl(list.RootFolder.ServerRelativeUrl, docSetName);
var folder = list.ParentWeb.GetFolder(folderUrl);
return folder.Exists;
}
Usage:
var docSetExists = IsDocumentSetExist(docs, "New Docset");
How do I remove a document set?
private static void DeleteDocumentSet(DocumentSet docSet)
{
docSet.Folder.Delete();
}

Set the value of custom webpart property in c#

How to set the value of custom webpart property Programatically in C#.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite SiteCollection = new SPSite(mySiteGuid))
{
SPWeb myWeb = SiteCollection.OpenWeb(myWebGuid);
myWeb .AllowUnsafeUpdates = true;
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
mgr = myWeb.GetLimitedWebPartManager ("default.aspx",System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
foreach (System.Web.UI.WebControls.WebParts.WebPart myWebPart in mgr.WebParts)
{
if (myWebPart.Title == "Other Webpart Name")
{
myWebPart.Visible = ! myWebPart.Visible;
myWeb.Update();
break;
}
}
}
});
I have a custom property in the webpart of type string to get the input from the user.
I wanted to updated the value of the property from c#.
Is there any way to set the value?
TIA
Try myWebPart.Update() instead of myWeb.Update().
Maybe it's a bit late for the answer, but here i let a piece of code i used for this.
var webCollection = new SPSite("http://mySharePointSite").AllWebs;
foreach (SPWeb web in webCollection)
{
var landingPageReference = #"/Pages/default.aspx";
var page = web.GetFile(landingPageReference);
if (!page.Exists)
continue;
page.CheckOut();
var spLimitedWebPartManager = web.GetLimitedWebPartManager(page.ServerRelativeUrl, PersonalizationScope.Shared);
foreach (WebPart webPartItem in spLimitedWebPartManager.WebParts)
{
if (webPartItem.Title.Equals("myWebPartTitle"))
{
// Specify Properties to change here
webPartItem.ChromeType = PartChromeType.Default;
webPartItem.Description = "AGAIN CHANGED";
// Save made changes
spLimitedWebPartManager.SaveChanges(webPartItem);
break;
}
}
page.CheckIn("Add Comment if desired");
page.Publish("Add Comment if desired");
web.Update();
web.Dispose();
}

Error :"Error:The user does not exist or is not unique " when add user in AD

I want add user in ActiveDirectory.
I use this code
private SPUser CreateUser(string strLoginName, string strEMail,
string strName, string strNotes, string strSiteURL)
{
SPUser spReturn = null;
SPSite spSite = null;
SPWeb spWeb = null;
try
{
//Open the SharePoint site
spSite = new SPSite(strSiteURL);
spWeb = spSite.OpenWeb();
//Assign role and add user to site
SPRoleAssignment spRoleAssignment =
new SPRoleAssignment(strLoginName, strEMail, strName, strNotes);
//Using Contribute, might need high access
SPRoleDefinition spSPRoleDefinition =
spWeb.RoleDefinitions["Contribute"];
spRoleAssignment.RoleDefinitionBindings.Add(spSPRoleDefinition);
spWeb.RoleAssignments.Add(spRoleAssignment);
//Update site
spWeb.Update();
spReturn = spWeb.AllUsers[strLoginName];
}
catch(Exception)
{
}
finally
{
spWeb.Close();
spSite.Close();
}
return spReturn;
}
when spWeb.RoleAssignments.Add(spRoleAssignment);
error :"Error:The user does not exist or is not unique "
EDIT
The following worked for me:
SPUser user = spWeb.EnsureUser(strLoginName);
SPRoleAssignment spRoleAssignment =
new SPRoleAssignment(user);
Your code will only grant Contribute access to an existing Active Directory user.
If you really want to create a new Active Directory user, see Create Active Directory user in .NET (C#).

How to programmatically set the task outcome (task response) of a Nintex Flexi Task?

Is there any way of set a Nintex Flexi task completion through Sharepoint's web services? We have tried updating the "WorkflowOutcome", "ApproverComments" and "Status" fields without success (actually the comments and status are successfully updated, however I can find no way of updating the WorkflowOutcome system field).
I can't use the Nintex Web service (ProcessTaskResponse) because it needs the task's assigned user's credentials (login, password, domain).
The Asp.net page doesn't have that information, it has only the Sharepoint Administrator credentials.
One way is to delegate the task to the admin first, and then call ProcessTaskResponse, but it isn't efficient and is prone to errors.
In my tests so far, any update (UpdateListItems) to the WorkflowOutcome field automatically set the Status field to "Completed" and the PercentComplete field to "1" (100%), ending the task (and continuing the flow), but with the wrong answer: always "Reject", no matter what I try to set it to.
Did you try this code: (try-cacth block with redirection does the trick)
\\set to actual outcome id here, for ex. from OutComePanel control
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldDecision] = 0;
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldComments] = " Some Comments";
taskItem.Update();
try
{
Nintex.Workflow.Utility.RedirectOrCloseDialog(HttpContext.Current, Web.Url);
}
catch
{
}
?
Here are my code to change outcome of nintex flexi task. My problem is permission. I had passed admin token to site. It's solve the problem.
var siteUrl = "...";
using (var tempSite = new SPSite(siteUrl))
{
var sysToken = tempSite.SystemAccount.UserToken;
using (var site = new SPSite(siteUrl, sysToken))
{
var web = site.OpenWeb();
...
var cancelled = "Cancelled";
task.Web.AllowUnsafeUpdates = true;
Hashtable ht = new Hashtable();
ht[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(new CultureInfo((int)task.Web.Language, false), Strings.WorkflowStatusCompleted, new object[0]);
ht["Completed"] = true;
ht["PercentComplete"] = 1;
ht["Status"] = "Completed";
ht["WorkflowOutcome"] = cancelled;
ht["Decision"] = CommonHelper.GetFlexiTaskOutcomeId(task, cancelled);
ht["ApproverComments"] = "cancelled";
CommonHelper.AlterTask((task as SPListItem), ht, true, 5, 100);
task.Web.AllowUnsafeUpdates = false;
}
}
}
}
}
}
public static string GetFlexiTaskOutcomeId(Microsoft.SharePoint.Workflow.SPWorkflowTask task, string outcome)
{
if (task["MultiOutcomeTaskInfo"] == null)
{
return string.Empty;
}
string xmlOutcome = HttpUtility.HtmlDecode(task["MultiOutcomeTaskInfo"].ToString());
if (string.IsNullOrEmpty(xmlOutcome))
{
return string.Empty;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlOutcome);
var node = doc.SelectSingleNode(string.Format("/MultiOutcomeResponseInfo/AvailableOutcomes/ConfiguredOutcome[#Name='{0}']", outcome));
return node.Attributes["Id"].Value;
}
public static bool AlterTask(SPListItem task, Hashtable htData, bool fSynchronous, int attempts, int milisecondsTimeout)
{
if ((int)task[SPBuiltInFieldId.WorkflowVersion] != 1)
{
SPList parentList = task.ParentList.ParentWeb.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
SPListItem parentItem = parentList.Items.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
for (int i = 0; i < attempts; i++)
{
SPWorkflow workflow = parentItem.Workflows[new Guid(task[SPBuiltInFieldId.WorkflowInstanceID].ToString())];
if (!workflow.IsLocked)
{
task[SPBuiltInFieldId.WorkflowVersion] = 1;
task.SystemUpdate();
break;
}
if (i != attempts - 1)
{
Thread.Sleep(milisecondsTimeout);
}
}
}
var result = SPWorkflowTask.AlterTask(task, htData, fSynchronous);
return result;
}