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!!
No comments:
Post a Comment