Підтримка обчислення функцій у формулах

Aspose.Tasks for .NET API підтримує обчислення функцій, визначених як формули всередині розширених атрибутів проекту.
Це дозволяє розробникам виконувати обчислення, подібні до тих, що доступні в Microsoft Project, що робить можливим реалізацію динамічних полів, які залежать від користувацької логіки.

API надає підтримку обчислення для наступних категорій функцій:

Ця можливість особливо корисна, коли потрібно:

Обчислення математичних виразів

Підтримуються наступні математичні функції:

  1. Abs( number )
  2. Atn( number )
  3. Cos( number )
  4. Exp( number )
  5. Fix( number )
  6. Int( number )
  7. Log( number )
  8. Rnd( number )
  9. Sgn( number )
  10. Sin( number )
  11. Sqr( number )
  12. Tan( number )
 1static void EvaluateSine()
 2{
 3    Project project = CreateTestProjectWithCustomField();
 4    
 5    // Set formula Sin(pi/2)
 6    project.ExtendedAttributes[0].Formula = "Sin(3.1415926/2)";
 7
 8    // Print Calculated value
 9    Task task = project.RootTask.Children.GetById(1);
10    Console.WriteLine("Sin(pi/2): {0}", task.ExtendedAttributes[0].NumericValue);
11}
12
13static Project CreateTestProjectWithCustomField()
14{
15    Project project = new Project();
16    ExtendedAttributeDefinition attr = ExtendedAttributeDefinition.CreateTaskDefinition(CustomFieldType.Number, ExtendedAttributeTask.Number1, "Sine");
17    project.ExtendedAttributes.Add(attr);
18
19    Task task = project.RootTask.Children.Add("Task");
20
21    ExtendedAttribute a = attr.CreateExtendedAttribute();
22    task.ExtendedAttributes.Add(a);
23    return project;
24}

Обчислення загальних функцій

Наступні функції забезпечують логічні та умовні обчислення:

  1. Choose( index, choice-1, choice-2, ... , choice-n ) – вибирає значення зі списку.
  2. IIf( expr, truepart, falsepart ) – повертає одне з двох значень залежно від умови.
  3. IsNumeric( expression ) – перевіряє, чи є вираз числовим.
  4. IsNull( expression ) – перевіряє, чи є вираз значенням null.
  5. Switch( expr-1, value-1, expr-2, value-2, ... ) – оцінює вирази по черзі й повертає перше відповідне значення.
 1static void EvaluateChoose()
 2{    
 3    Project project = CreateTestProjectWithCustomField();
 4    
 5    // Set Formula
 6    project.ExtendedAttributes[0].Formula = "Choose(3, \"This is a\", \"right\", \"choice\")";
 7    
 8    // Print extended attribute value
 9    Task task = project.RootTask.Children.GetById(1);
10    Console.WriteLine(task.ExtendedAttributes[0].TextValue);
11}
12
13static void EvaluateIsNumeric()
14{
15    string[] numericFormulas = { "IsNumeric('AAA')", "IsNumeric(1)", "IsNumeric(1<0)", "IsNumeric(\"1.1\")", "IsNumeric(Choose((2 + Sgn(2^-3)), 123, \"one two three\"))" };
16    
17    Project project = CreateTestProjectWithCustomField();
18    
19    foreach (string numericFormula in numericFormulas)    
20    {
21        // Set Formula
22        project.ExtendedAttributes[0].Formula = numericFormula;
23
24        // Print extended attribute value
25        Task task = project.RootTask.Children.GetById(1);
26        Console.WriteLine(task.ExtendedAttributes[0].TextValue);
27    }
28}
29
30static void EvaluateSwitch()
31{    
32    Project project = CreateTestProjectWithCustomField();
33
34    // Set Formula
35    project.ExtendedAttributes[0].Formula = "Switch( 0 < 1, \"0 is lesser than 1\", 0 > 1, \"0 is greater than 1\")";
36
37    // Print extended attribute value
38    Task task = project.RootTask.Children.GetById(1);
39    Console.WriteLine(task.ExtendedAttributes[0].TextValue);
40}

Обчислення текстових функцій

