I'm trying to link a c# application to a sharepoint directory, so I can create folders, download and upload files. However I am strugling with connecting to the correct folder.
I can retrieve the content from allitems.aspx, but I am not sure how to actually get the content from folder.
I have tried using the ClientContext - something like this:
ClientContext cxt = new ClientContext("https://xx.sharepoint.com/sites/");
cxt.Credentials = GetCredentials();
List list = cxt.Web.Lists.GetByTitle("Kontrakter");
var test = list.Views;
var test1 = cxt.Web.Lists;
cxt.Load(test1);
cxt.Load(list);
cxt.Load(test);
var a = 4;
var fullUri = new Uri("https://xx.sharepoint.com/sites/yy/Kontrakter/AllItems.aspx");
//var folder = cxt.Web.GetFolderByServerRelativeUrl(fullUri.AbsolutePath);
using (var rootCtx = new ClientContext(fullUri.GetLeftPart(UriPartial.Authority)))
{
rootCtx.Credentials = GetCredentials();
Uri webUri = Web.WebUrlFromPageUrlDirect(rootCtx, fullUri);
using (var ctx1 = new ClientContext(webUri))
{
ctx1.Credentials = GetCredentials();
var list1 = ctx1.Web.GetList(fullUri.AbsolutePath);
ctx1.Load(list1.RootFolder.Files);
ctx1.ExecuteQuery();
Console.WriteLine(list.RootFolder.Files.Count);
}
}
or via normal api calls like this:
https://xx.sharepoint.com/_api/Web/GetFolderByServerRelativeUrl('Kontrakter/Forms')/Files
The only way I can find some data is if I look into 'Shared documents/Forms'
I'm having problems understanding the directory structure and how I can actually find the content of files/folders.
Thanks in advance :)
Turned out I was missing a /sites in one of my uris.
Related
I am trying to automate some processes to make life a bit easier. We have multiple requests from the team to create a folder in TFS 2017 (they do not have permissions) and then set up the associated builds for that source control folder.
The build creation part I think I have a way to do, but querying our on premise TFS 2017 server to get a list of folders under a certain path is proving tricky. So far I am having trouble even connecting to the server in the first place with this :
var collectionUri = "http://tfs-server:8080/tfs/DefaultCollection/";
var teamProjectName = "MYPROJECT";
Uri uri = new Uri(collectionUri);
var clientCredentials = new VssCredentials(new WindowsCredential(new NetworkCredential("USERNAME", "PASSWORD", "COLLECTIONNAME")));
var connection = new VssConnection(uri, clientCredentials);
var sourceControlServer = connection.GetClient<TfvcHttpClient>();
That throws an exception : Error converting value "System.Security.Principal.WindowsIdentity;" to type 'Microsoft.VisualStudio.Services.Identity.IdentityDescriptor'
Can someone help me to get connected to the server first please! Documentation on this is very hard to find, and I dont see any examples that actually work.
What I was going to look at next was creating the folder if it doesn't exist. No idea how to do that yet, maybe using
sourceControlServer.GetBranchAsync(teamProjectName + FolderName);
Thanks!
EDIT:
Ok I got it to not error creating the connection by doing this instead :
Uri uri = new Uri("http://tfs-server:8080/tfs/DefaultCollection/");
var clientCredentials = new VssCredentials(new WindowsCredential(new NetworkCredential("USERNAME", "PASSWORD", "DOMAIN")));
var buildServer = new BuildHttpClient(uri, clientCredentials);
var sourceControlServer = new TfvcHttpClient(uri, clientCredentials);
So now to just figure out how to list and create folders from TFS and to create builds!
EDIT:
So I have got the querying working, so I can check if a folder exists under a path like this :
var teamProjectName = "USA";
Uri uri = new Uri("http://tfs-server:8080/tfs/DefaultCollection/");
var clientCredentials = new VssCredentials(new WindowsCredential(new NetworkCredential("USERNAME", "PASSWORD", "DOMAIN")));
TfvcHttpClient sourceControlServer = new TfvcHttpClient(uri, clientCredentials);
List<TfvcItem> branchItems;
using (sourceControlServer) {
branchItems = sourceControlServer.GetItemsAsync("$/USA/Development/NewFolder", VersionControlRecursionType.OneLevel).Result;
}
return branchItems.Count > 0;
That will find all the items under that folder. So if there isnt a folder, it will return 0, so I can go ahead and create that folder.
So next problem, is how to create the folder. Using CreateChangesetAsync.
Update:
To use Client API and CreateChangesetAsync method to create files in TFVC, you could refer below sample console app:
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
internal static async Task Main(string[] args)
{
var orgUrl = new Uri(args[0]);
string serverPath = args[1];
string localPath = args[2];
string contentType = args[3];
string pat = args[4];
var changes = new List<TfvcChange>()
{
new TfvcChange()
{
ChangeType = VersionControlChangeType.Add,
Item = new TfvcItem()
{
Path = serverPath,
ContentMetadata = new FileContentMetadata()
{
Encoding = Encoding.UTF8.WindowsCodePage,
ContentType = contentType,
}
},
NewContent = new ItemContent()
{
Content = Convert.ToBase64String(File.ReadAllBytes(localPath)),
ContentType = ItemContentType.Base64Encoded
}
}
};
var changeset = new TfvcChangeset()
{
Changes = changes,
Comment = $"Added {serverPath} from {localPath}"
};
var connection = new VssConnection(orgUrl, new VssBasicCredential(string.Empty, pat));
var tfvcClient = connection.GetClient<TfvcHttpClient>();
await tfvcClient.CreateChangesetAsync(changeset);
}
}
}
Besides, instead of using tf command line, please kindly check solution here:
C# TFS API: show project structure with folders and files, including their ChangeType (checked out, deleted,renamed) like in visual studio
I have a SharePoint Online where I can connect through my console application successfully:
private static ClientContext GetUserContext()
{
var o365SecurePassword = new SecureString();
foreach (char c in o365Password)
{
o365SecurePassword.AppendChar(c);
}
var o365Credentials = new SharePointOnlineCredentials(o365Username, o365SecurePassword);
var o365Context = new ClientContext(o365SiteUrl);
o365Context.Credentials = o365Credentials;
return o365Context;
}
But what I need now to do is to go into my SharePoint Document Library named "doc_archive" and check if there exists a folder with name "K20170409-01".
If not create a new one.
Failed Attempt
ClientContext context = GetUserContext();
Web web = context.Web;
Web webroot = context.Site.RootWeb;
context.Load(web);
context.Load(webroot);
List list = webroot.GetList("doc_archive");
context.Load(list);
FolderCollection folders = list.RootFolder.Folders;
context.Load(folders);
IEnumerable<Folder> existingFolders = context.LoadQuery(
folders.Include(
folder => folder.Name)
);
context.ExecuteQuery();
What is the fastest ways to check and create a folder within a document library in SharePoint Online via CSOM (commandline application)?
If you are happy with using external libraries then the OfficeDevPnP.Core has some great CSOM extensions for SharePoint and SharePoint Online. It's readily available as a NuGet package to add to your projects.
For your requirment there is the EnsureFolderPath extension. This function will check if a folder exists, create it if needed and return the Microsoft.SharePoint.Client.Folder object.
Very easy to use:
var webRelativeUrlToFolder = "/doc_archive/K20170409-01"
var folder = cc.Web.EnsureFolderPath(webRelativeUrlToFolder);
cc.Load(folder);
cc.ExecuteQuery();
I can't vouch for how fast this would be, but it works in the end on 0365. Note that it throws a ServerException if the target already exists.
using (var ctx = new ClientContext(siteUrl))
{
ctx.Credentials = new SharePointOnlineCredentials(username, securePwd);
var list = new ListCreationInformation()
{
Title = title
Description = "User Created Document Library",
TemplateType = asDocumentLibrary ? 101 : 100 // 100 is a custom list.
};
ctx.Web.Lists.Add(list);
ctx.ExecuteQuery();
success = true;
}
Most CSOM examples are found in Powershell. The process in C# CSOM is actually the same, so next time find a Powershell example when a C# one is not available.
I am attempting to create a .NET program that calls the NetSuite web services to return a list of files associated to a customer.
I have set the ShopperJoin to the customer I've searched for, but the web call still returns all files in the File Cabinet.
FileSearch file = new FileSearch();
CustomerSearchBasic custBasic = new CustomerSearchBasic();
custBasic.entityId= new SearchStringField();
custBasic.entityId.#operator = SearchStringFieldOperator.contains ;
custBasic.entityId.operatorSpecified = true;
file.shopperJoin = custBasic;
file.basic = new FileSearchBasic();custBasic.entityId.searchValue = "ID";
SearchResult result = _service.search(file);
I am using the 2015 SuiteTalk wsdl
https://webservices.na1.netsuite.com/wsdl/v2015_1_0/netsuite.wsdl
Have you checked if the customer id and the folder id are the same? (just a hunch)
After contacting NetSuite support, I learned that I had taken the wrong approach.
Files can be filtered based on customer via a customer search.
I was able to create a CustomerSearchAdvanced request that retrieves associated files.
When you create that, you add the columns you want to the FileJoin object in the request, and it will find the files based on whatever customer criteria you set up.
CustomerSearchAdvanced attachSearch = new CustomerSearchAdvanced();
SearchColumnStringField[] stringcols = new SearchColumnStringField[1];
stringcols[0] = new SearchColumnStringField();
SearchColumnStringField[] stringcols = new SearchColumnStringField[1];
stringcols[0] = new SearchColumnStringField();
attachSearch.columns = new CustomerSearchRow();
attachSearch.columns.fileJoin = new FileSearchRowBasic();
attachSearch.columns.fileJoin.internalId = selcols;
attachSearch.columns.fileJoin.description = stringcols;
attachSearch.columns.fileJoin.name = stringcols;
Using System.DirectoryServices, one can get the highestCommittedUSN this way:
using(DirectoryEntry entry = new DirectoryEntry("LDAP://servername:636/RootDSE"))
{
var usn = entry.Properties["highestCommittedUSN"].Value;
}
However, I need to get this information from a remote ADLDS using System.DirectoryServices.Protocols, which does not leverage ADSI. Following is a simplified code sample of what I'm attempting to do:
using(LdapConnection connection = GetWin32LdapConnection())
{
var filter = "(&(highestCommittedUSN=*))";
var searchRequest = new SearchRequest("RootDSE", filter, SearchScope.Subtree, "highestCommittedUSN");
var response = connection.SendRequest(searchRequest) as SearchResponse;
var usn = response.Entries[0].Attributes["highestCommittedUSN"][0];
}
Unfortunately this kicks back a "DirectoryOperationException: The distinguished name contains invalid syntax." At first I thought there might be something wrong in GetWin32LdapConnection() but that code is called in numerous other places to connect to the directory and never errors out.
Any ideas?
Thanks for the idea, Zilog. Apparently to connect to the RootDSE, you have to specify null for the root container. I also switched the filter to objectClass=* and the search scope to "base." Now it works!
using(LdapConnection connection = GetWin32LdapConnection())
{
var filter = "(&(objectClass=*))";
var searchRequest = new SearchRequest(null, filter, SearchScope.Base, "highestCommittedUSN");
var response = connection.SendRequest(searchRequest) as SearchResponse;
var usn = response.Entries[0].Attributes["highestcommittedusn"][0];
}
I hope this saves someone else some time in the future.
I can get all the documents in Google Docs using
public DocumentsFeed GetDocs()
{
DocumentsListQuery query = new DocumentsListQuery();
DocumentsFeed feed = service.Query(query);
return feed;
}
But how can I get the documents in a particular folder? I wan to discover the list of folders and then populate the folders in a tree view. On selection of a folder, I shall like to get the documents in that folder.
To get the folder, I am using
public DocumentsFeed GetFolders()
{
FolderQuery query = new FolderQuery("root"); //http://docs.google.com/feeds/documents/private/full
DocumentsFeed feed = service.Query(query);
return feed;
}
For the service, I am using private DocumentsService service;
Can somebody help?
Another guy using the API has described how he does it:
var docService = new DocumentsService("company-app-version");
docService.setUserCredentials("username", "password");
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Documents;
// snipped method declaration etc
var docService = new DocumentsService("company-app-version");
docService.setUserCredentials("username", "password");
var folderList = docService.Query(new FolderQuery());
var fLinks = folderList.Entries.Select(e =>
new
{
// note how to get the document Id of the folder
Id = DocumentsListQuery.DocumentId(e.Id.AbsoluteUri),
Name = e.Title.Text
});
foreach (var folder in fLinks)
{
Console.WriteLine("Folder {0}", folder.Name);
var fileList = docService.Query(
new SpreadsheetQuery()
{
// setting the base address to the folder's URI restricts your results
BaseAddress = DocumentsListQuery.folderBaseUri + folder.Id
});
foreach (var file in fileList.Entries)
{
Console.WriteLine(" - {0}", file.Title.Text);
}
}
Source:
http://jtnlex.com/blog/2010/06/09/google-docs-api-get-all-spreadsheetsdocs-in-a-folder/
Here's how :
instead of typing the name of the folder , use the resourceID of the folder query = new FolderQuery(FolderEntry.ResourceId);
But first you need to get ALL documents in the root and enable showing folders : query.ShowFolders = true; , that's how you get the resourceId's of the docs in the root and
folders!
Hope this helps !