Search in ListPanel in ax 2012

Description:- 

In previous article we created form with list panels allowing us to specify which of suppliers need to be marked as temporary vendors.

The number of suppliers most of times is very big so this time we will add search functionality.
To start we need new group in our form with two new filter groups:

To each group, “FilterTempVendors” and “FilterSuppliers”, we will add “StringEdit” and “Button” control:



Method updateListPanel() was created previously and contains the fill() method from list panel.

Now our form contains search fields for each of the panels but for the filter functionality to work we need to add more code into each of methods responsible for filling the data, so suppliers() and temporaryVendors():


Now our search functionality is in place. Final view of form new objects:

How to Create Scrollable Gridview in Asp.Net Using JavaScript


Description:-

In this example we will see how to create scrollable GridView in dot net using JQuery. Here bind Gridview from SQL Server and Fixed size we will assign for Gridview for Particular area so we can set Scroll in Gridview. Let’s start how to do it.

In you webpage Design your Gridview like below and create script for scrolling. Using Data Fields we can Retrieve Column Data from SQL Server.

Download File:- ScrollableGridPlugin.js, Jquery-1.4.1.min.js

Default.aspx:-

<div>
  <asp:GridView ID="fixedHeaderScrollableGridView" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False"
  DataKeyNames="ProductID" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" 
  ForeColor="Black" GridLines="Vertical" >
  <AlternatingRowStyle BackColor="#CCCCCC" />
  <Columns>
    <asp:BoundField DataField="ProductID" HeaderText="ProductID" />
    <asp:BoundField DataField="ProductName" HeaderText="ProductName" />
    <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" />
    <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
    <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
  </Columns>
  <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" />
 </asp:GridView>
 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString=
    "<%$ ConnectionStrings:DBCS %>" SelectCommand="SELECT * FROM [Products]"> </asp:SqlDataSource>
</div> 

Script for generating Gridview
<script src="jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="ScrollableGridPlugin.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
  $('#<%=fixedHeaderScrollableGridView.ClientID %>').Scrollable({ScrollHeight: 100});
  });
</script> 

Using ScrollableGridPlugin.js and Jquery-1.4.1.min.js you can create your Own Scrollable Gridview in browser and for giving Height you can assign limited height for Gridview.

In your Webpage Bind Gridview from SQL DataSource and Get data from SQL Database. Now Generate Script for Scrolling so we can Create Scroll in Gridview. For Connection String you Can Check your Web.config file. Here I have took my connection String for taking data from my Database. You can create our own when you bind connection string using SqlDataSource.

Now run your Webpage in Browser and you will get scroll in your Gridview.

How to Open Word document through Job in AX 2012


Description:-

If you want to Open Word file through Job in Ax you can user COM variant and open word file through Job. Using COM variant or dialog Field, Word Documents through we can achieve this functionality in ax 2012.

static void OpenWordTemplate()
{
    COM                     wordApp;
    dialog                  d;
    Dialog                  dialog = new dialog();
    dialogField             dialogFilename;
    COM                     wordDocuments;
    FileName                fileName;
    
    wordApp = new COM("word.application");
    wordDocuments = wordApp.Documents();

    d = new dialog();
    d.caption("select a file");
    //add a field where you select your file in a specific path
    dialogFilename = d.addField(extendedTypeStr(FilenameOpen),"File Name");
    d.run();//execute dialog
    
    if(d.closedOk())
    {
        filename = dialogFileName.value();//return path file value
    }
    
    try
    {
        wordDocuments.Open(fileName);
    }
    catch (Exception::Error)
    {
        throw error("File cannot be opened.");
    }
    wordApp.visible(true);
}

Run your Job after File Dialog will open select File from that Dialog and Click ‘OK’ to open that File through Job in ax 2012.

InitValue Table method in ax 2012

InitValue Table method in ax 2012

Description:-

This method is called when a new record is created. It populates the record with initial values for the fields.The initValue method can be overridden on a form data source by right-clicking the Methods node under the data source, pointing to Override Method, and then clicking initValue.

The initvalue() is usually executed automatically on insert and it loads the default value.Here is the sample code to Generate Number sequence from table method in ax 2012.

public void initValue()
{
    str 60 _newCode;
    int max1;
    Table1 Table1;
    super();
    select firstOnly SrNo from Table1 order by RecId desc;
    if(!Table1.SrNo)
    {
        ttsBegin;
        _newCode=strRFix(int2str(1),6, "0");
        this.SrNo = _newCode;
        ttsCommit;
    }
    else
    {
        ttsBegin;
        max1=str2int(subStr(Table1.SrNo,1,6))+1;
        this.SrNo =strRFix(int2str(max1),6, "0");
        ttsCommit;
    }
}

Insert record into Database using Gridview in Asp.net

Description:-

