Wednesday 18 July 2012

JQuery Autocomplete with display member and value member

This is a the second article for the JQuery auto complete text box which demonstrates how to create an autocomplete text box which retrieve value and key or by other words value member and display member,

in our previous article we know how we can retrieve data from Data Base and fill it into the autocomplete like here .

but in most scenarios this is not satisfied for us unless we get the two dimensions or fields.

Example: we need to create a autocomplete text box which can search by employee name and after selecting the employee name we can get his ID. 


First our method inside the aspx page to get the data      



 [WebMethod]
        [ScriptMethod]
        public static ArrayList GetAutoCompleteData(string EmployeeName)
        {
            List<Employee> result = new List<Employee>();
            List<string> result2 = new List<string>();
            ArrayList myArr = new ArrayList();
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            using (SqlConnection con = new SqlConnection("Data Source=sv-intranet04;Initial Catalog=HR_DEV;Persist Security Info=True;User ID=cpr1;Password=cpr1"))
            {
                using (SqlCommand cmd = new SqlCommand("select DISTINCT FullName_E as EmployeeName,EmployeeID as ID from EmployeeProfile_view1 where FullName_E LIKE '%" + EmployeeName + "%'", con))
                {
                    con.Open();

                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {

                        Employee newEmp = new Employee();
                     
                        newEmp.EmployeeName = dr["EmployeeName"].ToString();
                        newEmp.EmployeeID = dr["ID"].ToString();
                        newEmp.ID = dr["ID"].ToString();
                   
                        myArr.Add(newEmp);
                     
                    }
                    string str = serializer.Serialize(result);
                     return myArr;               
                }
            }
        }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Second our Emplyee Class



 [DataContract()]
    public class Employee
    {
        [DataMember]
        public string ID;

        [DataMember]
        public string EmployeeID;

        [DataMember]
        public string EmployeeName;

    }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Third our JQuery code


$(function () {

 SearchText();


});


function SearchText() {
    $("#autosuggest").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "MyTest.aspx/GetAutoCompleteData",
                data: "{'EmployeeName':'" + document.getElementById('autosuggest').value + "'}",
                dataType: "json",
                success: function (data) {
                    // response(data.d);
                    response($.map(data.d, function (item) {
                        return {
                            label: item.EmployeeName,
                            val: item.ID
                        }
                    }))

                },
                error: function (XMLHttpRequest, callStatus, errorThrown) { alert(callStatus); }
            });
        },
        select: function (event, ui) { $("#Result").text(ui.item.val); }
    });    

}



Tuesday 17 July 2012

Print from mobile application directly into a network printer

In this article i will explain how we can print a report directly from a mobile application connected through wireless network to the printer, so try the code below.


Dim strPrintData As String = "" 'Contains the string to be printed
Dim DataBytes() As Byte 'Contains the String converted into bytes
Dim PrintedStream AsNetworkStream 'Stream to transmit the bytes to the Network printer
Dim HostIPAddress AsSystem.Net.IPAddress 'IP Address of the Printer
Dim PrinterPort As NewSystem.Net.Sockets.TcpClient 'TCPClient to comunicate
'HostIPAddress = System.Net.IPAddress.Parse("192.168.201.201")
HostIPAddress = System.Net.IPAddress.Parse(dvWarehouseKeepers(0)("PCADDRESS").ToString)

          
          

strPrintData += Chr(27) &"&l1O"
     
strPrintData += "Hello world" & vbCrLf

Dim Unicode As NewSystem.Text.UnicodeEncoding
DataBytes = System.Text.Encoding.ASCII.GetBytes(strPrintData)

'If Not connected then connect
If NotPrinterPort.Client.Connected Then
'Printer Port 9100 for HP JetDirects
PrinterPort.Connect(HostIPAddress, 9100)
End If

PrintedStream = PrinterPort.GetStream
'Send the stream to the printer
 If PrintedStream.CanWriteThen
     PrintedStream.Write(DataBytes, 0, DataBytes.Length)
 End If
'Close the connections
PrintedStream.Close()
PrinterPort.Close()
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Happy coding

Wednesday 11 July 2012

JQuery autocompete from DataBase through JSON

Finally i found the simplest way to fill autocomplete text box by getting a list of employees as an example from Database, Using a normal web method will type it inside the aspx page.

