Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active April 15, 2021 09:51
Show Gist options
  • Save aspose-com-gists/10d4de13018b7279cf03bab28ed78aeb to your computer and use it in GitHub Desktop.
Save aspose-com-gists/10d4de13018b7279cf03bab28ed78aeb to your computer and use it in GitHub Desktop.
Aspose.Tasks for .NET
This Gist contains code snippets from examples of Aspose.Tasks for .NET
Project project = new Project("New Project.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("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("AlignCellContents_ResourceSheet_out.pdf", options);
Project project = new Project("New Project.mpp");
SaveOptions options = new XamlOptions();
options.UseGradientBrush = false;
project.Save("ChangeGanttBarsColorGradient_Solid_out.xaml", options);
options.UseGradientBrush = true;
project.Save("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 resource1 = project.Resources.Add("Resource 1");
Resource resource2 = project.Resources.Add("Resource 2");
Resource resource3 = project.Resources.Add("Resource 3");
ResourceAssignment assignment1 = project.ResourceAssignments.Add(task1, resource1);
ResourceAssignment assignment2 = project.ResourceAssignments.Add(task2, resource2);
ResourceAssignment assignment3 = project.ResourceAssignments.Add(task3, resource3);
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("output.pdf", options);
static void ImplementCustomBarStyle()
{
Project project = new Project("New Project.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);
MPPSaveOptions options = new MPPSaveOptions();
options.WriteViewData = true;
project.Save("ImplementCustomBarStyle_out.mpp", options);
}
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("New Project.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("New Project.mpp");
SaveOptions options = new XamlOptions();
options.PresentationFormat = PresentationFormat.GanttChart;
project.Save("RenderDifferentPresentationFormatsToXAML_out.xaml", options);
PdfSaveOptions options = new PdfSaveOptions();
options.PresentationFormat = PresentationFormat.GanttChart;
options.FitContent = true;
options.RollUpGanttBars = false;
options.DrawNonWorkingTime = false;
options.PageSize = PageSize.A3;
Project project = new Project(file);
project.Save("RenderGanttChartWithBarsNotRolledUp_out.pdf", (SaveOptions)options);
PdfSaveOptions options = new PdfSaveOptions();
options.PresentationFormat = PresentationFormat.GanttChart;
options.FitContent = true;
options.RollUpGanttBars = true;
options.DrawNonWorkingTime = true;
options.PageSize = PageSize.A3;
Project project = new Project(fileName);
project.Save("RenderGanttChartWithBarsNotRolledUp_out.pdf", (SaveOptions)options);
Project project = new Project("New Project.mpp");
// Save the project to TIFF
project.Save("RenderMultipageTIFF_out.tif", SaveFileFormat.TIFF);
// Save the project with CCITT4 compression
ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.TIFF);
options.TiffCompression = TiffCompression.Ccitt4;
project.Save("RenderMultipageTIFF_options_out.tif", (SaveOptions)options);
// Remove the compression
options.TiffCompression = TiffCompression.None;
project.Save("RenderMultipageTIFF_comp_none_out.tif", (SaveOptions)options);
Project project = new Project("New Project.mpp");
// Render the project to all Pre-Defined page sizes
foreach (PageSize pageSize in (PageSize[])Enum.GetValues(typeof(PageSize)))
{
PdfSaveOptions options = new PdfSaveOptions();
options.PresentationFormat = PresentationFormat.GanttChart;
options.FitContent = true;
options.PageSize = pageSize;
project.Save("PredefinedPageSizes_" + pageSize.ToString() + "_out.pdf", (SaveOptions)options);
}
Project project = new Project("New Project.mpp");
project.Save("RenderToXAML_out.xaml", SaveFileFormat.XAML);
Project project = new Project("New Project.mpp");
SaveOptions options = new XamlOptions();
options.FitContent = true;
options.LegendOnEachPage = false;
options.Timescale = Timescale.ThirdsOfMonths;
project.Save("RenderXAMLWithOptions_out.xaml", options);
Project project = new Project("New Project.mpp");
Task task = project.RootTask.Children.GetById(1);
File.WriteAllText("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("RetrieveTaskEmbeddedDocuments_out.doc");
}
}
}
}
Project project = new Project("New Project.mpp");
project.Set(Prj.TimescaleStart, new DateTime(2012, 4, 30));
project.Save("SetGanttChartViewStartDate_out.mpp", SaveFileFormat.MPP);
class SortTasksByColumnInGanttChart
{
public static void Run()
{
Project project = new Project("New Project.mpp");
SaveOptions options = new PdfSaveOptions();
options.Timescale = Timescale.Months;
options.TasksComparer = new TasksNameComparer();
project.Save("SortedByNames_out.pdf", options);
options.TasksComparer = new TasksDurationComparer();
project.Save("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("New Project.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("New Project.mpp");
PdfSaveOptions options = new PdfSaveOptions
{
PresentationFormat = PresentationFormat.GanttChart,
FitContent = true,
UseProjectDefaultFont = false,
DefaultFontName = "Segoe UI Black"
};
project.Save("CreateProject2_out.pdf", (SaveOptions)options);
Project project = new Project("New Project.mpp");
HtmlSaveOptions options = new HtmlSaveOptions
{
CssStylePrefix = "test_prefix"
};
project.Save("TestCssStylePrefix_out.html", options);
Project project = new Project("New Project.mpp");
HtmlSaveOptions options = new HtmlSaveOptions
{
CssStylePrefix = "test_prefix"
};
project.Save("TestCssStylePrefix_out.html", options);
Project project = new Project("New Project.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("ControlHeaderNameDuringHTMLExport_out.html", htmlSaveOptions);
Project project = new Project("New Project.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("CustomizeDateFormats1_out.pdf", SaveFileFormat.PDF);
// Export to date format 19/07/2016
project.Set(Prj.DateFormat, DateFormat.DateDdMmYyyy);
project.Save("CustomizeDateFormats2_out.pdf", SaveFileFormat.PDF);
Project project = new Project("New Project.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("CustomizeTextStyle_out.pdf", options);
Project project = new Project("New Project.mpp");
SaveOptions options = new PdfSaveOptions();
// Set option fit content to true
options.FitContent = true;
options.Timescale = Timescale.Months;
options.PresentationFormat = PresentationFormat.TaskUsage;
project.Save("FitContentsToCellSize_out.pdf", options);
SaveOptions options = new PdfSaveOptions();
// Set the LegendOnEachPage property to false to hide legends
options.LegendOnEachPage = false;
Project project = new Project("New Project.mpp");
ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.PNG);
options.StartDate = project.Get(Prj.StartDate).AddDays(-3);
options.EndDate = project.Get(Prj.FinishDate);
options.MarkCriticalTasks = true;
options.LegendOnEachPage = false;
options.Gridlines = new List<Gridline>();
Gridline gridline = new Gridline();
gridline.GridlineType = GridlineType.GanttRow;
gridline.Color = Color.CornflowerBlue;
gridline.Pattern = LinePattern.Dashed;
options.Gridlines.Add(gridline);
// Save the whole project layout to one file
project.Save("PrintProjectPagesToSeparateFiles1_out.png", (SaveOptions)options);
// Save project layout to separate files
options.SaveToSeparateFiles = true;
project.Save("PrintProjectPagesToSeparateFiles2_out.png", (SaveOptions)options);
Project project = new Project("New Project.mpp");
// Use ReduceFooterGap property to reduce the gap between list of tasks and Footer
ImageSaveOptions imageSaveOptions =
new ImageSaveOptions(SaveFileFormat.PNG) { ReduceFooterGap = true, SaveToSeparateFiles = true, PageSize = PageSize.A0, Timescale = Timescale.Days };
project.Save("ReducingGapBetweenTasksListAndFooter_out.png", (SaveOptions)imageSaveOptions);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions { ReduceFooterGap = true, SaveToSeparateFiles = true, PageSize = PageSize.A0, Timescale = Timescale.Days };
project.Save("ReducingGapBetweenTasksListAndFooter_out.pdf", (SaveOptions)pdfSaveOptions);
HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions
{
ReduceFooterGap = false,
IncludeProjectNameInPageHeader = false,
IncludeProjectNameInTitle = false,
PageSize = PageSize.A0,
Timescale = Timescale.Days
};
project.Save("ReducingGapBetweenTasksListAndFooter_out.html", htmlSaveOptions);
Project project = new Project("New Project.mpp");
project.DefaultView.PageInfo.PageViewSettings.PrintNotes = true;
project.Save("ProjectWithComments.pdf", SaveFileFormat.PDF);
Project project = new Project("New Project.mpp");
ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.TIFF);
options.HorizontalResolution = 72;
options.VerticalResolution = 72;
options.PixelFormat = PixelFormat.Format24bppRgb;
project.Save("RenderProjectDataToFormat24bppRgb_out.tif", (SaveOptions)options);
Project project = new Project("New Project.mpp");
project.Save("SaveProjectAsCSV_out.csv", SaveFileFormat.CSV);
Project project = new Project("New Project.mpp");
// in order to manipulate JPEG quality one can use ImageSaveOptions.JpegQuality property.
// The allowed value range is 0..100.
ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.JPEG) { JpegQuality = 50 };
project.Save("image_out.jpeg", (SaveOptions)options);
Project project = new Project("New Project.mpp");
project.Save("SaveProjectAsPDF_out.pdf", SaveFileFormat.PDF);
Project project = new Project("New Project.mpp");
project.Save("SaveProjectAsSVG_out.SVG", SaveFileFormat.SVG);
Project project = new Project("New Project.mpp");
project.Save("SaveProjectAsText_out.txt", SaveFileFormat.TXT);
Project project = new Project("New Project.mpp");
// convert MPP to Excel
project.Save("MS Project.xlsx", SaveFileFormat.XLSX);
Project project = new Project("New Project.mpp");
HtmlSaveOptions option = new HtmlSaveOptions();
project.Save("SaveProjectDataAsHTML_out.html", option);
// OR
// Adding only one page (page number 2)
option = new HtmlSaveOptions();
option.Pages.Add(2);
project.Save("SaveProjectDataAsHTML2_out.html", option);
Project project = new Project("New Project.mpp");
ProjectFileInfo projectFileInfo = Project.GetProjectFileInfo("New Project.mpp");
if (FileFormat.MPP14 == projectFileInfo.ProjectFileFormat)
{
Console.WriteLine("Project file format is ok");
}
SaveTemplateOptions options = new SaveTemplateOptions();
options.RemoveActualValues = true;
options.RemoveBaselineValues = true;
project.SaveAsTemplate("SaveProjectDataAsTemplate_out.mpt");
ProjectFileInfo templateFileInfo = Project.GetProjectFileInfo(templateName);
if (FileFormat.MPT14 == templateFileInfo.ProjectFileFormat)
{
Console.WriteLine("Template FileFormat is ok");
}
Project project = new Project("New Project.mpp");
project.Save("SaveProjectDataToSpreadsheet2003XML_out.xml", SaveFileFormat.Spreadsheet2003);
Project project = new Project("New Project.mpp");
PdfSaveOptions options = new PdfSaveOptions();
options.SaveToSeparateFiles = true;
options.Pages = new List<int>();
options.Pages.Add(1);
options.Pages.Add(4);
project.Save("SaveToMultiplePDFFiles_out.pdf", (SaveOptions)options);
Project project = new Project("New Project.mpp");
CsvOptions options = new CsvOptions();
// to change what columns will be exported the DataCategory property can be used
// changing the data category from DataCategory.Tasks to DataCategory.Resources
options.DataCategory = DataCategory.Resources;
project.Save("CsvOptionsWithResourceView.csv", options);
Project project = new Project("New Project.mpp");
CsvOptions options = new CsvOptions();
// changing the text encoding
options.Encoding = Encoding.UTF8;
project.Save("CsvOptionsWithCustomEncoding.csv", options);
Project project = new Project("New Project.mpp");
project.RootTask.Children.Add("Task");
CsvOptions options = new CsvOptions
{
TasksComparer = new ReversedByNameTaskComparer()
};
project.Save("CsvOptionsWithReversedTasks.csv", options);
// ...
private sealed class ReversedByNameTaskComparer : IComparer<Task>
{
public int Compare(Task x, Task y)
{
if (x == null)
{
throw new ArgumentNullException("x");
}
if (y == null)
{
throw new ArgumentNullException("y");
}
return -1 * string.Compare(x.Get(Tsk.Name), y.Get(Tsk.Name), StringComparison.Ordinal);
}
}
Project project = new Project("New Project.mpp");
CsvOptions options = new CsvOptions();
options.TasksFilter = new OutlineCodeFilter();
project.Save("CsvOptionsWithFilteredTasks.csv", options);
// ...
class OutlineCodeFilter : ICondition<Task>
{
public bool Check(Task el)
{
var code1 = el.OutlineCodes.GetByFieldId((int)ExtendedAttributeTask.OutlineCode1);
var code2 = el.OutlineCodes.GetByFieldId((int)ExtendedAttributeTask.OutlineCode2);
return code1 != null && code2 != null;
}
}
Project project = new Project("New Project.mpp");
CsvOptions options = new CsvOptions();
// changing text delimiter to tabs
options.TextDelimiter = CsvTextDelimiter.Tab;
project.Save("CsvOptionsWithCustomDelimiter.csv", options);
Project project = new Project("New Project.mpp");
CsvOptions options = new CsvOptions();
// suppress export of column headers
options.IncludeHeaders = false;
project.Save("CsvOptionsWithoutColumnHeaders.csv", options);
Project project = new Project("New Project.mpp");
CsvOptions options = new CsvOptions();
options.TextDelimiter = CsvTextDelimiter.Semicolon;
project.Save("UsingCsvOptions_out.csv", options);
Project project = new Project("New Project.mpp");
Spreadsheet2003SaveOptions options = new Spreadsheet2003SaveOptions();
GanttChartColumn col1 = new GanttChartColumn("WBS", 100, delegate(Task task) { return task.Get(Tsk.WBS); });
GanttChartColumn col2 = new GanttChartColumn("Name", 100, delegate(Task task) { return task.Get(Tsk.Name); });
options.View.Columns.Add(col1);
options.View.Columns.Add(col2);
project.Save("UsingSpreadsheet2003SaveOptions_out.xml", options);
Project project = new Project("New Project.mpp");
SaveOptions options = new SvgOptions();
options.FitContent = true;
options.Timescale = Timescale.ThirdsOfMonths;
project.Save("UseSvgOptions_out.svg", options);
Project project = new Project("New Project.mpp");
XlsxOptions options = new XlsxOptions();
// Customize Gantt Chart View
GanttChartColumn col1 = new GanttChartColumn("WBS", 100, delegate(Task task) { return task.Get(Tsk.WBS); });
GanttChartColumn col2 = new GanttChartColumn("Name", 100, delegate(Task task) { return task.Get(Tsk.Name); });
options.View.Columns.Add(col1);
options.View.Columns.Add(col2);
// convert MS Project MPP to Excel
project.Save("MS Project Gantt Chart.xlsx", options);
var info = Project.GetProjectFileInfo("PasswordProtected.mpp");
Console.WriteLine("Is file password protected?:" + info.IsPasswordProtected);
Project project = new Project("New Project.mpp");
ProjectServerCredentials credentials = new ProjectServerCredentials("https://contoso.sharepoint.com", "admin@contoso.onmicrosoft.com", "MyPassword");
ProjectServerManager manager = new ProjectServerManager(credentials);
ProjectServerSaveOptions options = new ProjectServerSaveOptions
{
Timeout = TimeSpan.FromSeconds(10)
};
manager.CreateNewProject(project, options);
try
{
const string SharepointDomainAddress = "https://contoso.sharepoint.com";
const string UserName = "admin@contoso.onmicrosoft.com";
const string Password = "MyPassword";
ProjectServerCredentials credentials = new ProjectServerCredentials(SharepointDomainAddress, UserName, Password);
Project project = new Project("New Project.mpp");
ProjectServerManager manager = new ProjectServerManager(credentials);
manager.CreateNewProject(project);
}
catch (ProjectOnlineException ex)
{
Console.WriteLine(ex.Message);
}
const string SharepointDomainAddress = "https://contoso.sharepoint.com";
const string UserName = "admin@contoso.onmicrosoft.com";
const string Password = "MyPassword";
ProjectServerCredentials credentials = new ProjectServerCredentials(SharepointDomainAddress, UserName, Password);
ProjectServerManager manager = new ProjectServerManager(credentials);
IEnumerable<ProjectInfo> list = manager.GetProjectList();
foreach (var info in list)
{
Project project = manager.GetProject(info.Id);
Console.WriteLine("{0} - {1} - {2}", info.Name, info.CreatedDate, info.LastSavedDate);
Console.WriteLine("Resources count: {0}", project.Resources.Count);
// an user can read the project as raw data stream
var stream = manager.GetProjectRawData(info.Id);
// work with raw project data
}
const string SharepointDomainAddress = "https://contoso.sharepoint.com";
const string UserName = "admin@contoso.onmicrosoft.com";
const string Password = "MyPassword";
ProjectServerCredentials credentials = new ProjectServerCredentials(SharepointDomainAddress, UserName, Password);
try
{
ProjectServerManager manager = new ProjectServerManager(credentials);
var projectInfo = manager.GetProjectList().FirstOrDefault(p => p.Name == "My project");
if (projectInfo == null)
{
Console.WriteLine("Project 'My project' not found in working store of Project Online account.");
return;
}
Project project = manager.GetProject(projectInfo.Id);
project.Set(Prj.FinishDate, new DateTime(2020, 03, 01));
Task task = project.RootTask.Children.Add("New task");
task.Set(Tsk.Start, new DateTime(2020, 02, 26));
task.Set(Tsk.Duration, project.GetDuration(2, TimeUnitType.Day));
ProjectServerSaveOptions options = new ProjectServerSaveOptions { Timeout = TimeSpan.FromMinutes(5) };
manager.UpdateProject(project, options);
}
catch (ProjectOnlineException ex)
{
Console.WriteLine("Failed to update the project. Error: " + ex);
}
const string URL = "https://contoso.sharepoint.com";
const string Domain = "CONTOSO.COM";
const string UserName = "Administrator";
const string Password = "MyPassword";
NetworkCredential windowsCredentials = new NetworkCredential(UserName, Password, Domain);
ProjectServerCredentials projectServerCredentials = new ProjectServerCredentials(URL, windowsCredentials);
try
{
ProjectServerManager manager = new ProjectServerManager(projectServerCredentials);
var projectInfo = manager.GetProjectList().FirstOrDefault(p => p.Name == "My project");
if (projectInfo == null)
{
Console.WriteLine("Project 'My project' not found in working store of Project Online account.");
return;
}
Project project = manager.GetProject(projectInfo.Id);
project.Set(Prj.FinishDate, new DateTime(2020, 03, 01));
Task task = project.RootTask.Children.Add("New task");
task.Set(Tsk.Start, new DateTime(2020, 02, 26));
task.Set(Tsk.Duration, project.GetDuration(2, TimeUnitType.Day));
manager.UpdateProject(project);
}
catch (ProjectOnlineException ex)
{
Console.WriteLine("Failed to update the project. Error: " + ex);
}
Project project = new Project("New Project.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);
project.Save("AddNewTask_out.xml", SaveFileFormat.XML);
Project project = new Project("New Project.mpp");
// Declare ChildTasksCollector class object
ChildTasksCollector collector = new ChildTasksCollector();
// Use TaskUtils to get all children tasks in RootTask
TaskUtils.Apply(project.RootTask, collector, 0);
// Define Resources
for (int i = 0; i <= 4; i++)
{
// Add resource to project
Resource newResource = project.Resources.Add("Developer0" + i);
newResource.Set(Rsc.Type, ResourceType.Work);
// Define assignment
ResourceAssignment newResourceAssignment = project.ResourceAssignments.Add((Task)collector.Tasks[i], newResource);
}
project.Save("CreateResourcesAndLinkToTasks_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.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 taskLink = project.TaskLinks.Add(task1, task2, TaskLinkType.FinishToStart);
taskLink = project.TaskLinks.Add(task2, task3, TaskLinkType.FinishToStart);
taskLink = project.TaskLinks.Add(task3, task4, TaskLinkType.FinishToStart);
taskLink = project.TaskLinks.Add(task4, task5, TaskLinkType.FinishToStart);
taskLink = project.TaskLinks.Add(task2, task5, TaskLinkType.FinishToStart);
// Display links among the tasks
TaskLinkCollection allinks = project.TaskLinks;
foreach (TaskLink link in allinks)
{
Console.WriteLine("From ID = " + link.PredTask.Get(Tsk.Id) + " => To ID = " + link.SuccTask.Get(Tsk.Id));
Console.WriteLine("________________________________________");
}
project.Save("LinkTasks_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.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));
}
Project project = new Project("New Project.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("ID: " + task.Get(Tsk.Id));
Console.WriteLine("Start: " + task.Get(Tsk.Start));
Console.WriteLine("Finish: " + task.Get(Tsk.Finish));
}
// 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("ID: " + resource.Get(Rsc.Id));
Console.WriteLine("Type: " + resourceType);
}
License license = new License();
license.SetLicense("Aspose.Tasks.lic");
using (FileStream stream = new FileStream("Aspose.Tasks.lic", FileMode.Open))
{
License license = new License();
license.SetLicense(stream);
}
// Create a project instance
Project project = new Project();
// Define Tasks
Task task1 = project.RootTask.Children.Add("Task1");
task1.Set(Tsk.ActualStart, DateTime.Parse("06-Apr-2010"));
Task task2 = project.RootTask.Children.Add("Task2");
task2.Set(Tsk.ActualStart, DateTime.Parse("10-Apr-2010"));
project.Save("EvalProject_out.xml", SaveFileFormat.XML);
Project project;
try
{
project = new Project("New 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);
}
}
// Analyze the project risks
RiskAnalyzer analyzer = new RiskAnalyzer(settings);
RiskAnalysisResult analysisResult = analyzer.Analyze(project);
Project project = new Project("New Project.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 default 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);
analysisResult.SaveReport("AnalysisReport_out.pdf");
Project project = new Project("Cyclic structure.mpp");
project.SaveReport("BestPracticeAnalyzer_out.pdf", ReportType.BestPracticeAnalyzer);
Project project = new Project("Homemoveplan.mpp");
project.SaveReport("Burndown_out.pdf", ReportType.Burndown);
Project project = new Project("New Project.mpp");
project.SaveReport("CashFlow_out.pdf", ReportType.CashFlow);
Project project = new Project("Software Development.mpp");
project.SaveReport("CostOverruns_out.pdf", ReportType.CostOverruns);
Project project = new Project("New Project.mpp");
project.SaveReport("CostOverview_out.pdf", ReportType.CostOverview);
Project project = new Project("New Project.mpp");
project.SaveReport("CriticalTasks_out.pdf", ReportType.CriticalTasks);
Project project = new Project("New Project.mpp");
project.SaveReport("LateTasks_out.pdf", ReportType.LateTasks);
Project project = new Project("New Project.mpp");
project.SaveReport("Milestones_out.pdf", ReportType.Milestones);
Project project = new Project("Software Development Plan.mpp");
project.SaveReport("OverAllocatedResources_out.pdf", ReportType.OverallocatedResources);
Project project = new Project("New Project.mpp");
project.SaveReport("ProjectOverView_out.pdf", ReportType.ProjectOverview);
Project project = new Project("New Project.mpp");
project.SaveReport("ResourceCostOverview_out.pdf", ReportType.ResourceCostOverview);
Project project = new Project("Software Development Plan.mpp");
project.SaveReport("ResourceOverview_out.pdf", ReportType.ResourceOverview);
Project project = new Project("New Project.mpp");
project.SaveReport("SlippingTasks_out.pdf", ReportType.SlippingTasks);
Project project = new Project("New Project.mpp");
project.SaveReport("TaskCostOverview_out.pdf", ReportType.TaskCostOverview);
Project project = new Project("New Project.mpp");
project.SaveReport("UpcomingTasks_out.pdf", ReportType.UpcomingTask);
Project project = new Project("New Project.mpp");
project.SaveReport("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("New Project.mpp");
List<Resource> resources = project.Resources.ToList();
resources.Sort(new RscNameComparer());
foreach (Resource resource in resources)
{
Console.WriteLine(resource);
}
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));
}
}
Project project = new Project("New Project.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);
}
Project project = new Project("New 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 resource 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);
project.Save("Updated_project_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.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 resource = project.Resources.Add("Rsc 1");
resource.Set(Rsc.Type, ResourceType.Work);
resource.Set(Rsc.Initials, "WR");
resource.Set(Rsc.AccrueAt, CostAccrualType.Prorated);
resource.Set(Rsc.MaxUnits, 1);
resource.Set(Rsc.Code, "Code 1");
resource.Set(Rsc.Group, "Workers");
resource.Set(Rsc.EMailAddress, "1@gmail.com");
resource.Set(Rsc.WindowsUserAccount, "user_acc1");
resource.Set(Rsc.IsGeneric, new NullableBool(true));
resource.Set(Rsc.AccrueAt, CostAccrualType.End);
resource.Set(Rsc.StandardRate, 10);
resource.Set(Rsc.StandardRateFormat, RateFormatType.Day);
resource.Set(Rsc.OvertimeRate, 15);
resource.Set(Rsc.OvertimeRateFormat, RateFormatType.Hour);
resource.Set(Rsc.IsTeamAssignmentPool, true);
resource.Set(Rsc.CostCenter, "Cost Center 1");
// Create resource assignment and set resource assignment meta data
ResourceAssignment assignment = project.ResourceAssignments.Add(task, resource);
assignment.Set(Asn.Uid, 1);
assignment.Set(Asn.Work, task.Get(Tsk.Duration));
assignment.Set(Asn.RemainingWork, assignment.Get(Asn.Work));
assignment.Set(Asn.RegularWork, assignment.Get(Asn.Work));
task.Set(Tsk.Work, assignment.Get(Asn.Work));
resource.Set(Rsc.Work, task.Get(Tsk.Work));
assignment.Set(Asn.Start, task.Get(Tsk.Start));
assignment.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);
project.Save("WriteMetaData_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
// Remove an exception
Calendar cal = project.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());
}
// Create a project instance
Project project = new Project();
// Define Calendar
Calendar cal = project.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);
project.Save("Project_DefineWeekDayException_out.xml", SaveFileFormat.XML);
// Define exception and specify occurrences
CalendarException except = new CalendarException();
except.EnteredByOccurrences = true;
except.Occurrences = 5;
except.Type = CalendarExceptionType.YearlyByDay;
Project project = new Project("New Project.mpp");
// Access calendars
foreach (Calendar cal in project.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
Project project = new Project("New Project.mpp");
// Access Task By Id
Task task = project.RootTask.Children.GetById(1);
// Access Calendar and it's start and end dates
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);
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.
Calendar cal1 = project.Calendars.Add("New Info");
Calendar cal2 = project.Calendars.Add("no name");
Calendar cal3 = project.Calendars.Add("cal3");
project.Save("CreatingCalendar_out.Xml", 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
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);
project.Save("Project_DefineCalendarWeekdays_out.xml", SaveFileFormat.XML);
// Create a project instance
Project project = new Project();
// Define Calendar and make it standard
Calendar cal1 = project.Calendars.Add("My Cal");
Calendar.MakeStandardCalendar(cal1);
project.Save("Project_MakeStandardCalendar_out.xml", SaveFileFormat.XML);
Project project = new Project("New Project.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("New Project.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("ReplaceCalendar_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
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);
project.Save("WriteUpdatedCalendarDataToMPP_out.mpp", SaveFileFormat.MPP);
// Load an existing project
Project project = new Project("Project_GeneralCalendarProperties.xml");
foreach (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());
}
}
}
Project project = new Project("ReadWorkWeeksInformation.mpp");
Calendar calendar = project.Calendars.GetByUid(3);
WorkWeekCollection collection = calendar.WorkWeeks;
foreach (WorkWeek workWeek in collection)
{
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;
}
}
// Create a project instance
Project project = new Project("RetrieveCalendarInfo.mpp");
// Retrieve Calendars Information