In this tutorial I am going to explain how to insert a new record into database using Gridview FooterTemplate in Asp.net.
In this article I am going to use Gridview to insert new record into database. To implement this use the FooterTemplate inside the Template Field. Put the textbox control inside FooterTemplate and set require field validation on textboxes.

Create a table:-
CREATE TABLE [dbo].[Employeee](
                [Number] [int] IDENTITY(1,1) NOT NULL,
                [Name] [varchar](50) NOT NULL,
                [Gender] [varchar](50) NOT NULL,
                [Email] [varchar](50) NOT NULL,
                [MobileNumber] [bigint] NOT NULL,
                [Bdate] [date] NULL,
 CONSTRAINT [PK_Employeee] PRIMARY KEY CLUSTERED
(
                [Number] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO

Default.aspx:-
    <div>
        <asp:GridView ID="GridView1" runat="server" Width="550px" AutoGenerateColumns="False"
            ShowFooter="True" AllowPaging="True" CellPadding="4" ForeColor="#333333"
            GridLines="None" onpageindexchanging="GridView1_PageIndexChanging"
            onrowcommand="GridView1_RowCommand">
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lblname" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtname" runat="server" />
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Enter Name"
                            ControlToValidate="txtname"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Gender">
                    <ItemTemplate>
                        <asp:Label ID="lblGender" runat="server" Text='<%# Eval("Gender") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtGender" runat="server" />
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Enter Gender"
                            ControlToValidate="txtGender"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Email">
                    <ItemTemplate>
                        <asp:Label ID="lblEmail" runat="server" Text='<%# Eval("Email") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Email"
                            ControlToValidate="txtEmail"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mobile Number">
                    <ItemTemplate>
                        <asp:Label ID="lblMobileNumber" runat="server" Text='<%# Eval("MobileNumber") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtMobileNumber" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Enter Mobile Number"
                            ControlToValidate="txtMobileNumber"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                    </ItemTemplate>
                    <FooterTemplate>
                     <asp:Button ID="btninsert" runat="server" Text="Insert Record" CommandName="Insert" />
                    </FooterTemplate>
                    <ItemStyle VerticalAlign="Top" />
                </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
    </div>

Web.Config:-
<connectionStrings>
    <add connectionString="ConnectionString" name="DBCS" providerName="System.Data.SqlClient"/>   
</connectionStrings>

Default.aspx.cs:-
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    BindGridview();
  }
}

public void BindGridview()
{
  try
  {
    SqlDataAdapter adp = new SqlDataAdapter("Select * from Employeee", con);
    DataTable dt = new DataTable();
    adp.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
  }
  catch (Exception ex)
  {
  }
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
  GridView1.PageIndex = e.NewPageIndex;
  BindGridview();
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Insert")
  {
    SqlCommand cmd = new SqlCommand("Insert into Employeee(Name,Gender,Email,MobileNumber) values(@Name,@Gender,@Email,@MobileNumber)", con);
    TextBox txtname = (TextBox)GridView1.FooterRow.FindControl("txtname");
    TextBox txtGender = (TextBox)GridView1.FooterRow.FindControl("txtGender");
    TextBox txtEmail = (TextBox)GridView1.FooterRow.FindControl("txtEmail");
    TextBox txtMobileNumber = (TextBox)GridView1.FooterRow.FindControl("txtMobileNumber");
    con.Open();
    cmd.Parameters.AddWithValue("@Name", txtname.Text);
    cmd.Parameters.AddWithValue("@Gender", txtGender.Text);
    cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
    cmd.Parameters.AddWithValue("@MobileNumber", txtMobileNumber.Text);
    cmd.ExecuteNonQuery();
    con.Close();
    Response.Write("<script type=\"text/javascript\">alert('Record Insert Successfully!!!');</script>");
    BindGridview();
    txtname.Text = string.Empty;
    txtGender.Text = string.Empty;
    txtEmail.Text = string.Empty;
    txtMobileNumber.Text = string.Empty;
  }
}

How clear added previously added datasource and ranges in querybuildrange in ax 2012

How clear added previously added datasource and ranges in querybuildrange in ax 2012

Description:-

Here I have given simple demonstration to remove ranges from DataSource in Ax 2012. In form DataSource I have generated executeQuery method to changes ranges in DataSource based on combo box selection.

public class FormRun extends ObjectRun
{
    QueryBuildRange         QBR,QbrRMId,QbrSTId;
    QueryBuildDataSource    QbdsRM, QbdsST;
}

