How to get FileID from Sharepoint - c#

How can I get FileID from Sharepoint. The fileID that I'm looking for is the Guid that we required to pass in to the 'GetFileById' method. For example
var clientContext = new ClientContext("http://myserver");
var fileGuid = new Guid("D51C440B-4F52-4005-90BE-BDC42E850975");
var file = clientContext.Web.GetFileById(fileGuid);
Additionally, I'm using Microsoft.SharePoint.Client from Nuget (version: 14.0.4762.1000) in a .NET console app to access sharepoint . I don't see the method 'GetFileById' anymore in this dll and due to this I'm using the below code to retrieve the sharepoint file object
using (ClientContext context = new ClientContext(new Uri("http://myserver")))
{
try
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = CredentialCache.DefaultNetworkCredentials;
Web web = context.Web;
Microsoft.SharePoint.Client.File doc = web.GetFileByServerRelativeUrl(docURL);
context.Load(doc, d => d.Name, d => d.Exists, d => d.ListItemAllFields);
context.ExecuteQuery();
}
}
How can I get fileID(Guid) from the above code snippet ? I tried using ListItemAllFields["_dlc_DocId"] but that is not fileID(Guid) that I'm looking for.
Any thoughts ?

Use ListItemAllFields["UniqueId"] to get the sharepoint FileID (Guid). See the below code
using (ClientContext context = new ClientContext(new Uri("http://myserver")))
{
try
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = CredentialCache.DefaultNetworkCredentials;
Web web = context.Web;
Microsoft.SharePoint.Client.File doc = web.GetFileByServerRelativeUrl(docURL);
context.Load(doc, d => d.Name, d => d.Exists, d => d.ListItemAllFields);
context.ExecuteQuery();
Console.WriteLine(doc.ListItemAllFields["UniqueId"]);
}
}

Related

How to validate ARM Template using azure .net SDK or Fluent API?

How to validate uploaded ARM Template using azure .net SDK or Fluent API ?
I want to validate my uploaded ARM template like azure portal do using azure .net SDK or Fluent API ?
For reference please see below image azure is showing message if ARM template not valid so same thing i want to implement using any .net API or REST API.
#Jim Below error I am getting:
If you want to validate your arm template, please refer to the following steps
Create a service principal and assign Contributor role to the sp
az ad sp create-for-rbac -n "MyApp"
Install Package
Install-Package Microsoft.Azure.Management.ResourceManager.Fluent -Version 1.34.0
Code
string clientId = "23****9c";
string clientSecret = "?s****/k";
string tenantDomain = "";
string subscription = "";
var creds= SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantDomain, AzureEnvironment.AzureGlobalCloud);
var restClient = RestClient.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithCredentials(creds)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Build();
ResourceManagementClient managementClient = new ResourceManagementClient(restClient);
managementClient.SubscriptionId = subscription;
//Validates whether the specified template is syntactically correct and will be accepted by Azure Resource Manager..
DeploymentValidateResultInner res = await managementClient.Deployments.ValidateAsync("<groupName>", "<deployName>", new DeploymentInner()
{
Location = "",
Properties = new DeploymentProperties()
{
ParametersLink = new ParametersLink("uri"),
TemplateLink = new TemplateLink("")
}
});
Console.WriteLine(res.Error.Message);
// get changes that will be made by the deployment if executed at the scope of resource group
WhatIfOperationResultInner res1 = await managementClient.Deployments.WhatIfAsync("<groupName>", "<deployName>", new DeploymentWhatIf() {
Location="",
Properties= new DeploymentWhatIfProperties() {
ParametersLink = new ParametersLink("uri"),
TemplateLink = new TemplateLink("")
}
});
foreach (var change in res1.Changes) {
//
}
I like that the accepted answer adds the "what if" to validation. However, Microsoft.Azure.Management.ResourceManager is deprecated, and it took me a bit to figure out a way to validate an ARM template using the replacement library: Azure.ResourceManager.
Here's a code snippet that provides template validation using the new library (it doesn't include the what-if call):
var credential = new DefaultAzureCredential();
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var client = new ArmClient(credential, subscriptionId);
var deploymentContent = new ArmDeploymentContent(new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
{
Template = BinaryData.FromString(templateContent),
Parameters = BinaryData.FromObjectAsJson(new
{
hostingPlanName = new
{
value = hostingPlanName
},
webSiteName = new
{
value = webAppName
},
skuName = new
{
value = webSkuName
},
skuCapacity = new
{
value = webSkuCapacity
},
})
});
var resourceGroupId = ResourceGroupResource.CreateResourceIdentifier(SubscriptionId!, resourceGroupName);
// This ArmDeploymentResource resource may or may not exist, but it doesn't matter - it's just a placeholder for validation
var deploymentResourceId = ArmDeploymentResource.CreateResourceIdentifier(resourceGroupId, deploymentName);
var armDeployment = client.GetArmDeploymentResource(deploymentResourceId);
var validateOperation = await armDeployment.ValidateAsync(WaitUntil.Completed, toValidate, _cancellationToken);
var validateResult = validateOperation.Value;
if (validateResult.Error != null)
{
_logger.LogEndOperation(loggerOpKey, false, validateResult.Error.Message ?? "Validation errored");
_logger.LogError(JsonConvert.SerializeObject(validateResult.Error, Formatting.Indented));
return false;
}
// Log this if you want:
string deploymentDetails = $"Deployment: {deploymentName} ProvisioningState:{validateResult.Properties.ProvisioningState}\n"
+ $" started:{validateResult.Properties.Timestamp} duration:{validateResult.Properties.Duration}\n"
+ $" correlationId:{validateResult.Properties.CorrelationId}\n"
+ $" outputs:{JsonConvert.SerializeObject(validateResult.Properties.Outputs)}";
bool succeeded = validateResult.Properties.ProvisioningState == "Succeeded";
return succeeded;

