How to create an Excel file and it by Email, using code x++ in Dynamics AX2012? - email

I need to create an Excel file and to send it by Email, by X++ code in to Dyncamics AX2012.
If it's possible I don't want to save the data in a physical path/folder.
I wrote this code, but after I need to send the Excel.
I would like to follow the D365 instructions (https://axexplorer.wordpress.com/2017/07/18/create-an-excel-file-and-send-it-through-e-mail-in-d365-for-operationax-7/ )in Dynamics AX 2012 (In AX2012 some command are not available)
SysEmailParameters parameters = SysEmailParameters::find();
SMTPRelayServerName relayServer;
SMTPPortNumber portNumber;
SMTPUserName userName;
SMTPPassword password;
Str1260 subject,body;
InteropPermission interopPermission;
SysMailerMessageBuilder mailer;
SysMailerAttachments attach;
System.Exception e;
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
SysExcelCell cell;
int row;
str contact;
int recordscount;
MYTABLE myTable;
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
row = 1 ;
mailer.subject("MY subject");
mailer.fromAddress("MY_from#com");
mailer.htmlBody("MY_BODY");
mailer.tos().appendAddress("MY_to.com");
application = SysExcelApplication::construct();
workbooks = application.workbooks();
workbook = workbooks.add();
worksheets = workbook.worksheets();
worksheet = worksheets.itemFromNum(1);
cells = worksheet.cells();
//cells.range(‘A:A’).numberFormat(‘#’);
cell = cells.item(1,1);
cell.value("Field_I");
cell = cells.item(1,2);
cell.value("Field_II");
while select myTable
{
row++;
cell = cells.item(row, 1);
cell.value(myTable.Field_I);
cell = cells.item(row, 2);
cell.value(myTable.Field_I);
}
application.visible(true);
application.save();
memoryStream.Seek(0, System.IO.SeekOrigin::Begin);
I'm not able to save the file in temporary stream.
In AX2012 are not available the
SysMailerMessageBuilder mailer = new SysMailerMessageBuilder();;
var package = new OfficeOpenXml.ExcelPackage(memoryStream)
//The below line used to attach excel file to email.
mailer.addAttachment(memoryStream, ‘MYFILE.xlsx’, ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’);
There is any way in Dynamics AX2012 to create an excel file and send the file to email (withouth saving in to the path).
Thanks in advance.

Following the #Alex Kwitny kind comment, I used this code:
#Properties
#AOT
#File
#define.io_rw("rw")
Filename filename;
str tempPath;
FileIOPermission fileIOPermission;
if(_runOnService)
{
fileIOPermission = new FileIOPermission('','r');
fileIOPermission.assert();
tempPath = WinAPIServer::getTempPath();
CodeAccessPermission::revertAssert();
filename = tempPath + _name + #xml;
}
else
{
tempPath = WinAPI::getTempPath();
filename = tempPath + _name + #xml;
}
tempPath = WinAPI::getTempPath();
tempPath = WinAPIServer::getTempPath();
Thanks all.

Related

How to Convert Table into a Normal Range of cells while exporting excel in c#

How to Convert Table into a Normal Range of cells while exporting excel in c#.
By default it is in Table format, not able to sort due to tabel format. I need this to normal range of cells.
After excel exported, you able to do in manually by selecting Table tools (design) and have option to select "convert to range". I need to done via code by using closedXML.
System.Data.DataTable dataTable = magicButtonApi.ExportData(magicButtonCheckedNodesBE);
var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx";
//save the file to server temp folder
string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);
using (MemoryStream stream = new MemoryStream())
{
// Start a new workbook
XLWorkbook wb = new XLWorkbook();
// Add a DataTable as a worksheet
var ws = wb.Worksheets.Add(dataTable, "MagicButton");
//wb.SaveAs(stream, false);
wb.SaveAs(fullPath);
return Json(new { fileName = fullPath, errorMessage = "" });
// Return a byte array
//return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "YourReportName.xlsx");
}
wb.Worksheets.Tables.Remove(dataTable.Name);

