cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
Adam12345
Regular Visitor

Getting attachments from SharePoint List and automatically attaching them to a DevOps work item

Hi,

 

I have been trying for the past 6 months to try and get attachments added from a Sharepoint list into a new RFQ work item.

 

The reason I want this, is to try and integrate attachments from SharePoint.

 

I just want attachments that are added on a SharePoint list to automatically attach onto a work item. 

 

Does anyone know any ideas on how to get this done? Im bust for ideas!

 

1 ACCEPTED SOLUTION

Accepted Solutions

10 REPLIES 10
MattWeston365
Memorable Member
Memorable Member

Hi @Adam12345, unfortunately this isn't something which can be done directly using native actions currently in Flow. However, there is a really useful action called "Send a HTTP Request to DevOps" which means that we can use the REST APIs to achieve what we want.

 

High level approach is:

  1. Get the work item from DevOps
  2. Get the attachments from the list item
  3. Get the content
  4. Upload it to Dev Ops
  5. Associate the attachment with the work item

HighLevel.PNG

 

Steps 1 - 3 are all straight forward with Flow, although if you need any pointers with these please shout and I'll be happy to ellaborate.

 

Let's focus on the first HTTP Request which is going to upload the attachment to DevOps, which in my overview is titled "Send an HTTP REquest to Azure DevOps - Upload Attachment."

 

This works in a similar way to the HTTP Connector for SharePoint, whereby you don't need to worry about generating tokens as the connection will handle the authentication for you. All you need to do is get your API call right.

 

Call1.PNG

Full documentation for this end point can be found here: https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-rest...

 

The most important part here is the URI for the endpoint. It will basically take the form of:

/{project}/_apis/wit/attachments?fileName={fileName}&uploadType={uploadType}&areaPath={areaPath}&api-version=5.0

fileName - the DisplayName dynamic content taken from the Get Attachments action

areaPath - the Area Path dynamic content taken from the Get Work Item actions

 

I will need to use the output of this REST call in my next one, so I need to use the Parse JSON action to transform the output into something useful. It will only return two pieces of information, so you can use this schema to parse it:

{
    "type": "object",
    "properties": {
        "id": {
            "type": "string"
        },
        "url": {
            "type": "string"
        }
    }
}

Once the file is uploaded, we need to associate it to the work item so that it shows up in attachments. Again, I'm going to use the "Send an HTTP Request to Azure DevOps" to do this. The difference this time, is rather than being a post, it is going to be a PATCH as I'm updating an already existing work item.

Call2.PNG

 

This time the relative URI is much more simple, as all I'm doing is providing the workitem ID (from my workitem action earlier). The majority of the work here takes place in the body of the call. Full documentation for this call can be found here:
https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-res...

 

The only part of the body which will need to change is the url which will come from the Parse JSON step. That is the URL where your attachment has been uploaded to within DevOps. 

 

This has worked for me by attaching a txt file onto a List Item, and watching that flow through into my workitem, and I don't see any reason why it shouldn't work for more complex file types.

 

Let us know how you get on, and if you need any more help please shout.

 

If you have found this post useful, please give it a thumbs up. If it has answered your question, please accept it as the solution so others can benefit.

@MattWeston365

 

 

 

 

 

 

Anonymous
Not applicable

Thanks for the detailed information 🙂

 

When we try to move the SharePoint list item attachments apart from text files all the other files are getting uploaded as corrupted files to the DevOps work Items.  

 

Please help.

Hi @Anonymous , I've stayed in contact with the OP as we did a couple of screen shares to get this built. He raised this same issue to me outside of the community so it's something I'm working on at the moment.

 

The issue is related to the way in which a Word document (or anything more complex than a txt file) is encoded within Flow as it is always encoded as a base64 string. The DevOps API actually wants a byte array (regardless of what the documentation suggests) and I've got this working in PowerShell.

 

