Search This Blog

Monday, May 23, 2022

 Create the User into ActiveDirectory

static void CreateADUSER(Args _args)

{

    System.DirectoryServices DirectoryServices;

    System.DirectoryServices.AccountManagement AccountManagement;

    System.DirectoryServices.AccountManagement.UserPrincipal up;

 

    System.DirectoryServices.AccountManagement.PrincipalContext pricipalContext;

    str networkDomain="KrishhDAX";

    InteropPermission                                               permission;

 

try

{

     permission = new InteropPermission(InteropKind::CLRInterop);

     permission.assert();

    pricipalContext = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType::Domain, "KRISHHDAX", "OU=mDK,OU=Users,OU=TestOU,DC=KrishhDAX,DC=com");

    //Sometimes we need to connect to AD using service/admin account credentials, in that case the above line of code will be as below

    //pricipalContext = new PrincipalContext(ContextType.Domain, "yourdomain.com", "OU=TestOU,DC=yourdomain,DC=com","YourAdminUser","YourAdminPassword");

    up = new System.DirectoryServices.AccountManagement.UserPrincipal(pricipalContext);

    up.set_SamAccountName("krishh");

    up.set_DisplayName("krishh Reddy");

    up.set_EmailAddress(krishh.009@KRISHHDAX.com);

    up.set_GivenName("krishh Reddy");

    up.set_UserPrincipalName(krishh.009@KRISHHDAX.com);

    up.set_Name("Krishh");

    up.set_Surname("Reddy");

    up.set_Description("User Created for testing");

    up.set_Enabled(True);

   

    up.SetPassword("KRISHHDAX#");

    up.Save();

   // info(strFmt("User Created %1",up.get_DisplayName()));

     CodeAccessPermission::revertAssert();

}

catch(Exception::CLRError)

{

       CodeAccessPermission::revertAssert();

        info(CLRInterop::getLastException().ToString());

}

}

Monday, October 22, 2018

Splitting dimension into dimension columns in SQL.

Getting dimension into splitted values

For ledger dimension
Select Dimension,MainAccount,Claims,Functions,ItemGroup,CostCenter,Market_IC,MTO,Projects,Vendor,Agreement from
 (
 select DIMENSIONATTRIBUTEVALUECOMBINATION.recid as dimension,DimensionAttribute.name,DimensionAttributeLevelValueAllView.DisplayValue from DIMENSIONATTRIBUTEVALUECOMBINATION
 join DimensionAttributeLevelValueAllView on DimensionAttributeLevelValueAllView.VALUECOMBINATIONRECID = DIMENSIONATTRIBUTEVALUECOMBINATION.RECID
 join DimensionAttribute on DIMENSIONATTRIBUTE.RecId = DimensionAttributeLevelValueAllView.DIMENSIONATTRIBUTE
 where DIMENSIONATTRIBUTEVALUECOMBINATION.MAINACCOUNT!=0
 ) d
PIVOT
(
 MAX(DisplayValue)
 FOR Name
 IN (MainAccount,Claims,Functions,ItemGroup,CostCenter,Market_IC,MTO,Projects,Vendor,Agreement)
)
AS PivotTable





select DefaultDimension,Claims,Functions,ItemGroup,CostCenter,Market_IC,MTO,Projects,Vendor,Agreement from
(
select DIMENSIONATTRIBUTEVALUECOMBINATION.recid as DefaultDimension,DimensionAttribute.name,DimensionAttributeValueSetItem.DisplayValue from DIMENSIONATTRIBUTEVALUECOMBINATION
join DimensionAttributeValueSet on DimensionAttributeValueSet.RecId = DIMENSIONATTRIBUTEVALUECOMBINATION.RECID
join DimensionAttributeValueSetItem on DimensionAttributeValueSetItem.DIMENSIONATTRIBUTEVALUESET = DimensionAttributeValueSet.RecID
join DimensionAttributeValue on DimensionAttributeValue.RECID = DimensionAttributeValueSetItem.DIMENSIONATTRIBUTEVALUE
join DimensionAttribute on DIMENSIONATTRIBUTE.RecId = DimensionAttributeValue.DIMENSIONATTRIBUTE
where DIMENSIONATTRIBUTEVALUECOMBINATION.MAINACCOUNT=0
) d
PIVOT
(
MAX(DisplayValue)
FOR Name
IN (Claims,Functions,ItemGroup,CostCenter,Market_IC,MTO,Projects,Vendor,Agreement)
)
AS PivotTable

Friday, August 24, 2018

Useful X++ functions



//Return the value from the xmlNode
static str getXmlNodeValue(XmlNode _node)
{
    System.Text.RegularExpressions.Regex re =
    // BP deviation documented
    new System.Text.RegularExpressions.Regex('^[ \r\n\t]*((.|\n)*?)[ \r\n\t]*$');
    System.Text.RegularExpressions.Match m = re.Match(_node.text());
    str result;
    ;

    result = m.Result('$1');
    return result;
}

/// <summary>
/// Provides a lookup of dimension values.
/// </summary>
/// <param name="_ctrl">The control to provide a lookup for.</param>
/// <param name="_dimensionName">The dimension attribute to filter by.</param>
public static client void lookupDimension(FormStringControl _ctrl, Name _dimensionName)
{
    SysTableLookup          sysTableLookup = SysTableLookup::newParameters(tablenum(DimensionAttribute),_ctrl);
    Query                   query = new Query();
    QueryBuildDataSource    queryBuildDataSource = query.addDataSource(tablenum(DimensionAttribute));

    sysTableLookup.addLookupfield(fieldnum(DimensionAttribute, Name));

    queryBuildDataSource.addRange(fieldnum(DimensionAttribute, Type)).value(queryNotValue(DimensionAttributeType::MainAccount));

    sysTableLookup.parmQuery(query);
    sysTableLookup.performFormLookup();

}


/// <summary>
/// This method has the complete source file as input and will concatenate the target path with the filename
/// </summary>
/// <param name="_sourceFilename">
///  This is the full filename including the path
/// </param>
/// <param name="_targetPath">
///  the target folder
/// </param>
/// <returns>
///  It will return the target filename.
/// </returns>

static filename getTargetFilename(Filename _sourceFilename, Filepath _targetPath)
{
    Filename    targetFilename;
    ;
    new InteropPermission(InteropKind::ClrInterop).assert();

    targetFilename = System.IO.Path::Combine(_targetPath, System.IO.Path::GetFileName(_sourceFilename));

    return targetFilename;
}


