How to get the count of number of pages printed on to SSRS report


Description:-

Recently, I came across an interesting requirement on the reports in AX 2012. If the total number of pages that gets rendered to the report is more than some X pages, the report should get saved to pdf, if not send it as an email.

Tricky part is how do I get the number of pages [page count] after the report got rendered. I tried to get the number of pages before rendering the report but was unsuccessful by using the adapter class and getNumberOfPages() method.

Finally, I found a solution. On Controller classes there is a method by name “reportViewerRefreshComplete” which can be overridden. This method gets triggered once the data has been rendered on to report viewer.

Override the “reportViewerRefreshComplete” method on any controller class and add the below code. This will help to get the count of printed physical pages on to report.

public void reportViewerRefreshComplete(SRSReportExecutionInfo _executionInfo)
{
  int page;
  super(_executionInfo);

  page = this.getReportContract().parmReportExecutionInfo().parmPrintedPhysicalPages();
  info("Total number of pages:" + int2str(page));
}

Below is the infolog with the counter of pages, after the report data got rendered on to report viewer.

How to ChangeCompany Dynamically in Ax 2012


Description:-

In this Example we will see how to Change Company Dynamically in Ax while Codding in form or any other else in ax. ChangeCompany is nothing but if we want to see data from other company Data then we can directly change in Coding through in Ax. Let’s see a demo how to change when we want data from other company. Here company is nothing but a legal entity where can store our configuration and data.
Create table and add data from different company so we can check through code behind in ax table.

Step 1: Create Table Name it “CrossCompanyDataCheck”. And Insert Filed in Table.
  • Expand AOT Node.
  • Open Data Dictionary Node.
  • Select Tables and right Click Select New Table.
  • Name it “CrossCompanyDataCheck”.
  • Now open table in Insert Some Data in CrossCompanyDataCheck table.

Create Job from AOT
  • In the AOT, click Job.
  • Right-click the Job node, and then select New Job.
Code:-
static void ChangeCompany(Args _args)
{
  CompanyName nameOfCompany;
  dev_multilinejournaltrans contractCompany; // trying to check companycode field from this table
  CompanyInfo company;
  ;
  // contractCompany = axpContractTable::find(warehouseTable.ContractId);
  //if (contractCompany.CompanyCode)
  while select contractCompany
  {
    if(contractCompany.dataAreaId == 'susb')
    {
      changecompany(contractCompany.LegalEntity)
      {
        nameOfCompany = curext();
        info(strFmt("Name : %1",nameOfCompany));
      }
    }

    if (contractCompany.dataAreaId == 'ceed')
    {
      changecompany(contractCompany.LegalEntity)
      {
        nameOfCompany =curext();
        info(strFmt("Name : %1",nameOfCompany));
      }
    }

    if (contractCompany.dataAreaId == 'ceu')
    {
      changecompany(contractCompany.LegalEntity)
      {
        nameOfCompany =curext();
        info(strFmt("Name : %1",nameOfCompany));
      }
    }
    //info(strFmt("Comapny-Name : %1",nameOfCompany));
  }
}

How to Get table Field Using TableId in Ax 2012

Description:- 

There are two main ways to do it I can think of offhand. Reflection and using the SysModelELements table. The first way will give you the name & label, the second will not give you labels reliably.

The first job demonstrates this with reflection. The second shows it with the SysModelElements tables, and is faster, but won't give you the label. You can use a DictField object to enumerate the label (as shown in the second method).

The first method is the most reliable as the second could have some cases I haven't thought about such as table views or maps.

Here what I will do I will take dict table and bind my table in dict table then I will get table fieldname and fieldlabel.

Create Job and Run and Assign your TableName in Str tablename Property in Job.

static void TableFieldLookup(Args _args)
{
    strtableName = 'table name';
    DictTable       dictTable;
    DictField       dictField;
    inti;

    dictTable = new DictTable(tableName2id(tableName));
    if (dictTable)
    {
        for (i=1; i<=dictTable.fieldCnt(); i++)
        {
            dictField = new DictField(dictTable.id(), dictTable.fieldCnt2Id(i));
            info(strFmt("Field Name: '%1'; Field Label: '%2'; IsSystem: %3",dictField.name(),dictField.label(),dictField.isSystem()));
        }
    }
    else
    {
        error(strFmt("Table '%1' not found!", tableName));
    }
}

