Monday, 31 December 2012

Resize or Reduce Dialog of jQuery UI DatePicker plugin using CSS

Dear all
Here is a new problem that all of us can we fix and after some time we forget how to do this again so i would  like to share it with all of you
which is how to increase or decrease the JQuery date picker dialog size thorough JQuery CSS class or our CSS class by the code below as it is

In our class

<style type = "text/css">
.ui-datepicker { font-size:9pt !important}
Or in the jQuery UI Calendar CSS file
.ui-datepicker { font-size:9pt !important}

Wednesday, 28 November 2012

.Net Business Connector Call a static method with dynamic parameters

Dear All
  Here a sample code for how to call a static method with a dynamic parameters because by default the CallStaticClassMethod allow you to only put max three parameters

so suppose we have a method in Axapta which is take two integer parameters and return the sum of them like this :

static int myMethod(int x,int y)
   Return x+y;

and here below is how to call this method with any number of parameters

            Dim param As Object() = New Object(1) {}
            param(0) = 3
            param(1) = 2       
            Return ax.CallStaticClassMethod("HBUnderQualityMovement", "myMethod", param)

Thanks and Regards
Happy Programming :)

Saturday, 17 November 2012

Convert English numbers into Arabic charchters

This artical is how to convert the English like 123456789 to ١٢٣٤٥٦٧٨٩٩٠

 public string ConvertToEasternArabicNumerals(string input)
            System.Text.UTF8Encoding utf8Encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decoder = utf8Encoder.GetDecoder();
            System.Text.StringBuilder convertedChars = new System.Text.StringBuilder();
            char[] convertedChar = new char[1];
            byte[] bytes = new byte[] { 217, 160 };
            char[] inputCharArray = input.ToCharArray();
            foreach (char c in inputCharArray)
                if (char.IsDigit(c))
                    bytes[1] = Convert.ToByte(160 + char.GetNumericValue(c));
                    utf8Decoder.GetChars(bytes, 0, 2, convertedChar, 0);
            return convertedChars.ToString();

Wednesday, 14 November 2012

View SSRS Report and passing parameters into it using report viewer ASP.NET

Dear All
As we like to make every thing is dynamic in this post i will show how to view a SSRS report published in the report server  using ASP.NET and also passing to it a parameters as the code below

        If Page.IsPostBack = False Then


                ReportViewer1.ServerReport.ReportServerCredentials = New ReportCredentials
                ReportViewer1.ShowCredentialPrompts = False
                ReportViewer1.ServerReport.ReportServerCredentials = New ReportCredentials()
                ReportViewer1.ProcessingMode = ProcessingMode.Remote

                Dim sReportName As String = "/budget/Budget_Actual"
                ReportViewer1.ServerReport.ReportServerUrl = New System.Uri("http://sv-ssrs01/Reportserver")
                ReportViewer1.ServerReport.ReportPath = sReportName

                ReportViewer1.ShowParameterPrompts = False

                ReportViewer1.ServerReport.SetParameters(New ReportParameter("BudgetYear", "2010"))
                ReportViewer1.ServerReport.SetParameters(New ReportParameter("BudgetYear2", "2012"))
                ReportViewer1.ServerReport.SetParameters(New ReportParameter("DepartmentID", "IT"))



            Catch ex As Exception

            End Try


Public Class ReportCredentials
    Implements IReportServerCredentials
    Private _Username As String
    Private _Password As String
    Private _Domain As String

    Public Sub New()
        _Username = ConfigurationManager.AppSettings("ReportServerUserName").ToString
        _Password = ConfigurationManager.AppSettings("ReportServerPassword").ToString
        _Domain = ConfigurationManager.AppSettings("DOMAIN").ToString
    End Sub

    Public ReadOnly Property ImpersonationUser() As WindowsIdentity Implements IReportServerCredentials.ImpersonationUser
            Return Nothing
        End Get
    End Property

    Public ReadOnly Property NetworkCredentials() As System.Net.ICredentials Implements IReportServerCredentials.NetworkCredentials
            Return New Net.NetworkCredential(_Username, _Password, _Domain)
        End Get
    End Property

    Public Function GetFormsCredentials(ByRef authCookie As System.Net.Cookie, ByRef userName As String, ByRef password As String, ByRef authority As String) As Boolean Implements IReportServerCredentials.GetFormsCredentials
        userName = _Username
        password = _Password
        authority = _Domain
        Return Nothing
    End Function