// Generate nodes into container.
static container containerFromXMLNode(XmlNode n)
{
    container retval, containerToInsert;
    Common recordToInsert;
    XmlNamedNodeMap attrs;
    XmlNode typeAttr, element, recordNode, containerNode;
    int elemNo = 1;
    ;
    //validate arguments before using them
    if (n == null)
        return retval;

    // Collect all the elements ...
    element = n.firstChild();
    if (element.name() == 'container')
    {
        element = element.firstChild();
    }
    while (element)
    {
        attrs = element.attributes();
        if (attrs)
        {
            typeAttr = attrs.getNamedItem('type');

            switch (typeAttr.nodeValue())
            {
                case 'int'      :
                    retval = conins(retval, elemNo, str2int(BisTools::getXmlNodeValue(element)));
                    break;

                case 'str'      :
                    retval = conins(retval, elemNo, BisTools::getXmlNodeValue(element));
                    break;

                case 'real'     :
                    retval = conins(retval, elemNo, str2num(BisTools::getXmlNodeValue(element)));
                    break;

                case 'enum':
                    retval = conins(retval, elemNo, str2int(BisTools::getXmlNodeValue(element)));
                    break;

                case 'date'     :
                    retval = conins(retval, elemNo, str2date(BisTools::getXmlNodeValue(element), 321));
                    break;

                case 'record'   :
                    recordNode = element.firstChild();
                    recordToInsert = Global::recordFromXMLNode(recordNode);
                    retval = conins(retval, elemNo, recordToInsert);
                    break;

                case 'container':
                    containerNode = element.firstChild();
                    containerToInsert = BisTools::containerFromXMLNode(containerNode);
                    retval = conins(retval, elemNo, containerToInsert);
                    break;

                case 'blob':
                    containerToInsert = BinData::stringToData(BisTools::getXmlNodeValue(element));
                    retval = conins(retval, elemNo, containerToInsert);
                    break;
            }
        }

        element = element.nextSibling();
        elemNo += 1;
    }

    return retval;
}




//Generate html from Record
static str record2html(Common record)
{
    str html;
    DictTable   dictTable = new dictTable(record.TableId);
    DictField   dictField;
    fieldId     fieldId;


    void addField2html(str fieldName, anyType fieldValue, str htmlCode, str fieldLabel)
    {
        str newValue = strFmt('%1',fieldValue);
        if (newValue == '')
        {
            newValue = '-';
        }
        html += strFmt('<tr><td width=30%>%3%4</td><td width=50%>%3%2</td><td width=20%>%3%1</td></tr>',fieldName, newValue , htmlCode, fieldLabel);
    }
    ;
    html = '<html><b>Record values<table border width=100%>';
    addField2html('Field name','Value','<b>','Label');

    fieldId = dictTable.fieldNext(0);
    while (fieldId)
    {
        dictField = dictTable.fieldObject(fieldId);
        if (dictField.arraySize() == 1 && dictField.baseType() != Types::Container && dictField.baseType() != Types::BLOB)
        {
            addField2html(dictField.name(), record.(fieldId),"", dictField.label());
        }
        fieldId = dictTable.fieldNext(fieldId);
    }


    html+='</table></html>';
    return html;
}




//Generate record to Text
static str record2text(Common record)
{
    str         text;
    DictTable   dictTable = new dictTable(record.TableId);
    DictField   dictField;
    fieldId     fieldId;


    void addField2text(str fieldName, anyType fieldValue, str fieldLabel)
    {
        str newValue = strFmt('%1',fieldValue);
        if (newValue == '')
        {
            newValue = '-';
        }
        text += strFmt('Field \'%1\' = \'%2\', Label: \'%3\'\n',fieldName, newValue, fieldLabel);
    }
    ;
    text = strFmt("@BIS635", tableid2name(record.tableId));
    addField2text('Field name','Value', 'Label');

    fieldId = dictTable.fieldNext(0);
    while (fieldId)
    {
        dictField = dictTable.fieldObject(fieldId);
        if (dictField.arraySize() == 1)
        {
            addField2text(dictField.name(), record.(fieldId), dictField.label());
        }
        fieldId = dictTable.fieldNext(fieldId);
    }


    return text;
}


//Create the table record from xmlnode
// Input is <Record table="name"> <Field:field1> value </Field:field1> ... </Record>
// it's the opposite from record.xml() method
static Common xml2record(XmlNode n, Common c = null)
{
    tableId table;
    fieldId field;
    DictTable dt;
    DictField df;
    XmlNode fieldNode;
    str fieldName;
    Struct content;
    str tableName;
    Types t;

    //validate arguments before using them
    if (n == null)
        return null;
    // If we don't have an incoming buffer, one is created
    if (prmisdefault(c))
    {
        // Create a buffer of the correct type
        tableName = n.name();
       // tableName = n.attributes().getNamedItem('name');

        // Check if table node can be accessed
        if (tableName != '')
        {
            table = tablename2id(tableName);
            dt = new DictTable(table);
            c = dt.makeRecord();
        }
    }
    else
    {
        table = c.TableId;
        dt = new DictTable(table);
    }

    fieldNode = n.firstChild();
    while (fieldNode)
    {
        fieldName = fieldNode.attributes().getNamedItem('name').text();
        field = dt.fieldName2Id(fieldName);
        df = new DictField(table, field);

        t = df.baseType();
        if (t == Types::Enum) //Enums need to be treated as Integers. By defult, Enums are getting treated as a boolean and hence loosing its value.
            t = Types::Integer;

        content = BisTools::valueFromXMLNode (t, fieldNode);

        c.(field) = content.value('value');

        fieldNode = fieldNode.nextSibling();
    }
    return c;
}

//Get next working date from the date .
public static date GetNextWorkDay(date _fromDate)
{
    WorkCalendarDate    workCalendar;
    ;

    select firstOnly TransDate from workCalendar
    order by TransDate ASC
        where workCalendar.TransDate > _fromDate
           && workCalendar.WorkTimeControl == WorkTimeControl::Open;

    return workCalendar.TransDate;
}


/// <summary>
///     Attempts to find executatble for file type specified, and open file with it.
/// </summary>
/// <param name="_filename">
///     File name to show
/// </param>
public static client void showFile(Filename _filename)
{
    str filePath, fileName, fileExt, executable;
    if (System.IO.File::Exists(_filename))
    {
        [filePath, filename, fileExt] = fileNameSplit(_filename);
        executable = WinAPI::findExecutable(_filename);
        if (!executable)
        {
            error(strFmt("Windows were not able to find executable for file %1", _filename));
            return;
        }
        if (fileExt == '.msg')
            WinAPI::shellExecute(strFmt('"%1"', executable),strFmt('/f "%1"', _filename),strFmt('"%1"', filePath)); // outlook requires extra parameter  /f
        else
            WinAPI::shellExecute(strFmt('"%1"', executable),strFmt('"%1"', _filename),strFmt('"%1"', filePath));
    }
    else
    {
        error("File not found");
    }
}