ASP.NET MVC: The sign-in name or password does not match one in the Microsoft account system

I wanted to fetch all files from the document library one of my Online Sharepoint site.
For that, I have created 2 apps i.e. Console App and ASP.Net MVC apps
Below is the code,
using ASPNetDemo.Models;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Web.Mvc;
namespace ASPNetDemo.Controllers
{
public class DocumentLibraryController : Controller
{
private readonly string baseURL;
private readonly string siteURL;
public DocumentLibraryController()
{
baseURL = "https://onevirtualoffice.sharepoint.com";
siteURL = $"{baseURL}/sites/mysite";
}
// GET: DocumentLibrary
public ActionResult Index()
{
var model = new FileUploadViewModel();
model.Username = "firstname.lastname#domain.com";
model.Password = "{password}";
var list = GetFiles(model);// get all files from
return View();
}
public List<string> GetFiles(FileUploadViewModel model)
{
try
{
using (var clientContext = new ClientContext(siteURL))
{
SecureString passWordSecure = new SecureString();
foreach (char c in model.Password.ToCharArray()) passWordSecure.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(model.Username, passWordSecure);
Web web = clientContext.Web;
#region get list
List<string> fileList = new List<string>();
var results = new Dictionary<string, IEnumerable<Microsoft.SharePoint.Client.File>>();
var lists = clientContext.LoadQuery(clientContext.Web.Lists.Where(l => l.BaseType == BaseType.DocumentLibrary));
clientContext.ExecuteQuery();
foreach (var list in lists)
{
if (list.Title.Equals("TestFolder"))
{
var items = list.GetItems(CreateAllFilesQuery());
clientContext.Load(items, icol => icol.Include(i => i.File));
results[list.Title] = items.Select(i => i.File);
}
}
clientContext.ExecuteQuery();
foreach (var result in results)
{
foreach (var file in result.Value)
{
var fileName = "";
if (string.IsNullOrEmpty(file.LinkingUri))
fileName = string.Concat(baseURL, file.ServerRelativeUrl);
else
fileName = file.LinkingUri;
fileList.Add(fileName);
}
}
return fileList;
#endregion
}
}
catch (Exception ex)
{
throw ex;
}
}
private CamlQuery CreateAllFilesQuery()
{
var qry = new CamlQuery();
qry.ViewXml = "<View Scope=\"RecursiveAll\"><Query><Where><Eq><FieldRef Name=\"FSObjType\" /><Value Type=\"Integer\">0</Value></Eq></Where></Query></View>";
return qry;
}
}
}
The above code is working fine in Console application and its fetching all the files under TestFolder document library. But When I tried the same code in ASP.Net MVC5 Framework 4.6.1 then it throwing an exception as The sign-in name or password does not match one in the Microsoft account system.
Could you please help to guide where I am wrong.

Uploading a single Sharepoint document with metadata

I defined terms in the Term Store Management Tool which I added as "Managed Metadata" columns in a document library.
I want to upload a document and to update its "Managed Metadata" columns.
In order to do so, I wrote the following code:
void UploadDocument(Document document)
{
try
{
using (ClientContext context = SPHelper.GetClientContext())
{
List library = context.Web.Lists.GetByTitle("MyDocumentLibrary");
FileCreationInformation fileInfo = new FileCreationInformation
{
Url = "MyFileTarget",
Content = document.Content,
Overwrite = true
};
File file = library.RootFolder.Files.Add(fileInfo);
ListItem item = file.ListItemAllFields;
item["RegularColumn"] = "some data";
item["Metadata"] = "some other data";
item.Update();
context.ExecuteQuery(); // "The given guid does not exist in the term store." Exception thrown
}
}
catch (Exception ex)
{
LogHelper.RecordError("Failed to upload document", ex, System.Reflection.MethodInfo.GetCurrentMethod().Name);
}
}
I can upload a file and update its regular columns but I can't update the Metadata columns.
Is there a way to specify item["Metadata"] GUID ?
The Term Guid can be found in Term Store:
Add reference to Microsoft.SharePoint.Client.Taxonomy.dll:
Here is the code snippet to set managed metadata field value with TaxonomyFieldValue class:
using (ClientContext context = new ClientContext(sharePointSite))
{
FileCreationInformation FCInfo = new FileCreationInformation();
FCInfo.Url = "http://sp2016/sites/dev/Shared%20Documents/Test.txt";
FCInfo.Overwrite = true;
FCInfo.Content = System.IO.File.ReadAllBytes(fileToUpload);
Web web = context.Web;
List library = web.Lists.GetByTitle(libraryName);
Microsoft.SharePoint.Client.File uploadfile = library.RootFolder.Files.Add(FCInfo);
ListItem item = uploadfile.ListItemAllFields;
item["Title"] = "some data";
var fields = library.Fields;
var field = fields.GetByInternalNameOrTitle("managedcolumn");
context.Load(fields);
context.Load(field);
context.ExecuteQuery();
var taxKeywordField = context.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = new TaxonomyFieldValue();
termValue.Label = "TermC";
termValue.TermGuid = "045830f1-f51e-4bac-b631-5815a7b6125f";
termValue.WssId = 3;
taxKeywordField.SetFieldValueByValue(item, termValue);
item.Update();
context.ExecuteQuery();
uploadfile.CheckIn("testcomment", CheckinType.MajorCheckIn);
context.ExecuteQuery();
}

