Search code examples
taskms-projectmpxj

mpxj Project c# resource assignment with fixed duration


I'm using the mpxj library to build a MS Project schedule. I would like to assgin a resource to a task with a fixed duration so it would show an even number of hours per day. For example, if the task is 3 days long and there are 9 hours of work, project will show 3 hours per day.

I tried everything but didn't manage to find a solution, here's my code:

Task task = file.addTask();                           
task.setName(name);
UID = java.lang.Integer.valueOf(c);
taskFielding.setUniqueID(UID);
mainTask.addChildTask(task, 2);
task.setActualStart(startdate);
task.setConstraintType(ConstraintType.MUST_START_ON);
task.setConstraintDate(startdate);
task.setEffortDriven(false);   
task.setType(TaskType.FIXED_DURATION);
task.setDuration(duration);
task.setActualDuration(durationFielding);
task.setManualDuration(durationFielding);
task.setOutlineNumber(outlinecount + "." + outlinesubcount);
task.setOutlineLevel(java.lang.Integer.valueOf(2));
ResourceAssignment resourceAssignment =         task.addResourceAssignment(assignedResource);
resourceAssignment.setWork(Duration.getInstance(15, TimeUnit.HOURS));
resourceAssignment.setActualWork(Duration.getInstance(5, TimeUnit.HOURS));
resourceAssignment.setRemainingWork(Duration.getInstance(10, TimeUnit.HOURS));
resourceAssignment.setStart(taskFielding.getStart());

Solution

  • You'll need to set the units attribute of the resource assignment to reduce the amount of time available each day for your resource. Here is an example:

    Resource assignedResource = file.addResource();
    assignedResource.Name = "Assigned Resource";
    
    Task task = file.addTask();
    task.Name = "StackOverflow Example Task";
    task.Start = DateTime.Parse("2017-03-13").ToJavaDate();
    task.Duration = Duration.getInstance(3, TimeUnit.DAYS);
    task.Work = Duration.getInstance(15, TimeUnit.HOURS);
    task.RemainingWork = Duration.getInstance(15, TimeUnit.HOURS);
    
    double hoursPerDay = 8.0;
    double hoursWorkedPerDay = 5.0;
    
    ResourceAssignment resourceAssignment = task.addResourceAssignment(assignedResource);
    resourceAssignment.Start = DateTime.Parse("2017-03-13").ToJavaDate();
    resourceAssignment.Work = Duration.getInstance(15, TimeUnit.HOURS);
    resourceAssignment.RemainingWork = Duration.getInstance(15, TimeUnit.HOURS);
    resourceAssignment.Units = NumberHelper.getDouble((hoursWorkedPerDay / hoursPerDay) * 100.0);
    

    This creates a task which has a duration of 3 days, but only 5 hours of work is carried out each day.

    The key part is calculating the value for the units attribute. Here we assume an 8 hour working day (you can set this up as part of your project). Units is a percentage, so we calculate the fraction of the day we want to work (in this case 5 hours / 8 hours) and multiply by 100 to give us a percentage.