TDConnection examples

This section provides some project script examples to help you understand how to use the TDConnection object.

Example: Reject a defect and convert it to a requirement

This example demonstrate the following use case:

When a defect is rejected with the reason "Convert to BLI", a requirement is automatically created and linked to the defect.

Copy code
var BUG_STATUS = "BG_STATUS";
var BUG_REJECT_REASON = "BG_USER_01";
var BUG_CONVERTED_BLI_FOLDER_ID = 1;

async function Bug_FieldChange(fieldName) {
    if (fieldName === BUG_STATUS) {
        var status = Bug_Fields(BUG_STATUS).Value;
        if (status === "Rejected") {
            Bug_Fields(BUG_REJECT_REASON).IsRequired = true;
        } else {
            Bug_Fields(BUG_REJECT_REASON).IsRequired = false;
        }
        return;
    }
    if (fieldName === BUG_REJECT_REASON) {
        var rejectReason = Bug_Fields(BUG_REJECT_REASON).Value;
        if (rejectReason !== "Converted to BLI") return;
        var isCreateBli = await MsgBox("Do you want to create a bli which links to this defect?", 1);
        if (!isCreateBli) return;
        try {
            // Create requirement
            var reqFactory = TDConnection.ReqFactory;
            var reqItem = reqFactory.AddItem(null);
            reqItem.Name = "Converted BLI from defect " + Bug_Fields("BG_BUG_ID").Value + ": " + Bug_Fields("BG_SUMMARY").Value;
            reqItem.ParentId = BUG_CONVERTED_BLI_FOLDER_ID;
            reqItem.Post();
            // Create linkage
            var linkFactory = reqItem.BugLinkFactory;
            linkFactory.AddItem(Bug_Fields("BG_BUG_ID").Value);
            var comments = Bug_Fields("BG_DEV_COMMENTS").Value;
            if (comments) {
                comments += "\n\n";
            } else {
                comments = "";
            }
            comments += (User.UserName + ", " + (new Date).toLocaleDateString() + ": Converted to bli " + reqItem.ID);
            Bug_Fields("BG_DEV_COMMENTS").Value = comments;
        } catch (e) {
            debugger;
        }
    }
}

Back to top

Example: Mail a defect

The following script sends the defect with the ID 1 to email. The defect attachments and history are also included in the email. The email is sent with high importance.

Copy code
var bug = TDConnection.BugFactory.Item(1)
bug.Mail(
        "abc@vip.com,123@vip.com,xyz@vip.com",
        "ccrecipient@vip.com",   
        "bccrecipient@vip.com",
        1 | 2 , // Send the entity's attachments and include the entity's history in this mail
        "This is the email subject line.",
        1,  // Set the priority as high
        "This is the email comment"
)

Back to top

Example: Filter records

Filter defects

Copy code
function bugFilter() {
    try {
        const bugFactory = TDConnection.BugFactory;
        const bugFilter = bugFactory.Filter;

        // Set the filter values
        bugFilter.Filter["BG_STATUS"] = "Closed";
        bugFilter.Order["BG_PRIORITY"] = 1;
        console.log(bugFilter.Text); // Output the filter text

        // Create a list of defects from the filter and show a few of them
        const bugList = bugFilter.NewList();
        let msg = `Number of defects = ${bugList.length}\n`;
        let count = 0;

        for (const theBug of bugList) {
            msg += `${theBug.ID}, ${theBug.Summary}, ${theBug.Status}, ${theBug.Priority}\n`;
            count++;
            if (count > 10) break; // Limiting to the first 10 bugs
        }
        // Display the message in a dialog box
        MsgBox(msg);

    } catch (error) {
        console.error("Error in bugFilter:", error);
    }
}

Filter requirements by type