/// <summary>
///     Converts enum value to enum label in language specified
/// </summary>
/// <param name="enumId">
///     Enum Id
/// </param>
/// <param name="value">
///     Enum value
/// </param>
/// <param name="languageId">
///     Language for label
/// </param>
/// <returns>
///     Label of enum value in language specified
/// </returns>
public static str enum2Label(EnumId enumId, int value, LanguageId languageId = SrsReportRunUtil::getCurrentUserLangId())
{
    DictEnum dictEnum;
    int      valueIndex, valueBuf;
    ;
    dictEnum = new DictEnum(enumId);
    if (dictEnum)
    {

        for (valueIndex = 0 ; valueIndex < dictEnum.values(); valueIndex++)
        {
            valueBuf = dictEnum.index2Value(valueIndex);
            if (valueBuf == value)
                return SysLabel::labelId2String(dictEnum.index2LabelId(valueIndex), languageId);
        }
    }
    return '';
}


/// <summary>
///     Converts time value into string with hours and minutes. Mostly used when generating file names
/// </summary>
/// <param name="time">
///     Time as integer
/// </param>
/// <returns>
///     Time converted to string in format HHMM
/// </returns>
public static TempStr time2StrHM(int time)
{
    return num2str( time div 3600       ,2,0,0,0) + num2Str0(time mod 3600 div 60,2,0,0,0);
}

/// <summary>
///     Converts any value to string. This is hardcoded conversion without using culture context
/// </summary>
/// <param name="_value">
///     The value to convert
/// </param>
/// <returns>
///     Converted value as string
/// </returns>
public static str any2String(anytype _value)
{
    switch(typeOf(_value))
    {
        // BP deviation documented
        case Types::Date: return date2str(_value, -1,-1,-1,-1,-1,-1,DateFlags::None);
        case Types::Time: return KrishhUtils::time2StrHM(_value);
        case Types::Int64, Types::Integer: return int2str(_value);
        case Types::Real: return strFmt('%1', _value);
        case Types::Enum: return strFmt('%1', _value);
        case Types::UtcDateTime: return DateTimeUtil::toStr(DateTimeUtil::applyTimeZoneOffset(_value, DateTimeUtil::getUserPreferredTimeZone())); // Hotfix 52
        default: return strFmt('%1', _value);
    }
    return "";
}


/// <summary>
///     Checks full path, and if \ is missing at the end - adds it
/// </summary>
/// <param name="path">
///     Full path to analyse
/// </param>
/// <returns>
///     Full path with \ at the end
/// </returns>
public static str fixPath(str path)
{
    str buf = strLRTrim(path);
    if (!path)
        return "";
    if (subStr(buf, strLen(buf),1) != '\\')
        buf = buf + '\\';
    return buf;
}