Функції обробки рядків дозволяють форматувати та порівнювати:

  1. Asc( string ) – повертає ASCII-код першого символу.
  2. Chr( charcode ) – повертає символ за ASCII-кодом.
  3. Format( expression, format, firstdayofweek, firstweekofyear ) – форматує числа/дати.
  4. Instr( start, string1, string2, compare ) – знаходить позицію одного рядка в іншому.
  5. LCase( string ) – перетворює на малі літери.
  6. Left( string, length ) – витягує ліві символи.
  7. Len( string ) – повертає довжину рядка.
  8. LTrim( string ) – видаляє пробіли на початку.
  9. Mid( string, start, length ) – витягує підрядок.
  10. Right( string, length ) – витягує праві символи.
  11. RTrim( string ) – видаляє пробіли в кінці.
  12. Space( number ) – повертає рядок із пробілами.
  13. StrComp( string1, string2, compare ) – порівнює два рядки.
  14. StrConv( string, conversion, LCID ) – перетворює рядок відповідно до локалі.
  15. String( number, character ) – повертає рядок, повторений n разів.
  16. Trim( string ) – видаляє пробіли на початку та в кінці.
  17. UCase( string ) – перетворює на великі літери.
 1static void EvaluateStrConv()
 2{
 3    Project project = CreateTestProjectWithCustomField();
 4    Task task = project.RootTask.Children.GetById(1);
 5
 6    // Set formulas and print extended attribute value
 7    project.ExtendedAttributes[0].Formula = "StrConv(\"sTring and sTRINg\",3)";
 8    Console.WriteLine(task.ExtendedAttributes[0].TextValue);
 9    project.ExtendedAttributes[0].Formula = "StrConv(\"sTring and sTRINg\",1)";
10    Console.WriteLine(task.ExtendedAttributes[0].TextValue);
11    project.ExtendedAttributes[0].Formula = "StrConv(\"sTring and sTRINg\",2)";
12    Console.WriteLine(task.ExtendedAttributes[0].TextValue);
13}
14
15static void EvaluateStringFunction()
16{
17    Project project = CreateTestProjectWithCustomField();
18    Task task = project.RootTask.Children.GetById(1);
19
20    // Set formulas and print extended attribute value
21    project.ExtendedAttributes[0].Formula = "String(5, 40)";
22    Console.WriteLine(task.ExtendedAttributes[0].TextValue);
23    project.ExtendedAttributes[0].Formula = "String(5, \"A\")";
24    Console.WriteLine(task.ExtendedAttributes[0].TextValue);
25    project.ExtendedAttributes[0].Formula = "String(-5, \"A\")";
26    // #Error
27    Console.WriteLine(task.ExtendedAttributes[0].TextValue);
28}

Обчислення функцій дати/часу

Aspose.Tasks підтримує як стандартні VB-подібні функції дати, так і специфічні для MS Project функції планування:

  1. CDate( expression ) – перетворює вираз на дату.
  2. Date() – повертає поточну системну дату.
  3. DateAdd( interval, number, date ) – додає інтервал до дати.
  4. DateDiff( interval, date1, date2 ) – різниця між двома датами.
  5. DatePart( interval, date ) – витягує частину дати (рік, місяць, день тощо).
  6. DateSerial( year, month, day ) – створює дату з компонентів.
  7. DateValue( date ) – перетворює рядок на дату.
  8. Day( date ) – день місяця.
  9. Hour( time ) – витягує годину.
  10. IsDate( expression ) – перевіряє, чи є вираз дійсною датою.
  11. Minute( time ) – витягує хвилини.
  12. Month( date ) – витягує місяць.
  13. Now() – повертає поточні дату та час.
  14. ProjDateAdd( date, duration, calendar ) – додає тривалість з урахуванням календаря проекту.
  15. ProjDateConv( expression, dateformat ) – перетворює дату у формат проекту.
  16. ProjDateDiff( date1, date2, calendar ) – різниця з урахуванням календаря проекту.
  17. ProjDateSub( date, duration, calendar ) – віднімає тривалість.
  18. ProjDateValue( expression ) – обчислює вираз дати.
  19. ProjDurConv( expression, durationunits ) – перетворює тривалості між одиницями.
  20. ProjDurValue( duration ) – обчислює вираз тривалості.
  21. Second( time ) – витягує секунди.
  22. Time() – повертає поточний системний час.
  23. Timer() – кількість секунд після опівночі.
  24. TimeSerial( hour, minute, second ) – створює значення часу.
  25. TimeValue( time ) – перетворює на час.
  26. Weekday( date, firstdayofweek ) – повертає день тижня.
  27. Year( date ) – витягує рік.
 1Project project = CreateTestProject();
 2Task task = project.RootTask.Children.GetById(1);
 3
 4ExtendedAttributeDefinition numberDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Number1, null);
 5project.ExtendedAttributes.Add(numberDefinition);
 6
 7ExtendedAttribute numberAttribute = numberDefinition.CreateExtendedAttribute();
 8task.ExtendedAttributes.Add(numberAttribute);
 9
