Sunday, July 6, 2014

Find Date Time Difference through X++ code

Date Time Difference :


To find the time difference in the given two date's. Using the below class we can find the total time difference and also the time difference in  the month and year wise difference. 

Class : TestDateTimeDifference 


Class Declaration : 


class TestDateTimeDifference
{
    int n,x,y,z,frommonth,tomonth,diffmonth,fromyear,toyear,remains;
    date d;
    System.DateTime temp,tempTo,tempFrom;
    System.TimeSpan totalDiff,fromDiff,toDiff,val;
}  

Method :  TimeDifferenceFind 


Public void timeDifferenceFind(utcDateTime _startDate,utcDateTime _endDate)
{
    tempFrom = _startDate;
    tempTo = _endDate;
    TotalDiff = tempTo.Subtract(tempFrom);
    info("Total Difference :  ");
    info(TotalDiff.ToString());

    fromyear = DateTimeUtil::year(_startDate);
    toyear   = DateTimeUtil::year(_endDate);
    frommonth = DateTimeUtil::month(_startDate);
    tomonth   = DateTimeUtil::month(_endDate);

    z= (toyear - fromyear);
    for(y=0;y<=z;y++)
    {
        if(z==0)        //To Find the Time Difference in same Year
            x = 0;
       
        if(z==1 && y==0)        //To find the Time Differnce for two differnt continuous years
             x=1;       
        else if(z==1 && y==1)
             x=3;
       
        if(z>1 && y==0)         // To find the Difference in two different years
             x = 1;
        else if(z>1 && y<z)
             x = 2;
        else if(z>1 && y==z)
             x = 3;
       
        switch(x)
        {
            case 0 :

                    info(strFmt("In %1 : ",fromyear));
                    this.startMonthDiff(_startDate);
                    n = frommonth + 1;
                    remains = tomonth - 1;
                    this.otherMonthsDiff(remains,n,fromyear);
                    this.endMonthDiff(_endDate);
                    break;

            case 1 :
                    frommonth = DateTimeUtil::month(_startDate);
                    tomonth   = 12;
                    info(strFmt("In %1 : ",fromyear));
                    this.startMonthDiff(_startDate);
                    n = frommonth + 1;
                    remains = tomonth;
                    this.otherMonthsDiff(remains,n,fromyear);
                    break;

            case 2:
                    frommonth = 0;
                    tomonth   = 12;
                    fromyear = fromyear+1;
                    info(strFmt("In %1 : ",fromyear));
                    n = frommonth + 1;
                    remains = tomonth;
                    this.otherMonthsDiff(remains,n,fromyear);
                    break;
            case 3 :
                    frommonth = 1;
                    tomonth   = DateTimeUtil::month(_endDate);
                    info(strFmt("In %1 : ",toyear));
                    n = frommonth;
                    remains = tomonth-1;
                    this.otherMonthsDiff(remains,n,toyear);
                    this.endMonthDiff(_endDate);
                    break;
        }
    }
} 


Method : OtherMonthsDiff 


Public void otherMonthsDiff(int _remain,int _start,int _dateYear)
{
    while(_start<=_remain)
    {
        d = mkDate(1,_start,_dateYear);
        d = endmth(d);
        val = new System.TimeSpan(dayOfMth(d),0,0,0,0);
        info(strFmt("The Time difference in  %1 is : ",mthName(_start)));
        info(val.ToString());
        _start++;
    }
} 


Method : StartMonthDiff 


Public System.TimeSpan startMonthDiff(utcDateTime _datefrom)
{
    d = endmth(DateTimeUtil::date(_datefrom));
    temp = mkDate(dayOfMth(d),frommonth,fromyear);
    fromdiff = temp.Subtract(_datefrom);
    info(strFmt("The Time difference in  %1 is : ",mthName(frommonth)));
    info(fromdiff.ToString());
    return fromDiff;
} 


Method : EndMonthDiff 


Public System.TimeSpan endMonthDiff(utcDateTime _dateTo)
{
    d = dateStartMth(DateTimeUtil::date(_dateTo));
    temp = mkDate(dayOfMth(d),tomonth,toyear);
    toDiff = tempto.Subtract(temp);
    toDiff = toDiff.Add(new System.TimeSpan(1,0,0,0,0));
    info(strFmt("The Time difference in   %1 is : ",mthName(tomonth)));
    info(toDiff.ToString());
    return toDiff;
} 


Job :


 DateTimeDifference  dateTimeDifference;   
    dateTimeDifference = new DateTimeDifference();

    dateTimeDifference.timeDifferenceFind(new System.DateTime(2012, 1, 15,23,15,0),new System.DateTime(2014, 2, 10,10,15,0));