/// <summary>
///     Generates temporrary file with extension. Also creates file and saves it.
/// </summary>
/// <param name="filePrefix">
///     File prefix to use
/// </param>
/// <param name="extension">
///     Extension to use
/// </param>
/// <param name="filePath">
///     File path to use
/// </param>
/// <returns>
///     Created temporrary file name
/// </returns>
/// <remarks>
///     Creates empty file with unique name. Safe to use with multiple threads
/// </remarks>
/// <exception cref="Exception::Error">
///     When 10 attempts to create file failed
/// </exception>
/// <exception cref="Exception::Error">
///     When 10 attempts to create file failed
/// </exception>
public static str getTempFile(str filePrefix, str extension, str filePath = '')
{
    #File
    str                  tmpPath;
    str                  fileName;
    System.IO.FileStream fileStream;
    boolean              ok;
    int                  i;

    if (filePath)
        tmpPath = KrishhUtils::fixPath(filePath);
    else
    {
        new InteropPermission(InteropKind::ClrInterop).assert();
        tmpPath = System.IO.Path::GetTempPath();
        CodeAccessPermission::revertAssert();
    }
    while(!ok)
    {
        fileName = tmpPath + (filePrefix?filePrefix:filePrefix + guid2str(newGuid())) + extension; // First attempt direct
        new InteropPermission(InteropKind::ClrInterop).assert();
        while(System.IO.File::Exists(fileName))
        {
            fileName = tmpPath + filePrefix + guid2str(newGuid()) + extension;
        }
        CodeAccessPermission::revertAssert();
        try
        {
            i++;
            if (i>10)
                throw Exception::Error;
            new FileIOPermission(fileName, #IO_WRITE).assert();
            fileStream = System.IO.File::Create(fileName);
            fileStream.Dispose();
            CodeAccessPermission::revertAssert();
            ok = true;
        }
        catch (Exception::Error)
        {
            throw error("@SYS326095");
        }
        catch
        {
            exceptionTextFallThrough();
            CodeAccessPermission::revertAssert();
        }
    }

    return fileName;
}



/// <summary>
///     Returns the number associated with the specified month name.
/// </summary>
/// <param name="_monthName">
/// The name of the month.
/// </param>
/// <returns>
/// The number associated with the month name.
/// </returns>
public static int monthUSName2Num(str _monthName)
{
    int ret;
    str monthName = _monthName;
    #Define.month1('january')
    #Define.jan('jan')
    #Define.month2('february')
    #Define.feb('feb')
    #Define.month3('march')
    #Define.mar('mar')
    #Define.month4('april')
    #Define.apr('apr')
    #Define.month5('may')
    #Define.month6('june')
    #Define.jun('jun')
    #Define.month7('july')
    #Define.jul('jul')
    #Define.month8('august')
    #Define.aug('aug')
    #Define.month9('september')
    #Define.sep('sep')
    #Define.month10('october')
    #Define.oct('oct')
    #Define.month11('november')
    #Define.nov('nov')
    #Define.month12('december')
    #Define.dec('dec');

    monthName = strLwr(_monthName);

    switch(monthName)
    {
        case #month1:
        case #jan:
            ret = 1;
            break;
        case #month2:
        case #feb:
            ret = 2;
            break;
        case  #month3:
        case #mar:
            ret = 3;
            break;
        case #month4:
        case #apr:
            ret = 4;
            break;
        case #month5:
            ret = 5;
            break;
        case #month6:
        case #jun:
            ret = 6;
            break;
        case #month7:
        case #jul:
            ret = 7;
            break;
        case #month8:
        case #aug:
            ret = 8;
            break;
        case #month9:
        case #sep:
            ret = 9;
            break;
        case #month10:
        case #oct:
            ret = 10;
            break;
        case #month11:
        case #nov:
            ret = 11;
            break;
        case #month12:
        case #dec:
            ret = 12;
            break;
        default:
            ret = 0;
            break;
    }
    return ret;
}


Get DimensionAttribute by providing the dimensionnumber



public static dimensionAttribute getDimensionByNumber(int _dimensionNumber)
{
    RecId companyLedger =  Ledger::findByLegalEntity(CompanyInfo::findDataArea(curext()).RecId).RecId;
    DimensionAttribute dimensionAttribute;
    Query query = new Query();
    QueryBuildDataSource qbd;
    QueryRun qr;
    ;
    if (! _dimensionNumber)
    {
        return dimensionAttribute;
    }
    qbd = query.addDataSource(tableNum(dimensionAttribute));
    qbd.fields().dynamic(false);
    qbd.fields().addField(fieldNum(dimensionAttribute, Name));
    qbd.addOrderByField(fieldNum(dimensionAttribute, Name));
    qbd.addGroupByField(fieldNum(dimensionAttribute, Name));
    qbd.addRange(fieldNum(dimensionAttribute, RecId)).value(queryNotValue(DimensionAttribute::getMainAccountDimensionAttribute()));
    qbd = qbd.addDataSource(tableNum(dimensionHierarchyLevel));
    qbd.fields().dynamic(true);
    qbd.relations(true);

    qbd = qbd.addDataSource(tableNum(ledgerStructure));
    qbd.relations(false);
    qbd.addLink(fieldNum(dimensionHierarchyLevel, DimensionHierarchy), fieldNum(ledgerStructure, DimensionHierarchy));
    qbd.addRange(fieldNum(ledgerStructure, Ledger)).value(queryvalue(companyLedger));

    qr = new QueryRun(query);
    qr.enablePositionPaging(true);
    qr.addPageRange(_dimensionNumber,1);
    if (qr.next())
    {
        dimensionAttribute = qr.getNo(1);
    }
    return dimensionAttribute;
}

Wednesday, May 30, 2018

Create Non clusterindex in Ax with include keyword.

Create non clustered index with include keyword suggestion given by query plan

 Index with Included Columns
You can extend the functionality of nonclustered indexes by adding nonkey columns to the leaf level of the nonclustered index. By including nonkey columns, you can create nonclustered indexes that cover more queries. This is because the nonkey columns have the following benefits:
•    They can be data types not allowed as index key columns.
•    They are not considered by the Database Engine when calculating the number of index key columns or index key size.
An index with included nonkey columns can significantly improve query performance when all columns in the query are included in the index either as key or nonkey columns. Performance gains are achieved because the query optimizer can locate all the column values within the index; table or clustered index data is not accessed resulting in fewer disk I/O operations.


Issue

Whenever a synchronization is done, AX overwrites the indexes which we put through SQL

Resolution

a. Created the index via AX as a table method


public static server void createSqlIndexes()
{

SqlStatementExecutePermission SqlStatementExecutePermission;
str createIndexSql;

Connection connection=new Connection(); Statement statement=connection.createStatement();
createIndexSql=
@"IF EXISTS(select * from sys.indexes where object_id=OBJECT_ID(N'[dbo].[InventDIM]')

AND NAME=N'sonIdx' )
DROP INDEX [sonIdx] on [dbo].[InventDIM] WITH (ONLINE=OFF)
CREATE NONCLUSTERED INDEX [sonIdx] ON [dbo].[INVENTDIM] ([INVENTBATCHID],[WMSLOCATIONID],[INVENTSERIALID],[INVENTSIZEID],[INVENTCOLORID],[INVENTGTDID_RU],[INVENTPROFILEID_RU],[INVENTOWNERID_RU],[INVENTSTYLEID],[LICENSEPLATEID],[INVENTSTATUSID],[DATAAREAID],[PARTITION],[INVENTLOCATIONID],[CONFIGID],[INVENTSITEID])
INCLUDE ([INVENTDIMID])
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)";


SqlStatementExecutePermission=new SqlStatementExecutePermission(createIndexSql);
SqlStatementExecutePermission.assert();
statement.executeUpdate(createIndexSql);
CodeAccessPermission::revertAssert();
}

Execute this code in the application class dbsynchronize method at the end of the method after standard dbsynch done. so that we will have an sql index.



Monday, July 17, 2017

Read xml file with namespace

static void krishh_samplexmlread(Args _args)
{
     XmlNode root;
     XmlNode book;
     XmlNodeList books;
     XmlNamespaceManager nsmgr;

     XmlDocument doc = new XmlDocument();
      int i=1;
      doc.Load(@"C:\Temp\book.xml");

      //Create an XmlNamespaceManager for resolving namespaces.
      nsmgr = new XmlNamespaceManager(doc.NameTable());
      nsmgr.AddNamespace("bk", "urn:samples");

      //Select the book node with the matching attribute value.


      root = doc.DocumentElement();

      books = root.selectNodes("descendant::book", nsmgr);
      for (i = 0; i < books.length(); i++)
      {
           book = books.item(i);
              info(book.selectSingleNode("bk:first-name").text());
              info(book.selectSingleNode("bk:last-name").text());


      }

}

//<?xml version="1.0"?>
//
//<!-- A fragment of a book store inventory database -->
//
//-<bookstore xmlns:bk="urn:samples">
//
//
//-<book bk:ISBN="1-861001-57-8" publicationdate="1997" genre="novel">
//
//<title>Pride And Prejudice</title>
//
//
//-<author>
//
//<first-name>Jane</first-name>
//
//<last-name>Austen</last-name>
//
//</author>
//
//<price>24.95</price>
//
//</book>
//
//
//-<book bk:ISBN="1-861002-30-1" publicationdate="1992" genre="novel">
//
//<title>The Handmaid's Tale</title>
//
//
//-<author>
//
//<first-name>Margaret</first-name>
//
//<last-name>Atwood</last-name>
//
//</author>
//
//<price>29.95</price>
//
//</book>
//
//
//-<book bk:ISBN="1-861001-57-6" publicationdate="1991" genre="novel">
//
//<title>Emma</title>
//
//
//-<author>
//
//<first-name>Jane</first-name>
//
//<last-name>Austen</last-name>
//
//</author>
//
//<price>19.95</price>
//
//</book>