bellow is how to do this


  • first the aspx page

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <link href="css/jquery.ui.all.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery.ui.theme.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery.ui.base.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery.ui.autocomplete.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.20.custom.min.js" type="text/javascript"></script>
    <title>hiiiiiiiiiiiiiii</title>
    <script type="text/javascript">
        $(document).ready(function () {
            SearchText();
        });
        function SearchText() {
            $("#autosuggest").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "MyTest2.aspx/GetAutoCompleteData",
                        data: "{'username':'" + document.getElementById('autosuggest').value + "'}",
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Error");
                        }
                    });
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="autosuggest" runat="server"></asp:TextBox>
    </div>
 
    </form>
</body>
</html>



  • Second the code behind (Put this method inside your aspx page)
 [WebMethod]
        public static List<string> GetAutoCompleteData(string username)
        {
            List<string> result = new List<string>();
            using (SqlConnection con = new SqlConnection("Data Source=sv-intranet04;Initial Catalog=HR_DEV;Persist Security Info=True;User ID=cpr1;Password=cpr1"))
            {
                using (SqlCommand cmd = new SqlCommand("select DISTINCT FullName_E from EmployeeProfile_view1 where FullName_E LIKE '%" + username + "%'", con))
                {
                    con.Open();
                  //  cmd.Parameters.AddWithValue("@SearchText", username);
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        result.Add(dr["FullName_E"].ToString());
                    }
                    return result;
                }
            }
        }

  • Happy Codding :)

Monday 9 July 2012

Lookup Form


Here in this example demonstrates how to make a look up form for a sub categories regarding to the selected category in grid and you can do the same for any controls.

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

AssetComponentsTable: the items table
AssetComponentsGroup: the group field  CompGroupId
AssetComponentsSubGroup: the sub group field CompSubGroupId

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Note: In the grid control the field of CompGroupId make the AutoDeclaration true
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void lookup()
{

//    super();

QueryBuildDataSource qbds;
Query q = new Query();
QueryBuildRange qbr;


SysTableLookup s =  SysTableLookup::newParameters(tableNum(AssetComponentsSubGroup),this);
s.addLookupField(fieldnum(AssetComponentsSubGroup,CompSubGroupId));
s.addLookupField(fieldnum(AssetComponentsSubGroup,Name));

qbds = q.addDataSource(tableNum(AssetComponentsSubGroup),"AssetComponentsSubGroup");
qbr  = qbds.addRange(fieldnum(AssetComponentsSubGroup,CompGroupId));

qbr.value(AssetComponentsTable.CompGroupId);

s.parmQuery(q);
s.performFormLookup();
}

Sunday 8 July 2012

Filter the DataSource with a condition and force the user to see his own data

In this Post i will demonstrates how filter a data regarding to the user who logged into Ax, in this example      i will filter only the data of the user related to his department.

First override the method execute query in the DataSource then type your code as the example below.


public void executeQuery()
{


// This is the table which include the matching between the user and the department 
 AssetExtensions_User_Department_SETUP myAssetExtensions_User_Department_SETUP;

// Get the department id of the user 
select DepartmentID from myAssetExtensions_User_Department_SETUP where myAssetExtensions_User_Department_SETUP.UserID == curUserId() ;


// Filter the data source

    myQueryBuildRange = this.query().dataSourceName('AssetComponentsTable').addRange(fieldnum(AssetComponentsTable,OwnerDepartmentID));
    myQueryBuildRange.value(myAssetExtensions_User_Department_SETUP.DepartmentID);


// Block the filter or do not allow the user to filter by any other departments
myQueryBuildRange.status(RangeStatus::Hidden);

    super();

}

Axapta Go to main table

This article demonstrates how to show in the context menu whenever the user select a cell in a grid open to him another form related to the first one through a relation between them.

 after creating the form expand to DataSource >> then got to the selected field >> Override the methods >>
JumpRef as the code below


Trucks_CT_SETUP : the form that will open
Trucks_CT       : the table name
TruckId         : the field name

////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void jumpRef()
{
   Args                args;
    FormRun             formRun;
    ;

    args = new Args(formStr(Trucks_CT_SETUP));
    args.caller(element);
    args.lookupField(fieldNum(Trucks_CT, TruckId));
    args.lookupValue(Drivers_CT.TruckId);

    formRun = ClassFactory::formRunClassOnClient(args);
    formRun.init();
    formRun.run();
    formRun.wait();
}