Copy code
function filterReqsByType() {
    try {

        const reqFactory = TDConnection.ReqFactory;
        const filter = reqFactory.Filter;

        // Use requirement type ID to fetch requirements of a specific type.
        filter.Filter["RQ_TYPE_ID"] = 101;

        const reqList = filter.NewList();

        // Print out each requirement's details
        reqList.forEach((req) => {
            console.log(`${req.Name} : ${req.TypeId} : ${req.RequirementType.Name}`);
        });

    } catch (error) {
        console.error("Error in filterReqsByType:", error);
    }
}

Back to top

Example: Download a file from an attachment object

Copy code
function attachmentDownload() {   
    try {  
        // Get the BugFactory from the global TDConnection object 
        let bugFact = TDConnection.BugFactory;  

        // Retrieve a specific bug object by ID (in this case, ID 1)  
        let bugObj = bugFact.Item(1);  
        console.log(bugObj.Summary); // Log the bug summary for reference  

        // Access the attachments associated with the bug object  
        let attachFact = bugObj.Attachments;  

        // Create a new list of attachments  
        let attachList = attachFact.NewList("");  
        
        if (attachList.length === 0) return;
        // Get the first attachment from the attachment list  
        let attachObj = attachList[0];
        console.log(attachObj.FileName); // Log the file name of the attachment  
        // Load the attachment  
        attachObj.Load();  
        console.log(`Attachment downloaded);  

        // Return success status  
        return "SUCCESS";  
    } catch (err) {   
        return "FAILURE"; // Return failure status  
    }  
}

Back to top

Example: Get and set defect properties

Copy code
function bugProperties(theBug) {
    try {
        // Print the properties.
        console.log("Initial Bug properties");
        console.log(theBug.Priority);
        console.log(theBug.AssignedTo);
        console.log(theBug.DetectedBy);
        console.log(theBug.Status);
        console.log(theBug.Summary);

        // Change the values.
        theBug.Priority = "4-Very High";
        theBug.AssignedTo = "steves";
        theBug.DetectedBy = "alex_alm";
        theBug.Status = "Fixed";
        theBug.Summary = "Amended: The list of flights is given even when past date set as Departing date";

        // Commit to database.
        theBug.Post();
        // Check the new values.
        console.log("Changed Bug properties");
        console.log(theBug.Priority);
        console.log(theBug.AssignedTo);
        console.log(theBug.DetectedBy);
        console.log(theBug.Status);
        console.log(theBug.Summary);

        return "SUCCESS";
    } catch (err) {
        return "FAILURE";
    }
}

Back to top

Example: Create links between defects

Copy code
async function linkDefects() {
    try {
        const bugF = TDConnection.BugFactory;

        // Create the first bug
        const bug1 = bugF.AddItem(null);
        bug1.Summary = "Lydia Bennet is 15 years old.";
        bug1.Status = "New";
        bug1.Priority = "3-High";
        bug1.Field["BG_SEVERITY"] = "3-High";
        bug1.DetectedBy = User.UserName;
        bug1.Field["BG_DETECTION_DATE"] = new Date();
        bug1.Field["BG_RESPONSIBLE"] =  User.UserName;
        bug1.Post();

        // Create the second bug
        const bug2 = await bugF.AddItem(null);
        bug2.Summary = "Mr. Bennet hides in library.";
        bug2.Status = "New";
        bug2.Priority = "3-High";
        bug2.Field["BG_SEVERITY"] = "3-High";
        bug2.DetectedBy = User.UserName;
        bug2.Field["BG_DETECTION_DATE"] = new Date();
        bug2.Field["BG_RESPONSIBLE"] =  User.UserName;
        await bug2.Post();

        // Link the new defects
        const bgLinkable = bug1; // Casting Bug1 to ILinkable
        const bugLinkF = bgLinkable.BugLinkFactory;

        // Create a link between Bug1 (source) and Bug2 (target)
        const bugLink = bugLinkF.AddItem(bug2);
        bugLink.LinkType = "Related";
        bugLink.Post();

        // Show the link definition
        let anObj = bugLink.SourceEntity;
        console.log(anObj.Summary); // Lydia Bennet is 15 years old. (Bug1)

        anObj = bugLink.TargetEntity;
        console.log(anObj.Summary); // Mr. Bennet hides in library. (Bug2)

    } catch (err) {
        console.error("Error in linkDefects:", err);
    }
}

Back to top

Example: Populate target release cycle to children

Copy code
function populateCycle() {  
    try {  
        const rFactory = TDConnection.ReqFactory;  
        
        // Fetch the requirement item by ID  
        const requirement = rFactory.Item(1);  

        // Apply the requirement's target cycle to all descendants  
        requirement.PopulateTargetCycleToChildren();  
        
    } catch (err) {  
        console.error("Error in populateCycle:", err);  
    }  
}  

Back to top

Example: Move requirements

Copy code
function moveReqs() {
    const rqFactory = TDConnection.ReqFactory;

    // Move requirements to a specific position
    rqFactory.MoveRequirements("5, 4, 3", "1, 2, 3", 2);
    console.assert(false, "After first move:");

    // ------------------------------------------------
    // Append the Reqs to the end of the existing children
    const last = tagTDAPI_POS_ORDER.TDPOSITION_LAST;
    const order = `${last},${last},${last}`;
    rqFactory.MoveRequirements("3, 5, 4", order, 1);
    console.assert(false, "After second move:");

    // ------------------------------------------------
    // Add the Reqs to the beginning of the existing children
    rqFactory.MoveRequirements("3, 4, 5", "1, 1, 1", 2);
    console.assert(false, "After third move:");

    // ------------------------------------------------
    // Place Reqs as specified
    rqFactory.MoveRequirements("3, 4, 5", "1, 2, 2", 1);
    console.assert(false, "After fourth move:");

}

Back to top

Example: Retrieve sorted requirements

Copy code
function retrieveOrderedRecords(sinceDate, currentSyncDate) {
    try {

        const reqFactory = TDConnection.ReqFactory;
        if (!reqFactory) {
            throw new Error("Request Factory is not initialized.");
        }

        const filter = reqFactory.Filter;
        if (!filter) {
            throw new Error("Filter is not initialized.");
        }

        // Query criteria
        filter.Filter["RQ_VTS"] = `> "${sinceDate.toISOString().slice(0, 19).replace('T', ' ')}" AND < "${currentSyncDate.toISOString().slice(0, 19).replace('T', ' ')}"`;

        // Sort by path to get parent requirements in list before children
        filter.Order["RQ_REQ_PATH"] = 1;
        filter.OrderDirection["RQ_REQ_PATH"] = TDOLE_ASCENDING;

        // Sort by version timestamp so earlier records output first
        filter.Order["RQ_VTS"] = 2;
        filter.OrderDirection["RQ_VTS"] = TDOLE_ASCENDING;

        // Return the list
        const orderedRecords = filter.NewList();
        return orderedRecords;

    } catch (error) {
        console.error("Error in retrieveOrderedRecords:", error);
        // Handle error appropriately

    }
}

Back to top

Example: Get coverage tests that have not run

Copy code
function bugProperties(theBug) {
    try {
        // Print the properties.
        console.log("Initial Bug properties");
        console.log(theBug.Priority);
        console.log(theBug.AssignedTo);
        console.log(theBug.DetectedBy);
        console.log(theBug.Status);
        console.log(theBug.Summary);

        // Change the values.
        theBug.Priority = "4-Very High";
        theBug.AssignedTo = "steves";
        theBug.DetectedBy = "alex_alm";
        theBug.Status = "Fixed";
        theBug.Summary = "Amended: The list of flights is given even when past date set as Departing date";

        // Commit to database.
        theBug.Post();
        // Check the new values.
        console.log("Changed Bug properties");
        console.log(theBug.Priority);
        console.log(theBug.AssignedTo);
        console.log(theBug.DetectedBy);
        console.log(theBug.Status);
        console.log(theBug.Summary);

        return "SUCCESS";
    } catch (err) {
        return "FAILURE";
    }
}

Back to top