//-<book bk:ISBN="1-861001-45-3" publicationdate="1982" genre="novel">
//
//<title>Sense and Sensibility</title>
//
//
//-<author>
//
//<first-name>Jane</first-name>
//
//<last-name>Austen</last-name>
//
//</author>
//
//<price>19.95</price>
//
//</book>
//
//</bookstore>

Thursday, April 20, 2017

AX2012 Run AIF Single Message manually

Execute single message for inbound without executing all inbound ports.

class Krishh_InboundParallelMsgProcessPerMsgId extends AifInboundParallelMsgProcess
{
    RecId                   gatewayQueueRecId;
    DialogField             dlgfRecId;
    AifMessageId            messageId;
}

protected Object dialog()
{
    DialogRunbase       dialogRunbase;

    dialogRunbase   = super();
    dialogRunbase.caption(AifInboundParallelMsgProcess::description());

    dialogRunbase.addText("Runbase framework doesnt allow Guid type fields");
    dialogRunbase.addText("reference field shows the gatewayqueue record");

    dlgfRecId   = dialogRunbase.addField(extendedTypeStr(AifGatewayQueueRecId));
    dlgfRecId.lookupButton(2);

    return dialogRunbase;
}

public AifGatewayQueue findGatewayQueue(RecId  _recId)
{
    AifGatewayQueue     aifGatewayQueue;

    select aifGatewayQueue
        where aifGatewayQueue.RecId == _recId;

    return aifGatewayQueue;
}

public boolean getFromDialog()
{
    boolean ret;

    ret = super();

    gateWayQueueRecId = dlgfRecId.value();

    return ret;
}

public AifMessageId parmMessageId(AifMessageId _messageId = messageId)
{
    messageId = _messageId;

    return messageId;
}

public void run()
{
    if (gatewayQueueRecId != 0 && messageId == emptyGuid())
    {
        messageId = this.findGatewayQueue(gateWayQueueRecId).MessageId;
    }

    try
    {
        ttsBegin;

        if (messageId != emptyGuid())
        {
            this.runSingleMsgId(messageId);
            AifQueueManager::createQueueManagerData();
        }
        else
        {
            throw error ("invalid message id please enter valid messageid");
        }

        ttsCommit;
    }
    catch
    {
        throw error("process has been aborted");
    }
}

private void runSingleMsgId(AifMessageId    _messageId)
{
    AifGatewayQueue         gatewayQueue;
    AifInboundMsgProcess    inboundMsgProcess;
    AifResourceLockId       resourceLockId;
    ;

    setprefix(classstr(InboundParallelMsgProcessPerMsgId) + '-' + methodstr(Krishh_InboundParallelMsgProcessPerMsgId , run));

    select firstOnly gatewayQueue
        where gatewayQueue.MessageId == _messageId;

    if (gatewayQueue)
    {
        resourceLockId = AifResourceLock::lockResource(guid2str(gatewayQueue.MessageId),
                                                       AifResourceType::Message,
                                                       AifResourceLockType::DocumentService);

        // Process message only if lock is created.
        if(resourceLockId)
        {
            AifResourceIdMap::createMsgResourceMap(guid2str(gatewayQueue.MessageId), gatewayQueue.MessageId);

            // remember selected record
            inboundMsgProcess = new AifInboundMsgProcess(gatewayQueue.data(), resourceLockId);

         

            inboundMsgProcess.run();
        }
    }
}

public boolean validate(Object calledFrom = null)
{
    boolean             ret;

    ret = super(calledFrom);

    if (this.findGatewayQueue(gateWayQueueRecId).RecId == 0)
    {
        throw error("Queue not found");
    }

    return ret;
}

public static Krishh_InboundParallelMsgProcessPerMsgId construct()
{
    return new Krishh_InboundParallelMsgProcessPerMsgId ();
}

public static void main(Args args)
{
    Krishh_InboundParallelMsgProcessPerMsgId inboundParallelMsgProcessPerMsgId;

    inboundParallelMsgProcessPerMsgId = Krishh_InboundParallelMsgProcessPerMsgId ::construct();

    if (inboundParallelMsgProcessPerMsgId.prompt())
    {
        inboundParallelMsgProcessPerMsgId.run();
    }
}

AX2012 Actiavte/Deactivate Ports using X++

create enum 1. AIFPortActivorDeactive  with Acivate,Decativate as enumvalues.
                    2. AIF portType with inbound and Outbound as enumvalues.

class krishhAIFPortsUtil extends RunBaseBatch
{
    Map serviceStatusMap;
    Map portWsdlUrlMap;
    AIFPortActivorDeactive portActiveorDeactive;
    AIFPortType aifPortType;


    DialogField     dlgActiveorDeactive;
    DialogField     dlgaifPortType;

    #define.CurrentVersion(1)
    #define.Version1(1)
    #localmacro.CurrentList
        portActiveorDeactive,
        aifPortType
    #endmacro
}

private void deployInboundPort(AifInboundPort port)
{
        startLengthyOperation();
        AifPortManager::deployPort(port.Name);
        this.updateServiceHostStatus();
        endLengthyOperation();
}

private void deployOutboundPort(AifOutboundPort port)
{
    startLengthyOperation();
    AifPortManager::deployPort(port.Name);
    endLengthyOperation();
}


public Object dialog()
{
    DialogRunbase       dialog = super();
    #resAppl
;

    dlgActiveorDeactive=dialog.addField(enumStr(AIFPortActivorDeactive), "Activate/Deactivate");
    dlgaifPortType=dialog.addField(enumStr(AIFPortType), "PortType");
    return dialog;
}

public boolean getFromDialog()
{
;
    portActiveorDeactive=dlgActiveorDeactive.value();
    aifPortType=dlgaifPortType.value();
    return super();
}