Take all text files in a folder and combine then into 1

I'm trying to merge all my text files into one file.
The problem I am having is that the file names are based on data previously captured in my app. I don't know how to define my path to where the text files are, maybe. I keep getting a error, but the path to the files are correct.
What am I missing?
string filesread = System.AppDomain.CurrentDomain.BaseDirectory + #"\data\Customers\" + CustComboB.SelectedItem + #"\";
Directory.GetFiles(filesread);
using (var output = File.Create("allfiles.txt"))
{
foreach (var file in new[] { filesread })
{
using (var input = File.OpenRead(file))
{
input.CopyTo(output);
}
}
}
System.Diagnostics.Process.Start("allfiles.txt");
my error:
System.IO.DirectoryNotFoundException
HResult=0x80070003
Message=Could not find a part of the path 'C:\Users\simeo\source\repos\UpMarker\UpMarker\bin\Debug\data\Customers\13Dec2018\'.
I cant post a pic, but let me try and give some more details on my form.
I select a combobox item, this item is a directory. then I have a listbox that displays the files in my directory. I then have a button that executes my desires of combining the files. thanks
I finally got it working.
string path = #"data\Customers\" + CustComboB.SelectedItem;
string topath = #"data\Customers\";
string files = "*.txt";
string[] txtFiles;
txtFiles = Directory.GetFiles(path, files);
using (StreamWriter writer = new StreamWriter(topath + #"\allfiles.txt"))
{
for (int i = 0; i < txtFiles.Length; i++)
{
using (StreamReader reader = File.OpenText(txtFiles[i]))
{
writer.Write(reader.ReadToEnd());
}
}
System.Diagnostics.Process.Start(topath + #"\allfiles.txt");
}

Programmatically create Infopath form in SharePoint form library with dates

I am programmatically creating InfoPath forms in a form library within SharePoint 2010 from data in a CSV file. It all works fine apart from the date fields. The form will refuse to open with a format error. I have tried multiple ways of formatting the date but no luck so far. Code below...
If I format 2016-10-10 then it does show in the Forms Library view but I still can not open the form. It just shows a datatype error.
// Get the data from CSV file.
string[,] values = LoadCsv("ImportTest.csv");
//Calulate how many columns and rows in the dataset
int countCols = values.GetUpperBound(1) + 1;
int countRows = values.GetUpperBound(0) + 1;
string rFormSite = "siteurl";
// opens the site
SPWeb webSite = new SPSite(rFormSite).OpenWeb();
// gets the blank file to copy
SPFile BLANK = webSite.Folders["EventSubmissions"].Files["Blank.xml"];
// reads the blank file into an xml document
MemoryStream inStream = new MemoryStream(BLANK.OpenBinary());
XmlTextReader reader = new XmlTextReader(inStream);
XmlDocument xdBlank = new XmlDocument();
xdBlank.Load(reader);
reader.Close();
inStream.Close();
//Get latest ID from the list
int itemID = GetNextID(webSite, "EventSubmissions");
if (itemID == -1) return;
//Iterate each row of the dataset
for (int row = 1; row < countRows; row++)
{
//display current event name
Console.WriteLine("Event name - " + values[row, 4]);
XmlDocument xd = xdBlank;
XmlElement root = xd.DocumentElement;
//Cycling through all columns of the document//
for (int col = 0; col < countCols; col++)
{
string field = values[0, col];
string value = values[row, col];
switch (field)
{
case "startDate":
value = //How do format the date here ;
break;
case "endDate":
value = "";
break;
case "AutoFormID":
value = itemID.ToString();
break;
}
XmlNodeList nodes = xd.GetElementsByTagName("my:" + field);
foreach (XmlNode node in nodes)
{
node.InnerText = value;
}
}
// saves the XML Document back as a file
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
SPFile newFile = webSite.Folders["EventSubmissions"].Files.Add(itemID.ToString() + ".xml", (encoding.GetBytes(xd.OuterXml)), true);
itemID++;
}
Console.WriteLine("Complete");
Console.ReadLine();
Thanks
For me this worked
DateTime.Now.ToString("yyyy-MM-dd")

How can I convert U2 Business Logic Subroutine’s multi-value data into .NET Objects such as DataSet/DataTable using U2 Toolkit for .NET?

I have the following subroutine. It takes INPUT as argument 1 and sends multi-value data OUTPUT as argument 2.
SUBROUTINE MV_TO_DATASET_SELECT_SUBROUTINE(ARG_INPUT,ARG_OUTPUT)
x = ARG_INPUT
ARG_OUTPUT = "100":#VM:"101":#VM:"102":#VM:"103":#FM:"Nancy":#VM:"Andrew":#VM:"Janet":#VM:"Margaret":#FM:"01/06/1991":#VM:"06/07/1996":#VM:"11/08/1999":#VM:"12/10/2001"
RETURN
The Schema of above subroutine’s multi-value data is as below.
DataSet ds = new DataSet();
DataTable dt = new DataTable("Employee");
ds.Tables.Add(dt);
dt.Columns.Add("ID",typeof(Int32));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("HireDate", typeof(DateTime));
You can achevieve this task one of the following ways:
Use MV_To_DataTable() and DataTable_To_MV(). You can create schema of
subroutine by dragging and dropping Empty DataTable into Empty
DataSet Deginer.
By draagging and dropping Visual Studio Server Explorer’s U2
Subroutine into DataSet Designer. U2 Subrotine returns
resultset/dataset by executing API such as ST=SQLExecDirect(#HSTMT,
"SELECT F1 AS COL1,F2 AS COL2 ,F3 AS COL3 FROM #TMP SLIST 9 ORDER BY
1")
Use MV_To_DataTable() and DataTable_To_MV()
Create ASP.NET Web Application Project. Type ‘WebApplication_Subroutine’ in Project Name.
Add Reference to U2NETDK Assembly (U2.Data.Client)
Change header ‘Welcome to ASP.NET!’ to ‘Welcome to U2 Toolkit for .NET Demo on Business Logic Subroutine’s multi-value string data to .NET DataSet!’
Open ‘Default.aspx’ file and Go to Design Mode.
Do the following:
Drag and Drop Button Control. Name it ‘Load’
Drag and Drop Button Control. Name it ‘Update’
Drag and Drop GridView Control.
Right Click on Solution Explorer. Select Add ->New Item-DataSet. In the Name box, type ‘Employee.xsd’
Drag and Drop DataTable into Designer. Change the name to ‘Employee’ Table.
Create 3 new Columns (U2 subroutine Schema):
ID – DataType : INT
Name – DataType : STRING
HireDate - DataType : DATE
Open ‘Default.aspx’ file in Design Mode. Double Click ‘Load Button’. It will create Event handler Code behind.
Cut and paste the following code.
protected void Button1_Click(object sender, EventArgs e)
{
U2ConnectionStringBuilder l = new U2ConnectionStringBuilder();
l.Server = "127.0.0.1";
l.UserID = "user";
l.Password = "pass";
l.Database = "HS.SALES";
l.ServerType = "universe";
string lconnstr = l.ToString();
U2Connection c = new U2Connection();
c.ConnectionString = lconnstr;
c.Open();
U2Command command = c.CreateCommand();
command.CommandText = "CALL MV_TO_DATASET_SELECT_SUBROUTINE(?,?)";
command.CommandType = CommandType.StoredProcedure;
U2Parameter p1 = new U2Parameter();
p1.Direction = ParameterDirection.InputOutput;
p1.Value = "";
p1.ParameterName = "#arg_input";
command.Parameters.Add(p1);
U2Parameter p2 = new U2Parameter();
p2.Direction = ParameterDirection.InputOutput;
p2.Value = "";
p2.ParameterName = "#arg_output";
command.Parameters.Add(p2);
command.ExecuteNonQuery();
Employee.EmployeeDataTable dt = new Employee.EmployeeDataTable();
command.Parameters[1].MV_To_DataTable(dt);
Session["GridDataset"] = dt;
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
Run the application. Press ‘Load’ Button.
Open ‘Default.aspx’ file in Design Mode. Double click ‘Update Button’. It will create Event Handler in Code behind page.
Cut and Paste the following Code.
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)Session["GridDataset"];
//To TEST, change first row
string s1 = (string)dt.Rows[0]["Name"];
dt.Rows[0]["Name"] = s1 + "NewValue";
// get the modified rows
DataTable dt_changed = dt.GetChanges();
//call DATASET_TO_MV_UPDATE_SUBROUTINE
U2ConnectionStringBuilder l = new U2ConnectionStringBuilder();
l.Server = "127.0.0.1";
l.UserID = "user";
l.Password = "pass";
l.Database = "HS.SALES";
l.ServerType = "universe";
string lconnstr = l.ToString();
U2Connection c = new U2Connection();
c.ConnectionString = lconnstr;
c.Open();
U2Command command = c.CreateCommand();
command.CommandText = "CALL DATASET_TO_MV_UPDATE_SUBROUTINE(?)";
command.CommandType = CommandType.StoredProcedure;
U2Parameter p1 = new U2Parameter();
p1.Value = "";
p1.Direction = ParameterDirection.InputOutput;
p1.ParameterName = "#arg_data";
command.Parameters.Add(p1);
command.Parameters[0].DataTable_To_MV(dt_changed);
// modified data going to subroutine
string lData = (string)command.Parameters[0].Value;
command.ExecuteNonQuery();
}
See the Modified Value in the Debugger when you click Update Button.
U2 Subrotine returns resultset/dataset
Create U2 Data Connection in Visual Studio Server Explorer. Expand Store Procedures Node.
Go to subroutine that returns resultset/dataset. Drag and Drop subroutine into DataSet Designer.
It shows INPUT argument and resultset/dataset columns.

CSV File create in Google Apps

I have tried to Upload .csv file via API using Google Apps (Script).
I give the below property in part of API URL.
"ZOHO_FILE":file.csv
Is there any way to create .csv file in Google Apps Script ?
If possible, pls let us know, how can create .csv file in Google Apps ?
Sorry for my english :-(
You can use this to convert a data range:
function convertRangeToCsvFile(dataRange) {
try {
var data = dataRange.getValues();
var csvFile = undefined;
// Loop through the data in the range and build a string with the CSV data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// Join each row's columns
// Add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
or this to download a whole sheet
function downloadSpreadsheet(){
//This function generates a pdf of your current spreadsheet and emails it to yourself as attachment
//Make sure your spreadsheet is not too big. The pdf size tends to be 200kb/page and if too large
//if the pdf is too large the urlFetch might timeout
var AUTH_TOKEN = "xxxxxxxxxxxxxx"; //Enter your AUTH_TOKEN
//You can receive it from https://appscripts.appspot.com/getAuthToken
var ssID=SpreadsheetApp.getActiveSpreadsheet().getId()+"&gid="+SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
+ ssID + "&exportFormat=csv";
//Add &gid=x at the end of above url if you only want a particular sheet
//gid of a sheet can be obtained by the undocumented function getSheetId()
//ex: SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
//exportFormat=xls did not work when I tried. I dont know why
var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
var res = UrlFetchApp.fetch(url, {headers: {Authorization: auth}});
var content=res.getContentText();
return content
}
You asked for Apps Script, I hope;
Section 2 and 3 of the article below tells how to import and export CSV
https://developers.google.com/apps-script/articles/docslist_tutorial#section2