Showing posts with label Axapta 2009. Show all posts
Showing posts with label Axapta 2009. Show all posts

Monday, 18 July 2016

X++: HTTP Web Request to URL

//This method makes HTTP web request to the given url and returns the response
System.Net.WebRequest webrequest;

System.Net.HttpWebResponse httpresponse;

System.IO.Stream stream;

System.IO.StreamReader streamReader;

xml responseXML;

System.Byte[] arrayOfBytes;

System.Text.Encoding encoding;
System.String netString = "Net string.";
  System.Exception netExcepn;

;

try

{

new InteropPermission(InteropKind::ClrInterop).assert();

//Use .Net framework reflections to make HttpRequest and get the response back

encoding = System.Text.Encoding::get_UTF8();
arrayOfBytes = encoding.GetBytes("");

webrequest = System.Net.WebRequest::Create('http://localhost/AxService/myService.asmx/HelloWorld');

webrequest.set_Method("POST");
webrequest.set_PreAuthenticate(true);
webrequest.set_Credentials(System.Net.CredentialCache::get_DefaultCredentials());

webrequest.set_ContentType("application/x-www-form-urlencoded");
webrequest.set_ContentLength(arrayOfBytes.get_Length());
stream = webrequest.GetRequestStream();
stream.Write(arrayOfBytes,0,arrayOfBytes.get_Length());
stream.Close ();



httpresponse = webrequest.GetResponse();

stream = httpresponse.GetResponseStream ();

streamReader = new System.IO.StreamReader (stream);

responseXML = streamReader.ReadToEnd ();

streamReader.Close ();

stream.Close ();

httpResponse.Close ();



codeAccessPermission::revertAssert();
    info(responseXML);
}

 catch (Exception::Error)
    {
        info("Caught 'Exception::Error'.");
    }
    catch (Exception::CLRError)
    {
        info("Caught 'Exception::CLRError'.");
        netExcepn = CLRInterop::getLastException();
        info(netExcepn.ToString());
    }

Thursday, 16 June 2016

Axapta 2009 This transaction has been marked for settlement by another user.

one of end user of AR is got stuck for knock off the account.
Then I  make  a solution that logon to database server of the AX 2009 then write a query
select * from SPECTRANS
then select a amount in table where Red Dot is came and put in the query
select * from SPECTRANS where BALANCE01=398.700
now check that record is came
Now delete that record by writing a query
delete from SPECTRANS where  BALANCE01=398.700
now again go to check the settlement transaction ,Red Dot  is gone .

Monday, 25 April 2016

Overdelivery of line is 100,00 percent, but the allowed overdelivery is only 0 percent.

We had the same problem with one of our client. The reason behind was, there were some orphans purchParmSubLine records lying in the table, which led to add up the remain del note qty and attempting to post Delivery note again. We suspected, the reasons these records were left in the table, when posting failed for any reason or client session crashed when posting was being done. Anyways, simple way to resolve it by creating a simple job to clean up those records and Hallelujah! the problem is gone!
static void tecDeleteOrphanParmRecords(Args _args)
{
   PurchParmTable purchParmTable;
   PurchParmLine  purchParmLine;
   ;
   ttsbegin;
   while select forupdate purchParmTable
       join forupdate purchParmLine
       where purchParmLine.ParmId == purchParmTable.ParmId
       && purchParmLine.TableRefId    == purchParmTable.TableRefId
       && purchParmTable.PurchId  == "Your PO number"
       && purchParmTable.ParmJobStatus == ParmJobStatus::Waiting
       && purchParmTable.Ordering == DocumentStatus::Invoice
   if(purchParmTable.RecId || purchParmLine.RecId)
   {
       purchParmTable.delete();
       purchParmLine.delete();
   }
   ttscommit;
}
Cleaning up PurchParmTable and Line will also clean up related tables (Sub tables) by itself.
Try posting again.  Everything should work smoothly.
Cheers!
PG

Monday, 15 February 2016

Send email using X++ code

SysMailer   mailer = new SysMailer();
        SysEmailParameters parameters = SysEmailParameters::find();
        ;

        if (parameters.SMTPRelayServerName)
        {
            mailer.SMTPRelayServer(parameters.SMTPRelayServerName,
                               parameters.SMTPPortNumber,
                               parameters.SMTPUserName,
                               SysEmailParameters::password(),
                               parameters.NTLM);
        }
        else
        {
            mailer.SMTPRelayServer(parameters.SMTPServerIPAddress,
                               parameters.SMTPPortNumber,
                               parameters.SMTPUserName,
                               SysEmailParameters::password(),
                               parameters.NTLM);
        }

        mailer.fromAddress('hesham.elgabarty@augpharma.com');
        mailer.tos().appendAddress('hesham.elgabarty@augpharma.com');
        mailer.htmlBody('AZZZ');
        mailer.subject('Comunicazione AX');

        mailer.sendMail();
        info('Done');

