Showing posts with label Blob storage. Show all posts
Showing posts with label Blob storage. Show all posts

Monday, February 27, 2023

Generate xml file and upload to blob storage using x++

 Generate XML file and upload to blob storage using x++.


using Microsoft.WindowsAzure.Storage;
Using Microsoft.WindowsAzure.Storage.Blob;

public class uploadXMLToBlobService extends SysOperationServiceBase
{
    System.Byte[]   reportBytes = new System.Byte[0]();
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

    public void processOperation()
    {	
		XmlDocument doc;
        XmlElement mainNodeXml;
        XmlElement oneChild;
        XmlElement secondChild;

       // #define.filename(@'D:\AnyNew.xml')
        doc = XmlDocument::newBlank();
        mainNodeXml = doc.createElement('HeaderXml');
        doc.appendChild(mainNodeXml);

        oneChild = doc.createElement('1child');
        oneChild.setAttribute('Name','Value');
        mainNodeXml.appendChild(oneChild);


        secondChild = doc.createElement('2child');
        secondChild.appendChild(doc.createTextNode('AccountName'));
        oneChild.appendChild(secondChild);

        //doc.save(#filename);

        reportBytes = enc.GetBytes(doc.outerXml());

        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(reportBytes);

        CloudBlobDirectory  cloudBlobDirectory;
        CloudBlobClient     cloudBlobClient;
        CloudBlobContainer  cloudBlobContainer;
        CloudStorageAccount  cloudStorageAccount;

        cloudStorageAccount  = CloudStorageAccount::Parse(invoiceParameters.StorageConnection);
        cloudBlobClient      = cloudStorageAccount.CreateCloudBlobClient();
        cloudBlobContainer   = cloudBlobClient.GetContainerReference('Container name');
        CloudBlockBlob  CloudBlockBlob = cloudBlobContainer.GetBlockBlobReference('FilePath + uniqueFilename');
        CloudBlockBlob.UploadFromStream(memoryStream, null, null, null);
    }
}


Keep Daxing!!


Friday, February 10, 2023

Upload and download file from Blob Storage using x++

 Upload and download file from Blob Storage using x++.

By using below code we connect to Blob storage. Below operations also we can do it.

  •     File List
  •     Read the file content
  •     Move the file between folder.
  •     Upload File
  •     Delete File