str getPortRuntimeError(AifInboundPort port)
{
    str serviceTypeName, status;
    boolean isPortStarted = false;
#Aif

    if (port.Deployed)
    {
        serviceTypeName = strFmt('%1.%2', #DotNetServiceNamespace, port.Name);

        if (!serviceStatusMap)
        {
            // If the map is null, then the IL appDomain does not exist and services are not available
            status = strFmt("@SYS345108");
        }
        else if (serviceStatusMap.exists(serviceTypeName))
        {
            status = serviceStatusMap.lookup(serviceTypeName);
            isPortStarted = strStartsWith(status, #WcfCommunicationState_Opened);
        }
    }

    return isPortStarted?"":status;
}

// BP deviation documented
str getPortWsdlUrl(AifInboundPort port)
{
    str wsdlUrl = '';
    AifPortName portName;
    AifWcfAdapter wcfAdapter;

    if (port.Deployed)
    {
        portName = port.Name;

        if (portWsdlUrlMap.exists(portName))
        {
            wsdlUrl = portWsdlUrlMap.lookup(portName);
        }
        else
        {
            wcfAdapter = AifWcfAdapter::getWcfAdapterForPort(port);

            if (wcfAdapter != null)
            {
                wsdlUrl = wcfAdapter.getWsdlUrl(port.ChannelId, port.Name);
            }

            portWsdlUrlMap.insert(portName, wsdlUrl);
        }
    }

    return wsdlUrl;
}

// BP deviation documented
boolean isPortRunning(AifInboundPort port)
{
    str serviceTypeName, status;
    boolean isPortStarted = false;
#Aif

    if (port.Deployed)
    {
        serviceTypeName = strFmt('%1.%2', #DotNetServiceNamespace, port.Name);

        // If the map is null, then the IL appDomain does not exist and services are not available
        if (serviceStatusMap && serviceStatusMap.exists(serviceTypeName))
        {
            status = serviceStatusMap.lookup(serviceTypeName);
            isPortStarted = strStartsWith(status, #WcfCommunicationState_Opened);
        }
    }

    return isPortStarted;
}

public container pack()
{
    return [#CurrentVersion,#CurrentList];
}

public boolean unpack(container packedClass)
{
    Version version = RunBase::getVersion(packedClass);
;
    switch (version)
    {
        case #CurrentVersion:
            [version,#CurrentList] = packedClass;
            break;
        default:
            return false;
    }

    return true;
}

public AIFPortType parmAifPortType(AIFPortType _aifPortType = aifPortType)
{
    aifPortType = _aifPortType;

    return aifPortType;
}

public AIFPortActivorDeactive parmPortActiveorDeactive(AIFPortActivorDeactive _portActiveorDeactive = portActiveorDeactive)
{
    portActiveorDeactive = _portActiveorDeactive;

    return portActiveorDeactive;
}

public void portinit()
{
    AifSetup::initialize();
    // Register out of the box adapters
    AifSetup::registerOutOfTheBoxAdapters();

    portWsdlUrlMap = new Map(Types::String, Types::String);
}

/// <summary>
///    Contains the code that does the actual job of the class.
/// </summary>
public void run()
{
    #OCCRetryCount
    AifInboundPort AifInboundPort;

    AifOutboundPort AifOutboundPort;

    try
    {
        this.updateServiceHostStatus();
        switch (aifPortType)
        {
            case AIFPortType::Inbound:
                if(AIFPortActivorDeactive::Activate==portActiveorDeactive)
                {
                    while select AifInboundPort //where AifInboundPort.PortCategory==AifPortCategory::Enhanced
                    {

                          if(this.isPortRunning(AifInboundPort))
                          {
                              this.portinit();
                              this.deployInboundPort(AifInboundPort);
                              if(this.getPortRuntimeError(AifInboundPort)!="")
                              {
                                  info(strFmt("@krishh1896",AifInboundPort.Name,this.getPortRuntimeError(AifInboundPort)));
                              }
                          }
                    }
                }
                else
                {
                    while select AifInboundPort where AifInboundPort.PortCategory==AifPortCategory::Enhanced
                    {
                          this.portinit();
                          this.undeployInboundPort(AifInboundPort);
                    }
                }
             break;
            case AIFPortType::OutBound:
                if(IFPortActivorDeactive::Activate==portActiveorDeactive)
                {
                    while select AifOutboundPort
                    {
                              this.portinit();
                              this.deployOutboundPort(AifOutboundPort);

                    }
                }
                else
                {
                    while select AifOutboundPort
                    {
                          this.portinit();
                          this.unDeployOutboundPort(AifOutboundPort);
                    }
                }
            break;
            default:
            throw error(strfmt("@SYS12580",aifPortType));



        }
    }
    catch (Exception::Deadlock)
    {
        retry;
    }
    catch (Exception::UpdateConflict)
    {
        if (appl.ttsLevel() == 0)
        {
            if (xSession::currentRetryCount() >= #RetryNum)
            {
                throw Exception::UpdateConflictNotRecovered;
            }
            else
            {
                retry;
            }
        }
        else
        {
            throw Exception::UpdateConflict;
        }
    }

}

private void undeployInboundPort(AifInboundPort port)
{
        startLengthyOperation();
        AifPortManager::undeployPort(port.Name);
        this.updateServiceHostStatus();
        //this.clearPortWsdlUrl(port);
        endLengthyOperation();
}

private void unDeployOutboundPort(AifOutboundPort port)
{
    startLengthyOperation();
    AifPortManager::undeployPort(port.Name);
    endLengthyOperation();
}
public void updateServiceHostStatus()
{
    // If the map is null, then the IL appDomain does not exist and services are not available
    serviceStatusMap = appl.getServiceHostStatus();
}

static krishhAIFPortsUtil construct()
{
    return new krishhAIFPortsUtil();
}
public static void main(Args _args)
{
    krishhAIFPortsUtil  krishhAIFPortsUtil ;
;
    krishhAIFPortsUtil = krishhAIFPortsUtil  ::construct();

    if (krishhAIFPortsUtil .prompt())
        krishhAIFPortsUtil .run();
}

public static void mainAutoRun(str _args)
{
    krishhAIFPortsUtil aifPortsUtil;
    ;
    aifPortsUtil = krishhAIFPortsUtil ::construct();

    if (!_args)
        return;

    switch(_args)
    {
        case('activate') :
            {
                aifPortsUtil.parmPortActiveorDeactive(AIFPortActivorDeactive::Activate);
            }

        case('deactivate') :
            {
                aifPortsUtil.parmPortActiveorDeactive(AIFPortActivorDeactive::Deactivate);
            }
    }

    aifPortsUtil.run();
}

AX2012 Export ActiveDirectory Data to file.


Created the framework class called ADReader which reads the data from ActiveDirectory of current domains in the nework that connected.

static void krishh_ADExportToCSV(Args _args)
{
    AxaptaUserManager mgr;
    container domainNames;
    int i;
    int domainCount;
    str name;
    System.Collections.ArrayList domains = new System.Collections.ArrayList();

    TextIo          ioData;
    FileIOPermission permission;
    str filename = "c:\\temp\\tmotest_"+FileUtil::createFilenameTimeStamp()+".csv";

    ADReader    adReader = new ADReader();
    map costcenter = new Map(types::String, types::String);
    str key;

    #File

    permission = new FileIOPermission(filename,  #io_write);
    permission.assert();

    // Open file for writing
    ioData = new TextIo(filename, #io_write);

    // Check file open status
    if (!ioData)
    {
        // File '%1' could not be opened.
        throw error(strfmt("@SYS19312", filename));
    }

    // Set file delimiters
    ioData.outRecordDelimiter('\r\n');
    ioData.outFieldDelimiter(';');
    ioData.write(
        [
          "Domain"
        , "Company"
        , "Country"
        , "DepartmentNumber"
        , "EmployeeType"
        , "Mail"
        , "Manager"
        , "Manager_Converted"
        , "GivenName"
        , "Sn"
        , "TelephoneNumber"
        , "UserId"
        , "samAccountName"
        , "EmployeeNumber"
        , "EmployeeNumber_Converted"
        , "Disabled"
        , "MemberOf"
        , "ADGroups"
        ]);


    mgr = new AxaptaUserManager();
    // Get the names of the domains from the kernel class
    domainNames = mgr.enumerateDomains('');
    if(domainNames)
    {
        domainCount = conLen(domainNames);
        // Add all the domain names to the domains combo box
        // dual loop to sort the domains alphabetically using the default comparator
        if(domainCount > 0)
        {
            domains.Clear();
            for(i = 0; i < domainCount; i++)
            {
                if (conPeek(domainNames, i+1) == "Krishhdax.com")
                {
                    adReader.reset();
                    adReader.parmSelectedDomainName(conPeek(domainNames, i+1));

                    while(adReader.next())
                    {
                        if (   adReader.getEmployeeType() == "Employee Master Account"
                            || adReader.getEmployeeType() == "Consultant Master Account")
                        {
                            ioData.write(
                            [
                              adReader.parmSelectedDomainName()
                            , adReader.getCompany()
                            , adReader.getCountry()
                            , adReader.getDepartmentNumber()
                            , adReader.getEmployeeType()
                            , adReader.getMail()
                            , adReader.getManager()
                            , subStr(adReader.getManager()
                                     , strfind(adReader.getManager(), "CN=", 1, strLen(adReader.getManager()))+3
                                     , strfind(adReader.getManager(), ",", strfind(adReader.getManager(), "CN=", 1, strLen(adReader.getManager())), strLen(adReader.getManager())) - strfind(adReader.getManager(), "CN=",1 , strLen(adReader.getManager())) - 3
                                    )
                            , adReader.getGivenName()
                            , adReader.getSn()
                            , adReader.getTelephoneNumber()
                            , adReader.getUserId()
                            , adReader.getsamAccountName()
                            , adReader.getEmployeeNumber()
                            , subStr(adReader.getEmployeeNumber(), 4, 255)
                            , adReader.getDisabled()
                            , con2Str(adReader.getMemberOf())
                            , con2Str(adReader.getADGroups())
                            ]);
                        }
                    }
                }
            }
        }
    }

    CodeAccessPermission::revertAssert();
}




class ADReader
{
    System.DirectoryServices.DirectorySearcher          directorySearcher;
    System.DirectoryServices.SearchResultCollection     searchResultCollection;
    System.DirectoryServices.SearchResult               searchResult;
    System.DirectoryServices.DirectoryEntry             entry;
    System.DirectoryServices.PropertyValueCollection    propertyValueCollection;
    System.DirectoryServices.SearchScope                searchScope;
    str                                                 selectedDomainName;
    str                                                 prefix;
    str                                                 criteria;
    Filename            filename;

    System.Collections.Specialized.StringCollection  propertyList;
    System.DirectoryServices.PropertyCollection      propertyCollection;
    int                                              numberOfUsers, currentUserNumber;

    NetworkAlias                                    networkAlias;
    Description                                     company;
    Description                                     department;
    Description                                     title;
    Email                                           mail;
    Name                                            givenName;
    str                                             manager, departmentNumber, telephoneNumber, userId, sn, employeeType, employeeNumber, country, samAccountName;
    container                                       memberOf, adGroups;
    Integer                                         userAccountControl;

}
public container getADGroups()
{
    str memberOfStr, searchStr;
    Counter pos, posCount;

    Counter posFrom, posTo, searchStrLen;


    if (!ADGroups)
    {
        searchStr = 'CN=';
        searchStrLen = strLen(searchStr);

        posCount = conlen(memberOf);
        for (Pos=1; pos<=posCount;pos++)
        {
            memberOfStr = conpeek(memberOf, pos);

            posTo = 0;
            posFrom = strScan(memberOfStr, searchStr, posTo, strLen(memberOfStr));
            while (posFrom)
            {
                posTo = strScan(memberOfStr, ',', posFrom, strLen(memberOfStr));
                ADGroups += [subStr(memberOfStr, posFrom+searchStrLen, posTo-posFrom-searchStrLen)];
                posFrom = strScan(memberOfStr, searchStr, posTo, strLen(memberOfStr));
            }
        }
    }

    return ADGroups;
}
private void setSearchPropertyList(System.DirectoryServices.DirectorySearcher _directorySearcher)
{
    propertyList = _directorySearcher.get_PropertiesToLoad();
    propertyList.Add('samaccountname');
    propertyList.Add('company');
    propertyList.Add('department');
    propertyList.Add('title');
    propertyList.Add('displayName');
    propertyList.Add('distinguishedName');
    propertyList.Add('objectClass');
    propertyList.Add('member');
    propertyList.Add('manager');
    propertyList.Add('mail');
    propertyList.Add('telephoneNumber');
    propertyList.Add('Userid');
    propertyList.Add('sn');
    propertyList.Add('EmployeeType');
    propertyList.Add('employeeNumber');
    propertyList.Add('c');
    propertyList.Add('samAccountName');
}


public boolean next()
{
    Counter pos, posCount;
    str memberOfStr;
    CLRObject clrenumerator;

    networkAlias        = "";
    company             = "";
    department          = "";
    title               = "";
    mail                = "";
    givenName           = "";
    manager             = "";
    departmentNumber    = "";
    telephoneNumber     = "";
    userId              = "";
    sn                  = "";
    employeeType        = "";
    adGroups            = conNull();
    memberOf            = conNull();

    try
    {
        if (currentUserNumber == 0 && searchResultCollection == null)
        {
            prefix = 'LDAP://';
            searchScope = System.DirectoryServices.SearchScope::Subtree;

            entry = new System.DirectoryServices.DirectoryEntry(prefix+selectedDomainName);

            directorySearcher = new System.DirectoryServices.DirectorySearcher(entry);

            directorySearcher.set_PageSize(65535);
            directorySearcher.set_CacheResults(false);
            directorySearcher.set_SearchScope(searchScope);

            directorySearcher.set_Filter(strFmt('(&(objectClass=user)(objectCategory=person)%1(userAccountControl:1.2.840.113556.1.4.803:=512))', criteria));
            this.setSearchPropertyList(directorySearcher);

            searchResultCollection = directorySearcher.FindAll();
            numberOfUsers = searchResultCollection.get_Count();
        }

        do
        {
            currentUserNumber++;

            if (currentUserNumber > numberOfUsers)
            {
                return false;
            }

            searchResult = searchResultCollection.get_Item(currentUserNumber-1);
            entry = searchResult.GetDirectoryEntry();

            if (entry)
            {
                PropertyCollection = entry.get_Properties();
            }

            if (!PropertyCollection)
            {
                entry.Dispose();
            }
        }
        while (!PropertyCollection);

        propertyValueCollection = PropertyCollection.get_Item('samaccountname');

        if (PropertyValueCollection)
        {
            if (PropertyValueCollection.get_Value())
            {
                NetworkAlias = PropertyValueCollection.get_Value();
            }
        }


        propertyValueCollection  = PropertyCollection.get_Item('company');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {

                company = PropertyValueCollection.get_Value();
            }
        }

        propertyValueCollection  = PropertyCollection.get_Item('telephoneNumber');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {

                telephoneNumber = PropertyValueCollection.get_Value();
                telephoneNumber = telephoneNumber; //str2int(telephoneNumber)==0 ? "" : telephoneNumber;
            }
        }

        PropertyValueCollection = propertyCollection.get_Item('department');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {

                department = PropertyValueCollection.get_Value();
            }
        }

        PropertyValueCollection = propertyCollection.get_Item('departmentNumber');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {

                departmentNumber = PropertyValueCollection.get_Value();
            }
        }

        PropertyValueCollection = propertyCollection.get_Item('title');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {
                title = PropertyValueCollection.get_Value();
            }
        }

        PropertyValueCollection = propertyCollection.get_Item('mail');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {
                mail = PropertyValueCollection.get_Value();
            }
        }


        PropertyValueCollection = propertyCollection.get_Item('givenName');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {

                givenName = PropertyValueCollection.get_Value();
            }
        }

        PropertyValueCollection = propertyCollection.get_Item('Userid');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {

                UserId = PropertyValueCollection.get_Value();
            }
        }

        PropertyValueCollection = propertyCollection.get_Item('EmployeeNumber');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {

                employeeNumber = PropertyValueCollection.get_Value();
            }
        }

        PropertyValueCollection = propertyCollection.get_Item('sn');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {

                sn = PropertyValueCollection.get_Value();
            }
        }

        PropertyValueCollection = propertyCollection.get_Item('EmployeeType');

        if (PropertyValueCollection && PropertyValueCollection.get_Count())
        {
            if (PropertyValueCollection.get_Value())
            {

                employeeType = PropertyValueCollection.get_Value();
            }
        }

        propertyValueCollection = PropertyCollection.get_Item('manager');

        if (PropertyValueCollection)
        {
            if (PropertyValueCollection.get_Value())
            {
                manager = PropertyValueCollection.get_Value();
            }
        }

        propertyValueCollection = PropertyCollection.get_Item('c');

        if (PropertyValueCollection)
        {
            if (PropertyValueCollection.get_Value())
            {
                country = PropertyValueCollection.get_Value();
            }
        }

        propertyValueCollection = PropertyCollection.get_Item('samAccountName');

        if (PropertyValueCollection)
        {
            if (PropertyValueCollection.get_Value())
            {
                samAccountName = PropertyValueCollection.get_Value();
            }
        }

        propertyValueCollection = PropertyCollection.get_Item('userAccountControl');

        if (PropertyValueCollection)
        {
            if (PropertyValueCollection.get_Value())
            {
                userAccountControl = PropertyValueCollection.get_Value();
            }
        }

        propertyValueCollection = PropertyCollection.get_Item('memberOf');

        if (PropertyValueCollection)
        {
            if (PropertyValueCollection.get_Value())
            {
                clrenumerator = PropertyValueCollection.GetEnumerator();
                while (clrenumerator.MoveNext())
                {
                    memberOfStr = clrenumerator.get_Current();
                    memberOf += [memberOfStr];
                }
                //posCount = PropertyValueCollection.get_Count();
                //for (Pos=0; pos<posCount;pos++)
                //{
                    //memberOfStr = PropertyValueCollection.get_Item(pos);
                    //memberOf += [memberOfStr];
                //}
            }
        }
    }
    catch (Exception::CLRError)
    {
        //SRSProxy::handleClrException(Exception::Warning);
        //warning(strFmt("@SYS117734"));
        curext();
    }


    return true;
}