10// Set ProjDateDiff formula and print extended attribute value
11numberDefinition.Formula = "ProjDateDiff(\"03/23/2015\",\"03/18/2015\")";
12Console.WriteLine(numberAttribute.NumericValue);
13numberDefinition.Formula = "ProjDateDiff(\"03/23/2015\",\"03/25/2015\")";
14Console.WriteLine(numberAttribute.NumericValue);
15
16ExtendedAttributeDefinition dateDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Date1, null);
17project.ExtendedAttributes.Add(dateDefinition);
18ExtendedAttribute dateAttribute = dateDefinition.CreateExtendedAttribute();
19task.ExtendedAttributes.Add(dateAttribute);
20
21ExtendedAttributeDefinition durationDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Duration4, "Custom duration field");
22project.ExtendedAttributes.Add(durationDefinition);
23ExtendedAttribute durationAttribute = durationDefinition.CreateExtendedAttribute();
24task.ExtendedAttributes.Add(durationAttribute);
25
26ExtendedAttributeDefinition textDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Text5, "Custom text field");
27project.ExtendedAttributes.Add(textDefinition);
28ExtendedAttribute textAttribute = textDefinition.CreateExtendedAttribute();
29task.ExtendedAttributes.Add(textAttribute);
30
31// Set ProjDateSub formula and print extended attribute value
32dateDefinition.Formula = "ProjDateSub(\"3/19/2015\", \"1d\")";
33Console.WriteLine(dateAttribute.DateValue);
34
35// We can set ProjDurConv formula to duration-valued attribute as well as to text-valued attribute.
36
37// Set ProjDurConv formula to duration-valued extended attribute and print its value.
38durationDefinition.Formula = "ProjDurConv([Duration], pjHours)";
39Console.WriteLine(durationAttribute.DurationValue);
40
41// Set ProjDurConv formula to text-valued extended attribute and print its value.
42textDefinition.Formula = "ProjDurConv([Duration], pjHours)";
43Console.WriteLine(textAttribute.TextValue);
44
45textDefinition.Formula = "ProjDurConv([Duration], pjWeeks)";
46Console.WriteLine(textAttribute.TextValue);
47
48// Set Second formula and print entended attribute value
49numberDefinition.Formula = "Second(\"4/21/2015 2:53:41 AM\")";
50Console.WriteLine(numberAttribute.NumericValue);
51
52// Set Weekday formula and print entended attribute value
53numberDefinition.Formula = "Weekday(\"24/3/2015\", 1)";
54Console.WriteLine(numberAttribute.NumericValue);
55numberDefinition.Formula = "Weekday(\"24/3/2015\", 2)";
56Console.WriteLine(numberAttribute.NumericValue);
57numberDefinition.Formula = "Weekday(\"24/3/2015\", 3)";
58Console.WriteLine(numberAttribute.NumericValue);

Практичний приклад

Ось приклад реального використання формул:

 1    var project = new Project();
 2    var task = project.RootTask.Children.Add("Task 1");
 3
 4    // Create an extended attribute with a custom formula
 5    ExtendedAttributeDefinition attrDef = ExtendedAttributeDefinition.CreateTaskDefinition(
 6        ExtendedAttributeTask.Text1, "Custom Formula");
 7        attrDef.Formula = "IIf([Duration] > 480, \"Long Task\", \"Short Task\")";
 8        project.ExtendedAttributes.Add(attrDef);
 9
10    var attr = attrDef.CreateExtendedAttribute();
11    task.ExtendedAttributes.Add(attr);
12
13    // The formula is automatically evaluated by Aspose.Tasks
14    Console.WriteLine(task.Get(Tsk.Name) + " -> " + task.ExtendedAttributes[0].TextValue);

Ключові переваги підтримки формул

Див. також

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.