Output : 





Monday, February 17, 2014

AX Tables – Update field values without affecting system fields



In AX if we update any field values in table means it will also change the system fields like Modified DateTime, Modified by.
We also can able to update those table fields without changing those system fields or we can change as per our requirement.

Note: It will update the system fields but this blog is not recommended to update the system fields. Because it will lead to date inconsistency. It may affect few business logic's those written based on the system fields.


In our example i took the Modified date time field.


1. Updating table without modifying system fields :


The following steps will update the sales name field in the “Sales Table”

Steps :

1. Create a new class and set the class property “Run on" as "Server”
2. Create a new method and write the below code in that method
3. Call that method from the place (e.g Forms) you want to update the table.
4. In my example i wrote the method called “SystemFieldsOverwrite” in class name “TestClass” to update the sales name of the particular sales id.


Code: (Class -> TestClass->SystemFieldsOverwrite)


Public str systemFieldsOverwrite(SalesId _salesId,SalesName _salesName)
{
   SalesTable salesTable;
   str Result;
   ;
   salesTable = SalesTable::find(_salesId,true);
   Result += "Before Update the Sales Order\n";
   Result += " Sales ID : " + _salesId+"\n";
   Result += " Sales Name : " + salesTable.SalesName+"\n";
   Result += " Modified DateTime : " + strfmt("%1",salesTable.modifiedDateTime)+"\n";
   ttsbegin;
            new OverwriteSystemfieldsPermission().assert();
           salesTable.overwriteSystemfields(true);
           salesTable.SalesName = _salesName;
           salesTable.(fieldnum(SalesTable,modifiedDateTime)) = salesTable.modifiedDateTime;
           salesTable.doUpdate();
           salesTable.overwriteSystemfields(false);
           CodeAccessPermission::revertAssert();
  ttscommit;
  Result += "After Update the Sales Order\n";
  Result += " Sales ID : " + _salesId+"\n";
  Result += " Sales Name : " + salesTable.SalesName+"\n";
  Result += " Modified DateTime : " + strfmt("%1",salesTable.modifiedDateTime);
  return Result;
}

5. I am calling this particular method from the Job called “SystemFieldTest”.


Code: (Job->SystemFieldTest)


static void SystemFields_Test(Args _args)
{
     TestClass testclass = new TestClass();
     SalesId salesId = "SO-101398";
     SalesName salesname = "Testing";
     str Result;
     ; 
     Result = testclass.SystemFieldsOverwrite(salesId,salesname);
     info(Result);
}

Output:

Here the Sales Name is updated but the Modified date time remains the same.

2. Updating the Modified DateTime as per our requirement.


Instead of passing the existing modified date time in the “systemFieldOverwrite” method we can pass our own date time.

Note: It will update the system fields but this is not recommended to update the system fields. Because it will lead to date inconsistency. It may affect few business logic's those written based on the system fields.

Ex :

salesTable.(fieldnum(SalesTable,modifiedDateTime)) = str2datetime("2010/04/03 11:00:00",321);


Output:

Note : We can able to edit or change "Created DateTime and Created by " fields only at the time of insertion (salesTable.insert()) of a new record.



Thanks for read this blog.


Tuesday, February 4, 2014

Dynamics AX User Roles Retrieval

User Roles retrieval:

 To retrieve the roles of a particular user based on username in AX.

  Tables:
             The user and their roles are relate with three different tables. All three tables are system tables and those tables are listed below,
                             1. SecurityUserRole
                                    2. SecurityRole
                                    3. UserInfo          
            
 Relation:
            The relations between those tables are,
                         1. Userinfo.Networkalias == username
                         2. SecurityUserRole.user == userinfo.id
                         3. SecurityRole.recid == SecurityUserRole.securityrole


The below job is used to List the roles of a particular user by Passing the user name like a parameter.

Code :
       static void retriveUserRoles(Args _args)
      {
          //Tables
         SecurityUserRole    _secUserRole;
         SecurityRole           _secRole;
         UserInfo                 _userInfo;

         //Parameter
         NetworkAlias         _userName = "Admin";
    
         //List to store the roles 
         List userroles = new List(Types::String);

         select  _userInfo where _userInfo.networkAlias==_userName;
        
         while select  _secUserRole where _secUserRole.User==_userInfo.id
        {
           while select  _secRole where _secRole.RecId == _secUserRole.SecurityRole
            {
                  userroles.addEnd(_secRole.Name); //we can also add more role details in List
            }
        }
        setPrefix("The roles assigned for user : " + _userName);   
        info(userroles.toString());   
    }

Output :

       


Thanks for read this blog.