1

I've been trying to connect to my sharepoint for a while now and it just won't work. I've tried many different thing but eventually ended up with this code:

private static readonly HttpClient client = new HttpClient();
[FunctionName("SendFiles")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    log.LogInformation("SendFiles Triggered");
      ClientContext context = new ClientContext("https://abc.sharepoint.com/sites/a-b");
    SecureString secureString = new SecureString();
    foreach(char c in "dummypass")
    {
        secureString.AppendChar(c);
    }
    // var cred = new NetworkCredential("x.y@faktion.com",secureString); // add domain?
    // context.Credentials = cred;
    context.Credentials = new SharePointOnlineCredentials("x.y@faktion.com", secureString);
    Web site = context.Web;
      string jsonInput = req.Content.ReadAsStringAsync().Result;
    SendFilesInput input = JsonConvert.DeserializeObject<SendFilesInput>(jsonInput);
      string url = "https://a.b.com/gql/api/organisations/" + input.OrganisationId + "/projects/" + input.ProjectId + "/process";
    string response = null;
    bool succesfullRequest = false;
    MultipartFormDataContent formdata = new MultipartFormDataContent();
    log.LogInformation("Adding files to MultiPartFormData and sending the files");
    try
    {
        foreach (var filePath in input.Files)
        {
            // create filestream content
            var fileurl = "https://abc.sharepoint.com/sites/a-b" + "/" + filePath;
            Microsoft.SharePoint.Client.File temp = site.GetFileByServerRelativeUrl(filePath);  // every single property says:
            Microsoft.SharePoint.Client.File temp2 = site.GetFileByUrl(fileurl);                // Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException
            ClientResult<Stream> crstream = temp.OpenBinaryStream();
            ClientResult<Stream> crstream2 = temp2.OpenBinaryStream();
            context.Load(temp);
            context.Load(temp2);
            context.ExecuteQuery(); // throws the exception
            var tempfile = Path.GetTempFileName();
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            if (crstream.Value != null)
            {
                crstream.Value.CopyTo(fs);
            }
            HttpContent content = new StreamContent(fs);
            string name = GetFileName(filePath);
            content.Headers.Add("Content-Type", GetFileType(name));
            formdata.Add(content, "files", name);
            System.IO.File.Decrypt(tempfile);
        }
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", input.BearerToken);
        // send content to the backend and parse result
        var resultPost = client.PostAsync(url, formdata).Result;
        response = resultPost.Content.ReadAsStringAsync().Result;
        succesfullRequest = resultPost.IsSuccessStatusCode;
    }
    // I absolutely want to catch every exception and pass these along to the workflow
    catch (Exception ex)
    {
        req.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
    // if something went wrong in the backend, throw an error
    if (!succesfullRequest)
    {
        req.CreateErrorResponse(HttpStatusCode.BadRequest, "Something went wrong during the upload process");
    }
    [...] // not important for the problem

I just want to read out a file stored on my sharepoint, turn this into a filestream and add it to my multipart formdata. Since it's an azure function, I can't use the local os because azure functions can't access the os.

Exception

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

If you cehck the comments in the code, you can see that all the properties of the file throw a Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException. I don't know if this is because it can't execute the query or due to another reason.

4
  • Is Modern Auth (+perhaps MFA for this account) enabled on this tenant? Is there a reason you don't use the strongly preferred client id/secret approach?
    – Trevor Seward
    Apr 15 '20 at 0:38
  • I have about 0 experience with SharePoint, I have no clue what the client id/secret approach is or where to find it on sharepoint. I passed it in the docs but looked a bit strange with al the inline XML strings. Apr 15 '20 at 10:30
  • See docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/… for more information.
    – Trevor Seward
    Apr 15 '20 at 15:37
  • I don't have access to that url because I only have access to certain sites, not to all the whole sharepoint platform Apr 16 '20 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.