Or else you can achieve this functionality by other way.

static void TableFieldLookup(Args _args)
{
    tableName tableName = 'A_PurchaseOrder';
    SysModelElement     tables;
    SysModelElement     fields;
    DictField           dictField;

    while select tables
    where tables.ElementType == UtilElementType::Table && tables.Name == tableName
    join fields
    where fields.ElementType == UtilElementType::TableField &&
    fields.ParentModelElement == tables.RecId
    {
        dictField = new DictField(tables.AxId, fields.AxId);
        info(strFmt("Field Name: '%1'; Field Label: '%2'; IsSystem: %3",dictField.name(),dictField.label(),dictField.isSystem()));
    }
}

Output:-


How to get all address in AX 2012

Description:-
In this example we will show how to get all address from ax 2012 it could be customer, vendor, bank account, authority address. For that we have to create table so we can save address when we got from job.

Step 1: Create Table Name it “ALLAddresses”. Create Field CustAccount, Address, Name.
  • Expand AOT Node.
  • Open Data Dictionary Node.
  • Select Tables and right Click Select New Table.
  • Name it “ALLAddresses”.
  • Now open table in Insert Some Data in ALLAddresses table.

Create Job from AOT:-

In the AOT, click Job.
Right-click the Job node, and then select New Job. 

static void GettingAllAddresses(Args _args)
{
    CustTable               custTable;
    VendTable               vendTable;
    TaxAuthorityAddress     taxAuthorityAddress;
    LogisticsPostalAddress  logisticsPostalAddress;
    AllAddresses            allAddresses;
    bankAccountTable        bankAccountTable;
    ;
    while select * from custTable
    {
        allAddresses.Address = custTable.address();
        allAddresses.Name = custTable.name();
        allAddresses.CustAccount = custTable.AccountNum;
        allAddresses.doInsert();
    }
    //Getting all vendors
    while select * from vendTable
    {
        //allAddresses.Address = vendTable.address_BR();
        allAddresses.Name = vendTable.name();
        allAddresses.doInsert();
    }
    //Getting all tax authorities addresses
    while select * from taxAuthorityAddress
    {
        allAddresses.Address = TaxAuthorityAddress::address(taxAuthorityAddress.TaxAuthority);
        allAddresses.Name = taxAuthorityAddress.Name;
        allAddresses.doInsert();
    }
    //Getting all bank addresses
    while select * from bankAccountTable
    {
        logisticsPostalAddress = LogisticsLocationEntity::location2PostalAddress(bankAccountTable.Location);
        allAddresses.Address = logisticsPostalAddress.Address;
        allAddresses.Name = bankAccountTable.Name;
        allAddresses.doInsert();
    }
}

Now run your job and see table you will get all address from database.

How to create Contact Us page in Asp.net



Description:

In this article I have explained how we can create contact us page in Asp,net. Contact us page is a major part of websites through which users send comments, queries feedback etc. of website to admin/website owner.
Add a new webform to website. Drag and drop the Textbox, button, validation controls from Toolbox and desgin the .aspx page as shown below:

Default.aspx:-

<table align="center">
    <tr>
        <td>
            <h1>Contact Us</h1>
        </td>
        <td></td>
    </tr>
    <tr>
        <td>Name:</td>
        <td>
            <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtname" Display="None" 
                    ErrorMessage="Enter Name" EnableTheming="True"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>Email:</td>
        <td>
            <asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvrequireemail" runat="server" ControlToValidate="txtemail" Display="None"
                    ErrorMessage="Enter Email" EnableTheming="True"></asp:RequiredFieldValidator>
         <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtemail" 
                    ErrorMessage="Enter Valid Email" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
         </asp:RegularExpressionValidator>
         </td>
    </tr>
    <tr>
        <td>Subject:</td>
        <td>
            <asp:TextBox ID="txtsubject" runat="server"></asp:TextBox> 
            <asp:RequiredFieldValidator ID="rfvsubject" runat="server" ControlToValidate="txtsubject" Display="None"
                    ErrorMessage="Enter Subject" EnableTheming="True"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>Description:</td>
        <td>
            <asp:TextBox ID="txtdescription" runat="server" TextMode="MultiLine" textl></asp:TextBox> 
            <asp:RequiredFieldValidator ID="rfvdescription" runat="server" ControlToValidate="txtdescription" Display="None"
                    ErrorMessage="Enter Description" EnableTheming="True"></asp:RequiredFieldValidator>
        </td>
    </tr>
            <asp:ValidationSummary ID="ValidationSummary1" runat="server"  ShowMessageBox="true" ShowSummary="false"/>
    <tr>
        <td>&nbsp;</td>
        <td>
            <asp:button ID="btnsend" runat="server" Text="Send" onclick="btnsend_Click" />
        </td>
    </tr>
</table>

Namespaces:-

using System.Net.Mail;

Default.aspx.cs:-

    protected void btnsend_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage msg = new MailMessage("Sender Email Id","Recevier Email Id");
            msg.Subject = txtsubject.Text;
            msg.Body = "Name:"+txtname.Text+"<br> Email:"+txtemail.Text+"<br>" + txtsubject.Text;
            msg.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.Credentials = new System.Net.NetworkCredential("Email Id", "Password");
                smtp.EnableSsl = true;
            smtp.Send(msg);
            Clear();
            Messagebox("Mail send Successfully");
        }
        catch (Exception ex)
        {
        }
    }

    private void Clear()
    {
        txtname.Text = "";
        txtsubject.Text = "";
        txtemail.Text = "";
        txtdescription.Text = "";
    }

    //Show Message
    private void Messagebox(string Message)
    {
        Label lblMessageBox = new Label();

        lblMessageBox.Text =
            "<script language='javascript'>" + Environment.NewLine +
            "window.alert('" + Message + "')</script>";
        Page.Controls.Add(lblMessageBox);
    }

How to Get AOS Server Name of Current Session using X++ in Ax



Description:-

The following code obtains the AOS server name for the current session. Create Job and run.

Code:-

Static void getServerNameForCurrentSession(Args _args) 
{ 
    sysClientSessions cliSessions; 
    sysServerSessions svrSessions; 
    ; 
    select svrSessions
      existsjoin cliSessions
      where cliSessions.SessionId == sessionID() 
            &&cliSessions.ServerID == svrSessions.ServerId; 
    info(substr(svrSessions.AOSId, 1, strfind(svrSessions.AOSId, '@', 1, strlen(svrSessions.AOSId))-1)); 
 }

Or the current AOS server name you're logged onto:

static void CurAOSServerName(Args _args)
{
    xSession xSession;
    ;
    xSession = new xSession();
    info(strfmt('Current AOS server name-%1',xSession.AOSName()));
}

How to Open Ajax ColorPicker on Button Click event in Asp.Net

Description:-

In this Article we will Use Ajax Color Picker Control on Button Click event. Here we will Open Color Picker on Button Click event and Preview Color in Other Tag and Display Color Code in Text Control by Selecting Color from Color Picker Control.

Default.aspx:-

<div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:TextBox ID="TextBox1" runat="server" Width="170px" />
        <br /><br />
        <div id="preview" style="width: 54px; height: 35px; border: 1px solid #000; margin: 0 3px; float: left">
        </div>
        <asp:Button ID="Button1" runat="server" Text="Choose Color" Width="96px"
            Height="34px" />
        <cc1:ColorPickerExtender ID="ColorPicker1" runat="server" TargetControlID="TextBox1"
            SampleControlID="preview" PopupButtonID="Button1" PopupPosition="Right" OnClientColorSelectionChanged="Color_Changed" />
</div>

Here you can see I have assigned TargetControlId to Textbox Control and to Open Color Picker Control I have Set PopUpButtonId to Button1 Control and for Preview Color I have use Div tag to Preview Color in this Area.

for Selecting Color and Display Color code in Textbox Control I have Use Script.

Script:-

<script type="text/javascript">
        function Color_Changed(sender) {
            sender.get_element().value = "#" + sender.get_selectedColor();
        }
</script>

Now runs your Application and Click on button to Open Color Picker and Select Color.


Multi-select lookup dialog for SSRS Report Parameter in Dynamics Ax

Multi-select lookup dialog for SSRS Report Parameter in Dynamics Ax


Description:-

In your data contract class declaration method, define your parameter with 'List'. For example I want to create a multi select dialog for customers in which I need Customer account to be selected when a user selects any customer. 
SO, I will write List accountNum; In your DataMemberAttribue method type the following code.

[DataMemberAttribute('AccuontNum'),AifCollectionTypeAttribute('AccountNum', Types::String),
SysOperationLabelAttribute(literalstr("@SYS302")) ]
public List parmAccountNum(List _accountNum = accountNum)
{
    accountNum = _accountNum;
    return accountNum;
}

Now that you have completed the contract class, let’s move on to. The UI Builder class. In your main lookup method write the following code.

public void lookup(FormStringControl    _control)
{
    Query query = new Query(queryStr(CustTableSRS));
    container   cnt;
    SysLookupMultiSelectGrid::lookup(query, _control, _control, cnt);
}

you may have to create 3 more methods to run your code without any error. They are etFromDialog, initializeFields and postRun. Here is the code for these methods. you have to change the contract class name with your contract class First create a new mothod for initializeFields and paste the following code

public void initializeFields()
{
    custMultiSelectContract contract = this.dataContractObject();
}

Then create another method for getFromDialog

public void getFromDialog()
{
    custMultiSelectContract contract =  this.dataContractObject();
    super();
}

and then another method for postRun

public void postRun()
{
    custMultiSelectContract contract = this.dataContractObject();
}

How to validate email,URL and number in Dynamics ax



Description:-

In this Article we will See how to Validate Email Pattern and URL pattern in X++. Here I have Create Job to Validate Email Pattern and URL Pattern to See Enter Email and URL Pattern Using X++.

Validate E-Mail

public void validateEMail()
{
    Boolean valid;
    Boolean xppBool;
    System.Boolean netBool;
    str emailid="UmeshPatel@gmail.com";
    Str MatchEmailPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"+
        @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."+
        @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"+
        @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
    System.Text.RegularExpressions.Match myMatch;
    new InteropPermission(InteropKind::ClrInterop).assert();
    myMatch = System.Text.RegularExpressions.Regex::Match(emailid,MatchEmailPattern);
    netBool = myMatch.get_Success();
    xppBool = netBool;
    CodeAccessPermission::revertAssert();
    info(strFmt("%1",xppBool));
}

Validate URL

Static Server boolean validateURL(URL _url)
{
    Boolean valid;
    Boolean xppBool;
    System.Boolean netBool;
    Str matchURLPattern = "^(https?://)"
        + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@+ @"(([0-9]{1,3}\.){3}[0-9]{1,3}" 
        //IP- 199.194.52.184+ "|" 
        //allows either IP or domain+ @"([0-9a-z_!~*'()-]+\.)*" 
        //tertiary domain(s)- http://www.+ @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." 
        //second level domain+ "[a-z]{2,6})" 
        //first level domain- .com or .museum+ "(:[0-9]{1,4})?" 
        //port number- :80+ ((/?)|" 
        //a slash isn’t required if there is no file name+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
    System.Text.RegularExpressions.Match myMatch;
    new InteropPermission(InteropKind::ClrInterop).assert();
    myMatch = System.Text.RegularExpressions.Regex::Match(_url,matchURLPattern);
    netBool = myMatch.get_Success();
    xppBool = netBool;
    CodeAccessPermission::revertAssert();
    Return xppBool;
}

Validate Number

static void TextBuffer_regularExpression(Args _args)
{
    TextBuffer txt = new TextBuffer();
    str msg = "9999667788";
    ;
    txt.setText(msg);
    txt.regularExpressions(true);//activate regular expr in search
    //Regular expression to validate only digits
    if (txt.find("^[0-9]+$"))
    {
        info("string contains only numbers");
    }
}