End Class

Sunday, 9 September 2012

JQuery Loading animation in postback

I want to demonstrate in this article is how to make our web site is looking more attractive by putting an animation while loading the page in post back.

first we can create and design the loading animation from this website Here.

1- First we will create a simple button and do not forget to add the JQUERY reference classes like this.

<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.effects.core.js" type="text/javascript"></script>

2- put a simple button 
 <asp:Button ID="btnSearch" runat="server" Text="Search"  />

3-After creating and downloading the animation as a .gif image put it like this.

<div style="text-align: center; vertical-align: middle; font-family: Verdana; color: Blue;
                        position: absolute; top: 50%; left: 50%; margin-left: -88px; font-size: small;
                        background-color: White; border:2px solid #f90;" id="dvProgress" runat="server">
                        Please Wait ...
                        <img src="images/ajax-loader.gif" id="loader" style="vertical-align: middle;" alt="Processing" />

4-Put the below JQUERY code.

 <script type="text/javascript">

$(document).ready(function () {

    $('#dvProgress').hide();  // This is to hide the animation progress at first time

       $("#btnSearch").click(function () {     // show the animation progress upon we click the search button

Note: as we know that how is the IE is sucks you will find in all other browsers that the animation running perfectly except the IE so put this extra line of  code like this. 

        setTimeout('document.images["loader"].src = "images/ajax-loader.gif"', 200);  

Happy Programming :)

Wednesday, 15 August 2012

Microsoft JScript runtime error: 'jQuery' is undefined

In  some cases  as we know the silly internet explorer gives us a weird errors as the tittle of this post, so after searching a lot of time please make sure while you adding the JQuery References class to put it like this (~/).

 <script src="~/Scripts/jquery-ui-1.8.20.custom.min.js" type="text/javascript"></script>
 <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> 

Instead of this

 <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>

This error may appear or may be not just make sure to prevent any wasting time in the future 

Thursday, 9 August 2012

Enable and Disable controls by X++

In this post i will explain how to disable and enable controls in the form regarding to the business needs

Normal element control

    ControlName.Enabled(false); // Disable the control

Control Inside a grid or field

   TableName_ds.object(fieldnum(TableName,FieldName)).enabled(false);    //Disable the field

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      

        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))

                    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();
                    string str = serializer.Serialize(result);
                     return myArr;               
Second our Emplyee Class

    public class Employee
        public string ID;

        public string EmployeeID;

        public string EmployeeName;

Third our JQuery code

$(function () {



function SearchText() {
        source: function (request, response) {
                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("")
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
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="">

<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>
    <script type="text/javascript">
        $(document).ready(function () {
        function SearchText() {
                source: function (request, response) {
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "MyTest2.aspx/GetAutoCompleteData",
                        data: "{'username':'" + document.getElementById('autosuggest').value + "'}",
                        dataType: "json",
                        success: function (data) {
                        error: function (result) {
    <form id="form1" runat="server">
        <asp:TextBox ID="autosuggest" runat="server"></asp:TextBox>

  • Second the code behind (Put this method inside your aspx page)
        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))
                  //  cmd.Parameters.AddWithValue("@SearchText", username);
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    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);

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



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));

// Block the filter or do not allow the user to filter by any other departments



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.lookupField(fieldNum(Trucks_CT, TruckId));

    formRun = ClassFactory::formRunClassOnClient(args);

Sunday, 13 May 2012

WPF Browser application suddenly not working for the client

Some times a WPF browser applications suddenly is not working for the client and appearing to him an error occurred when the application is starting , but in the design mode and in another machine working  fine,  this is mainly happened after publishing a new version into the server.

That is because a conflict happened between the DLLs for the old and new version, so we need to delete the old DLLs and rerun the new fresh version into the client machine by deleting and file or folder inside the below path .

C:\Users\'USER NAME'\AppData\Local\Apps\2.0

Do not hesitate to send to me any problems

Enjoy Debugging

Tuesday, 20 March 2012

Calling Axapta 2009 Static Method from outside the domain using LogonAs

Dear All here is an article to how to call an Axapta static method from outside the domain server through a web service and business connector

Dim creds As New System.Net.NetworkCredential()
creds.Domain = ConfigurationSettings.AppSettings("Domain").ToString '
creds.UserName = ConfigurationSettings.AppSettings("ProxyName").ToString
creds.Password = ConfigurationSettings.AppSettings("ProxyPassword").ToString            ax.LogonAs(ConfigurationSettings.AppSettings("AdminName").ToString,ConfigurationSettings.AppSettings("Domain").ToString, creds, "", "", ConfigurationSettings.AppSettings("AXServer").ToString, "")

ax.CallStaticClassMethod("ClassName", "MethodName",)


Note: Be sure that the proxy user name and password will be the proxy defined inside the Axapta which we can get from here Administration > Setup > Security > System Service account
Above the business connector  there is the alias name and the domain which we will use in the Network Credential parameters

Tuesday, 13 March 2012

JQuery methods dose not work after calling any ajax event

After doing any event from any ajax controls i found that the JQuery code dose not work this is happening because of any Ajax event is removeing the scripts which is loaded at first time when we open the page,  so we need to load again each time the functions of the JQuery after each Ajax event.

Here below an example for what i did to fix these problem

$(document).ready(function () {



function load() {

function EndRequestHandler() {

    $("#pHeader1").click(function () {

    $("#pHeader2").click(function () {

    $("#pHeader3").click(function () {

EndRequestHandler function is a function include inside it all the JQuerys calls and the function Load() where we add all the JQuery code again after firing any ajax event

ASP.NET Print a crystal report by code to a specific printer via printer IP and Name

 Dim rdpDocument As New ReportDocument
            Dim crConnectionInfo As New ConnectionInfo()

            crConnectionInfo.ServerName = "MIS-009"
            crConnectionInfo.DatabaseName = "HR_DEV"
            crConnectionInfo.IntegratedSecurity = False
            crConnectionInfo.UserID = "sa"
            crConnectionInfo.Password = "sa"

            rdpDocument.SetDatabaseLogon("sa", "sa")

            rdpDocument.SetDataSource(GetData("@PICKINGROUTEID", "034333_138", "REPORT_TRUCK_CONSIGNMENT"))
            rdpDocument.PrintOptions.PrinterName = "\\\" & "HP Color LaserJet 4700 PS"
            rdpDocument.PrintToPrinter(1, True, 0, 1)         

If you faced any problem or error related to that you can not identify the printer IP or address here some steps to get the printer address

1) Add Printer to server. 2) run regedit 3) Search for printername to find your printer 4) value of uNCName property is printer name you need. oRpt.PrintOptions.PrinterName = "value";

Monday, 12 March 2012

Axapta 2009 create a new sales line


         inventdim.InventLocationId = SalesTable::find(salesid).InventLocationId;
         inventdim.inventBatchId = _HBInventTx_D_V2.inventBatchId;
         inventdim = inventdim::findOrCreate(inventdim);

         _SalesLine.InventDimId = inventdim.inventDimId;
         _SalesLine.SalesId = salesid;
         _SalesLine.ItemId = _HBInventTx_D_V2.ItemId;
         _SalesLine.SalesQty = _HBInventTx_D_V2.qty * -1;
         _SalesLine.ReturnReasonCodeId = '01';

         _SalesLine.createLine(NoYes::Yes, // Validate
                               NoYes::Yes, // initFromSalesTable
                               NoYes::Yes, // initFromInventTable
                               NoYes::Yes, // calcInventQty
                               NoYes::Yes, // searchMarkup
                               NoYes::Yes); // searchPrice

Windows Mobile set the device date and time

 <DllImport("coredll.dll")> _
   Private Function SetSystemTime(ByRef time As SYSTEMTIME) As Boolean
    End Function

Public Sub setDeviceDateTime(ByVal dt As DateTime)
        Dim ServerTime As New SYSTEMTIME

        ServerTime.Day = dt.ToUniversalTime.Day
        ServerTime.Month = dt.ToUniversalTime.Month
        ServerTime.Year = dt.ToUniversalTime.Year
        ServerTime.Hour = dt.ToUniversalTime.Hour
        ServerTime.Minute = dt.ToUniversalTime.Minute
        ServerTime.Second = dt.ToUniversalTime.Second

    End Sub
    Public Structure SYSTEMTIME
        Public Year As Short
        Public Month As Short
        Public DayOfWeek As Short
        Public Day As Short
        Public Hour As Short
        Public Minute As Short
        Public Second As Short
        Public Milliseconds As Short
    End Structure