using Microsoft.WindowsAzure.Storage;
Using Microsoft.WindowsAzure.Storage.Blob;
using System.IO;
class TestAzureBlob 
{
    public static void main(Args _args)
    {
        TestAzureBlob       testAzureBlob = new TestAzureBlob();
        CloudBlobContainer  blobContainer;

        // Connecting container
        blobContainer = testAzureBlob.connectToAzureBlob();

        // Get's the file List
        testAzureBlob.getFilesList(blobContainer);// Way 1
        testAzureBlob.readTheFiles(blobContainer);// Way 2

        // Read the data in file
        testAzureBlob.readFileValue(blobContainer);

        // upload the file
        testAzureBlob.UploadFileToBlob(blobContainer);

        // move the file
        testAzureBlob.moveTheFileFromOneFolderToAnotherFolder(blobContainer);

        // delete the file
        testAzureBlob.deleteFileFromFolder(blobContainer);
    }
}


    Connect to Blob:

    public CloudBlobContainer connectToAzureBlob()
    {
        CloudBlobClient 	cloudBlobClient;
        CloudBlobContainer	cloudBlobContainer;
        CloudStorageAccount cloudStorageAccount;
  
        cloudStorageAccount = CloudStorageAccount::Parse("Azure Blob Connection String");
        // Example :
        // ("DefaultEndpointsProtocol = https;
        // AccountName = 'AccountName';AccountKey = 'AccountKey';EndpointSuffix=core.windows.net");
        cloudBlobClient 	= cloudStorageAccount.CreateCloudBlobClient();
        cloudBlobContainer 	= cloudBlobClient.GetContainerReference("mycontainer");
  
        Info(cloudBlobContainer.Name);

        return cloudBlobContainer;
    }

    Get the files List:

    Way 1:

     public void getFilesList(CloudBlobContainer _cloudBlobContainer)
    {
        // Directory of blob container
        CloudBlobDirectory  cloudBlobDirectory;
        container           fileCon;

        // Folder Path
        cloudBlobDirectory = _cloudBlobContainer.GetDirectoryReference("My Folder");

        System.Collections.IEnumerable lstEnumarable = cloudBlobDirectory.ListBlobs(false, 0, null, null);
        System.Collections.IEnumerator lstEnumarator = lstEnumarable.GetEnumerator();

        List filenames = new List(Types::String);

        while(lstEnumarator.MoveNext())
        {
            IListBlobItem item = lstEnumarator.Current;

            if (item is CloudBlockBlob)
            {
                CloudBlockBlob      blob = item;

                blob.FetchAttributes(null, null, null);

                fileCon = str2con(blob.name, "/");

                filenames.addStart(conPeek(filecon, conLen(filecon)));

                info(strFmt("File : %1", conPeek(filecon, conLen(filecon))));
            }
        }
    }

    Way 2:

    public void readTheFiles(CloudBlobContainer _cloudBlobContainer)
    {
        System.Collections.IEnumerable lstEnumarable = _cloudBlobContainer.ListBlobs(null, false, 0, null, null);
        System.Collections.IEnumerator lstEnumarator = lstEnumarable.GetEnumerator();

        List filenames = new List(Types::String);
        while (lstEnumarator.MoveNext())
        {
            IListBlobItem item = lstEnumarator.Current;

            if (item is CloudBlockBlob)
            {
                CloudBlockBlob blob = item;
                System.IO.StreamReader  reader = new System.IO.StreamReader(blob.OpenRead(null, null, null));
                Info(reader.ReadToEnd());
            }
        }
    }

    Read the file content:

    public void readFileValue(CloudBlobContainer _cloudBlobContainer)
    {
        CloudBlobDirectory  cloudBlobDirectory  = _cloudBlobContainer.GetDirectoryReference("My Folder");
        CloudBlockBlob      blob                = cloudBlobDirectory.GetBlockBlobReference("File");

        System.IO.Stream memory = blob.openRead(null, null, null);

        // Read the content
        System.IO.StreamReader streamReader = new System.IO.StreamReader(memory);

        // Read each line
        str  strRecord = streamReader.ReadLine();

        // while (!System.String::IsNullOrEmpty(strRecord))
        {
            try
            {
                container   conRecord = str2con_RU(strRecord, ',');

                info(conPeek(conRecord, 1));

                info(conPeek(conRecord, 2));

                strRecord = streamReader.ReadLine();
            }
            catch
            {
                throw error("Message");
            }
        
        }
    }

    Upload the file:

     public void UploadFileToBlob(CloudBlobContainer _cloudBlobContainer)
    {
        CloudBlobDirectory      cloudBlobDirectory;
        CloudBlockBlob          CloudBlockBlob;
        System.Byte[]           reportBytes = new System.Byte[0]();

        // File path
        cloudBlobDirectory  = _cloudBlobContainer.GetDirectoryReference("My Folder");
        CloudBlockBlob      = cloudBlobDirectory.GetBlockBlobReference("File.Txt");

        // ---------------- or ----------------
        CloudBlockBlob      = _cloudBlobContainer.GetBlockBlobReference("File.Txt");

        // Encode
        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
        reportBytes = enc.GetBytes("YOUR XML STRING/TEXT or Data in file");
        System.IO.MemoryStream stream = new System.IO.MemoryStream(reportBytes);
 
        // upload stream
        CloudBlockBlob.UploadFromStream(stream, null, null, null);
    }

    Move the file:

    public void moveTheFileFromOneFolderToAnotherFolder(CloudBlobContainer _cloudBlobContainer)
    {
        CloudBlobDirectory      sourceCloudBlobDirectory;
        CloudBlobDirectory      destinationCloudBlobDirectory;
        CloudBlockBlob          sourceCloudBlockBlob;
        CloudBlockBlob          destinationCloudBlockBlob;

        sourceCloudBlobDirectory        = _cloudBlobContainer.GetDirectoryReference("My Folder");
        destinationCloudBlobDirectory   = _cloudBlobContainer.GetDirectoryReference("My Folder 2");

        sourceCloudBlockBlob            = sourceCloudBlobDirectory.GetBlockBlobReference("File1.Txt");
        destinationCloudBlockBlob       = destinationCloudBlobDirectory.GetBlockBlobReference("File1.Txt");

        // Upload the file to destination
        destinationCloudBlockBlob.UploadFromStream(sourceCloudBlockBlob.OpenRead(null, null, null), null, null, null);
    }

    Delete the file:

    public void deleteFileFromFolder(CloudBlobContainer _cloudBlobContainer)
    {
        CloudBlobDirectory      sourceCloudBlobDirectory;
        CloudBlockBlob          sourceCloudBlockBlob;

        sourceCloudBlobDirectory        = _cloudBlobContainer.GetDirectoryReference("My Folder");
        sourceCloudBlockBlob            = sourceCloudBlobDirectory.GetBlockBlobReference("File2.Txt");

        // Delete file
        sourceCloudBlockBlob.delete(0, null, null, null);
    }