Tuesday, 26 January 2016

Can not post a purchase invoice

We have come across some scenarios where it was not possible to complete purchase invoicing, for example:
  • There is pending invoice in AX that is not visible in invoicepool. It can be seen only from purchase order side. It blocks many orders.
  • A Pending Invoice is not appearing in PL>common>Pending Supplier Invoices however when you go to the PO and look at the invoice tab, the Pending Invoice is still highlighted and when you select this you can see the detail of the pending invoice but we cannot do anything with it
  • When trying to post a purchase invoice you get an error message that says: Invoice %1 could not post because it contained matching errors which must be approved.
  • While selecting Pending vendor invoice gets an error as “One or more pending invoices cannot be displayed because they are in use” and the invoice is not displayed.
It may happen that if AOS gets stopped suddenly or the client loses connection with the AOS, some records stay in specific tables that causes these kind of situations. In other cases we or Partners could not find repro steps to get those scenarios.
I found a list of the SQL tables where the ‘pending’ record may exist. If the record is found in any of the following tables, the recommendation is to remove it when you have no users accessing AOS (and take normal precautions first of backing up the data). Also test the procedures in a test/development environment before applying it to a live enviroment. Then, check to see if you are able to properly invoice update the PO.
PurchParmTable
PurchParmLine
PurchParmSubTable
PurchParmSubLine
PurchParmUpdate
VendInvoiceInfoTable
VendInvoiceInfoLine
VendInvoiceInfoSubTable
VendInvoiceInfoSubLine
Of course, you can also delete these records going through Forms, these are the ones I used (ensure no users besides you are working in the application):
1. Firstly checking PurchParm tables when looking History forms (Account Payable/ Inquiries/ History/ Purchase orders), and delete those records where the status is “Waiting”.
2. The next step is to check VendInvoiceInfo tables where you found the wrong records, You can access those records in the list page: Accounts payable module > Places > Pending Purchase Order Invoices. Here you can delete it as well. Note: pending invoice of your case will be in this list page.
Hope it’s helpful

VendTmpInvoiceInfoTable

Friday, 15 January 2016

Unreserved "Physical Reserved" Qty in Ax 2009 thru x++

To remove a reservation (just reverse the sign on the qty):
In the code below, ‘inventTransParent’ is the inventTransId of the record that has the reservation (e.g. salesline.inventTransId)
You probably will want to modify the ‘where’ clause a bit to make sure you get the reservation records only, but this is just an example.
//Remove any existing reservations
InventTrans            inventTransReserve    ;
InventMovement         inventMovement        ;
InventUpd_Reservation  inventUpd_Reservation ;
;
while select inventTransReserve where inventTransReserve.InventTransId == inventTransParent
{
   Inventmovement = inventTransReserve.inventmovement(true);
   inventUpd_Reservation = InventUpd_Reservation::newInventDim(inventmovement,inventTransReserve.inventDim(), -1 * inventTransReserve.Qty ,false);    inventUpd_Reservation.updatenow();
}

Wednesday, 24 June 2015

Simple Lookup Form

 SysTableLookup _SysTableLookup = SysTableLookup::newParameters(tablenum(carTable),this) ;
     _SysTableLookup.addLookupfield(fieldnum(carTable,carID));
     _SysTableLookup.addLookupfield(fieldnum(carTable,carName));
     _SysTableLookup.performFormLookup();

Monday, 28 April 2014

How to pass values between Axapta forms

How to pass values between Axapta forms 

void clicked()
{
    Args myArgs;
    FormRun myFormRun;
    ;
    // Keep this call to super() when overriding the clicked method.
    super();

    myArgs = new Args();

    // Provide the name of the form to launch.
    myArgs.name("WebformBarcodeBatchPrint");

    // The DataSource_WorkOrder_M data source variable name
    // represents the currently selected item in the grid
    // on the parent form (and thus in the data source).
    myArgs.record(InventBatch);

    myFormRun = ClassFactory.formRunClass(myArgs);

    // if(DataSource_WorkOrder_M.WOStatus_fn()!=WOStatus::Closed) {
    myFormRun.init();
    myFormRun.run();
    myFormRun.wait();
}

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

Thursday, 9 August 2012

Enable and Disable controls by X++

Hi
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


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

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

ax.Logoff()

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

Monday, 12 March 2012

Axapta 2009 create a new sales line


 _SalesLine.clear();

         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