› Dynamics CRM › Download SharePoint file programmatically without sharing it – Dynamics CRM and ADX portal or custom portal

Download SharePoint file programmatically without sharing it – Dynamics CRM and ADX portal or custom portal

 Vivek Shah   Leave a comment

This blog intends to able to download a SharePoint file without sharing it using Dynamics CRM and (optionally on-prem ADX portal since we can use below approach in custom portal as well).

Many times we come across scenarios where we want to share SharePoint documents with end users on web portals without give them sharing access from SharePoint.

Prerequisite

  1. CRM online
  2. SharePoint online
  3. Web portal code access (ADX on-prem or custom portal).

Step 1: Enable SharePoint integration with CRM.

Step 2: Custom code to access SharePoint document.

Add the following code on the page where you want to show list of SharePoint documents to the end user.

  1. CS file code:
    DataTable dt = new DataTable();
    
    var password = new SecureString();
                    foreach (var c in "yourpassword".ToCharArray())
                        password.AppendChar(c);
    
    ClientContext cxt = new ClientContext("https://yourdomain.sharepoint.com/Site1");
                    cxt.Credentials = new SharePointOnlineCredentials("Username", password);
                    List list = cxt.Web.Lists.GetByTitle("Document Sharing");
    
                    cxt.Load(list);
                    cxt.Load(list.RootFolder);
                    cxt.Load(list.RootFolder.Folders);
                    cxt.Load(list.RootFolder.Files);
                    cxt.ExecuteQuery();
                    FolderCollection fcol = list.RootFolder.Folders;
                    List<string> lstFile = new List<string>();
    
                    DataRow dr;
                    foreach (Folder f in fcol)
                    {
                        if (f.Name == relativeURL) //relative url of the file.
                        {
                            
                            cxt.Load(f.Files);
                            cxt.ExecuteQuery();
                            FileCollection fileCol = f.Files;
                            foreach (File file in fileCol)
                            {
                                dr = dt.NewRow();
                                lstFile.Add(file.Name);
                                dr["fileName"] = file.Name.ToString();
                                dr["createdOn"] = file.TimeCreated.ToShortDateString();
                                dr["fileURL"] = @"javascript:downLoadFile('" + file.ServerRelativeUrl.ToString() + "')"; //Append Javascript function to the row.
                                dt.Rows.Add(dr);
                            }
                        }
                    }
    
                GridView2.DataSource = dt; //GridView2 being a grid added on your .aspx page.
                GridView2.DataBind();
    
    GridView2.DataSource = dt; //GridView2 being a grid added on your .aspx page.
    
    GridView2.DataBind();
    

    GridView2 in .aspx page:

    //Javascript function 
    <script type="text/javascript">
            function downLoadFile(link) {
                window.open("DownloadFile?url=" + link, "_blank");
            }
        </script>
    
    //GridView Code
    <asp:GridView ID="GridView2" runat="server" Visible="true"
            AutoGenerateColumns="False"
            BorderWidth="1px" BackColor="White" GridLines="Vertical"
            CellPadding="4" BorderStyle="None"
            BorderColor="#DEDFDE" ForeColor="Black">
            <FooterStyle BackColor="#CCCC99">
            <PagerStyle ForeColor="Black" HorizontalAlign="Right"
                BackColor="#F7F7DE">
            <HeaderStyle ForeColor="White" Font-Bold="True"
                BackColor="#6B696B">
            <AlternatingRowStyle BackColor="White">
                <asp:BoundField HeaderText="File Name" DataField="fileName" Visible="false" HeaderStyle-Width="10%" ItemStyle-Width="10%"
                FooterStyle-Width="10%"></asp:BoundField>
    
                <asp:TemplateField HeaderText="File Name" HeaderStyle-Width="10%" ItemStyle-Width="10%"
                FooterStyle-Width="10%">
                    <ItemTemplate>
                        <%# Eval("fileName") %> 
                    </ItemTemplate>
                </asp:TemplateField>
    
                <asp:BoundField HeaderText="Created On" DataField="createdOn" HeaderStyle-Width="5%" ItemStyle-Width="5%"
                FooterStyle-Width="5%"></asp:BoundField>
            </Columns>
            <SelectedRowStyle ForeColor="White" Font-Bold="True"
                BackColor="#CE5D5A"></SelectedRowStyle>
            <RowStyle BackColor="#F7F7DE"></RowStyle>
        </asp:GridView>
    

     

  2. Download File:
    Add a new blank .aspx page to the portal named ‘DownloadFile.aspx’. This page will act as bridge for portal to connect to SharePoint and authenticate for being able to download the file.

    This file will contain code to authenticate the SharePoint connection for the portal to be able to download the file.

    DownloadFile.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
            {
                string partialURL = "";
                partialURL = Convert.ToString(Request.QueryString["url"]);
                downloadFile(partialURL);
            }
    
            private void downloadFile(string relativeURL)
            {
                ClientContext cxt = new ClientContext("https://yourdomain.sharepoint.com/Site1");
                var password = new SecureString();
                foreach (var c in "password".ToCharArray())
                    password.AppendChar(c);
                cxt.Credentials = new SharePointOnlineCredentials("username", password);
                    int pos = relativeURL.LastIndexOf("/") + 1;
                    var fileRef = relativeURL;
                    var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(cxt, fileRef);
                    var fileName = relativeURL.Substring(pos, relativeURL.Length - pos);
                    using (var fileStream = new System.IO.MemoryStream())
                    {
                        int extpos = fileName.LastIndexOf(".") + 1;
                      fileInfo.Stream.CopyTo(fileStream);
                        StreamToFileAttachment(fileStream, fileName);
                    }
            }
            
    
            void StreamToFileAttachment(Stream str, string fileName)
            {
                byte[] byteBuffer = new byte[str.Length];  
                str.Position = 0;
                           Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                Response.AddHeader("Content-Length", str.Length.ToString());
                Response.ContentType = "application/octet-stream";
                int len = 0;
                while ((len = str.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                {
                   {
                        Response.BinaryWrite(byteBuffer);
                    }
                    Response.Flush();
                }
             }
    

Conclusion

Using above code we can download SharePoint Document without actually sharing document with the end user.


Liked it? Share it.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.