So I'm working on a solution which will combine my findings in PowerShell with what is available through Flow. I'll report back once I've got the end-to-end solution working.

Anonymous
Not applicable

Thanks a lot @MattWeston365. Will wait for you reply.

May I know by when can we have this fix ready for planning a workaround.

Hi @Anonymous and @Adam12345 

 

I've now got a solution to this. Give me a day or so as this is going to be a blog style solution since I've had to revert to Azure Automation to actually get this working as I want. The good news though is that it will now take the attachments from a list item and put them into Azure, and the documents don't corrupt.

 

I had a call with Adam not so long back, and I told him I don't do failure, so I'm finally there! Back in touch shortly.

@Anonymous , @Adam12345 

 

Sorry it's taken me longer than I anticipated to get this to you. Here's a blog outlining my solution to your issue:

https://blog.mattweston365.com/2019/06/uploading-attachments-from-sharepoint.html

 

I'll be making an associated video shortly, but if you have any questions in the meantime please shout.

Anonymous
Not applicable

Thanks @MattWeston365.  I had used Azure Function to handle this.  For Uploading and tagging the attachment I'm using Azure Function which is being called in the Flow with the required parameters.

@Anonymous : Could you please send me the flow you have created after the issue got resolved. I am facing similar issue and the solution might be helpful.

 

Thanks in advance!

Hi @kthaththathreya , As mentioned I'm calling the Azure Function from the Flows to perform the following 

  1. Upload the attachment to the Azure DevOps Instance
  2. Update the upload attachment reference to DevOps Work Item

Below is the Azure Function Code. I hope this will help