CSOM Set Sharing on OneDrive Folder

I'd like to set sharing rights on a folder in OneDrive. I know there is a post out there about ListItems, but I need it at a folder level. First, is this possible or am I wasting my time? I've tried the following:
I'm able to get the site object but I'm not able to get the folder in order to share it. The web object doesn't have the folders available to enumerate through. It says it's not initialized. This code below successfully runs but the folder object is not working:
static void Main(string[] args)
{
var webUrl = "https://tenant-my.sharepoint.com/personal/me_tenant_com";
var userName = "me";
string securePassword = "mypassword";
SecureString sec_pass = new SecureString();
Array.ForEach(securePassword.ToArray(), sec_pass.AppendChar);
using (var ctx = new ClientContext(webUrl))
{
ctx.Credentials = new SharePointOnlineCredentials(userName, sec_pass);
var web = ctx.Web;
ClientResult<Microsoft.SharePoint.Client.Utilities.PrincipalInfo> persons = Microsoft.SharePoint.Client.Utilities.Utility.ResolvePrincipal(ctx, ctx.Web, "dpunchak#AvvenireInc.com", Microsoft.SharePoint.Client.Utilities.PrincipalType.User, Microsoft.SharePoint.Client.Utilities.PrincipalSource.All, null, true);
ctx.ExecuteQuery();
var folder = ctx.Web.GetFolderByServerRelativeUrl("/documents/Test Folder");
Microsoft.SharePoint.Client.Utilities.PrincipalInfo person = persons.Value;
//ShareListItem(folder, person, "Read");
}
}
public static void ShareListItem(ListItem listItem, Principal principal, string permissionLevelName)
{
var ctx = listItem.Context as ClientContext;
var roleDefinition = ctx.Site.RootWeb.RoleDefinitions.GetByName(permissionLevelName);
listItem.BreakRoleInheritance(true, false);
var roleBindings = new RoleDefinitionBindingCollection(ctx) { roleDefinition };
listItem.RoleAssignments.Add(principal, roleBindings);
ctx.ExecuteQuery();
}
I think you have to pass folder.ListItemAllFields property to ShareListItem().
To avoid collection has not been initialized error you can try placing RoleAssignments.Add() inside ctx.ExecuteQuery():
ctx.ExecuteQuery(listItem.RoleAssignments.Add(principal, roleBindings);

How to rename a folder on OneDrive using Windows Phone API?

This is how I was creating a folder on OneDrive using Windows Phone API.
public async Task<string> CreateSkyDriveFolder()
{
string folderId = null;
var opResult = await Client.GetAsync("me/skydrive/files?filter=folders");
dynamic result = opResult.Result;
foreach (dynamic folder in result.data)
{
if (folder.name.ToLowerInvariant().Trim() == skyDriveFolderName.ToLowerInvariant().Trim())
{
folderId = folder.id;
break;
}
}
if (folderId == null)
{
var folderData = new Dictionary<string, object>();
folderData.Add("name", skyDriveFolderName);
opResult = await Client.PostAsync("me/skydrive", folderData);
result = opResult.Result;
folderId = result.id;
}
}
But now, I just want to replace a folder name 'OldFolder' on OneDrive to 'NewFolder'. How can I do this using API?
Any help will much be appreciated. Thanks. :-)
Each folder in the OneDrive API is considered to be an "item".
And each item can be updated with a new name.
These rows should update the item with id "folderId" and give it the new name "NewFolder".
var Client = new HttpClient();
var request = new HttpRequestMessage(
new HttpMethod("PATCH"),
String.Format("/drive/items/{0}", folderId)
);
var renameInstruction = new StringContent("{\"name\":\"NewFolder\"}");
request.Content = renameInstruction;
var opResult = await Client.SendAsync(request);
Tested on my private OneDrive folder using the OneDrive console.
API source: https://github.com/OneDrive/onedrive-api-docs/blob/master/items/update.md
Let me know if anything is unclear or strange in any way. Have a marvelous day!

Categories

Resources