public str getCompany()
{
    return company;
}
public str getCountry()
{
    return country;
}
public str getDepartmentNumber()
{
    return departmentNumber;
}

public boolean getDisabled()
{
   
    // Added new conditions for when a user should be seen as disabled.
    boolean ret;
    ;
    //ACCOUNTDISABLE    0x0002    2
    ret =  bitTest(userAccountControl, 1 << 1);

    if (!ret && title == 'SLUTAT')
        ret = true;

    if (!ret && (strLen(departmentNumber) > 0 && !strRem(departmentNumber,'0')) && (strLen(employeeNumber) > 0 && !strRem(employeeNumber,'0')))
        ret = true;

    return ret;
   
}

public str getEmployeeNumber()
{
    return employeeNumber;
}

public str getEmployeeType()
{
    return EmployeeType;
}
public str getGivenName()
{
    return givenName;
}

public email getMail()
{
    return mail;
}

public str getManager()
{
    return subStr(manager
                  , strfind(manager, 'CN=', 1, strLen(manager))+3
                  , strfind(manager, ',', strfind(manager, 'CN=', 1, strLen(manager)), strLen(manager)) - strfind(manager, 'CN=',1 , strLen(manager)) - 3
              );
}

public container getMemberOf()
{
    return memberOf;
}

public str getSamAccountName()
{
    return samAccountName;
}

public str getSn()
{
    return sn;
}

public str getTelephoneNumber()
{
    return telephoneNumber;
}

public str getUserId()
{
    return UserId;
}

public int parmCurrentUserNumber(int _currentUserNumber = currentUserNumber)
{

    currentUserNumber = _currentUserNumber;

    return currentUserNumber;
}

public str parmFileName(Filename _filename = filename)
{
    filename  = _filename;

    return filename;
}

public str parmselectedDomainName(str _selectedDomainName = selectedDomainName)
{
    selectedDomainName  = _selectedDomainName;

    return selectedDomainName;
}

public void reset()
{
    currentUserNumber = 0;
}