Monday, May 8, 2023

How to create a new folder on Sharepoint

There are some useful code behind OfficeSharePointFolderSelectionDiaolog form; however, there is a limitation.


Well, we can create a new folder via REST API call as follows. Take note that the access token is created in testSharePointConnection

using Microsoft.Dynamics.Platform.Integration.SharePoint;
using System.Net;
using System.Net.Http;

[Form]
public class wzhSPFolderForm extends FormRun
{
    str                 apiUrl;
    System.Exception    ex;
    ISharePointProxy    proxy;


    public void init()
    {
        super();
        fNewFolder.text('_wzhNewFolder');
        fServer.text('https://wzhServer.sharepoint.com');
        fRootFolder.text('Shared Documents');
    }

    public boolean testSharePointConnection()
    {
        str src = fServer.text();
        boolean validConnection = false;

        if(src)
        {
            System.UriBuilder   builder     = new System.UriBuilder(src);
            str                 hostName    = builder.Host;
            str                 siteName    = fRootFolder.text();
            str                 externalId  = xUserInfo::getExternalId();
            
            proxy   = SharePointHelper::CreateProxy(hostName, '/', externalId);
            if(proxy)
            {
                if(SharePointHelper::VerifyAuthentication(proxy))
                {
                    validConnection = true;
                    info(strfmt('@ApplicationFoundation:SPServerCommunicationSuccess', hostName));
                }
                else
                {
                    info(strfmt('@ApplicationFoundation:SPServerUserNotAuthorized', hostName));
                }
            }
            else
            {
                info(strfmt('@ApplicationFoundation:SPSelectionDlg_ErrorNoProxy', hostName));
            }
        }

        return validConnection;
    }

    public str GetAuthorizationToken()
    {
        return proxy.AccessToken;
    }

    public void createSPFolder()
    {
        apiUrl = strFmt("%1/_api/web/lists/getbytitle('%2')/rootfolder/folders/add('%3')", fServer.text(), fRootFolder.text(), fNewFolder.text());
        try
        {
            if(this.testSharePointConnection())
            {
                str token = this.GetAuthorizationToken();
            
                System.Net.WebHeaderCollection  httpHeader  = new System.Net.WebHeaderCollection();
                httpHeader.Add("Authorization", 'Bearer ' + token);

                HttpWebRequest                  request     = System.Net.WebRequest::Create(apiUrl);
                request.set_Headers(httpHeader);
                request.set_ContentLength(0);
                request.set_Method("POST");
                request.set_ContentType("application/json;odata=verbose");

                System.Net.HttpWebResponse  response        = request.GetResponse();
                int                         statusCode      = response.get_StatusCode();

                info(strFmt("HTTP status code: %1", statusCode));
            }
        }
        catch
        {
            //exception
            ex = CLRInterop::getLastException().GetBaseException();
            error(ex.get_Message());
        }
    }

    [Control("Button")]
    class bCreateREST
    {
        /// <summary>
        ///
        /// </summary>
        public void clicked()
        {
            element.createSPFolder();
            super();
        }

    }

    [Control("Button")]
    class bTestConnection
    {
        /// <summary>
        ///
        /// </summary>
        public void clicked()
        {
            element.testSharePointConnection();
            super();
        }

    }

}

No comments: