How to Insert_RecordSet in Ax 2012

Description:-

Insert_RecordSet() is Nothing but if you want to Insert Multiple record in Dynamically in AX Table then you can insert like this. May some condition you need to insert multiple record based on condition in any method then you can use Insert_RecordSet in Method for inserting multiple records in table. Int this example we will create job and explain how to insert multiple record in table.

Create Job from AOT

  • In the AOT, click Job.
  • Right-click the Job node, and then select New Job.
static void Insert_RecordsetInsert(Args _args)
{
    A_Student _Student;
    A_Student    _StudentTemp;
    /*Set the carTableTmp variable to be a temporary table.
    This means that its contents are only store in memory not in the database.*/
    _StudentTemp.setTmp();
    // Insert 3 records into the temporary table.
    _StudentTemp.Student_ID = "CT_023";
    _StudentTemp.Student_Name = "Manshi";
    _StudentTemp.insert();
    _StudentTemp.Student_ID = "CT_024";
    _StudentTemp.Student_Name = "Kishor";
    _StudentTemp.insert();
    _StudentTemp.Student_ID = "CT_025";
    _StudentTemp.Student_Name = "Jankiben";
    _StudentTemp.insert();
    _StudentTemp.Student_ID = "CT_026";
    _StudentTemp.Student_Name = "Lalita";
    _StudentTemp.insert();

    Insert_Recordset _Student (Student_ID, Student_Name)
    select Student_ID, Student_Name from _StudentTemp;

    info(strFmt("Recoed Inserted !!"));
}

Now Here I Have Used Table A_Student let’s First See How many Data in this Table.
Now run your Job after run Info log will open for Information.
Now open you table and See Data its Inserted or What?



How to Generate ExcelSheet in Asp.Net


Description:-

Here we will Generate Excel Sheet from Gridview Data. First we will bind Data in Gridview and on button Click event we will Generate Excel Sheet from Data. Create method for bind Gridview and Code for Excel Sheet generation in dot net.

Default.aspx:-

<div>
  <asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" CellPadding="3"
  ForeColor="Black" GridLines="Vertical" BackColor="White"
  BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px">
  <AlternatingRowStyle BackColor="#CCCCCC" />
  <FooterStyle BackColor="#CCCCCC" />
  <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
  <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
  <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
  <SortedAscendingCellStyle BackColor="#F1F1F1" />
  <SortedAscendingHeaderStyle BackColor="#808080" />
  <SortedDescendingCellStyle BackColor="#CAC9C9" />
  <SortedDescendingHeaderStyle BackColor="#383838" />
  <Columns>
    <asp:BoundField DataField="EmpID" HeaderText="id" />
    <asp:BoundField DataField="FirstName" HeaderText="Name" />
    <asp:BoundField DataField="LastName" HeaderText="City" />
    <asp:BoundField DataField="Salary" HeaderText="Address" />
    <asp:BoundField DataField="Address" HeaderText="Designation" />
  </Columns>
  </asp:GridView>
  <br />
  <asp:Button ID="Button1" runat="server" Text="Create Excel File" OnClick="Button1_Click" />
</div>

Default.aspx.cs:-

private SqlConnection con;
private SqlCommand com;
private string constr, query;
private void connection()
{
  constr = ConfigurationManager.ConnectionStrings["DBCS"].ToString();
  con = new SqlConnection(constr);
  con.Open();
}

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    Bindgrid();
  }
}

private void Bindgrid()
{
  connection();
  query = "select *from Employee";//not recommended this i have written just for example, write stored procedure for security  
  com = new SqlCommand(query, con);
  SqlDataAdapter da = new SqlDataAdapter(query, con);
  DataSet ds = new DataSet();
  da.Fill(ds);
  GridView1.DataSource = ds;
  GridView1.DataBind();
  con.Close();
  ViewState["DataTable"] = ds.Tables[0];
}

public void CreateExcelFile(DataTable Excel)
{
  Response.ClearContent();
  Response.AddHeader("content-disposition", string.Format("attachment; filename=ExcellSheet.xls"));
  Response.ContentType = "application/vnd.ms-excel";
  string space = "";
  foreach (DataColumn dcolumn in Excel.Columns)
  {
    Response.Write(space + dcolumn.ColumnName);
    space = "\t";
  }
  Response.Write("\n");
  int countcolumn;
  foreach (DataRow dr in Excel.Rows)
  {
    space = "";
    for (countcolumn = 0; countcolumn < Excel.Columns.Count; countcolumn++)
    {
      Response.Write(space + dr[countcolumn].ToString());
      space = "\t";
    }
    Response.Write("\n");
  }
  Response.End();
}

protected void Button1_Click(object sender, EventArgs e)
{
  DataTable dt = (DataTable)ViewState["DataTable"];
  CreateExcelFile(dt);
}

Run your Webpage in browser and Click button to Generate ExcelSheet.


How to get Client IP Address in Asp.net

Description:-

In this Example we see how to get Client IP Address in dot net. We will use IPHostEntry Class for Getting Client IP Address when come in any site to get IP Address we will create method for getting IP Address. Using Dns Class through we will get Hostname and using this we will get Client IP Address. IPAddress is the Address of Client PC. 

The "IP" part of IP address stands for "Internet Protocol." The "address" part refers to a unique number that gets linked to all online activity you do...somewhat like a return address on a letter you'd send out.

An IP address is a fascinating product of modern computer technology designed to allow one computer (or other digital device) to communicate with another via the Internet. IP addresses allow the location of literally billions of digital devices that are connected to the Internet to be pinpointed and differentiated from other devices. In the same sense that someone needs your mailing address to send you a letter, a remote computer needs your IP address to communicate with your computer.

An IP address consists of four numbers, each of which contains one to three digits, with a single dot (.) separating each number or set of digits. Each of the four numbers can range from 0 to 255.

Your IP address is something you probably rarely think about, but it's vitally important to your online lifestyle. Without an IP address, you wouldn't be able to get today's weather, check the latest news or look at videos online. So we can Store our client IPAddress we he/she visits our Site or Application.

So let’s start and get Client IPAddress using dot net. Create Webpage and Drag button Control to get IP.

Html Code:-

<div>
   <table>
      <tr>
         <td>
            <asp:Button ID="btnClick" runat="server" Text="Get IPAddress" Height="35px" Width="105px" OnClick="btnClick_Click" />
         </td>
      </tr>
      <tr>
         <td>
            <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="X-Large" Text=""></asp:Label>
         </td>
      </tr>
   </table>
</div>

Now go to Code behind and Create Code for getting IPAddress of Client.

protected void btnClick_Click(object sender, EventArgs e)
{
    Label1.Text = GetIpAddress() + ", HostName is "+ GetCompCode();
}

public static string GetIpAddress()// Get IP Address
{
    string ip = "";
    IPHostEntry ipEntry = Dns.GetHostEntry(GetCompCode());
    IPAddress[] addr = ipEntry.AddressList;
    ip = addr[1].ToString();
    return ip;
}

public static string GetCompCode()// Get Computer Name
{
    string strHostName = "";
    strHostName = Dns.GetHostName();
    return strHostName;
}

Now run your Webpage and Click on Button you will get IPAddress or Host name. 

How to Bind DataList from XML File Dynamically in Asp.Net

Description:-

The Data list Web server control displays data in a format that you can define using templates and styles. The Data List control is useful for data in any repeating structure, such as a table. The Data List control can display rows in different layouts, such as ordering them in columns or rows.
AlternatingItemTemplate
The contents of this template are displayed for every other row rendered by the GridView
EditItemTemplate
The contents of this template are displayed when a row is selected for editing
FooterTemplate
The contents of this template are displayed in the column footer
HeaderTemplate
The contents of this template are displayed in the column header
InsertTemplate
The contents of this template are displayed when a new data item is inserted
ItemTemplate
The contents of this template are displayed for every row rendered by the GridView
We can create TemplateFields in the GridView control using <TemplateField> element. Steps to create the <TemplateField> element in the GridView control

Declare the GridView and set the AutoGenerateColumns property to 'false'.
Create a Template column using <asp: TemplateField> tag within the <Columns> element.
Create <ItemTemplate> within the <asp: TemplateField> element to display value of field as text.
Create <EditItemTemplate> to display TextBox control to modify value of field when editing the record.

Now  Create Webpage and Drag GridView Control and Add Property what you need for Column.

<div>
   <asp:DataList ID="DataList1" runat="server" BackColor="Gray" BorderColor="#B40431"
      BorderStyle="None" BorderWidth="2px" CellPadding="3" CellSpacing="2" Font-Names="Verdana" Font-Size="Small" GridLines="Both" RepeatColumns="3" RepeatDirection="Horizontal"Width="600px">
      <FooterStyle BackColor="#F7DFB5" ForeColor="#0101DF" />
      <HeaderStyle BackColor="#6E6E6E" Font-Bold="True" Font-Size="Large" ForeColor="#868A08" BorderStyle="Groove" HorizontalAlign="Center" VerticalAlign="Middle" />
      <HeaderTemplate>
         Employee Details
      </HeaderTemplate>
      <ItemStyle BackColor="#BDBDBD" ForeColor="#000000" BorderWidth="2px" />
      <ItemTemplate>
         <b>Employee ID:</b>
         <asp:Label ID="Label1" runat="server" Text='<%# Bind("empid") %>'></asp:Label>
         <br />
         <b>Employee Name:</b>
         <asp:Label ID="lblCName" runat="server" Text='<%# Bind("name") %>'></asp:Label>
         <br />
         <b>Designation:</b>
         <asp:Label ID="lblName" runat="server" Text='<%# Bind("designation") %>'></asp:Label>
         <br />
         <b>City:</b>
         <asp:Label ID="lblCity" runat="server" Text=' <%# Bind("city") %>'></asp:Label>
         <br />
         <b>Country:</b>
         <asp:Label ID="lblCountry" runat="server" Text='<%# Bind("country") %>'></asp:Label>
         <br />
      </ItemTemplate>
   </asp:DataList>
</div>

Now create your XML File Like below what I have done.

<?xml version="1.0" encoding="utf-8"?>
<EmployeeDetails>
   <Employee>
      <empid>1001</empid>
      <name>Umesh</name>
      <designation>Software Engineer</designation>
      <city>Ahmedabad</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1002</empid>
      <name>Suresh</name>
      <designation>Web Developer</designation>
      <city>New Delhi</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1003</empid>
      <name>Steve</name>
      <designation>Web Developer</designation>
      <city>Bangalore</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1004</empid>
      <name>Karthik</name>
      <designation>Business Analyst</designation>
      <city>New Delhi</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1005</empid>
      <name>Chirag</name>
      <designation>Software developer</designation>
      <city>Ahmedabad</city>
      <country>India</country>
   </Employee>
   <Employee>
      <empid>1006</empid>
      <name>Jenish</name>
      <designation>Designer</designation>
      <city>Ahmedabad</city>
      <country>India</country>
   </Employee>
</EmployeeDetails>
Now go to Code behind and Create Method for Retrieve data from SQL table and Call in Page_Load () method so we can Load when Page load First time in browser.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}

protected void BindData()
{
    DataSet ds = new DataSet();
    try
    {
        ds.ReadXml(Server.MapPath("EmployeeDetails.xml"));
        if (ds != null && ds.HasChanges())
        {
            DataList1.DataSource = ds;
            DataList1.DataBind();
        }
        else
        {
            DataList1.DataBind();
        }
    }
    catch (Exception ex)
    {
    }
}

Now browse you Webpage in browser so we can check XML file called in GridView or Not.

Comparison of the SysOperation and RunBase frameworks in Ax 2012

Description:- SysOperation is a framework in Microsoft Dynamics® AX 2012 that allows application logic to be written in a way that supports running operations interactively or via the Microsoft Dynamics AX batch server. The framework provides capabilities that are very similar to the RunBase framework that came before it. The batch framework has very specific requirements for defining operations:

1.       The operation must support parameter serialization so that its parameters can be saved to the batch table.
2.       The operation must have a way to display a user interface that can be launched from the batch job configuration user interface.
3.       The operation must implement the interfaces needed for integration with the batch server runtime.

The RunBase framework defines coding patterns that implement these requirements. The SysOperation framework provides base implementations for many of the patterns defined by the RunBase framework.

SysOperation and RunBase are frameworks geared toward building operations that can run via the batch server or interactively. In order for an operation to run via the batch server, it must meet these requirements:

1.       It must support parameter serialization via the SysPackable interface.
2.       It must support the standard run () method defined in the BatchRunable interface.
3.       It must support the batch server integration methods found in the Batchable interface.
4.       It must provide a mechanism to show input parameters with a user interface.

Currently in Microsoft Dynamics AX, all operations that must run via the batch server must derive from either the SysOperationController or the RunBaseBatch base class.
The following two samples illustrate the basic capabilities provided by the two frameworks:

1.       SysOpSampleBasicRunbaseBatch
2.       SysOpSampleBasicController

The simplest operation based on the RunBaseBatch base class has to implement 12 overrides. The purpose of this sample is simply to compare the RunBase and SysOperation frameworks. For full details of the RunBase framework, see the following article on MSDN: RunBaseBatch FrameWork

Create Class in Ax Classes node and Name itSysOpSampleBasicRunbaseBatch”. 
ClassDeclaration
  1. Derives from RunBaseBatch.
  2. Declares variables for operation input parameters.
  3. Declares variables for dialog box controls.
  4. Declares a macro defining a list of variables that need to be serialized.
class SysOpSampleBasicRunbaseBatch extends RunBaseBatch
{
    str text;
    int number;
    DialogRunbase       dialog;

    DialogField numberField;
    DialogField textField;

    #define.CurrentVersion(1)

    #LOCALMACRO.CurrentList
        text,
        number
    #ENDMACRO
}

Dialog

Populates the dialog box created by the base class with controls needed to get user input. The initial values from the class member variables are used to initialize the controls. The type of each control is determined by the EDT identifier name.

protected Object dialog()

{

dialog = super();

textField = dialog.addFieldValue(IdentifierStr(Description255),

text,

'Text Property',

'Type some text here');

numberField = dialog.addFieldValue(IdentifierStr(Counter),

number,

'Number Property',

'Type some number here');

return dialog;

}

getFromDialog

Transfers the contents of dialog box controls to operation input parameters.

public boolean getFromDialog()

{

text = textField.value();

number = numberField.value();

return super();


putToDialog

Transfers the contents of operation input parameters to dialog box controls.

protected void putToDialog()

{

super();

textField.value(text);

numberField.value(number);


pack

Serializes operation input parameters.

public container pack()

{

return [#CurrentVersion, #CurrentList];


unpack

Deserializes operation input parameters.

public boolean unpack(container packedClass)

{

Integer version = conPeek(packedClass,1);

switch (version)

{

case #CurrentVersion:

[version,#CurrentList] = packedClass;

break;

default:

return false;

}

return true;


run

Runs the operation. This sample prints the input parameters via the Infolog. It also prints the tier that the operation is running on and the runtime that is used for execution.

public void run()
{
    if (xSession::isCLRSession())
    {
        info('Running in a CLR session.');
    }
    else
    {
        info('Running in an interpreter session.');
        if (isRunningOnServer())
        {
            info('Running on the AOS.');
        }
        else
        {
            info('Running on the Client.');
        }
    }
    info(strFmt('SysOpSampleBasicRunbaseBatch: %1, %2', this.parmNumber(), this.parmText()));
}

description

A static description for the operation. This description is used as the default value for the caption shown in batch and the operation user interface.

public static ClassDescription description()
{
    return 'Basic RunBaseBatch Sample';
}

main

The main interaction code for the operation. This code prompts the user for input, and then runs the operation or adds it to the batch queue.

public static void main(Args args)
{
    SysOpSampleBasicRunbaseBatch operation;

    operation = new SysOpSampleBasicRunbaseBatch();
    if (operation.prompt())
    {
        operation.run();
    }
}

parmNumber

Optional. It is a Microsoft Dynamics AX best practice to expose operation parameters with the property pattern for better testability and for access to class member variables outside the class.

public int parmNumber(int _number = number)
{
    number = _number;

    return number;
}

parmText

Optional. It is a best practice to expose operation parameters with the property pattern.

public str parmText(str _text = text)
{
    text = _text;

    return text;
}
After it is implemented, the operation can be run by using the Go button on the code editor toolbar.
 If an X++ class implements the main operation, it is automatically called by the code editor. The sample’s main operation will prompt the user for input for the operation when operation.prompt () is called. If the prompt returns true, main calls operation.run () directly. If the prompt returns false, the user either cancelled the operation or scheduled it via batch.
To run the operation interactively, enter data on the General tab of the operation user interface.


Make sure that the Batch processing check box is cleared on the Batch tab.


Clicking OK will run the operation and print the following output to the Infolog window.

The Infolog messages show that the operation ran on the server, because the sample class is marked to run on the server. The operation ran via the X++ interpreter, which is the default for X++ code. 

If you repeat the previous steps but select the Batch processing check box on the Batch tab, the operation will to run via the batch server. When the Batch processing check box is selected, the following Infolog message is shown, indicating that the operation has been added to the batch queue.

The operation may take up to a minute to get scheduled. After waiting for about a minute, open the Batch job form from the Application Object Tree (AOT).
 Repeatedly update the form by pressing the F5 key, until the job entry shows that the job has ended. Sorting by the Scheduled start date/time column may help you find the operation if there are many job entries in the grid. After you find the correct job, select it, and then click Log on the toolbar.

Clicking Log opens an Infolog window indicating that the operation ran in a CLR session, which is the batch server execution environment.



In summary, this sample shows the minimum overrides needed to create an operation that can run either interactively or via the batch server by using the RunBaseBatch base class. 

SysOpSampleBasicController 
The purpose of the SysOperation framework is to provide the same capabilities as the RunBase framework but with base implementations for common overrides. The SysOperation framework handles basic user interface creation, parameter serialization, and routing to the CLR execution environment. The following table of overrides shows the code needed to match the functionality demonstrated for the RunBase-based sample in the previous section.

The SysOperation sample contains two classes: a controller class named SysOpSampleBasicController and a data contract class named SysOpSampleBasicDataContract.



SysOpSampleBasicController should derive from SysOperationServiceController, which provides all the base functionality for building operations; however, there are a few issues with that class as it is shipped with Microsoft Dynamics AX 2012, and these will be addressed in a future service pack. In the meantime, to work around the issues, a new common class, SysOperationSampleBaseController, is provided. Details of the issues worked around will be discussed at the end of this paper. 
Create Class in Classes node and Name it SysOperationSampleBaseController.
classDeclaration

Derives from the framework base class SysOpSampleBaseController.
Normally the operation should derive from the SysOperationServiceController class. The sample base class provides a few fixes for issues in that class.

class SysOpSampleBasicController extends SysOpSampleBaseController
{
}

new

Identifies the class and method for the operation. In the sample, this points to a method on the controller class; however, in general, it can be any class method.
The framework will reflect on this class/method to automatically provide the user interface and parameter serialization.

void new()
{
    super();

    this.parmClassName(classStr(SysOpSampleBasicController));
    this.parmMethodName(methodStr(SysOpSampleBasicController, showTextInInfolog));
    this.parmDialogCaption('Basic SysOperation Sample');
}

showTextInInfolog

Prints the input parameters via the Infolog. Also prints the tier that the operation is running on and the runtime that is used for execution.

public void showTextInInfolog(SysOpSampleBasicDataContract data)
{
    if (xSession::isCLRSession())
    {
        info('Running in a CLR session.');
    }
    else
    {
        info('Running in an interpreter session.');
        if (isRunningOnServer())
        {
            info('Running on the AOS.');
        }
        else
        {
            info('Running on the Client.');
        }
    }
    info(strFmt('SysOpSampleBasicController: %1, %2', data.parmNumber(), data.parmText()));
}

caption

A description for the operation. This description is used as the default value for the caption shown in batch and the operation user interface.

public ClassDescription caption()
{
return 'Basic SysOperation Sample';
}

main

The main interaction code for the operation. This code prompts the user for input, and then runs the operation or adds it to the batch queue.

public static void main(Args args)
{
    SysOpSampleBasicController operation;

    operation = new SysOpSampleBasicController();
    operation.startOperation();
}

Now Create a Class from Classes node and name it “SysOpSampleBasicDataContract”.

classDeclaration

The data contract attribute is used by the base framework to reflect on the operation.

[DataContractAttribute]
class SysOpSampleBasicDataContract
{
    str text;
    int number;
}

parmNumber

The data member attribute identifies this property method as part of the data contract. The label, help text, and display order attributes provide hints for user interface creation.

[DataMemberAttribute,
SysOperationLabelAttribute('Number Property'),
SysOperationHelpTextAttribute('Type some number >= 0'),
SysOperationDisplayOrderAttribute('2')]
public int parmNumber(int _number = number)
{
    number = _number;

    return number;
}

parmText

The data member attribute identifies this property method as part of the data contract. The label, help text, and display order attributes provide hints for user interface creation.

[DataMemberAttribute,
SysOperationLabelAttribute('Text Property'),
SysOperationHelpTextAttribute('Type some text'),
SysOperationDisplayOrderAttribute('1')]
public Description255 parmText(str _text = text)
{
    text = _text;

    return text;
}

As in the RunBase sample, the operation can be run by using the Go button on the code editor toolbar.
The main class calls operation.startOperation(), which handles running the operation synchronously or adding it to the batch queue. Although operation.run() can also be called, this should be done only if the data contract has been programmatically filled out. The startOperation method invokes the user interface for the operation, and then calls run.
To run the operation interactively, enter data on the General tab of the operation user interface. The user interface created by the framework is very similar to the one created in the RunBase sample.
Make sure that the Batch processing check box is cleared on the Batch tab.
Clicking OK will run the operation and print the following output to the Infolog window.
The Infolog messages show that, unlike in the RunBase sample, the operation ran in a CLR session on the server. If you repeat the previous steps but select the Batch processing check box on the Batch tab, the operation will run via batch, just as in the RunBase sample.
The operation may take up to a minute to get scheduled. After waiting for about a minute, open the Batch job form from the AOT, as in the RunBase sample.
Repeatedly update the form by pressing the F5 key, until the job entry shows that the job has ended. Sorting by the Scheduled start date/time column may help you find the operation if there are many jobs entries in the grid. After you find the correct job, select it, and then click Log on the toolbar.
Clicking Log opens an Infolog window indicating that the operation ran in a CLR session, which is the batch server execution environment.
This sample showed that the SysOperation framework can provide the same basic functionality as the RunBase framework. In addition, it provides implementation for common RunBase overrides, such as parameter serialization and user interface creation. It also provides the capability to route synchronous operations to a CLR session.