Sharepoint 2010 DocumentSets - How to Manage Programatically? - sharepoint-2010

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();
}

Related

how to read excel file in memory (without saving it in disk) and return its content dotnet core

Im working on a webApi using dotnet core that takes the excel file from IFormFile and reads its content.Iam following the article
https://levelup.gitconnected.com/reading-an-excel-file-using-an-asp-net-core-mvc-application-2693545577db which is doing the same thing except that the file here is present on the server and mine will be provided by user.
here is the code:
public IActionResult Test(IFormFile file)
{
List<UserModel> users = new List<UserModel>();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = System.IO.File.Open(file.FileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read()) //Each row of the file
{
users.Add(new UserModel
{
Name = reader.GetValue(0).ToString(),
Email = reader.GetValue(1).ToString(),
Phone = reader.GetValue(2).ToString()
});
}
}
}
return Ok(users);
}
}
When system.IO tries to open the file, it could not find the path as the path is not present. How it is possible to either get the file path (that would vary based on user selection of file)? are there any other ways to make it possible.
PS: I dont want to upload the file on the server first, then read it.
You're using the file.FileName property, which refers to the file name the browser send. It's good to know, but not a real file on the server yet. You have to use the CopyTo(Stream) Method to access the data:
public IActionResult Test(IFormFile file)
{
List<UserModel> users = new List<UserModel>();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = new MemoryStream())
{
file.CopyTo(stream);
stream.Position = 0;
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read()) //Each row of the file
{
users.Add(new UserModel{Name = reader.GetValue(0).ToString(), Email = reader.GetValue(1).ToString(), Phone = reader.GetValue(2).ToString()});
}
}
}
return Ok(users);
}
Reference

Export DataList to Excel using Asp.net core

I want to export data list to Excel format but I could not find any third party library or any refrence. I am building my project on .net core. Any one expert here to suggest any solution. Thanks
If cross plattform (Windows, Linux, Mac) is a major concern for you then you have to use some "pre release" stuff.
There is an issue for .NET Core support for OpenXML, which can be used to create Open XML Office Documents (e.g. XLSX), (https://github.com/OfficeDev/Open-XML-SDK/issues/65). Some work has to be done before it is ready.
Someone who had your demand as well ported it to .NET Core and published his project on GitHub (https://github.com/xrkolovos/Open-XML-SDK-for-NET-Platform-Standard). I have not tried it myself, but it may be worthwile to try.
If your application runs on Windows only, then you can build your ASP.NET Core project on top of the full .NET Framework (with the well known third party libraries for creating Excel).
i had posted this question almost 7 months ago and i have found the solution, so i want to share it.
add "PdfRpt.Core": "1.0.0-*" on project.json
on controller
[HttpGet("exportexcell")]
public async Task<FileContentResult> ExportExcel()
{
var loggedUser = await GetCurrentUserAsync();
var users = _userManager.Users.Select(u => new UserListVM
{
Id = u.Id,
Name = u.UserName,
Email = u.Email
}).ToList();
if (users == null) return null;
//column Header name
var columnsHeader = new List<string>{
"S/N",
"User Name",
"Email"
};
var filecontent = ExportExcell(users, columnsHeader, "Users");
return File(filecontent, "application/ms-excel", "users.xlsx"); ;
}
helper method
private static byte[] ExportExcell(List<UserListVM> data, List<string> columns, string heading)
{
byte[] result = null;
using (ExcelPackage package = new ExcelPackage())
{
// add a new worksheet to the empty workbook
var worksheet = package.Workbook.Worksheets.Add(heading);
using (var cells = worksheet.Cells[1, 1, 1, 7])
{
cells.Style.Font.Bold = true;
cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
cells.Style.Fill.BackgroundColor.SetColor(Color.Green);
}
//First add the headers
for (int i = 0; i < columns.Count(); i++)
{
worksheet.Cells[1, i + 1].Value = columns[i];
}
//Add values
var j = 2;
var count = 1;
foreach (var item in data)
{
worksheet.Cells["A" + j].Value = count;
worksheet.Cells["B" + j].Value = item.Name;
worksheet.Cells["C" + j].Value = item.Email;
worksheet.Cells["D" + j].Value = item.RoleNam
j++;
count++;
}
result = package.GetAsByteArray();
}
return result;
}
//it work fine for me.. it may help to you too.
you can find demo here

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();
}

Programmatically add claim to a list

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.

Get custom templates programmatically sharepoint 2010

To get standard templates I do:
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
SPWebTemplateCollection Templates = siteCollection.GetWebTemplates(1033);
foreach (SPWebTemplate template in Templates)
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
I thought I could do:
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
SPWebTemplateCollection Templates = siteCollection.GetCustomWebTemplates(1033);
foreach (SPCustomWebTemplate template in Templates)
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
To get the custom templates but the dropdown is empty, what am I doing wrong here?
Thanks in advance.
Edit: the templates are activated in the solutions gallery.
I got it to work with
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
SPWebTemplateCollection Templates = siteCollection.GetAvailableWebTemplates(1033);
foreach (SPCustomWebTemplate template in Templates)
{
//this gives me all templates, both standard and custom so I filter by name
if(template.name.ToUpper().StartsWith("CUSTOM"))
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
}
SPSite does not contain a GetAvailableWebTemplates method. For those who would like to use the code use the one below. So I have added this line of code:
using(SPWeb web = siteCollection.OpenWeb())
{
SPWebTemplateCollection Templates = web.GetAvailableWebTemplates(1033);
Full code:
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
using(SPWeb web = siteCollection.OpenWeb())
{
SPWebTemplateCollection Templates = web.GetAvailableWebTemplates(1033);
foreach (SPCustomWebTemplate template in Templates)
{
//this gives me all templates, both standard and custom so I filter by name
if(template.name.ToUpper().StartsWith("CUSTOM"))
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
}
}