namespace DevOpsSharePointIntegration
{
    public static class AddAttachmentToWorkItem
    {
        [FunctionName("AddAttachmentToWorkItem")]
        public static async Task<string> Run([HttpTrigger(AuthorizationLevel.Function, "POST", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("Reading the request body in HTTP Triggers");
            string responseBody=string.Empty, 
                responsePatchBody = string.Empty;
            // Arrange.
            try
            {
                var configuration = new HttpConfiguration();
                req.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;

                // Read body
                FileData file = await req.Content.ReadAsAsync<FileData>();
                
                byte[] bytes = Convert.FromBase64String(file.data);

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/octet-stream"));

                    client.DefaultRequestHeaders.Authorization = req.Headers.Authorization;

                    ByteArrayContent byteContent = new ByteArrayContent(bytes);

                    string urlPost = "https://dev.azure.com/" + file.organization + "/" + file.project + "/_apis/wit/attachments?fileName=" + file.fileName + "&uploadType=Simple&areaPath=" + file.areaPath + "&api-version=5.0";
                    string requestPatchUrl = "https://dev.azure.com/" + file.organization + "/" + file.project + "/_apis/wit/WorkItems/"+file.workItemID+"?api-version=5.0";

                    using (HttpResponseMessage response = await client.PostAsync(
                                urlPost, byteContent))
                    {
                        response.EnsureSuccessStatusCode();
                        responseBody = await response.Content.ReadAsStringAsync();
                        FileDataOutput fileDataInfo = JsonConvert.DeserializeObject<FileDataOutput>(responseBody);

                        string jsonInputData = "[ { \"op\": \"add\", \"path\": \"/relations/-\", \"value\": { \"rel\": \"AttachedFile\", \"url\": \""+ fileDataInfo.url + "\", \"attributes\": { \"comment\": \"Uploaded from SharePoint List\" } }, } ]";

                        HttpRequestMessage requestPatch = new HttpRequestMessage
                        {
                            Method = new HttpMethod("PATCH"),
                            RequestUri = new Uri(requestPatchUrl)
                        };
                        requestPatch.Content = new StringContent(jsonInputData,
                                    Encoding.UTF8,
                                    "application/json-patch+json");//CONTENT-TYPE header
                        client.DefaultRequestHeaders.Accept.Remove(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/octet-stream"));
                        client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                        using (HttpResponseMessage responsePatch = await client.SendAsync(requestPatch))
                        {
                            responsePatch.EnsureSuccessStatusCode();
                            responsePatchBody = await responsePatch.Content.ReadAsStringAsync();
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                responsePatchBody = ex.Message + "  : " + ex.StackTrace;
            }
            
            return responsePatchBody;
        }
        
        public class FileData
        {
            public string data { get; set; }
            public string organization { get; set; }
            public string project { get; set; }
            public string fileName { get; set; }
            public string areaPath { get; set; }
            public string workItemID { get; set; }
        }
        public class FileDataOutput
        {
            public string id { get; set; }
            public string url { get; set; }
        }
    }
}

 

Helpful resources

Announcements

Community will be READ ONLY July 16th, 5p PDT -July 22nd

Dear Community Members,   We'd like to let you know of an upcoming change to the community platform: starting July 16th, the platform will transition to a READ ONLY mode until July 22nd.   During this period, members will not be able to Kudo, Comment, or Reply to any posts.   On July 22nd, please be on the lookout for a message sent to the email address registered on your community profile. This email is crucial as it will contain your unique code and link to register for the new platform encompassing all of the communities.   What to Expect in the New Community: A more unified experience where all products, including Power Apps, Power Automate, Copilot Studio, and Power Pages, will be accessible from one community.Community Blogs that you can syndicate and link to for automatic updates. We appreciate your understanding and cooperation during this transition. Stay tuned for the exciting new features and a seamless community experience ahead!

Summer of Solutions | Week 4 Results | Winners will be posted on July 24th

We are excited to announce the Summer of Solutions Challenge!    This challenge is kicking off on Monday, June 17th and will run for (4) weeks.  The challenge is open to all Power Platform (Power Apps, Power Automate, Copilot Studio & Power Pages) community members. We invite you to participate in a quest to provide solutions to as many questions as you can. Answers can be provided in all the communities.    Entry Period: This Challenge will consist of four weekly Entry Periods as follows (each an “Entry Period”)   - 12:00 a.m. PT on June 17, 2024 – 11:59 p.m. PT on June 23, 2024 - 12:00 a.m. PT on June 24, 2024 – 11:59 p.m. PT on June 30, 2024 - 12:00 a.m. PT on July 1, 2024 – 11:59 p.m. PT on July 7, 2024 - 12:00 a.m. PT on July 8, 2024 – 11:59 p.m. PT on July 14, 2024   Entries will be eligible for the Entry Period in which they are received and will not carryover to subsequent weekly entry periods.  You must enter into each weekly Entry Period separately.   How to Enter: We invite you to participate in a quest to provide "Accepted Solutions" to as many questions as you can. Answers can be provided in all the communities. Users must provide a solution which can be an “Accepted Solution” in the Forums in all of the communities and there are no limits to the number of “Accepted Solutions” that a member can provide for entries in this challenge, but each entry must be substantially unique and different.    Winner Selection and Prizes: At the end of each week, we will list the top ten (10) Community users which will consist of: 5 Community Members & 5 Super Users and they will advance to the final drawing. We will post each week in the News & Announcements the top 10 Solution providers.  At the end of the challenge, we will add all of the top 10 weekly names and enter them into a random drawing.  Then we will randomly select ten (10) winners (5 Community Members & 5 Super Users) from among all eligible entrants received across all weekly Entry Periods to receive the prize listed below. If a winner declines, we will draw again at random for the next winner.  A user will only be able to win once overall. If they are drawn multiple times, another user will be drawn at random.  Individuals will be contacted before the announcement with the opportunity to claim or deny the prize.  Once all of the winners have been notified, we will post in the News & Announcements of each community with the list of winners.   Each winner will receive one (1) Pass to the Power Platform Conference in Las Vegas, Sep. 18-20, 2024 ($1800 value). NOTE: Prize is for conference attendance only and any other costs such as airfare, lodging, transportation, and food are the sole responsibility of the winner. Tickets are not transferable to any other party or to next year’s event.   ** PLEASE SEE THE ATTACHED RULES for this CHALLENGE**   Week 1 Results: Congratulations to the Week 1 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge.   Community MembersNumber SolutionsSuper UsersNumber Solutions Deenuji 9 @NathanAlvares24  17 @Anil_g  7 @ManishSolanki  13 @eetuRobo  5 @David_MA  10 @VishnuReddy1997  5 @SpongYe  9JhonatanOB19932 (tie) @Nived_Nambiar  8 @maltie  2 (tie)   @PA-Noob  2 (tie)   @LukeMcG  2 (tie)   @tgut03  2 (tie)       Week 2 Results: Congratulations to the Week 2 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 2: Community MembersSolutionsSuper UsersSolutionsPower Automate  @Deenuji  12@ManishSolanki 19 @Anil_g  10 @NathanAlvares24  17 @VishnuReddy1997  6 @Expiscornovus  10 @Tjan  5 @Nived_Nambiar  10 @eetuRobo  3 @SudeepGhatakNZ 8     Week 3 Results: Congratulations to the Week 3 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 3:Community MembersSolutionsSuper UsersSolutionsPower Automate Deenuji32ManishSolanki55VishnuReddy199724NathanAlvares2444Anil_g22SudeepGhatakNZ40eetuRobo18Nived_Nambiar28Tjan8David_MA22   Week 4 Results: Congratulations to the Week 4 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 4:Community MembersSolutionsSuper UsersSolutionsPower Automate Deenuji11FLMike31Sayan11ManishSolanki16VishnuReddy199710creativeopinion14Akshansh-Sharma3SudeepGhatakNZ7claudiovc2CFernandes5 misc2Nived_Nambiar5 Usernametwice232rzaneti5 eetuRobo2   Anil_g2   SharonS2  

Check Out | 2024 Release Wave 2 Plans for Microsoft Dynamics 365 and Microsoft Power Platform

On July 16, 2024, we published the 2024 release wave 2 plans for Microsoft Dynamics 365 and Microsoft Power Platform. These plans are a compilation of the new capabilities planned to be released between October 2024 to March 2025. This release introduces a wealth of new features designed to enhance customer understanding and improve overall user experience, showcasing our dedication to driving digital transformation for our customers and partners.    The upcoming wave is centered around utilizing advanced AI and Microsoft Copilot technologies to enhance user productivity and streamline operations across diverse business applications. These enhancements include intelligent automation, AI-powered insights, and immersive user experiences that are designed to break down barriers between data, insights, and individuals. Watch a summary of the release highlights.    Discover the latest features that empower organizations to operate more efficiently and adaptively. From AI-driven sales insights and customer service enhancements to predictive analytics in supply chain management and autonomous financial processes, the new capabilities enable businesses to proactively address challenges and capitalize on opportunities.    

Updates to Transitions in the Power Platform Communities

We're embarking on a journey to enhance your experience by transitioning to a new community platform. Our team has been diligently working to create a fresh community site, leveraging the very Dynamics 365 and Power Platform tools our community advocates for.  We started this journey with transitioning Copilot Studio forums and blogs in June. The move marks the beginning of a new chapter, and we're eager for you to be a part of it. The rest of the Power Platform product sites will be moving over this summer.   Stay tuned for more updates as we get closer to the launch. We can't wait to welcome you to our new community space, designed with you in mind. Let's connect, learn, and grow together.   Here's to new beginnings and endless possibilities!   If you have any questions, observations or concerns throughout this process please go to https://aka.ms/PPCommSupport.   To stay up to date on the latest details of this migration and other important Community updates subscribe to our News and Announcements forums: Copilot Studio, Power Apps, Power Automate, Power Pages