Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Aspose.Tasks for .NET
This Gist contains code snippets from examples of Aspose.Tasks for .NET
Project project = new Project(dataDir + "Project2.mpp");
SaveOptions options = new PdfSaveOptions();
options.Timescale = Timescale.Months;
options.View = ProjectView.GetDefaultGanttChartView();
GanttChartColumn column1 = options.View.Columns[2] as GanttChartColumn;
column1.StringAlignment = StringAlignment.Center;
column1 = options.View.Columns[3] as GanttChartColumn;
column1.StringAlignment = StringAlignment.Far;
column1 = options.View.Columns[4] as GanttChartColumn;
column1.StringAlignment = StringAlignment.Far;
project.Save(dataDir + "AlignCellContents_GanttChart_out.pdf", options);
options.PresentationFormat = PresentationFormat.ResourceSheet;
options.View = ProjectView.GetDefaultResourceSheetView();
ResourceViewColumn column2 = options.View.Columns[2] as ResourceViewColumn;
column2.StringAlignment = StringAlignment.Center;
column2 = options.View.Columns[3] as ResourceViewColumn;
column2.StringAlignment = StringAlignment.Far;
column2 = options.View.Columns[4] as ResourceViewColumn;
column2.StringAlignment = StringAlignment.Far;
project.Save(dataDir + "AlignCellContents_ResourceSheet_out.pdf", options);
Project project = new Project(dataDir + "Project2.mpp");
SaveOptions options = new XamlOptions();
options.UseGradientBrush = false;
project.Save(dataDir + "ChangeGanttBarsColorGradient_Solid_out.xaml", options);
options.UseGradientBrush = true;
project.Save(dataDir + "ChangeGanttBarsColorGradient_Gradient_out.xaml", options);
Project project = new Project();
Task task1 = project.RootTask.Children.Add("Task 1");
Task task2 = project.RootTask.Children.Add("Task 2");
task1.Set(Tsk.Duration, project.GetDuration(1, TimeUnitType.Day));
task2.Set(Tsk.Duration, project.GetDuration(1, TimeUnitType.Day));
TaskLink link = project.TaskLinks.Add(task1, task2, TaskLinkType.FinishToStart);
Task task3 = project.RootTask.Children.Add("Task 3");
Resource rsc1 = project.Resources.Add("Resource 1");
Resource rsc2 = project.Resources.Add("Resource 2");
Resource rsc3 = project.Resources.Add("Resource 3");
ResourceAssignment assn1 = project.ResourceAssignments.Add(task1, rsc1);
ResourceAssignment assn2 = project.ResourceAssignments.Add(task2, rsc2);
ResourceAssignment assn3 = project.ResourceAssignments.Add(task3, rsc3);
SaveOptions options = new PdfSaveOptions();
options.Timescale = Timescale.ThirdsOfMonths;
BarStyle style = new BarStyle();
style.ItemType = BarItemType.CriticalTask;
style.BarTextConverter = delegate (Task t)
{
return string.Format("This task is on critical path");
};
BarStyle style2 = new BarStyle();
style2.BarColor = Color.DarkOrchid;
style2.ItemType = BarItemType.Task;
options.BarStyles = new List<BarStyle>();
options.BarStyles.Add(style);
options.BarStyles.Add(style2);
project.Save(dataDir + "result2.pdf", options);
static void ImplementCustomBarSytle()
{
try
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = new Project(dataDir + "Blank2010.mpp");
project.RootTask.Children.Add("Task");
GanttChartView view = project.DefaultView as GanttChartView;
GanttBarStyle custom = GetCustomBarStyle();
// Add the custom bar style to the custom bar collection of the project view
view.CustomBarStyles.Add(custom);
string file = "ImplementCustomBarStyleWriting_out.mpp";
MPPSaveOptions options = new MPPSaveOptions();
options.WriteViewData = true;
project.Save(dataDir + file, options);
}
catch (NotSupportedException ex)
{
Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http://www.aspose.com/purchase/default.aspx.");
}
}
private static GanttBarStyle GetCustomBarStyle()
{
GanttBarStyle style = new GanttBarStyle();
style.ShowFor = "1";
style.MiddleShape = GanttBarMiddleShape.RectangleBottom;
style.MiddleFillPattern = GanttBarFillPattern.MediumFill;
style.MiddleShapeColor = Color.Blue;
style.StartShape = GanttBarEndShape.ArrowDown;
style.StartShapeColor = Color.Red;
style.EndShape = GanttBarEndShape.ArrowUp;
style.EndShapeColor = Color.Yellow;
style.LeftField = Field.TaskResourceNames;
style.RightField = Field.TaskName;
style.TopField = Field.TaskStart;
style.BottomField = Field.TaskFinish;
style.InsideField = Field.TaskDuration;
return style;
}
Project project = new Project(dataDir + "CustomBarStyle.mpp");
GanttChartView view = project.DefaultView as GanttChartView;
Console.WriteLine("Custom bar styles count: {0}", view.CustomBarStyles.Count);
GanttBarStyle style1 = view.CustomBarStyles[0];
Console.WriteLine("Style1.LeftField is TaskDurationText : {0}", style1.LeftField.Equals(Field.TaskDurationText));
Console.WriteLine("Style1.RightField is TaskResourceNames : {0}", style1.RightField.Equals(Field.TaskResourceNames));
Console.WriteLine("Style1.TopField is TaskACWP: {0}", style1.TopField.Equals(Field.TaskACWP));
Console.WriteLine("Style1.BottomField is Undefined : {0}", style1.BottomField.Equals(Field.Undefined));
Console.WriteLine("Style1.InsideField is Undefined : {0}", style1.InsideField.Equals(Field.Undefined));
GanttBarStyle style2 = view.CustomBarStyles[1];
Console.WriteLine("Style2.LeftField is TaskActualWork : {0}", style2.LeftField.Equals(Field.TaskActualWork));
Console.WriteLine("Style2.RightField is TaskActualCost : {0}", style2.RightField.Equals(Field.TaskActualCost));
Console.WriteLine("Style2.TopField is Undefined : {0}", style2.TopField.Equals(Field.Undefined));
Console.WriteLine("Style2.BottomField is Undefined : {0}", style2.BottomField.Equals(Field.Undefined));
Console.WriteLine("Style2.InsideField is Undefined : {0}", style2.InsideField.Equals(Field.Undefined));
GanttBarStyle style3 = view.CustomBarStyles[2];
Console.WriteLine("Style3.LeftField is TaskPercentComplete : {0}", style3.LeftField.Equals(Field.TaskPercentComplete));
Console.WriteLine("Style3.RightField is TaskPercentWorkComplete : {0}", style3.RightField.Equals(Field.TaskPercentWorkComplete));
Console.WriteLine("Style3.TopField is Field.TaskActive : {0}", style3.TopField.Equals(Field.TaskActive));
Console.WriteLine("Style3.BottomField is TaskActualCost : {0}", style3.BottomField.Equals(Field.TaskActualCost));
Console.WriteLine("Style3.InsideField is Field.TaskActualDuration : {0}", style3.InsideField.Equals(Field.TaskActualDuration));
Console.WriteLine("Style3.StartShape is HouseDown : {0}", style3.StartShape.Equals(GanttBarEndShape.HouseDown));
Console.WriteLine("Style3.StartShapeType is Framed : {0}", style3.StartShapeType.Equals(GanttBarType.Framed));
Console.WriteLine("Style3.StartShapeColor is Red : {0}", style3.StartShapeColor.Equals(Color.FromArgb(Color.Red.ToArgb())));
Console.WriteLine("Style3.EndShape is CircleDiamond : {0}", style3.EndShape.Equals(GanttBarEndShape.CircleDiamond));
Console.WriteLine("Style3.EndShapeType is Solid : {0}", style3.EndShapeType.Equals(GanttBarType.Solid) );
Console.WriteLine("Style3.EndShapeColor is Yellow : {0}", style3.EndShapeColor.Equals(Color.FromArgb(Color.Yellow.ToArgb())));
Console.WriteLine("Style3.MiddleShape is RectangleTop : {0}", style3.MiddleShape.Equals(GanttBarMiddleShape.RectangleTop));
Console.WriteLine("Style3.MiddleFillPattern is SolidFill : {0}", style3.MiddleFillPattern.Equals(GanttBarFillPattern.SolidFill));
Console.WriteLine("Style3.EndShapeColor is Red : {0}", style3.MiddleShapeColor.Equals(Color.FromArgb(Color.Red.ToArgb())));
Project project = new Project(dataDir + "Project2.mpp");
PresentationFormat presentationFormat = PresentationFormat.GanttChart;
string resultFile = "RenderDifferentPresentationFormatsToXAML_" + presentationFormat + "_out.xaml";
SaveOptions options = new XamlOptions();
options.PresentationFormat = presentationFormat;
project.Save(dataDir + resultFile, options);
PdfSaveOptions options = new PdfSaveOptions();
options.PresentationFormat = PresentationFormat.GanttChart;
options.FitContent = true;
options.RollUpGanttBars = false;
options.DrawNonWorkingTime = false;
options.PageSize = PageSize.A3;
string file = Path.Combine(dataDir, fileName);
string resultFile = Path.Combine(dataDir, "RenderGanttChartWithBarsNotRolledUp_out.pdf");
Project project = new Project(file);
project.Save(resultFile, (SaveOptions)options);
PdfSaveOptions options = new PdfSaveOptions();
options.PresentationFormat = PresentationFormat.GanttChart;
options.FitContent = true;
options.RollUpGanttBars = true;
options.DrawNonWorkingTime = true;
options.PageSize = PageSize.A3;
string file = Path.Combine(dataDir, fileName);
string resultFile = Path.Combine(dataDir, "RenderGanttChartWithBarsNotRolledUp_out.pdf");
Project project = new Project(file);
project.Save(resultFile, (SaveOptions)options);
// Source file to be converted to TIFF
string file = "Project2.mpp";
Project project = new Project(dataDir + file);
// Save the project to TIFF
project.Save(dataDir + "RenderMultipageTIFF_out.tif", SaveFileFormat.TIFF);
// Save the project with CCITT4 compression
ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.TIFF);
options.TiffCompression = TiffCompression.Ccitt4;
project.Save(dataDir + "RenderMultipageTIFF_options_out.tif", (SaveOptions)options);
// Remove the compression
options.TiffCompression = TiffCompression.None;
project.Save(dataDir + "RenderMultipageTIFF_comp_none_out.tif", (SaveOptions)options);
// Source File to Render
string fileName = "Project2.mpp";
// Read the Project
Project project1 = new Project(dataDir + fileName);
// Select a Presentation format
PresentationFormat format = PresentationFormat.GanttChart;
// Render the project to all Pre-Defined page sizes
foreach (PageSize pageSize in (PageSize[])Enum.GetValues(typeof(PageSize)))
{
PdfSaveOptions options = new PdfSaveOptions();
options.PresentationFormat = format;
options.FitContent = true;
options.PageSize = pageSize;
string resultFile = "result_PredefinedPageSizes_" + format.ToString() + "_" + pageSize.ToString() + "_out.pdf";
project1.Save(dataDir + resultFile, (SaveOptions)options);
}
Project project = new Project(dataDir + "Project2.mpp");
string resultFile = "RenderToXAML_out.xaml";
project.Save(dataDir + resultFile, SaveFileFormat.XAML);
Project project = new Project(dataDir + "Project2.mpp");
const string resultFile = "RenderXAMLWithOptions_out.xaml";
SaveOptions options = new XamlOptions();
options.FitContent = true;
options.LegendOnEachPage = false;
options.Timescale = Timescale.ThirdsOfMonths;
project.Save(dataDir + resultFile, options);
Project project = new Project(dataDir + "TaskEmbeddedDocuments.mpp");
Task task = project.RootTask.Children.GetById(1);
File.WriteAllText(dataDir + "Notes_out.rtf", task.Get(Tsk.NotesRTF));
Document doc = null;
using (MemoryStream stream = new MemoryStream())
using (StreamWriter streamWriter = new StreamWriter(stream))
{
streamWriter.Write(task.Get(Tsk.NotesRTF));
doc = new Document(stream);
}
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
foreach (Aspose.Words.Drawing.Shape shape in shapes)
{
if (shape.OleFormat != null)
{
if (!shape.OleFormat.IsLink)
{
// Extract OLE Word object
if (shape.OleFormat.ProgId == "Word.Document.12")
{
MemoryStream stream = new MemoryStream();
shape.OleFormat.Save(stream);
Document newDoc = new Document(stream);
newDoc.Save(dataDir + "RetrieveTaskEmbeddedDocuments_out.doc");
}
}
}
}
Project project = new Project(dataDir + "Project2.mpp");
project.Set(Prj.TimescaleStart, new DateTime(2012, 4, 30));
project.Save(dataDir + "SetGanttChartViewStartDate_out.mpp", SaveFileFormat.MPP);
class SortTasksByColumnInGanttChart
{
public static void Run()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = new Project(dataDir + "Project2.mpp");
SaveOptions options = new PdfSaveOptions();
options.Timescale = Timescale.Months;
options.TasksComparer = new TasksNameComparer();
project.Save(dataDir + "SortedByNames_out.pdf", options);
options.TasksComparer = new TasksDurationComparer();
project.Save(dataDir + "SortedByDurations_out.pdf", options);
}
public class TasksNameComparer : IComparer<Task>
{
public int Compare(Task x, Task y)
{
return x.Get(Tsk.Name).CompareTo(y.Get(Tsk.Name));
}
}
public class TasksDurationComparer : IComparer<Task>
{
public int Compare(Task x, Task y)
{
Duration durX = x.Get(Tsk.Duration);
Duration durY = y.Get(Tsk.Duration);
return durX.TimeSpan.CompareTo(durY.TimeSpan);
}
}
}
Project project = new Project("Project2.mpp");
// Save to one page image (Timescale.days by default)
project.Save("NewProductDevDays.jpeg", new ImageSaveOptions(SaveFileFormat.JPEG));
// Save to one page image (Timescale.ThirdsOfMonths)
ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.JPEG);
options.Timescale = Timescale.ThirdsOfMonths;
project.Save("NewProductDevThirdsOfMonths.jpeg", options);
// Save to one page image (Timescale.Months)
options.Timescale = Timescale.Months;
project.Save("NewProductDevMonths.jpeg", options);
Project project = new Project(dataDir + "CreateProject2.mpp");
var options = new PdfSaveOptions
{
PresentationFormat = PresentationFormat.GanttChart,
FitContent = true,
UseProjectDefaultFont = false,
DefaultFontName = "Segoe UI Black"
};
project.Save(dataDir + "CreateProject2_out.pdf", (SaveOptions)options);
Project project = new Project(dataDir + "CreateProject2.mpp");
HtmlSaveOptions options = new HtmlSaveOptions
{
CssStylePrefix = "test_prefix"
};
project.Save(dataDir + "TestCssStylePrefix_out.html", options);
Project project = new Project(dataDir + "CreateProject2.mpp");
HtmlSaveOptions options = new HtmlSaveOptions
{
CssStylePrefix = "test_prefix"
};
project.Save(dataDir + "TestCssStylePrefix_out.html", options);
Project project = new Project(dataDir + "CreateProject2.mpp");
HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
// Determines whether to include project name in HTML title (true by default)
htmlSaveOptions.IncludeProjectNameInTitle = false;
// Determines whether to include project name in HTML page header (true by default)
htmlSaveOptions.IncludeProjectNameInPageHeader = false;
htmlSaveOptions.Pages = new List<int>();
htmlSaveOptions.Pages.Add(1);
project.Save(dataDir + "ControlHeaderNameDuringHTMLExport_out.html", htmlSaveOptions);
Project project = new Project(dataDir + "CreateProject2.mpp");
project.Set(Prj.StartDate, new DateTime(2014, 9, 22));
// By default project.DateFormat == DateFormat.Date_ddd_mm_dd_yy (Mon 09/22/14) customize DateFormat (September 22, 2014)
project.Set(Prj.DateFormat, DateFormat.DateMmmmDdYyyy);
project.Save(dataDir + "CustomizeDateFormats1_out.pdf", SaveFileFormat.PDF);
// Export to date format 19/07/2016
project.Set(Prj.DateFormat, DateFormat.DateDdMmYyyy);
project.Save(dataDir + "CustomizeDateFormats2_out.pdf", SaveFileFormat.PDF);
Project project = new Project(dataDir + "CreateProject2.mpp");
SaveOptions options = new PdfSaveOptions();
options.PresentationFormat = PresentationFormat.ResourceSheet;
TextStyle style = new TextStyle();
style.Color = Color.OrangeRed;
style.FontStyle = FontStyle.Bold;
style.FontStyle |= FontStyle.Italic;
style.ItemType = TextItemType.OverallocatedResources;
options.TextStyles = new List<TextStyle>();
options.TextStyles.Add(style);
project.Save(dataDir + "CustomizeTextStyle_out.pdf", options);
Project project = new Project(dataDir + "CreateProject2.mpp");
SaveOptions saveOptions = new PdfSaveOptions();
// Set option fit content to true
saveOptions.FitContent = true;
saveOptions.Timescale = Timescale.Months;
saveOptions.PresentationFormat = PresentationFormat.TaskUsage;
project.Save(dataDir + "FitContentsToCellSize_out.pdf", saveOptions);
SaveOptions saveOptions = new PdfSaveOptions();
// Set the LegendOnEachPage property to false to hide legends
saveOptions.LegendOnEachPage = false;
Project project = new Project(dataDir + "CreateProject2.mpp");
ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFileFormat.PNG);
saveOptions.StartDate = project.Get(Prj.StartDate).AddDays(-3);
saveOptions.EndDate = project.Get(Prj.FinishDate);
saveOptions.MarkCriticalTasks = true;
saveOptions.LegendOnEachPage = false;
saveOptions.Gridlines = new List<Gridline>();
Gridline gridline = new Gridline();
gridline.GridlineType = GridlineType.GanttRow;
gridline.Color = Color.CornflowerBlue;
gridline.Pattern = LinePattern.Dashed;
saveOptions.Gridlines.Add(gridline);
// Save the whole project layout to one file
project.Save(dataDir + "PrintProjectPagesToSeparateFiles1_out.png", (SaveOptions)saveOptions);
// Save project layout to separate files
saveOptions.SaveToSeparateFiles = true;
project.Save(dataDir + "PrintProjectPagesToSeparateFiles2_out.png", (SaveOptions)saveOptions);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
//Read the MPP file.
Project project = new Project(dataDir + "CreateProject2.mpp");
//Use ReduceFooterGap property to reduce the gap between list of tasks and Footer
var imageSaveOptions =
new ImageSaveOptions(SaveFileFormat.PNG) { ReduceFooterGap = true, /* set to true */ SaveToSeparateFiles = true, PageSize = PageSize.A0, Timescale = Timescale.Days };
project.Save(dataDir + "ReducingGapBetweenTasksListAndFooter_out.png", (SaveOptions)imageSaveOptions);
var pdfSaveOptions = new PdfSaveOptions { ReduceFooterGap = true, /* set to true */ SaveToSeparateFiles = true, PageSize = PageSize.A0, Timescale = Timescale.Days };
project.Save(dataDir + "ReducingGapBetweenTasksListAndFooter_out.pdf", (SaveOptions)pdfSaveOptions);
var htmlSaveOptions = new HtmlSaveOptions
{
ReduceFooterGap = false, // set to true
IncludeProjectNameInPageHeader = false,
IncludeProjectNameInTitle = false,
PageSize = PageSize.A0,
Timescale = Timescale.Days
};
project.Save(dataDir + "ReducingGapBetweenTasksListAndFooter_out.html", htmlSaveOptions);
Project project = new Project(dataDir + "PrintProject5.mpp");
project.DefaultView.PageInfo.PageViewSettings.PrintNotes = true;
project.Save(dataDir + "ProjectWithComments.pdf", Saving.SaveFileFormat.PDF);
Project project = new Project(dataDir + "TestProject1.mpp");
ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.TIFF);
options.HorizontalResolution = 72;
options.VerticalResolution = 72;
options.PixelFormat = PixelFormat.Format24bppRgb;
project.Save(dataDir + "RenderProjectDataToFormat24bppRgb_out.tif", (SaveOptions)options);
Project project = new Project(dataDir + "CreateProject1.mpp");
project.Save(dataDir + "SaveProjectAsCSV_out.csv", SaveFileFormat.CSV);
Project project = new Project(dataDir + "CreateProject2.mpp");
// in order to manipulate JPEG quality one can use ImageSaveOptions.JpegQuality property.
// The allowed value range is 0..100.
var options = new ImageSaveOptions(SaveFileFormat.JPEG) { JpegQuality = 50 };
project.Save(dataDir + "image_out.jpeg", (SaveOptions)options);
// Read the input Project file
Project project = new Project(dataDir + "CreateProject2.mpp");
// Save the Project as PDF
project.Save(dataDir + "SaveProjectAsPDF_out.pdf", SaveFileFormat.PDF);
// Read the input Project file
Project project = new Project(dataDir + "CreateProject1.mpp");
// Save the Project as SVG
project.Save(dataDir + "SaveProjectAsSVG_out.SVG", SaveFileFormat.SVG);
// Read the input Project file
Project project = new Project(dataDir + "CreateProject2.mpp");
// Save the Project as text
project.Save(dataDir + "SaveProjectAsText_out.txt", SaveFileFormat.TXT);
// Read the input Project file
Project project = new Project(dataDir + "CreateProject2.mpp");
// Save the Project as XLSX
project.Save(dataDir + "SaveProjectAsXLSX_out.xlsx", SaveFileFormat.XLSX);
Project project = new Project(dataDir + "CreateProject2.mpp");
HtmlSaveOptions option = new HtmlSaveOptions();
project.Save(dataDir + "SaveProjectDataAsHTML_out.html", option);
// OR
// Adding only one page (page number 2)
option = new HtmlSaveOptions();
option.Pages.Add(2);
project.Save(dataDir + "SaveProjectDataAsHTML2_out.html", option);
const string projectName = "Project2.mpp";
Project project = new Project(dataDir + projectName);
ProjectFileInfo projectFileInfo = Project.GetProjectFileInfo(dataDir + projectName);
if (FileFormat.MPP14 == projectFileInfo.ProjectFileFormat)
{
Console.WriteLine("Project file format is ok");
}
SaveTemplateOptions options = new SaveTemplateOptions();
options.RemoveActualValues = true;
options.RemoveBaselineValues = true;
const string templateName = "SaveProjectDataAsTemplate_out.mpt";
project.SaveAsTemplate(dataDir + templateName);
ProjectFileInfo templateFileInfo = Project.GetProjectFileInfo(dataDir + templateName);
if (FileFormat.MPT14 == templateFileInfo.ProjectFileFormat)
{
Console.WriteLine("Template FileFormat is ok");
}
Project project = new Project(dataDir + "CreateProject2.mpp");
project.Save(dataDir + "SaveProjectDataToSpreadsheet2003XML_out.xml", SaveFileFormat.Spreadsheet2003);
Project project = new Project(dataDir + "Software Development Plan.mpp");
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.SaveToSeparateFiles = true;
saveOptions.Pages = new List<int>();
saveOptions.Pages.Add(1);
saveOptions.Pages.Add(4);
project.Save(dataDir + "SaveToMultiplePDFFiles_out.pdf", (SaveOptions)saveOptions);
Spreadsheet2003SaveOptions options = new Spreadsheet2003SaveOptions();
GanttChartColumn col = new GanttChartColumn("WBS", 100, delegate(Task task) { return task.Get(Tsk.WBS); });
options.View.Columns.Add(col);
ResourceViewColumn rscCol = new ResourceViewColumn("Cost center", 100, delegate(Resource resource)
{ return resource.Get(Rsc.CostCenter); });
options.ResourceView.Columns.Add(rscCol);
AssignmentViewColumn assnCol = new AssignmentViewColumn("Notes", 200, delegate(ResourceAssignment assignment)
{ return assignment.Get(Asn.Notes); });
options.AssignmentView.Columns.Add(assnCol);
project.Save(dataDir + "UsingSpreadsheet2003SaveOptions_out.xml", options);
// Read the input Project file
Project project = new Project(dataDir + "CreateProject2.mpp");
SaveOptions saveOptions = new SvgOptions();
saveOptions.FitContent = true;
saveOptions.Timescale = Timescale.ThirdsOfMonths;
project.Save(dataDir + "UseSvgOptions_out.svg", saveOptions);
// Read the input Project file
Project project = new Project(dataDir + "CreateProject2.mpp");
XlsxOptions options = new XlsxOptions();
// Add desired Gantt Chart columns
GanttChartColumn col = new GanttChartColumn("WBS", 100, delegate(Task task) { return task.Get(Tsk.WBS); });
options.View.Columns.Add(col);
// Add desired resource view columns
ResourceViewColumn rscCol = new ResourceViewColumn("Cost center", 100, delegate(Resource resource)
{ return resource.Get(Rsc.CostCenter); });
options.ResourceView.Columns.Add(rscCol);
// Add desired assignment view columns
AssignmentViewColumn assnCol = new AssignmentViewColumn("Notes", 200, delegate(ResourceAssignment assignment)
{ return assignment.Get(Asn.Notes); });
options.AssignmentView.Columns.Add(assnCol);
project.Save(dataDir + "UsingXlsxOptions_out.xlsx", options);
Project project = new Project(dataDir + "Project1.mpp");
Task task = project.RootTask.Children.Add("Task1");
task.Set(Tsk.ActualStart, DateTime.Parse("23-Aug-2012"));
// Set duration in hours
task.Set(Tsk.Duration, project.GetDuration(24, TimeUnitType.Hour));
task.Set(Tsk.DurationFormat, TimeUnitType.Day);
// Save the Project as XML
project.Save(dataDir + "AddNewTask_out.xml", SaveFileFormat.XML);
Project project1 = new Project(dataDir + "SampleProject.mpp");
// Declare ChildTasksCollector class object
ChildTasksCollector collector = new ChildTasksCollector();
// Use TaskUtils to get all children tasks in RootTask
TaskUtils.Apply(project1.RootTask, collector, 0);
// Define Resources
for (int i = 0; i <= 4; i++)
{
string devloper = "Developer0" + i;
// Add resource to project
Resource newResource = project1.Resources.Add(devloper);
newResource.Set(Rsc.Type, ResourceType.Work);
// Define assignment
ResourceAssignment newResourceAssignment = project1.ResourceAssignments.Add((Task)collector.Tasks[i], newResource);
}
project1.Save(dataDir + "CreateResourcesAndLinkToTasks_out.mpp", SaveFileFormat.MPP);
Project project = new Project(dataDir + "SampleProject.mpp");
Task task1 = project.RootTask.Children.GetById(1);
Task task2 = project.RootTask.Children.GetById(2);
Task task3 = project.RootTask.Children.GetById(3);
Task task4 = project.RootTask.Children.GetById(4);
Task task5 = project.RootTask.Children.GetById(5);
// Link the tasks
TaskLink tsklnk = project.TaskLinks.Add(task1, task2, TaskLinkType.FinishToStart);
tsklnk = project.TaskLinks.Add(task2, task3, TaskLinkType.FinishToStart);
tsklnk = project.TaskLinks.Add(task3, task4, TaskLinkType.FinishToStart);
tsklnk = project.TaskLinks.Add(task4, task5, TaskLinkType.FinishToStart);
tsklnk = project.TaskLinks.Add(task2, task5, TaskLinkType.FinishToStart);
// Display links among the tasks
TaskLinkCollection allinks = project.TaskLinks;
foreach (TaskLink tasklnk in allinks)
{
Console.WriteLine("From ID = " + tasklnk.PredTask.Get(Tsk.Id) + "=>To ID = " + tasklnk.SuccTask.Get(Tsk.Id));
Console.WriteLine("________________________________________");
}
// Save the project
project.Save(dataDir + "LinkTasks_out.mpp", SaveFileFormat.MPP);
// Load MPP file
Project project = new Project(dataDir + "Project1.mpp");
// Get the critical path
TaskCollection criticalPath = project.CriticalPath;
// Enumerate the tasks in the critical path
foreach (Task task in criticalPath)
{
Console.WriteLine(task.Get(Tsk.Id) + " " + task.Get(Tsk.Name));
Console.WriteLine(task.Get(Tsk.Start));
Console.WriteLine(task.Get(Tsk.Finish) + "\n");
}
// Load MPP file
Project project = new Project(dataDir + "Project1.mpp");
// Load all tasks
TaskCollection allTasks = project.RootTask.Children;
// Loop through each task and read information related to tasks
foreach (Task task in allTasks)
{
Console.WriteLine("Reading Task " + task.Get(Tsk.Name));
Console.WriteLine("\nID: " + task.Get(Tsk.Id));
Console.WriteLine("Start: " + task.Get(Tsk.Start));
Console.WriteLine("Finish: " + task.Get(Tsk.Finish));
Console.WriteLine("\n===========================\n");
}
// Loop through each resource and read information related to resources
foreach (Resource resource in project.Resources)
{
string resourceType = null;
switch (resource.Get(Rsc.Type))
{
case ResourceType.Material:
resourceType = "Material";
break;
case ResourceType.Work:
resourceType = "Work";
break;
default:
resourceType = "Cost";
break;
}
Console.WriteLine("Reading Resource " + resource.Get(Rsc.Name));
Console.WriteLine("\nID: " + resource.Get(Rsc.Id));
Console.WriteLine("Type: " + resourceType);
Console.WriteLine("\n===========================\n");
}
Aspose.Tasks.License license = new Aspose.Tasks.License();
license.SetLicense("Aspose.Tasks.lic");
Aspose.Tasks.License license = new Aspose.Tasks.License();
FileStream myStream = new FileStream("Aspose.Tasks.lic", FileMode.Open);
license.SetLicense(myStream);
// Create a prject instance
Project project1 = new Project();
// Define Tasks
Task task1 = project1.RootTask.Children.Add("Task1");
task1.Set(Tsk.ActualStart, DateTime.Parse("06-Apr-2010"));
Task task2 = project1.RootTask.Children.Add("Task2");
task2.Set(Tsk.ActualStart, DateTime.Parse("10-Apr-2010"));
// Save the Project as XML
project1.Save("EvalProject_out.xml", SaveFileFormat.XML);
Project project;
try
{
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
project = new Project(dataDir + "project.mpp");
}
catch (TasksReadingException ex)
{
Console.WriteLine("Message:");
Console.WriteLine(ex.Message);
Console.WriteLine("Log:");
Console.WriteLine(ex.LogText);
if (ex.InnerException != null)
{
Console.WriteLine("Inner exception message:");
Console.WriteLine(ex.InnerException.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// Analyze the project risks
RiskAnalyzer analyzer = new RiskAnalyzer(settings);
RiskAnalysisResult analysisResult = analyzer.Analyze(project);
Project project = new Project(dataDir + "Software Development Plan-1.mpp");
Task task = project.RootTask.Children.GetById(17);
// Initialize a risk pattern
RiskPattern pattern = new RiskPattern(task);
// Select a distribution type for the random number generator to generate possible values from (only two types currently supported, namely normal and uniform)
// For more details see here: https://en.wikipedia.org/wiki/Normal_distribution)
pattern.Distribution = ProbabilityDistributionType.Normal;
// Set the percentage of the most likely task duration which can happen in the best possible project scenario
// The default value is 75, which means that if the estimated specified task duration is 4 days then the optimistic duration will be 3 days
pattern.Optimistic = 70;
// Set the percentage of the most likely task duration which can happen in the worst possible project scenario
// The defaut value is 125, which means that if the estimated specified task duration is 4 days then the pessimistic duration will be 5 days.
pattern.Pessimistic = 130;
// Set a confidence level that correspond to the percentage of the time the actual values will be within optimistic and pessimistic estimates.
// You can think of it as a value of standard deviation: the more uncertain about your estimates you are, the more the value of standard deviation used in random number generator is
pattern.ConfidenceLevel = ConfidenceLevel.CL75;
settings.Patterns.Add(pattern);
RiskAnalysisSettings settings = new RiskAnalysisSettings();
// Set number of iterations for Monte Carlo simulation (the default value is 100).
settings.IterationsCount = 200;
// Select the desired output (here we get early finish of the root task)
RiskItemStatistics rootEarlyFinish = analysisResult.GetRiskItems(RiskItemType.EarlyFinish).Get(project.RootTask);
Console.WriteLine("Expected value: {0}", rootEarlyFinish.ExpectedValue);
Console.WriteLine("StandardDeviation: {0}", rootEarlyFinish.StandardDeviation);
Console.WriteLine("10% Percentile: {0}", rootEarlyFinish.GetPercentile(10));
Console.WriteLine("50% Percentile: {0}", rootEarlyFinish.GetPercentile(50));
Console.WriteLine("90% Percentile: {0}", rootEarlyFinish.GetPercentile(90));
Console.WriteLine("Minimum: {0}", rootEarlyFinish.Minimum);
Console.WriteLine("Maximum: {0}", rootEarlyFinish.Maximum);
// Save PDF report which is rendered for Project Root Task Finish date
analysisResult.SaveReport(dataDir + "AnalysisReport_out.pdf");
Project project1 = new Project(dataDir + "Cyclic stucture.mpp");
project1.SaveReport(dataDir + "BestPracticeAnalyzer_out.pdf", ReportType.BestPracticeAnalyzer);
Project project1 = new Project(dataDir + "Homemoveplan.mpp");
project1.SaveReport(dataDir + "Burndown_out.pdf", ReportType.Burndown);
Project project1 = new Project(dataDir + "OzBuild 16 Orig.mpp");
project1.SaveReport(dataDir + "CashFlow_out.pdf", ReportType.CashFlow);
Project project1 = new Project(dataDir + "Software Development.mpp");
project1.SaveReport(dataDir + "CostOverruns_out.pdf", ReportType.CostOverruns);
Project project1 = new Project(dataDir + "OzBuild 16 Orig.mpp");
project1.SaveReport(dataDir + "CostOverview_out.pdf", ReportType.CostOverview);
Project project1 = new Project(dataDir + "Residential Construction.mpp");
project1.SaveReport(dataDir + "CriticalTasks_out.pdf", ReportType.CriticalTasks);
Project project1 = new Project(dataDir + "Residential Construction.mpp");
project1.SaveReport(dataDir + "LateTasks_out.pdf", ReportType.LateTasks);
Project project1 = new Project(dataDir + "Residential Construction.mpp");
project1.SaveReport(dataDir + "Milestones_out.pdf", ReportType.Milestones);
Project project1 = new Project(dataDir + "Software Development Plan.mpp");
project1.SaveReport(dataDir + "OverAllocatedResources_out.pdf", ReportType.OverallocatedResources);
Project project1 = new Project(dataDir + "Cyclic stucture.mpp");
project1.SaveReport(dataDir + "ProjectOverView_out.pdf", ReportType.ProjectOverview);
Project project1 = new Project(dataDir + "OzBuild 16 Orig.mpp");
project1.SaveReport(dataDir + "ResourceCostOverview_out.pdf", ReportType.ResourceCostOverview);
Project project1 = new Project(dataDir + "Software Development Plan.mpp");
project1.SaveReport(dataDir + "ResourceOverview_out.pdf", ReportType.ResourceOverview);
Project project1 = new Project(dataDir + "Homemoveplan.mpp");
project1.SaveReport(dataDir + "SlippingTasks_out.pdf", ReportType.SlippingTasks);
Project project1 = new Project(dataDir + "Software Development.mpp");
project1.SaveReport(dataDir + "TaskCostOverview_out.pdf", ReportType.TaskCostOverview);
Project project1 = new Project(dataDir + "UpcomingTasks.mpp");
project1.SaveReport(dataDir + "UpcomingTasks_out.pdf", ReportType.UpcomingTask);
Project project1 = new Project(dataDir + "Residential Construction.mpp");
project1.SaveReport(dataDir + "WorkOverview_out.pdf", ReportType.WorkOverview);
private class RscNameComparer : IComparer<Resource>
{
public int Compare(Resource x, Resource y)
{
if (string.IsNullOrEmpty(x.Get(Rsc.Name)))
return 1;
if (string.IsNullOrEmpty(y.Get(Rsc.Name)))
return -1;
return x.Get(Rsc.Name).CompareTo(y.Get(Rsc.Name));
}
}
Project project = new Project(dataDir + "project-sort.mpp");
List<Resource> resources = project.Resources.ToList();
resources.Sort(new RscNameComparer());
foreach (Resource rsc in resources)
{
Console.WriteLine(rsc);
}
private class TaskNameComparer : IComparer<Task>
{
public int Compare(Task x, Task y)
{
if (string.IsNullOrEmpty(x.Get(Tsk.Name)))
return 1;
if (string.IsNullOrEmpty(y.Get(Tsk.Name)))
return -1;
return x.Get(Tsk.Name).CompareTo(y.Get(Tsk.Name));
}
}
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = new Project(dataDir + "project-sort.mpp");
ChildTasksCollector coll = new ChildTasksCollector();
TaskUtils.Apply(project.RootTask, coll, 0);
List<Task> tasks = coll.Tasks;
tasks.Sort(new TaskNameComparer());
foreach (Task task in tasks)
{
Console.WriteLine(task);
}
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = new Project(dataDir + "project.mpp");
// Define outline code and its outline mask
OutlineCodeDefinition code1 = new OutlineCodeDefinition();
code1.Alias = "New task outline code1";
code1.FieldId = ((int)ExtendedAttributeTask.OutlineCode1).ToString();
code1.FieldName = "Outline Code1";
OutlineMask mask = new OutlineMask();
mask.Separator = "+";
mask.Level = 1;
mask.Type = MaskType.Numbers;
code1.Masks.Add(mask);
// Add outline value
OutlineValue value = new OutlineValue();
value.Description = "Value description";
value.ValueId = 1;
value.Value = "123456";
value.Type = OutlineValueType.Number;
code1.Values.Add(value);
// Add outline code to project
project.OutlineCodes.Add(code1);
// Define outline code and its outline mask
OutlineCodeDefinition code2 = new OutlineCodeDefinition();
code2.Alias = "New rsc outline code2";
code2.FieldId = ((int)ExtendedAttributeResource.OutlineCode2).ToString();
code2.FieldName = "Outline Code2";
OutlineMask mask2 = new OutlineMask();
mask2.Separator = "/";
mask2.Level = 1;
mask2.Type = MaskType.Numbers;
code2.Masks.Add(mask2);
// Add outline value
OutlineValue value2 = new OutlineValue();
value2.Description = "Value2 description";
value2.ValueId = 2;
value2.Value = "987654";
value2.Type = OutlineValueType.Number;
code2.Values.Add(value2);
// Add outline code to project
project.OutlineCodes.Add(code2);
// Save project as MPP
project.Save(dataDir + "Updated_project_out.mpp", SaveFileFormat.MPP);
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = new Project(dataDir + "Project1.mpp");
// Add working times to project calendar
WorkingTime wt = new WorkingTime();
wt.FromTime = new DateTime(2010, 1, 1, 19, 0, 0);
wt.ToTime = new DateTime(2010, 1, 1, 20, 0, 0);
WeekDay day = project.Get(Prj.Calendar).WeekDays.ToList()[1];
day.WorkingTimes.Add(wt);
// Change calendar name
project.Get(Prj.Calendar).Name = "CHANGED NAME!";
// Add tasks and set task meta data
Task task = project.RootTask.Children.Add("Task 1");
task.Set(Tsk.DurationFormat, TimeUnitType.Day);
task.Set(Tsk.Duration, project.GetDuration(3));
task.Set(Tsk.Contact, "Rsc 1");
task.Set(Tsk.IsMarked, true);
task.Set(Tsk.IgnoreWarnings, true);
Task task2 = project.RootTask.Children.Add("Task 2");
task2.Set(Tsk.DurationFormat, TimeUnitType.Day);
task2.Set(Tsk.Contact, "Rsc 2");
// Link tasks
project.TaskLinks.Add(task, task2, TaskLinkType.FinishToStart, project.GetDuration(-1, TimeUnitType.Day));
// Set project start date
project.Set(Prj.StartDate, new DateTime(2013, 8, 13, 9, 0, 0));
// Add resource and set resource meta data
Resource rsc1 = project.Resources.Add("Rsc 1");
rsc1.Set(Rsc.Type, ResourceType.Work);
rsc1.Set(Rsc.Initials, "WR");
rsc1.Set(Rsc.AccrueAt, CostAccrualType.Prorated);
rsc1.Set(Rsc.MaxUnits, 1);
rsc1.Set(Rsc.Code, "Code 1");
rsc1.Set(Rsc.Group, "Workers");
rsc1.Set(Rsc.EMailAddress, "1@gmail.com");
rsc1.Set(Rsc.WindowsUserAccount, "user_acc1");
rsc1.Set(Rsc.IsGeneric, new NullableBool(true));
rsc1.Set(Rsc.AccrueAt, CostAccrualType.End);
rsc1.Set(Rsc.StandardRate, 10);
rsc1.Set(Rsc.StandardRateFormat, RateFormatType.Day);
rsc1.Set(Rsc.OvertimeRate, 15);
rsc1.Set(Rsc.OvertimeRateFormat, RateFormatType.Hour);
rsc1.Set(Rsc.IsTeamAssignmentPool, true);
rsc1.Set(Rsc.CostCenter, "Cost Center 1");
// Create resource assignment and set resource assignment meta data
ResourceAssignment assn = project.ResourceAssignments.Add(task, rsc1);
assn.Set(Asn.Uid, 1);
assn.Set(Asn.Work, task.Get(Tsk.Duration));
assn.Set(Asn.RemainingWork, assn.Get(Asn.Work));
assn.Set(Asn.RegularWork, assn.Get(Asn.Work));
task.Set(Tsk.Work, assn.Get(Asn.Work));
rsc1.Set(Rsc.Work, task.Get(Tsk.Work));
assn.Set(Asn.Start, task.Get(Tsk.Start));
assn.Set(Asn.Finish, task.Get(Tsk.Finish));
// Add extended attribute for project and task
ExtendedAttributeDefinition attr = ExtendedAttributeDefinition.CreateTaskDefinition(CustomFieldType.Flag, ExtendedAttributeTask.Flag1, "My Flag Field");
project.ExtendedAttributes.Add(attr);
ExtendedAttribute taskAttr = attr.CreateExtendedAttribute();
taskAttr.FlagValue = true;
task2.ExtendedAttributes.Add(taskAttr);
// Save project as MPP
project.Save(dataDir + "WriteMetaData_out.mpp", SaveFileFormat.MPP);
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
using (FileStream fs = new FileStream(dataDir + "project_test.mpp", FileMode.Open))
{
// Create project instance
Project prj = new Project(fs);
// Remove an exception
Aspose.Tasks.Calendar cal = prj.Calendars.ToList()[0];
if (cal.Exceptions.Count > 1)
{
CalendarException exc = cal.Exceptions.ToList()[0];
cal.Exceptions.Remove(exc);
}
// Add an exception
CalendarException calExc = new CalendarException();
calExc.FromDate = new System.DateTime(2009, 1, 1);
calExc.ToDate = new System.DateTime(2009, 1, 3);
cal.Exceptions.Add(calExc);
// Display exceptions
foreach (CalendarException calExc1 in cal.Exceptions)
{
Console.WriteLine("From" + calExc1.FromDate.ToShortDateString());
Console.WriteLine("To" + calExc1.ToDate.ToShortDateString());
}
}
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
// Create a project instance
Project prj = new Project();
// Define Calendar
Aspose.Tasks.Calendar cal = prj.Calendars.Add("Calendar1");
// Define week days exception for a holiday
CalendarException except = new CalendarException();
except.EnteredByOccurrences = false;
except.FromDate = new DateTime(2009, 12, 24, 0, 0, 0);
except.ToDate = new DateTime(2009, 12, 31, 23, 59, 0);
except.Type = CalendarExceptionType.Daily;
except.DayWorking = false;
cal.Exceptions.Add(except);
// Save the Project
prj.Save(dataDir + "Project_DefineWeekDayException_out.xml", Aspose.Tasks.Saving.SaveFileFormat.XML);
// Define exception and specify occurences
CalendarException except = new CalendarException();
except.EnteredByOccurrences = true;
except.Occurrences = 5;
except.Type = CalendarExceptionType.YearlyByDay;
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
// Create project instance
Project project1 = new Project(dataDir + "project_RetrieveExceptions_test.mpp");
// Access calendars
foreach (Aspose.Tasks.Calendar cal in project1.Calendars)
{
// Access calendar exceptions
foreach (CalendarException calExc in cal.Exceptions)
{
Console.WriteLine("From: " + calExc.FromDate.ToShortDateString());
Console.WriteLine("To: " + calExc.ToDate.ToShortDateString());
}
}
// Load an existing project
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = new Project(dataDir + "CalculateWorkHours.mpp");
// Access Task By Id
Task task = project.RootTask.Children.GetById(1);
// Access Calendar and it's start and end dates
Aspose.Tasks.Calendar taskCalendar = task.Get(Tsk.Calendar);
DateTime startDate = task.Get(Tsk.Start);
DateTime endDate = task.Get(Tsk.Finish);
DateTime tempDate = startDate;
// Access resource and their calendar
Resource resource = project.Resources.GetByUid(1);
Aspose.Tasks.Calendar resourceCalendar = resource.Get(Rsc.Calendar);
TimeSpan timeSpan;
// Get Duration in Minutes
double durationInMins = 0;
while (tempDate < endDate)
{
if (taskCalendar.IsDayWorking(tempDate) && resourceCalendar.IsDayWorking(tempDate))
{
timeSpan = taskCalendar.GetWorkingHours(tempDate);
durationInMins = durationInMins + timeSpan.TotalMinutes;
}
tempDate = tempDate.AddDays(1);
}
tempDate = startDate;
// Get Duration in Hours
double durationInHours = 0;
while (tempDate < endDate)
{
if (taskCalendar.IsDayWorking(tempDate) && resourceCalendar.IsDayWorking(tempDate))
{
timeSpan = taskCalendar.GetWorkingHours(tempDate);
durationInHours = durationInHours + timeSpan.TotalHours;
}
tempDate = tempDate.AddDays(1);
}
tempDate = startDate;
// Get Duration in Days
double durationInDays = 0;
while (tempDate < endDate)
{
if (taskCalendar.IsDayWorking(tempDate) && resourceCalendar.IsDayWorking(tempDate))
{
timeSpan = taskCalendar.GetWorkingHours(tempDate);
if (timeSpan.TotalHours > 0)
durationInDays = durationInDays + timeSpan.TotalDays * (24 / (timeSpan.TotalHours));
}
tempDate = tempDate.AddDays(1);
}
Console.WriteLine("Duration in Minutes = " + durationInMins);
Console.WriteLine("Duration in Hours = " + durationInHours);
Console.WriteLine("Duration in Days = " + durationInDays);
// Create a project instance
Project project = new Project();
// New calendar can be added to a project's calendar collection using the collection's Add method.
Aspose.Tasks.Calendar cal1 = project.Calendars.Add("New Info");
Aspose.Tasks.Calendar cal2 = project.Calendars.Add("no name");
Aspose.Tasks.Calendar cal3 = project.Calendars.Add("cal3");
// Save the Project
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
project.Save(dataDir + "CreatingCalendar_out.Xml", Aspose.Tasks.Saving.SaveFileFormat.XML);
// This example shows how Aspose.Tasks API can be used to define a new Calendar, add week days to it and define working times for days
// Create a project instance
Project project = new Project();
// Define Calendar
Aspose.Tasks.Calendar cal = project.Calendars.Add("Calendar1");
// Add working days monday through thursday with default timings
cal.WeekDays.Add(WeekDay.CreateDefaultWorkingDay(DayType.Monday));
cal.WeekDays.Add(WeekDay.CreateDefaultWorkingDay(DayType.Tuesday));
cal.WeekDays.Add(WeekDay.CreateDefaultWorkingDay(DayType.Wednesday));
cal.WeekDays.Add(WeekDay.CreateDefaultWorkingDay(DayType.Thursday));
cal.WeekDays.Add(new WeekDay(DayType.Saturday));
cal.WeekDays.Add(new WeekDay(DayType.Sunday));
// Set friday as short working day
WeekDay myWeekDay = new WeekDay(DayType.Friday);
// Sets working time. Only time part of DateTime is important
WorkingTime wt1 = new WorkingTime();
wt1.FromTime = new DateTime(1, 1, 1, 9, 0, 0, 0);
wt1.ToTime = new DateTime(1, 1, 1, 12, 0, 0, 0);
WorkingTime wt2 = new WorkingTime();
wt2.FromTime = new DateTime(1, 1, 1, 13, 0, 0, 0);
wt2.ToTime = new DateTime(1, 1, 1, 16, 0, 0, 0);
myWeekDay.WorkingTimes.Add(wt1);
myWeekDay.WorkingTimes.Add(wt2);
myWeekDay.DayWorking = true;
cal.WeekDays.Add(myWeekDay);
// Save the Project
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
project.Save("Project_DefineCalendarWeekdays_out.xml", Aspose.Tasks.Saving.SaveFileFormat.XML);
// Create a project instance
Project project = new Project();
// Define Calendar and make it standard
Aspose.Tasks.Calendar cal1 = project.Calendars.Add("My Cal");
Aspose.Tasks.Calendar.MakeStandardCalendar(cal1);
// Save the Project
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
project.Save(dataDir + "Project_MakeStandardCalendar_out.xml", Aspose.Tasks.Saving.SaveFileFormat.XML);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = new Project(dataDir + "ReplaceCalendar.mpp");
// Add a new calendar to the project's calendars collection
project.Calendars.Add("New cal1", project.Get(Prj.Calendar));
// Now traverse through project calendars and replace the already added calendar with a new one
CalendarCollection calColl = project.Calendars;
foreach (Calendar c in calColl)
{
if (c.Name == "New cal1")
{
calColl.Remove(c);
calColl.Add("New cal2", project.Get(Prj.Calendar));
break;
}
}
// Create project
Project project = new Project(dataDir + "Project5.mpp");
// Access project calendars
CalendarCollection calColl = project.Calendars;
foreach (Calendar myCalendar in calColl)
{
if (myCalendar.Name == "TestCalendar")
{
// Remove calendar
calColl.Remove(myCalendar);
}
}
// Add new calendar
Calendar newCalendar = calColl.Add("TestCalendar");
project.Save(dataDir + "ReplaceCalendar_out.mpp", SaveFileFormat.MPP);
string resultFile = "result_WriteUpdatedCalendarDataToMPP_out.mpp";
string newFile = "project_update_test.mpp";
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
try
{
// Create project instance and access calendar
Project project = new Project(dataDir + newFile);
Calendar cal = project.Calendars.GetByUid(3);
// Update the calendar information
Calendar.MakeStandardCalendar(cal);
cal.Name = "Test calendar";
CalendarException exc = new CalendarException();
exc.FromDate = DateTime.Now;
exc.ToDate = DateTime.Now.AddDays(2);
exc.DayWorking = true;
WorkingTime wt1 = new WorkingTime();
wt1.FromTime = new DateTime(10, 1, 1, 9, 0, 0);
wt1.ToTime = new DateTime(10, 1, 1, 13, 0, 0);
WorkingTime wt2 = new WorkingTime();
wt2.FromTime = new DateTime(10, 1, 1, 14, 0, 0);
wt2.ToTime = new DateTime(10, 1, 1, 19, 0, 0);
WorkingTime wt3 = new WorkingTime();
wt3.FromTime = new DateTime(10, 1, 1, 20, 0, 0);
wt3.ToTime = new DateTime(10, 1, 1, 21, 0, 0);
exc.WorkingTimes.Add(wt1);
exc.WorkingTimes.Add(wt2);
exc.WorkingTimes.Add(wt3);
cal.Exceptions.Add(exc);
CalendarException exc2 = new CalendarException();
exc2.FromDate = DateTime.Now.AddDays(7);
exc2.ToDate = exc2.FromDate;
exc2.DayWorking = false;
cal.Exceptions.Add(exc2);
project.Set(Prj.Calendar, cal);
// Save project
project.Save(dataDir + resultFile, SaveFileFormat.MPP);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
}
// Load an existing project
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = new Project(dataDir + "Project_GeneralCalendarProperties.xml");
foreach (Aspose.Tasks.Calendar cal in project.Calendars)
{
if (cal.Name != null)
{
Console.WriteLine("UID : " + cal.Uid.ToString() + " Name: " + cal.Name);
// Show if it is has a base calendar
Console.Write("Base Calendar : ");
if (cal.IsBaseCalendar)
Console.WriteLine("Self");
else
Console.WriteLine(cal.BaseCalendar.Name);
// Get Time in hours on each working day
foreach (WeekDay wd in cal.WeekDays)
{
TimeSpan ts = wd.GetWorkingTime();
Console.WriteLine("Day Type: " + wd.DayType.ToString() + " Hours: " + ts.ToString());
}
}
}
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
// Create project instance and access calendar and work weeks collection
Project project = new Project(dataDir + "ReadWorkWeeksInformation.mpp");
Calendar calendar = project.Calendars.GetByUid(3);
WorkWeekCollection collection = calendar.WorkWeeks;
foreach (WorkWeek workWeek in collection)
{
// Display work week name, from and to dates
string Name = workWeek.Name;
DateTime fromDate = workWeek.FromDate;
DateTime toDate = workWeek.ToDate;
// This data is all about "Details." button you can set special working times for special WeekDay or even make it nonworking
WeekDayCollection weekDays = workWeek.WeekDays;
foreach (WeekDay day in weekDays)
{
// You can further traverse through working times and display these
WorkingTimeCollection workingTimes = day.WorkingTimes;
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
// Create a project instance
Project project = new Project(dataDir + "RetrieveCalendarInfo.mpp");
// Retrieve Calendars Information
CalendarCollection alCals = project.Calendars;
foreach (Calendar cal in alCals)
{
if (cal.Name != null)
{
Console.WriteLine("Calendar UID : " + cal.Uid);
Console.WriteLine("Calendar Name : " + cal.Name);
WeekDayCollection alDays = cal.WeekDays;
foreach (WeekDay wd in alDays)
{
TimeSpan ts = wd.GetWorkingTime();
if (wd.DayWorking)
{
Console.WriteLine(wd.DayType.ToString() + ":");
Console.WriteLine(ts.ToString());
}
}
}
}
Project project1 = new Project(dataDir + "project.mpp");
Console.WriteLine(project1.Get(Prj.CurrencyCode));
Project project1 = new Project(dataDir + "project.mpp");
Console.WriteLine(project1.Get(Prj.CurrencyDigits));
Project project1 = new Project(dataDir + "project.mpp");
Console.WriteLine(project1.Get(Prj.CurrencySymbol));
// Create new project and set currency code
Project project1 = new Project();
project1.Set(Prj.CurrencyCode, "USD");
// Create new project and set currency digits
Project project1 = new Project();
project1.Set(Prj.CurrencyDigits, 2);
// Create new project and set currency symbol
Project project1 = new Project();
project1.Set(Prj.CurrencySymbol, "$$");
// Create new project and extended attribute definition
Project project = new Project();
ExtendedAttributeDefinition attribute = ExtendedAttributeDefinition.CreateTaskDefinition(CustomFieldType.Cost, ExtendedAttributeTask.Cost1, "");
attribute.Formula = "[Cost]-[Actual Cost]";
project.ExtendedAttributes.Add(attribute);
// Add task
Task task = project.RootTask.Children.Add("Task");
// Create extended attribute
ExtendedAttribute extendedAttribute = attribute.CreateExtendedAttribute();
task.ExtendedAttributes.Add(extendedAttribute);
// Display if extended attributes are read only or not
Console.WriteLine(extendedAttribute.ValueReadOnly == true ? "Value is Read only" : "Value is not read only");
extendedAttribute.NumericValue = -1000000M;
Console.WriteLine(extendedAttribute.NumericValue == -1000000M ? "Formula values are read-only" : "Values are not read-only");
Project project = CreateTestProject();
Task task = project.RootTask.Children.GetById(1);
ExtendedAttributeDefinition numberDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Number1, null);
project.ExtendedAttributes.Add(numberDefinition);
ExtendedAttribute numberAttribute = numberDefinition.CreateExtendedAttribute();
task.ExtendedAttributes.Add(numberAttribute);
// Set ProjDateDiff formula and print extended attribute value
numberDefinition.Formula = "ProjDateDiff(\"03/23/2015\",\"03/18/2015\")";
Console.WriteLine(numberAttribute.NumericValue);
numberDefinition.Formula = "ProjDateDiff(\"03/23/2015\",\"03/25/2015\")";
Console.WriteLine(numberAttribute.NumericValue);
ExtendedAttributeDefinition dateDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Date1, null);
project.ExtendedAttributes.Add(dateDefinition);
ExtendedAttribute dateAttribute = dateDefinition.CreateExtendedAttribute();
task.ExtendedAttributes.Add(dateAttribute);
ExtendedAttributeDefinition durationDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Duration4, "Custom duration field");
project.ExtendedAttributes.Add(durationDefinition);
ExtendedAttribute durationAttribute = durationDefinition.CreateExtendedAttribute();
task.ExtendedAttributes.Add(durationAttribute);
ExtendedAttributeDefinition textDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Text5, "Custom text field");
project.ExtendedAttributes.Add(textDefinition);
ExtendedAttribute textAttribute = textDefinition.CreateExtendedAttribute();
task.ExtendedAttributes.Add(textAttribute);
// Set ProjDateSub formula and print extended attribute value
dateDefinition.Formula = "ProjDateSub(\"3/19/2015\", \"1d\")";
Console.WriteLine(dateAttribute.DateValue);
// We can set ProjDurConv formula to duration-valued attribute as well as to text-valued attribute.
// Set ProjDurConv formula to duration-valued extended attribute and print its value.
durationDefinition.Formula = "ProjDurConv([Duration], pjHours)";
Console.WriteLine(durationAttribute.DurationValue);
// Set ProjDurConv formula to text-valued extended attribute and print its value.
textDefinition.Formula = "ProjDurConv([Duration], pjHours)";
Console.WriteLine(textAttribute.TextValue);
textDefinition.Formula = "ProjDurConv([Duration], pjWeeks)";
Console.WriteLine(textAttribute.TextValue);
// Set Second formula and print entended attribute value
numberDefinition.Formula = "Second(\"4/21/2015 2:53:41 AM\")";
Console.WriteLine(numberAttribute.NumericValue);
// Set Weekday formula and print entended attribute value
numberDefinition.Formula = "Weekday(\"24/3/2015\", 1)";
Console.WriteLine(numberAttribute.NumericValue);
numberDefinition.Formula = "Weekday(\"24/3/2015\", 2)";
Console.WriteLine(numberAttribute.NumericValue);
numberDefinition.Formula = "Weekday(\"24/3/2015\", 3)";
Console.WriteLine(numberAttribute.NumericValue);
public static void EvaluateChoose()
{
Project project = CreateTestProjectWithCustomField();
// Set Formula
project.ExtendedAttributes[0].Formula = "Choose(3, \"This is a\", \"right\", \"choice\")";
// Print extended attribute value
Task task = project.RootTask.Children.GetById(1);
Console.WriteLine(task.ExtendedAttributes[0].TextValue);
}
public static void EvaluateIsNumeric()
{
string[] numericFormulas = { "IsNumeric('AAA')", "IsNUmeric(1)", "IsNumeric(1<0)", "IsNumeric(\"1.1\")", "IsNumeric(Choose((2 + Sgn(2^-3)), 123, \"one two three\"))" };
Project project = CreateTestProjectWithCustomField();
foreach (string numericFormula in numericFormulas)
{
// Set Formula
project.ExtendedAttributes[0].Formula = numericFormula;
// Print extended attribute value
Task task = project.RootTask.Children.GetById(1);
Console.WriteLine(task.ExtendedAttributes[0].TextValue);
}
}
public static void EvaluateSwitch()
{
Project project = CreateTestProjectWithCustomField();
// Set Formula
project.ExtendedAttributes[0].Formula = "Switch( 0 < 1, \"0 is lesser than 1\", 0 > 1, \"0 is greater than 1\")";
// Print extended attribute value
Task task = project.RootTask.Children.GetById(1);
Console.WriteLine(task.ExtendedAttributes[0].TextValue);
}
public static void EvaluateSine()
{
Project project = CreateTestProjectWithCustomField();
// Set formula Sin(pi/2)
project.ExtendedAttributes[0].Formula = "Sin(3.1415926/2)";
// Print Calculated value
Task task = project.RootTask.Children.GetById(1);
Console.WriteLine("Sin(pi/2): {0}", task.ExtendedAttributes[0].NumericValue);
}
public static Project CreateTestProjectWithCustomField()
{
Project project = new Project();
ExtendedAttributeDefinition attr = ExtendedAttributeDefinition.CreateTaskDefinition(CustomFieldType.Number, ExtendedAttributeTask.Number1, "Sine");
project.ExtendedAttributes.Add(attr);
Task task = project.RootTask.Children.Add("Task");
ExtendedAttribute a = attr.CreateExtendedAttribute();
task.ExtendedAttributes.Add(a);
return project;
}
public static void EvaluateStrConv()
{
Project project = CreateTestProjectWithCustomField();
Task task = project.RootTask.Children.GetById(1);
// Set formulas and print extended attribute value
project.ExtendedAttributes[0].Formula = "StrConv(\"sTring and sTRINg\",3)";
Console.WriteLine(task.ExtendedAttributes[0].TextValue);
project.ExtendedAttributes[0].Formula = "StrConv(\"sTring and sTRINg\",1)";
Console.WriteLine(task.ExtendedAttributes[0].TextValue);
project.ExtendedAttributes[0].Formula = "StrConv(\"sTring and sTRINg\",2)";
Console.WriteLine(task.ExtendedAttributes[0].TextValue);
}
public static void EvaluateStringFunction()
{
Project project = CreateTestProjectWithCustomField();
Task task = project.RootTask.Children.GetById(1);
// Set formulas and print extended attribute value
project.ExtendedAttributes[0].Formula = "String(5, 40)";
Console.WriteLine(task.ExtendedAttributes[0].TextValue);
project.ExtendedAttributes[0].Formula = "String(5, \"A\")";
Console.WriteLine(task.ExtendedAttributes[0].TextValue);
project.ExtendedAttributes[0].Formula = "String(-5, \"A\")";
// #Error
Console.WriteLine(task.ExtendedAttributes[0].TextValue);
}
Project project = CreateTestProjectWithCustomField();
// Set formula for extended attribute
project.ExtendedAttributes[0].Formula = "[Critical]-[Marked]+4+[Active]-Not [Active]";
// Print value of extened attribute
Task task = project.RootTask.Children.GetById(1);
Console.WriteLine("Formula with boolean values: " + task.ExtendedAttributes[0].TextValue);
public static void Run()
{
Project project = CreateTestProjectWithCustomFieldWithoutResource();
// Set formula
project.ExtendedAttributes[0].Formula = "\"Total tasks: \" & [Task Count] & \" Total resources: \" & [Resource Count]";
// Print if formula value is computed correctly
Task task = project.RootTask.Children.GetById(1);
Console.WriteLine("Check Total tasks: 1 Total resources: 0 - {0}", task.ExtendedAttributes[0].TextValue.Equals("Total tasks: 1 Total resources: 0"));
}
static Project CreateTestProjectWithCustomFieldWithoutResource()
{
Project project = new Project();
project.Set(Prj.StartDate, new DateTime(2015, 3, 6, 8, 0, 0));
ExtendedAttributeDefinition attr = ExtendedAttributeDefinition.CreateTaskDefinition(CustomFieldType.Text, ExtendedAttributeTask.Text1, "Custom");
project.ExtendedAttributes.Add(attr);
Task task = project.RootTask.Children.Add("Task");
ExtendedAttribute a = attr.CreateExtendedAttribute();
task.ExtendedAttributes.Add(a);
return project;
}
// The path to the documents directory.
// Create project instance
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project1 = new Project(dataDir + "ReadFormulas.mpp"); // Attached test mpp
// Read extended attribute formula
ExtendedAttributeDefinition attr = project1.ExtendedAttributes[0];
Console.WriteLine("Attribute Formula: " + attr.Formula);
Project project = CreateTestProjectWithCustomField();
// Set arithmetic formula for extended attribute
ExtendedAttributeDefinition attr = project.ExtendedAttributes[0];
attr.Alias = "Arithmetic Expression";
attr.Formula = "(1+3*(2+ -5)+8/2)^3";
// Display extended attribute value
Task task = project.RootTask.Children.GetById(1);
Console.WriteLine(task.ExtendedAttributes[0].NumericValue);
Project project = CreateTestProjectWithCustomField();
// Set formula
ExtendedAttributeDefinition attr = project.ExtendedAttributes[0];
attr.Alias = "Task number fields";
attr.Formula = "([Outline Level] + [Priority] + [% Complete])/2";
Task task = project.RootTask.Children.GetById(1);
// Print extended attribute value before and after updating task percent complete
Console.WriteLine(task.ExtendedAttributes[0].NumericValue);
task.Set(Tsk.PercentComplete, 50);
Console.WriteLine(task.ExtendedAttributes[0].NumericValue);
public static void Run()
{
try
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = CreateTestProjectWithCustomField();
Task task = project.RootTask.Children.GetById(1);
// Set formula for extended attribute
ExtendedAttributeDefinition extendedAttributeDefinition1 = project.ExtendedAttributes[0];
extendedAttributeDefinition1.Alias = "Days from finish to deadline";
extendedAttributeDefinition1.Formula = "[Deadline] - [Finish]";
// Set Task Deadline and save project
Task task1 = project.RootTask.Children.GetById(1);
task.Set(Tsk.Deadline, new DateTime(2015, 3, 20, 17, 0, 0));
project.Save(dataDir + "project_UsingTasksAndResourceFields_out.mpp", SaveFileFormat.MPP);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http://www.aspose.com/purchase/default.aspx.");
}
}
// Helper method to create project
private static Project CreateTestProjectWithCustomField()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
// Create new project instance
Project project = new Project(dataDir + "Blank2010.mpp");
project.Set(Prj.StartDate, new DateTime(2015, 3, 6, 8, 0, 0));
// Add new task with extended attribute
Task task = project.RootTask.Children.Add("Task");
ExtendedAttributeDefinition extendedAttributeDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(CustomFieldType.Text, ExtendedAttributeTask.Text5, "My Ext Attr");
project.ExtendedAttributes.Add(extendedAttributeDefinition);
ExtendedAttribute extendedAttribute = extendedAttributeDefinition.CreateExtendedAttribute();
task.ExtendedAttributes.Add(extendedAttribute);
// Add resource and resource assignment
Resource rsc = project.Resources.Add("Rsc");
ResourceAssignment assn = project.ResourceAssignments.Add(task, rsc);
return project;
}
// Create project instance
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
Project project = new Project(dataDir + "Project1.mpp");
project.Set(Prj.NewTasksAreManual, false);
// Create new custom field (Task Text1) with formula which will double task cost
ExtendedAttributeDefinition attr = ExtendedAttributeDefinition.CreateTaskDefinition(CustomFieldType.Text, ExtendedAttributeTask.Text1, "Custom");
attr.Alias = "Double Costs";
attr.Formula = "[Cost]*2";
project.ExtendedAttributes.Add(attr);
// Add a task
Task task = project.RootTask.Children.Add("Task");
// Set task cost
task.Set(Tsk.Cost, 100);
// Save project
project.Save(dataDir + "WriteFormulasInExtendedAttributesToMPP_out.mpp", SaveFileFormat.MPP);
Project project = new Project(dataDir + "AddImageToPageHeaderFooter.mpp");