Keep Daxing!!

Thursday, January 12, 2023

Upload pdf to share Point or Blob storage using x++

    

 Hi Guys, Today we will see how to upload a pdf file to "Share point" and "Blob storage" based on the caller.


For this, I have created one class, extends from the Runbase batch class, and creates 2 action menu Items.



Code :

using System.IO;
using System.IO.Path;
using Microsoft.Azure;
using Blobstorage = Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
class InvoiceUpload extends RunBase
{
    Dialog                          dialog;
    DialogField                     formatDlgfield,formFolderField;
    FormatId                        formatId;
    FileUpload                      fileUploadControl;
    FileUploadTemporaryStorageResult fileUploadResult;
    Args                             callerArgs;
	
    /// <summary>
    ///
    /// </summary>
    client static void main(Args   _args)
    {
        InvoiceUpload      invoiceUpload = new InvoiceUpload();
        invoiceUpload.parmArgs(_args);
       
        if (invoiceUpload.prompt())
        {
            invoiceUpload.runOperation();
        }
    }

    protected boolean canRunInNewSession()
    {
        return false;
    }

    public Args parmArgs(Args _args = callerArgs)
    {
        callerArgs = _args;
        return callerArgs;
    }

    /// <summary>
    ///
    /// </summary>
    public void run()
    {
        System.IO.Stream            stream;
        FormatTable            		formatTable;
        Filename                    fileName;
        FileUploadTrack        		FileUploadTrack;

        formatTable = FormatTable::find(formatId);
        if (fileUploadResult != null && fileUploadResult.getUploadStatus())
        {
            stream      = fileUploadResult.openResult();
            fileName 	= fileUploadResult.getFileName();
            try
            {
                if (this.parmArgs().caller() && this.parmArgs().menuItemName() == menuItemActionStr(InvoiceUploadForBlob))
                {
                    Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount =
                            BlobStorage.CloudStorageAccount::Parse(formatTable.ConnectionString);//"ConnectionString value"
                    if(storageAccount)
                    {
                        CloudBlobClient blobClient 	 = storageAccount.CreateCloudBlobClient();
                        CloudBlobContainer blobContainer = blobClient.GetContainerReference(formatTable.ConatinerName);//"ConatinerName value"
                        blobContainer.CreateIfNotExistsAsync();
                        CloudBlockBlob blockBlob 	= blobContainer.GetBlockBlobReference(fileName);
                        if(blockBlob && !blockBlob.Exists(null,null))
                        {
                            blockBlob.UploadFromStreamAsync(stream).Wait();
                            blockBlob.fetchAttributes(null,null,null);
                            BlobProperties blobProperties = blockBlob.Properties;
                            if(blobProperties.Length == stream.Length)
                            {
                                Info("File uploaded successfully.");
                            }
                        }
                        else
                        {
                            warning("File cannot be uploaded.");
                        }
                    }
                    else
                    {
                        warning("Not able to access storage account.");
                    }
                }
                else
                {
                    FolderMaster FolderMaster = FolderMaster::Find(formFolderField.value());
                    const str defaultSPServer = 'xxxxx.sharepoint.com';// SharePoint server
                    const str spSite = 'sites/Dynamics365';// Path

                    str spFolderPath = FolderMaster.SharePointFilePath + "/" + FolderMaster.Department;
					
		    //FolderMaster.SharePointFilePath - contains path - "shared documents/'folder name'/"
		    // FolderMaster.Department - contains Final folder name;
					
                    //filename = docuValue.filename();
                    str fileContetType = System.Web.MimeMapping::GetMimeMapping(filename);

                    // Get the file stream of the document attachment.
                    //fileStream = DocumentManagement::getAttachmentStream(_docuRef);
                    // Specify a user who has an External Id.
                    str externalId = xUserInfo::getExternalId(curUserId());

                    // Instantiate SharePoint document storage provider with sharepoint address path.
                    Microsoft.Dynamics.AX.Framework.FileManagement.IDocumentStorageProvider storageProvider 
                        = new Microsoft.Dynamics.AX.Framework.FileManagement.SharePointDocumentStorageProvider(
                    defaultSPServer,
                    spSite,
                    spFolderPath,
                    externalId);

                    storageProvider.ProviderId = DocuStorageProviderType::SharePoint;

                    if (storageProvider != null)
                    {
                        // Generates a unique file name in case the file name already exists on SharePoint path.
                        str uniqueFilename = storageProvider.GenerateUniqueName(filename);
                        // Upload file to SharePoint Online path.
                        Microsoft.Dynamics.AX.Framework.FileManagement.DocumentLocation location = storageProvider.SaveFile(
                        newGuid(),
                        fileName,
                        fileContetType,
                        stream);

                        if (location != null)
                        {
			    info(strFmt("File path: %1", location.get_NavigationUri().ToString()));
                        }
                    }
                }

            }
            catch(Exception::Error)
            {
                error("Upload failed.");
            }
        }
    }

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public Object dialog()
    {
        DialogGroup             dlgUploadGroup;
        FileUploadBuild         fileUploadBuild;
        FormBuildControl        formBuildControl;
        FormBuildStringControl  control;
        dialog = super();
        Args                    args = this.parmArgs();
		
        formFolderField     = dialog.addField(extendedTypeStr(Name),'Folder Structure');
        control             = formFolderField.control();
        control.registerOverrideMethod(methodStr(FormStringControl,lookup),methodStr(InvoiceUpload, name_Lookup),this);

        formatDlgfield      = dialog.addField(extendedTypeStr(FormatId));

        if (args.caller() && args.menuItemName() == menuItemActionStr(InvoiceUploadForBlob))
        {
            formatDlgfield.value(curExt());
            control.visible(NoYes::No);
        }
        else
        {
            formatDlgfield.value('Generic');
        }
        
        dlgUploadGroup      = dialog.addGroup("Upload file");
        formBuildControl    = dialog.formBuildDesign().control(dlgUploadGroup.name());
        fileUploadBuild     = formBuildControl.addControlEx(classstr(FileUpload), 'Upload');
        fileUploadBuild.style(FileUploadStyle::MinimalWithFilename);
        fileUploadBuild.fileTypesAccepted('.pdf');
    
        return dialog;
    }

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public boolean getFromDialog()
    {
        boolean ret = true;
        FormatTable    formatTable;
    
        formatId    		= formatDlgfield.value();
        fileUploadControl     	= dialog.formRun().control(dialog.formRun().controlId('Upload'));
        fileUploadResult 	= fileUploadControl.getFileUploadResult();

        formatTable = FormatTable::find(formatId);

        if (!formatTable.ConnectionString)
        {
            ret = checkFailed("Connection string not configured.");
        }

        if (!formatTable.ConatinerName)
        {
            ret = checkFailed("Container name not specified.");
        }
        return ret;
    }

    static ClassDescription description()
    {
        return "Upload invoice";
    }

    private void name_Lookup(FormStringControl _control)
    {
        SysTableLookup sysTableLookup;
        QueryBuildDataSource qbds;

        Query query = new Query();
        qbds = Query.addDataSource(tableNum(FolderMaster));

        sysTableLookup = SysTableLookup::newParameters(tableNum(FolderMaster), _control,true);
        sysTableLookup.addLookupfield(fieldNum(FolderMaster, Name), true);
        sysTableLookup.addLookupfield(fieldNum(FolderMaster, SharePointFilePath));
        sysTableLookup.parmQuery(query);
        sysTableLookup.performFormLookup();
    }

}

Keep Daxing!!