public void executeQuery()
{
    QbdsRM = DataSourceName_ds.query().dataSourceNo(1);
    QbdsST= DataSourceName_ds.query().dataSourceNo(1);
    if(FilterData.valueStr() == enum2str(EnumRM::All))
    {
        QbdsRM.clearRanges();
        QbdsST.clearRanges();
    }
    else if(FilterData.valueStr() == enum2str(EnumRM::RMId))
    {
        QbdsST.clearRanges();
        QbrSTId = sysQuery::findOrCreateRange(QbdsRM,fieldnum(DataSourceName, DataSourceField));
        QbrSTId.value(sysquery::valueEmptyString());
        QbdsRM.clearRanges();
        QbrRMId = sysQuery::findOrCreateRange(QbdsRM,fieldnum(DataSourceName, DataSourceField));
        QbrRMId.value(sysquery::valueNotEmptyString());
    }
    else if(FilterData.valueStr() == enum2str(EnumRM::STId))
    {
        QbdsRM.clearRanges();
        QbrRMId = sysQuery::findOrCreateRange(QbdsRM,fieldnum(DataSourceName, DataSourceField));
        QbrRMId.value(sysquery::valueEmptyString());
        QbdsST.clearRanges();
        QbrSTId = sysQuery::findOrCreateRange(QbdsRM,fieldnum(DataSourceName, DataSourceField));
        QbrSTId.value(sysquery::valueNotEmptyString());
    }
    super();
}

Combo box modified method.

public boolean modified()
{
    boolean ret;
    ret = super();
    DataSourceName_ds.executeQuery();
    return ret;
}

How to Create GUID in Dynamics Ax


Actually GUIDs are used in several places in Ax, like AIF Service, exchangeRateProvide etc.

You can create your own GUID with Ax as well, if you have a need for one. The WinAPI class has a method for that.

Example:

static void CreateGUID(Args _args)
{
    str myGUID;
    ;
    myGUID=Winapi::createGUID();
    info(myGUID);
}

This method depends on the kernel function newguid() to create a globally unique identifier.
Note that you can have the GUID with or without the { } or () or -.

How to Set Up AutoLogout in Ax


Description:-

Open AX> System Administrator>users Select user and click user option.  In the automatic shutdown, fill in the time you want to shut down when left un-use. Default value is "0" means no auto time out!
You get to it through the user interface of AX.

Path: Administration > Users > User options button > Automatic shutdown field.
If set at 0, it will not auto-shutdown. Set it to 15 in your case! :)

For "global parameter" and for all the user at once use this job:

You need to create a job.

static void User_Timeout(Args _args)
{
    UserInfo userInfo;
    ;
    ttsbegin;
    while select forupdate * from userInfo 
        where userInfo.id=='UserId'
    {
        userInfo.autoLogOff = 15;
        userInfo.update();
        info(strFmt("Set time '%1' for user to AutoLogOff '%2'",userInfo.autoLogOff,userInfo.id));
    }
    ttscommit;
}

Create google gauge chart in asp.net


Description:-

In this Article we will see how to Create Google Gauge Chart in dot net.  Here I have Generate Script Dynamically from Database to bind Chart from Script. You can Generate what event data you will pass in the Database based on that it will Create Gauge Chart. Here is the Sample Demo Example to Generate Chart.

Default.aspx:-

<div>
  <asp:Literal ID="lt" runat="server"></asp:Literal>
</div>
<div id="chart_div"></div>

Default.aspx.cs:-

protected void Page_Load(object sender, EventArgs e)
{
  if (Page.IsPostBack == false)
  {
    BindChart();
  }
}

private DataTable GetData()
{
  DataTable dt = new DataTable();
  string cmd = "select Name, Price from products";
  SqlDataAdapter adp = new SqlDataAdapter(cmd, conn);
  adp.Fill(dt);
  return dt;
}

private void BindChart()
{
  DataTable dt = new DataTable();
  try
  {
    dt = GetData();
    str.Append(@"<script type=text/javascript> google.load( *visualization*, *1*, {packages:[*gauge*]});
        google.setOnLoadCallback(drawChart);
        function drawChart() {
           var data = new google.visualization.DataTable();
           data.addColumn('string', 'item');
           data.addColumn('number', 'value');      
           data.addRows(" + dt.Rows.Count + ");");
           for (int i = 0; i <= dt.Rows.Count - 1; i++)
           {
             str.Append("data.setValue( " + i + "," + 0 + "," + "'" + dt.Rows[i]["Name"].ToString() + "');");
             str.Append("data.setValue(" + i + "," + 1 + "," + dt.Rows[i]["Price"].ToString() + ") ;");
           }
           str.Append("var options = {width: 600, height: 300,redFrom: 90, redTo: 100,yellowFrom:75, yellowTo: 90,minorTicks: 5};");
           str.Append(" var chart = new google.visualization.Gauge(document.getElementById('chart_div'));");
           str.Append(" chart.draw(data, options); }");
           str.Append("</script>");
           lt.Text = str.ToString().TrimEnd(',').Replace('*', '"');
  }
  catch
  { }
}

Now run your application to Get Data from Database and Using JavaScript it will Generate Gauge Chart on your Webpage.