Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active April 15, 2021 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
CalendarCollection calendars = project.Calendars;
foreach (Calendar cal in calendars)
{
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 project = new Project("New Project.mpp");
Console.WriteLine(project.Get(Prj.CurrencyCode));
Project project = new Project("New Project.mpp");
Console.WriteLine(project.Get(Prj.CurrencyDigits));
Project project = new Project("New Project.mpp");
Console.WriteLine(project.Get(Prj.CurrencySymbol));
// Create new project and set currency code
Project project = new Project();
project.Set(Prj.CurrencyCode, "USD");
// Create new project and set currency digits
Project project = new Project();
project.Set(Prj.CurrencyDigits, 2);
// Create new project and set currency symbol
Project project = new Project();
project.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);
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);
}
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);
}
}
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);
}
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);
}
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;
}
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);
}
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 extended attribute
Task task = project.RootTask.Children.GetById(1);
Console.WriteLine("Formula with boolean values: " + task.ExtendedAttributes[0].TextValue);
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;
}
Project project = new Project("New Project.mpp"); // Attached test mpp
// Read extended attribute formula
ExtendedAttributeDefinition attr = project.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);
static void Run()
{
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 task = project.RootTask.Children.GetById(1);
task.Set(Tsk.Deadline, new DateTime(2015, 3, 20, 17, 0, 0));
project.Save("UsingTasksAndResourceFields_out.mpp", SaveFileFormat.MPP);
}
// Helper method to create project
static Project CreateTestProjectWithCustomField()
{
// Create new project instance
Project project = new Project("New Project.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 resource = project.Resources.Add("Rsc");
ResourceAssignment assignment = project.ResourceAssignments.Add(task, resource);
return project;
}
Project project = new Project("New Project.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);
project.Save("WriteFormulasInExtendedAttributesToMPP_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
project.RootTask.Children.Add("Task1");
PageInfo pageInfo = project.DefaultView.PageInfo;
using (Image image = Image.FromFile("Image1.png"))
{
pageInfo.Header.CenteredImage = image;
pageInfo.Legend.LeftImage = image;
pageInfo.Legend.LeftText = string.Empty;
MPPSaveOptions options = new MPPSaveOptions();
options.WriteViewData = true;
project.Save("AddImageToPageHeaderFooter_out.mpp", options);
}
// there is no more need to load MPP template to save it into MPP
// add tasks, resources, etc.
Project project = new Project();
// !The project will be saved into MPP by using internal MPP template.
project.Save("New Project.mpp", SaveFileFormat.MPP);
// Create a project instance
Project newProject = new Project();
// Create a file stream
using (FileStream stream = new FileStream("EmptyProjectSaveStream_out.xml", FileMode.Create, FileAccess.Write))
{
// Write the stream into XML format
newProject.Save(stream, SaveFileFormat.XML);
}
Project project = new Project();
project.Save("EmptyProjectSaveXML_out.xml", SaveFileFormat.XML);
string sharepointDomainAddress = "https://contoso.sharepoint.com";
string userName = "admin@contoso.onmicrosoft.com";
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);
static void Run()
{
// Open modified xml stream
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(GetModifiedXml())))
{
Project project = new Project(stream, new ParseErrorCallback(CustomDurationHandler));
}
}
static string GetModifiedXml()
{
// Open valid xml file and modify it
using (TextReader reader = new StreamReader("IgnoreInvalidCharacters.xml"))
{
string xml = reader.ReadToEnd();
Regex regex = new Regex("PT(\\d+)H(\\d+)M(\\d+)S");
return regex.Replace(xml, "**$1Hrs$2Mins$3Secs**");
}
}
static object CustomDurationHandler(object sender, ParseErrorArgs args)
{
Regex regex = new Regex("[*]{2}(\\d+)Hrs(\\d+)Mins(\\d+)Secs[*]{2}");
if (args.FieldType == typeof(TimeSpan))
{
Debug.Print("Object field : {0}, Invalid value : {1}", args.FieldName, args.InvalidValue);
string duration = regex.Replace(args.InvalidValue, "PT$1H$2M$3S");
TimeSpan newValue = Duration.ParseTimeSpan(duration);
Debug.Print("New value : {0}", newValue);
return newValue;
}
// Here we handle only TimeSpan instances, so rethrow original exception with other types
throw args.Exception;
}
// Create connection string
SqlConnectionStringBuilder sqlConnectionString = new SqlConnectionStringBuilder();
sqlConnectionString.DataSource = "192.168.56.2,1433";
sqlConnectionString.Encrypt = true;
sqlConnectionString.TrustServerCertificate = true;
sqlConnectionString.InitialCatalog = "ProjectServer_Published";
sqlConnectionString.NetworkLibrary = "DBMSSOCN";
sqlConnectionString.UserID = "sa";
sqlConnectionString.Password = "*****";
// Use Aspose.Tasks.Connectivity namespace
MspDbSettings settings = new MspDbSettings(sqlConnectionString.ConnectionString, new Guid("E6426C44-D6CB-4B9C-AF16-48910ACE0F54"));
Project project = new Project(settings);
DbSettings settings = new MpdSettings("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + "MpdFileToRead.mpd", 1);
Project project = new Project(settings);
Project project = new Project("New Project.mpp");
NetworkCredential windowsCredentials = new NetworkCredential("Administrator", "MyPassword", "CONTOSO.COM");
ProjectServerCredentials projectServerCredentials = new ProjectServerCredentials("https://contoso.sharepoint.com", windowsCredentials);
ProjectServerManager manager = new ProjectServerManager(projectServerCredentials);
manager.CreateNewProject(project);
string url = "https://contoso.sharepoint.com";
string domain = "CONTOSO.COM";
string userName = "Administrator";
string password = "MyPassword";
NetworkCredential windowsCredentials = new NetworkCredential(userName, password, domain);
ProjectServerCredentials projectServerCredentials = new ProjectServerCredentials(url, windowsCredentials);
ProjectServerManager manager = new ProjectServerManager(projectServerCredentials);
var list = manager.GetProjectList();
foreach (var projectInfo in list)
{
Console.WriteLine("{0} - {1} - {2}", projectInfo.Id, projectInfo.CreatedDate, projectInfo.Name);
}
string sharepointDomainAddress = "https://contoso.sharepoint.com";
string userName = "admin@contoso.onmicrosoft.com";
string password = "MyPassword";
ProjectServerCredentials credentials = new ProjectServerCredentials(sharepointDomainAddress, userName, password);
ProjectServerManager manager = new ProjectServerManager(credentials);
var list = manager.GetProjectList();
foreach (var p in list)
{
Console.WriteLine("{0} - {1} - {2}", p.Name, p.CreatedDate, p.LastSavedDate);
}
foreach (var p in list)
{
Project project = manager.GetProject(p.Id);
Console.WriteLine("Project '{0}' loaded. Resources count: {1}",
p.Name,
project.Resources.Count);
}
// Read the project xml into file stream
using (FileStream stream = new FileStream("ReadProjectFileFromStream.xml", FileMode.Open))
{
// Create project using file stream
Project project = new Project(stream);
}
// Read existing project template file
Project project = new Project("New Project.mpp");
// Specify Encodings
using (StreamReader streamReader = new StreamReader("Project.mpx", System.Text.Encoding.GetEncoding("ISO-8859-1")))
{
Project project = new Project(streamReader.BaseStream);
}
Project project = new Project("New Project.mpp");
// Get number of pages, Timescale.Months, Timescale.ThirdsOfMonths
int iPages = project.GetPageCount();
iPages = project.GetPageCount(Timescale.Months);
iPages = project.GetPageCount(Timescale.ThirdsOfMonths);
Project project = new Project("New Project.mpp");
// Get number of pages, Months and ThirdsOfMonths
Console.WriteLine(string.Format("Number of Pages = '{0}'", project.GetPageCount(PresentationFormat.ResourceUsage, Timescale.Days)));
Console.WriteLine(string.Format("Number of Pages = '{0}'", project.GetPageCount(PresentationFormat.ResourceUsage, Timescale.Months)));
Console.WriteLine(string.Format("Number of Pages = '{0}'", project.GetPageCount(PresentationFormat.ResourceUsage, Timescale.ThirdsOfMonths)));
Project project = new Project("New Project.mpp");
ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.PNG)
{
SaveToSeparateFiles = true,
PageSize = PageSize.A3,
Timescale = Timescale.Months,
StartDate = project.Get(Prj.StartDate) - TimeSpan.FromDays(10),
EndDate = project.Get(Prj.FinishDate) + TimeSpan.FromDays(30)
};
int pageCount = project.GetPageCount(
PageSize.A3,
Timescale.Months,
project.Get(Prj.StartDate) - TimeSpan.FromDays(10),
project.Get(Prj.FinishDate) + TimeSpan.FromDays(30));
Console.WriteLine(pageCount);
Project project = new Project("New Project.mpp");
project.Save("ExportProjectDataToPrimaveraMPXFormat_out.xml", SaveFileFormat.MPX);
Project project = new Project("New Project.mpp");
project.Save("ExportProjectDataToXERFormat_out.mpp", SaveFileFormat.PrimaveraXER);
Project project = new Project("New Project.mpp");
project.Save("ExportProjectDataToXMLFormat_out.xml", SaveFileFormat.PrimaveraP6XML);
Project project = new Project("Primavera1.mpx");
ProjectFileInfo info = Project.GetProjectFileInfo("primavera1.mpx");
Console.WriteLine(info.ProjectFileFormat);
Project project = new Project("Project.xml");
ProjectFileInfo info = Project.GetProjectFileInfo("Project.xml");
Console.WriteLine(info.ProjectFileFormat);
SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
sb.DataSource = "192.168.56.3,1433";
sb.Encrypt = true;
sb.TrustServerCertificate = true;
sb.InitialCatalog = "PrimaveraEDB";
sb.NetworkLibrary = "DBMSSOCN";
sb.UserID = "privuser";
sb.Password = "***";
// Initialize a new instance of the PrimaveraDbSettings class with connection string and project id
PrimaveraDbSettings settings = new PrimaveraDbSettings(sb.ConnectionString, 4502);
// Initialize a new instance of the Project class
Project project = new Project(settings);
PrimaveraXmlReader reader = new PrimaveraXmlReader("Project.xml");
List<int> listOpProjectUids = reader.GetProjectUids();
PrimaveraXmlReadingOptions options = new PrimaveraXmlReadingOptions();
options.ProjectUid = 4557;
// Returns project with special Uid
Project project = new Project("Project.xml", options);
const int projectId = 4502;
// Create Primavera DB Settings using connection string and project id
PrimaveraDbSettings primaveraDbSettings = new PrimaveraDbSettings("Data Source=\\PPMDBSQLite.db", projectId);
primaveraDbSettings.ProviderInvariantName = "System.Data.SQLite";
// Create new project using primavera db settings
Project project = new Project(primaveraDbSettings);
Project project = new Project("project.xml");
// Specify xml save options
PrimaveraXmlSaveOptions options = new PrimaveraXmlSaveOptions();
options.SaveRootTask = false;
project.Save("UsingPrimaveraXMLSaveOptions_out.xml", options);
Project project = new Project("New Project.mpp");
project.CalculationMode = CalculationMode.Automatic;
Task subtask1 = project.RootTask.Children.Add("1");
Task subtask2 = project.RootTask.Children.Add("2");
Task subtask3 = project.RootTask.Children.Add("3");
project.TaskLinks.Add(subtask1, subtask2, TaskLinkType.FinishToStart);
// Display the critical path now
foreach (Task task in project.CriticalPath)
{
Console.WriteLine(task.Get(Tsk.Name));
}
IDictionary<string, string> fileFormatExt = new Dictionary<string, string>();
fileFormatExt.Add("RTF", "_rtfFile_out.rtf");
fileFormatExt.Add("MSWordDoc", "_wordFile_out.docx");
fileFormatExt.Add("ExcelML12", "_excelFile_out.xlsx");
Project project = new Project("New Project.mpp");
foreach (OleObject oleObject in project.OleObjects)
{
if (!string.IsNullOrEmpty(oleObject.FileFormat) && fileFormatExt.ContainsKey(oleObject.FileFormat))
{
using (FileStream stream = new FileStream("EmbeddedContent_" + fileFormatExt[oleObject.FileFormat], FileMode.Create))
{
stream.Write(oleObject.Content, 0, oleObject.Content.Length);
}
}
}
Project project = new Project("ExtractEmbeddedObjects.mpp");
OleObject ole = project.OleObjects.ToList()[0];
// We have to check this property because it can be null if the embedded object was created inside the ms project application Or, alternatively, you can use this check: if (ole.FileFormat == "Package")
if (!string.IsNullOrEmpty(ole.FullPath))
{
using (FileStream stream = new FileStream("out.ole", FileMode.Create))
{
stream.Write(ole.Content, 0, ole.Content.Length);
}
}
try
{
Project project = new Project("New Project.mpp");
Console.Write("This 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.");
project.Save("output.mpp", SaveFileFormat.MPP);
}
catch (TasksWritingException ex)
{
Console.WriteLine(ex.LogText);
}
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.");
}
Project project = new Project("New Project.mpp");
Filter filter = project.TaskFilters.ToList()[1];
Console.WriteLine(filter.Criteria.CriteriaRows.Count);
Console.WriteLine(filter.Criteria.Operation.ToString());
FilterCriteria criteria1 = filter.Criteria.CriteriaRows[0];
Console.WriteLine(criteria1.Test.ToString());
Console.WriteLine(criteria1.Field.ToString());
Console.WriteLine(criteria1.Values[0].ToString());
FilterCriteria criteria2 = filter.Criteria.CriteriaRows[1];
Console.WriteLine(criteria2.Operation.ToString());
Console.WriteLine(criteria2.CriteriaRows.Count);
FilterCriteria criteria21 = criteria2.CriteriaRows[0];
Console.WriteLine(criteria21.Test.ToString());
Console.WriteLine(criteria21.Field.ToString());
Console.WriteLine(criteria21.Values[0].ToString());
FilterCriteria criteria22 = criteria2.CriteriaRows[1];
Console.WriteLine(criteria22.Test.ToString());
Console.WriteLine(criteria22.Field.ToString());
Console.WriteLine(criteria22.Values[0].ToString());
Console.WriteLine(filter.Criteria);
// Instantiate project and access task filters
Project project = new Project("ReadFilterDefinitionData.mpp");
List<Filter> taskFilters = project.TaskFilters.ToList();
Console.WriteLine("Task Filters Count: " + taskFilters.Count);
Console.WriteLine("All Tasks: " + taskFilters[0].Name);
Console.WriteLine("Task Item: " + taskFilters[0].FilterType);
Console.WriteLine("Task Filters Show In Menu: " + taskFilters[0].ShowInMenu);
Console.WriteLine("Task filter ShowRelatedSummaryRows: " + taskFilters[0].ShowRelatedSummaryRows);
// Access resource filters
List<Filter> filters = project.ResourceFilters.ToList();
Console.WriteLine("Project.ResourceFilters count: " + filters.Count);
Console.WriteLine("Resource Filter Item Type: Item.ResourceType: " + filters[0].FilterType);
Console.WriteLine("Resource filter ShowInMenu" + filters[0].ShowInMenu);
Console.WriteLine("Resource filter ShowRelatedSummaryRows: " + filters[0].ShowRelatedSummaryRows);
Project project = new Project("New Project.mpp");
Console.WriteLine("Task Groups Count: " + project.TaskGroups.Count);
Group taskGroup = project.TaskGroups.ToList()[1];
Console.WriteLine("Group Name:", taskGroup.Name);
Console.WriteLine("Group Criteria count: " + taskGroup.GroupCriteria.Count);
Console.WriteLine("************* Retrieving Task Group's Criterion information *************");
GroupCriterion criterion = taskGroup.GroupCriteria.ToList()[0];
Console.WriteLine("Criterion Field: " + criterion.Field.ToString());
Console.WriteLine("Criterion GroupOn: " + criterion.GroupOn.ToString());
Console.WriteLine("Criterion Cell Color: " + criterion.CellColor);
Console.WriteLine("Criterion Pattern: " + criterion.Pattern.ToString());
if (taskGroup == criterion.ParentGroup)
{
Console.WriteLine("Parent Group is equal to task Group.");
}
Console.WriteLine("*********** Retrieving Criterion's Font Information ***********");
Console.WriteLine("Font Name: " + criterion.Font.Name);
Console.WriteLine("Font Size: " + criterion.Font.Size);
Console.WriteLine("Font Style: " + criterion.Font.Style);
Console.WriteLine("Ascending/Descending: " + criterion.Ascending);
Project project = new Project("New Project.mpp");
// Access table
Table task1 = project.Tables.ToList()[0];
Console.WriteLine("Table Fields Count" + task1.TableFields.Count);
// Display all table fields information
foreach (TableField tableField in task1.TableFields)
{
Console.WriteLine("Field width: " + tableField.Width);
Console.WriteLine("Field Title: " + tableField.Title);
Console.WriteLine("Field Title Alignment: " + tableField.AlignTitle.ToString());
Console.WriteLine("Field Align Data: " + tableField.AlignData.ToString());
}
Project project = new Project("New Project.mpp");
// Create a new task
Task task = project.RootTask.Children.Add("Task1");
task.Set(Tsk.Start, new DateTime(2012, 8, 1));
task.Set(Tsk.Finish, new DateTime(2012, 8, 5));
project.Save("AfterLinking_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
PrintOptions options = new PrintOptions();
options.Timescale = Timescale.ThirdsOfMonths;
if (project.GetPageCount(Timescale.ThirdsOfMonths) <= 280)
project.Print(options);
Project project = new Project("New Project.mpp");
PrintOptions options = new PrintOptions();
options.Timescale = Timescale.Months;
// Print first two pages
PrinterSettings printerSettings = new PrinterSettings();
printerSettings.PrintRange = PrintRange.SomePages;
printerSettings.FromPage = 1;
printerSettings.ToPage = 2;
System.Drawing.Printing.PageSettings pageSettings = printerSettings.DefaultPageSettings;
pageSettings.PaperSize = new PaperSize("Custom Size", 1000, 700);
project.Print(printerSettings, options);
Project project = new Project("New Project.mpp");
foreach (string printer in PrinterSettings.InstalledPrinters)
{
if (printer.ToUpperInvariant().Contains( "Microsoft Print to PDF".ToUpperInvariant()))
{
project.Print(printer);
break;
}
}
Project project = new Project("New Project.mpp");
project.Print();
static void Run()
{
// Create project and project info instances
Project project = new Project("New Project.mpp");
PageInfo info = project.DefaultView.PageInfo;
Console.WriteLine("Page data cannot be null : {0} ", !info.Equals(null));
if (info != null)
{
AssertHeaderFooterCorrect(info);
AssertPageSettingsCorrect(info);
AssertPageViewSettingsCorrect(info);
AssertMarginsCorrect(info);
AssertLegendCorrect(info);
}
}
static void AssertHeaderFooterCorrect(PageInfo info)
{
Console.WriteLine("Header left text Equals LEFT HEADER : {0} ", info.Header.LeftText.Equals("LEFT HEADER"));
Console.WriteLine("Header center text Equals CENTER HEADER : {0} ", info.Header.CenteredText.Equals("CENTER HEADER"));
Console.WriteLine("Header right text Equals RIGHT HEADER : {0} ", info.Header.RightText.Equals("RIGHT HEADER"));
Console.WriteLine("Footer left text Equals LEFT FOOTER : {0} ", info.Footer.LeftText.Equals("LEFT FOOTER"));
Console.WriteLine("Footer center text Equals CENTER FOOTER : {0} ", info.Footer.CenteredText.Equals("CENTER FOOTER"));
Console.WriteLine("Footer right text Equals RIGHT FOOTER : {0} ", info.Footer.RightText.Equals("RIGHT FOOTER"));
}
static void AssertPageSettingsCorrect(PageInfo info)
{
Console.WriteLine("Portrait Orientation is Portrait : {0} ", info.PageSettings.IsPortrait.Equals(true));
Console.WriteLine("AdjustToPercentOfNormalSize is enabled : {0} ", info.PageSettings.AdjustToPercentOfNormalSize.Equals(true));
Console.WriteLine("PercentOfNormalSize Equals 150 : {0} ", info.PageSettings.PercentOfNormalSize.Equals(150));
Console.WriteLine("PagesInWidth Equals 3 : {0} ", info.PageSettings.PagesInWidth.Equals(3));
Console.WriteLine("PagesInHeight Equals 7 : {0} ", info.PageSettings.PagesInHeight.Equals(7));
Console.WriteLine("PaperSize Equals PaperA4 : {0} ", info.PageSettings.PaperSize.Equals(PrinterPaperSize.PaperA4));
Console.WriteLine("FirstPageNumber : {0} ", info.PageSettings.FirstPageNumber);
}
static void AssertPageViewSettingsCorrect(PageInfo info)
{
Console.WriteLine("PrintAllSheetColumns is set to false : {0} ", info.PageViewSettings.PrintAllSheetColumns.Equals(false));
Console.WriteLine("PrintFirstColumnsCountOnAllPages is set to true : {0} ", info.PageViewSettings.PrintFirstColumnsCountOnAllPages.Equals(true));
Console.WriteLine("FirstColumnsCount Equals 3 : {0} ", info.PageViewSettings.FirstColumnsCount.Equals(3));
Console.WriteLine("PrintNotes is set to true : {0} ", info.PageViewSettings.PrintNotes.Equals(true));
Console.WriteLine("PrintBlankPages is set to false : {0} ", info.PageViewSettings.PrintBlankPages.Equals(false));
Console.WriteLine("FitTimescaleToEndOfPage is set to true : {0} ", info.PageViewSettings.FitTimescaleToEndOfPage.Equals(true));
}
static void AssertMarginsCorrect(PageInfo info)
{
Console.WriteLine("Margins.Left Equals 1 : {0} ", (info.Margins.Left - 1 <= 1e-5) ? true : false);
Console.WriteLine("Margins.Top Equals 1.1 : {0} ", (info.Margins.Top - 1.1 <= 1e-5) ? true : false);
Console.WriteLine("Margins.Right Equals 1.2 : {0} ", (info.Margins.Right - 1.2 <= 1e-5) ? true : false);
Console.WriteLine("Margins.Bottom Equals 1.2 : {0} ", (info.Margins.Bottom - 1.3 <= 1e-5) ? true : false);
Console.WriteLine("Margin.Borders Equals Border.AroundEveryPage : {0} ",info.Margins.Borders.Equals(Border.AroundEveryPage));
}
static void AssertLegendCorrect(PageInfo info)
{
Console.WriteLine("Legend left text Equals LEFT LEGEND : {0} ", info.Legend.LeftText.Equals("LEFT LEGEND"));
Console.WriteLine("Legend center text Equals CENTER LEGEND : {0} ", info.Legend.CenteredText.Equals("CENTER LEGEND"));
Console.WriteLine("Legend right text Equals RIGHT LEGEND : {0} ", info.Legend.RightText.Equals("RIGHT LEGEND"));
Console.WriteLine("LegendOn Equals Legend.OnEveryPage : {0} ", info.Legend.LegendOn.Equals(Legend.OnEveryPage));
Console.WriteLine("Legend Width Equals 5 : {0} ", (info.Legend.Width - 5 <= 1e-5) ? true : false);
}
Project project = new Project("New Project.mpp");
project.Set(Prj.ScheduleFromStart, false);
project.Set(Prj.FinishDate, new DateTime(2020, 1, 1));
// Now all tasks dates (Start, Finish, EarlyStart, EarlyFinish, LateStart, LateFinish) are calculated. To get the critical path we need to calculate slacks (can be invoked in separate thread, but only after calculation of all early/late dates)
project.Recalculate();
TaskCollection criticalPath = project.CriticalPath;
Project project = new Project("New Project.mpp");
project.Set(Prj.ScheduleFromStart, true);
project.Set(Prj.StartDate, new DateTime(2014, 1, 1));
// Now all tasks dates (Start, Finish, EarlyStart, EarlyFinish, LateStart, LateFinish) are calculated. To get the critical path we need to calculate slacks (can be invoked in separate thread, but only after calculation of all early/late dates)
project.Recalculate();
TaskCollection criticalPath = project.CriticalPath;
Project project = new Project("New Project.mpp");
project.Set(Prj.ScheduleFromStart, false);
project.Set(Prj.FinishDate, new DateTime(2020, 1, 1));
// Now all tasks dates (Start, Finish, EarlyStart, EarlyFinish, LateStart, LateFinish) are calculated. To get the critical path we need to calculate slacks (can be invoked in separate thread, but only after calculation of all early/late dates)
project.Recalculate();
TaskCollection criticalPath = project.CriticalPath;
// Create a new project and set start date
Project project = new Project();
project.Set(Prj.StartDate, new DateTime(2014, 1, 27, 8, 0, 0));
// Add new tasks
Task task1 = project.RootTask.Children.Add("Task 1");
Task task2 = project.RootTask.Children.Add("Task 2");
task2.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));
Task task3 = project.RootTask.Children.Add("Task 3");
task3.Set(Tsk.Duration, task2.ParentProject.GetDuration(24, TimeUnitType.Hour));
Task task4 = project.RootTask.Children.Add("Task 4");
task4.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));
Task task5 = project.RootTask.Children.Add("Task 5");
task5.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));
// Add links between tasks
TaskLink link12 = project.TaskLinks.Add(task1, task2, TaskLinkType.FinishToStart);
TaskLink link23 = project.TaskLinks.Add(task2, task3, TaskLinkType.FinishToStart);
// One day lag
link23.LinkLag = 4800;
TaskLink link34 = project.TaskLinks.Add(task3, task4, TaskLinkType.FinishToStart);
TaskLink link45 = project.TaskLinks.Add(task4, task5, TaskLinkType.FinishToStart);
// Add new tasks
Task task6 = project.RootTask.Children.Add("Task 6");
Task task7 = project.RootTask.Children.Add("Task 7");
task7.Set(Tsk.Duration, task7.ParentProject.GetDuration(24, TimeUnitType.Hour));
Task task8 = project.RootTask.Children.Add("Task 8");
task8.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));
Task task9 = project.RootTask.Children.Add("Task 9");
task9.Set(Tsk.Duration, task2.ParentProject.GetDuration(16, TimeUnitType.Hour));
Task task10 = project.RootTask.Children.Add("Task 10");
// Add links between tasks
TaskLink link67 = project.TaskLinks.Add(task6, task7, TaskLinkType.FinishToStart);
TaskLink link78 = project.TaskLinks.Add(task7, task8, TaskLinkType.FinishToStart);
TaskLink link89 = project.TaskLinks.Add(task8, task9, TaskLinkType.FinishToStart);
TaskLink link910 = project.TaskLinks.Add(task9, task10, TaskLinkType.FinishToStart);
task6.Set(Tsk.IsManual, true);
task7.Set(Tsk.IsManual, true);
task8.Set(Tsk.IsManual, true);
task9.Set(Tsk.IsManual, true);
task10.Set(Tsk.IsManual, true);
// Save project before and after updating work as completed
project.Save("RescheduleUncompletedWork_not updated_out.xml", SaveFileFormat.XML);
project.UpdateProjectWorkAsComplete(new DateTime(2014, 1, 28, 17, 0, 0), false);
project.Save("RescheduleUncompletedWork_updated_out.xml", SaveFileFormat.XML);
// Save project after rescheduling uncompleted work
project.RescheduleUncompletedWorkToStartAfter(new DateTime(2014, 2, 7, 8, 0, 0));
project.Save("RescheduleUncompletedWork_rescheduled_out.xml", SaveFileFormat.XML);
Project project = new Project();
Console.WriteLine(project.Get(Prj.StartDate));
Console.WriteLine(project.CalculationMode.ToString());
project.CalculationMode = CalculationMode.None;
Console.WriteLine(project.CalculationMode.ToString());
Task task = project.RootTask.Children.Add("Task1");
task.Set(Tsk.Start, new DateTime(2012, 8, 1));
task.Set(Tsk.Finish, new DateTime(2012, 8, 5));
Console.WriteLine("*************** Before Recalculate *****************");
Console.WriteLine(task.Get(Tsk.Start));
Console.WriteLine(task.Get(Tsk.Finish));
project.Recalculate();
Console.WriteLine("*************** After Recalculate *****************");
Console.WriteLine(task.Get(Tsk.Start));
Console.WriteLine(task.Get(Tsk.Finish));
Project project = new Project("New Project.mpp");
ExtendedAttributeDefinition myTextAttributeDefinition = project.ExtendedAttributes.GetById((int)ExtendedAttributeTask.Text1);
// If the Custom field doesn't exist in Project, create it
if (myTextAttributeDefinition == null)
{
myTextAttributeDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Text1, "My text field");
project.ExtendedAttributes.Add(myTextAttributeDefinition);
}
// Generate Extended Attribute from definition
ExtendedAttribute text1TaskAttribute = myTextAttributeDefinition.CreateExtendedAttribute();
text1TaskAttribute.TextValue = "Text attribute value";
// Add extended attribute to task
Task task = project.RootTask.Children.Add("Task 1");
task.ExtendedAttributes.Add(text1TaskAttribute);
project.Save("CreateExtendedAttributes_out.mpp", SaveFileFormat.MPP);
Project project = new Project("ExtendedAttributes.mpp");
// Create extended attribute definition
ExtendedAttributeDefinition attributeDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(CustomFieldType.Start, ExtendedAttributeTask.Start7, "Start 7");
project.ExtendedAttributes.Add(attributeDefinition);
// Get zero index task
Task task = project.RootTask.Children.GetById(1);
// Add extended attribute
ExtendedAttribute attribute = attributeDefinition.CreateExtendedAttribute();
attribute.DateValue = DateTime.Now;
// Also the following short syntax can be used: ExtendedAttribute attribute = attributeDefinition.CreateExtendedAttribute(DateTime.Now);
task.ExtendedAttributes.Add(attribute);
Project project = new Project("New Project.mpp");
// Add new text3 extended attribute with lookup and one lookup value
ExtendedAttributeDefinition taskTextAttributeDefinition = ExtendedAttributeDefinition.CreateLookupTaskDefinition(ExtendedAttributeTask.Text3, "New text3 attribute");
taskTextAttributeDefinition.ElementType = ElementType.Task;
project.ExtendedAttributes.Add(taskTextAttributeDefinition);
Value textVal = new Value();
textVal.Id = 1;
textVal.Description = "Text value descr";
textVal.Val = "Text value1";
taskTextAttributeDefinition.AddLookupValue(textVal);
// Add new cost1 extended attribute with lookup and two cost values
ExtendedAttributeDefinition taskCostAttributeDefinition = ExtendedAttributeDefinition.CreateLookupTaskDefinition(ExtendedAttributeTask.Cost1, "New cost1 attribute");
project.ExtendedAttributes.Add(taskCostAttributeDefinition);
Value costVal1 = new Value();
costVal1.Id = 2;
costVal1.Description = "Cost value 1 descr";
costVal1.Val = "99900";
Value costVal2 = new Value();
costVal2.Id = 3;
costVal2.Description = "Cost value 2 descr";
costVal2.Val = "11100";
taskCostAttributeDefinition.AddLookupValue(costVal1);
taskCostAttributeDefinition.AddLookupValue(costVal2);
// Add new task and assign attribute lookup value.
Task task = project.RootTask.Children.Add("New task");
ExtendedAttribute taskAttr = taskCostAttributeDefinition.CreateExtendedAttribute(costVal1);
task.ExtendedAttributes.Add(taskAttr);
ExtendedAttributeDefinition taskStartAttributeDefinition = ExtendedAttributeDefinition.CreateLookupTaskDefinition(ExtendedAttributeTask.Start7, "New start 7 attribute");
Value startVal = new Value();
startVal.Id = 4;
startVal.DateTimeValue = DateTime.Now;
startVal.Description = "Start 7 value description";
taskStartAttributeDefinition.AddLookupValue(startVal);
project.ExtendedAttributes.Add(taskStartAttributeDefinition);
ExtendedAttributeDefinition taskFinishAttributeDefinition = ExtendedAttributeDefinition.CreateLookupTaskDefinition(ExtendedAttributeTask.Finish4, "New finish 4 attribute");
Value finishVal = new Value();
finishVal.Id = 5;
finishVal.DateTimeValue = DateTime.Now;
finishVal.Description = "Finish 4 value description";
taskFinishAttributeDefinition.ValueList.Add(finishVal);
project.ExtendedAttributes.Add(taskFinishAttributeDefinition);
ExtendedAttributeDefinition numberAttributeDefinition = ExtendedAttributeDefinition.CreateLookupTaskDefinition(ExtendedAttributeTask.Number20, "New number attribute");
Value val1 = new Value();
val1.Id = 6;
val1.Val = "1";
val1.Description = "Number 1 value";
Value val2 = new Value();
val2.Id = 7;
val2.Val = "2";
val2.Description = "Number 2 value";
Value val3 = new Value();
val2.Id = 8;
val3.Val = "3";
val3.Description = "Number 3 value";
numberAttributeDefinition.AddLookupValue(val1);
numberAttributeDefinition.AddLookupValue(val2);
numberAttributeDefinition.AddLookupValue(val3);
project.ExtendedAttributes.Add(numberAttributeDefinition);
ExtendedAttributeDefinition resourceStartAttributeDefinition = ExtendedAttributeDefinition.CreateLookupResourceDefinition(ExtendedAttributeResource.Start5, "New start5 attribute");
Value startVal2 = new Value();
startVal2.Id = 9;
startVal2.DateTimeValue = DateTime.Now;
startVal2.Description = "this is start5 value descr";
resourceStartAttributeDefinition.AddLookupValue(startVal2);
project.ExtendedAttributes.Add(resourceStartAttributeDefinition);
// Define a duration attribute without lookup.
ExtendedAttributeDefinition taskDurationAttributeDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Duration1, "New Duration");
project.ExtendedAttributes.Add(taskDurationAttributeDefinition);
// Add new task and assign duration value to the previously defined duration attribute.
Task timeTask = project.RootTask.Children.Add("New task");
ExtendedAttribute durationExtendedAttribute = taskDurationAttributeDefinition.CreateExtendedAttribute();
durationExtendedAttribute.DurationValue = project.GetDuration(3.0, TimeUnitType.Hour);
timeTask.ExtendedAttributes.Add(durationExtendedAttribute);
MPPSaveOptions mppSaveOptions = new MPPSaveOptions();
mppSaveOptions.WriteViewData = true;
project.Save("WriteUpdatedExtendedAttributeDefinitions_out.mpp", mppSaveOptions);
Project project = new Project("New Project.mpp");
OutlineCodeDefinition textOutline = new OutlineCodeDefinition();
textOutline.FieldId = ExtendedAttributeTask.OutlineCode7.ToString("D");
textOutline.Alias = "My Outline Code";
project.OutlineCodes.Add(textOutline);
OutlineMask mask = new OutlineMask();
mask.Type = MaskType.Characters;
textOutline.Masks.Add(mask);
OutlineValue textValue = new OutlineValue();
textValue.Value = "Text value 1";
textValue.ValueId = 1;
textValue.Type = OutlineValueType.Text;
textValue.Description = "Text value descr 1";
textOutline.Values.Add(textValue);
project.Save("MultipleOutlineValues.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
foreach (OutlineCodeDefinition ocd in project.OutlineCodes)
{
Console.WriteLine("Alias = " + ocd.Alias);
if (ocd.AllLevelsRequired)
Console.WriteLine("It contains property: must have all levels");
else
Console.WriteLine("It does not contain property: must have all levels");
if (ocd.Enterprise)
Console.WriteLine("It is an enterprise custom outline code.");
else
Console.WriteLine("It is not an enterprise custom outline code.");
Console.WriteLine("Reference to another custom field for which this outline code definition is an alias is = " + ocd.EnterpriseOutlineCodeAlias);
Console.WriteLine("Field Id = " + ocd.FieldId);
Console.WriteLine("Field Name = " + ocd.FieldName);
Console.WriteLine("Phonetic Alias = " + ocd.PhoneticAlias);
Console.WriteLine("Guid = " + ocd.Guid);
// Display outline code masks
foreach (OutlineMask outlineMask in ocd.Masks)
{
Console.WriteLine("Level of a mask = " + outlineMask.Level);
Console.WriteLine("Mask = " + outlineMask.ToString());
}
// Display out line code values
foreach (OutlineValue outlineMask1 in ocd.Values)
{
Console.WriteLine("Description of outline value = " + outlineMask1.Description);
Console.WriteLine("Value Id = " + outlineMask1.ValueId);
Console.WriteLine("Value = " + outlineMask1.Value);
Console.WriteLine("Type = " + outlineMask1.Type);
}
}
// Create empty project and set calculation mode to Automatic
Project project = new Project();
project.CalculationMode = CalculationMode.Automatic;
// Set project start date and add new tasks
project.Set(Prj.StartDate, new DateTime(2015, 4, 15));
Task task1 = project.RootTask.Children.Add("Task 1");
Task task2 = project.RootTask.Children.Add("Task 2");
// Link tasks
TaskLink link = project.TaskLinks.Add(task1, task2, TaskLinkType.FinishToStart);
// Verify dates have been recalculated
Console.WriteLine("Task1 Start + 1 Equals Task2 Start : {0} ", task1.Get(Tsk.Start).AddDays(1).Equals(task2.Get(Tsk.Start)));
Console.WriteLine("Task1 Finish + 1 Equals Task2 Finish : {0} ", task1.Get(Tsk.Finish).AddDays(1).Equals(task2.Get(Tsk.Finish)));
Console.WriteLine("RootTask Finish Equals Task2 Finish : {0} ", task2.Get(Tsk.Finish).Equals(project.RootTask.Get(Tsk.Finish)));
Console.WriteLine("Project Finish Date Equals Task2 Finish : {0} ", task2.Get(Tsk.Finish).Equals(project.Get(Prj.FinishDate)));
// Create empty project and set calculation mode to Manual
Project project = new Project();
project.CalculationMode = CalculationMode.Manual;
// Set project start date and add new tasks
project.Set(Prj.StartDate, new DateTime(2015, 4, 15));
Task task1 = project.RootTask.Children.Add("Task 1");
Task task2 = project.RootTask.Children.Add("Task 2");
// The necessary properties are set in manual mode
Console.WriteLine("Task1.Id Equals 1 : {0} ", task1.Get(Tsk.Id).Equals(1));
Console.WriteLine("Task1 OutlineLevel Equals 1 : {0} ", task1.Get(Tsk.OutlineLevel).Equals(1));
Console.WriteLine("Task1 Start Equals 15/04/2015 08:00 AM : {0} ", task1.Get(Tsk.Start).Equals(new DateTime(2015, 4, 15, 8, 0, 0)));
Console.WriteLine("Task1 Finish Equals 15/04/2015 05:00 PM : {0} ", task1.Get(Tsk.Finish).Equals(new DateTime(2015, 4, 15, 17, 0, 0)));
Console.WriteLine("Task1 Duration Equals 1 day : {0} ", task1.Get(Tsk.Duration).ToString().Equals("1 day"));
Console.WriteLine("Task2 Start Equals 15/04/2015 08:00 AM : {0} ", task2.Get(Tsk.Start).Equals(new DateTime(2015, 4, 15, 8, 0, 0)));
Console.WriteLine("Task2 Finish Equals 15/04/2015 05:00 PM : {0} ", task2.Get(Tsk.Finish).Equals(new DateTime(2015, 4, 15, 17, 0, 0)));
Console.WriteLine("Task2 Duration Equals 1 day : {0} ", task2.Get(Tsk.Duration).ToString().Equals("1 day"));
// When we link two tasks together their dates are not recalculated in manual mode
TaskLink link = project.TaskLinks.Add(task1, task2, TaskLinkType.FinishToStart);
// Task 2 Start has not been changed
Console.WriteLine("Task1 Start Equals Task2 Start : {0} ", task1.Get(Tsk.Start).Equals(task2.Get(Tsk.Start)));
Console.WriteLine("Task1 Finish Equals Task2 Finish : {0} ", task1.Get(Tsk.Finish).Equals(task2.Get(Tsk.Finish)));
// Create empty project and set calculation mode to None
Project project = new Project();
project.CalculationMode = CalculationMode.None;
// Add a new task
Task task = project.RootTask.Children.Add("Task");
// Note that even ids were not calculated
Console.WriteLine("Task.Id Equals 0 : {0} ", task.Get(Tsk.Id).Equals(0));
Console.WriteLine("Task.OutlineLevel Equals 0 : {0} ", task.Get(Tsk.OutlineLevel).Equals(0));
Console.WriteLine("Task Start Equals DateTime.MinValue : {0} ", task.Get(Tsk.Start).Equals(DateTime.MinValue));
Console.WriteLine("Task Finish Equals DateTime.MinValue : {0} ", task.Get(Tsk.Finish).Equals(DateTime.MinValue));
Console.WriteLine("Task Duration Equals 0 mins : {0} ", task.Get(Tsk.Duration).ToString().Equals("0 mins"));
// Set duration property
task.Set(Tsk.Duration, project.GetDuration(2, TimeUnitType.Day));
Console.WriteLine("Task Duration Equals 2 days : {0} ", task.Get(Tsk.Duration).ToString().Equals("2 days"));
Console.WriteLine("Task Start Equals DateTime.MinValue : {0} ", task.Get(Tsk.Start).Equals(DateTime.MinValue));
Console.WriteLine("Task Finish Equals DateTime.MinValue : {0} ", task.Get(Tsk.Finish).Equals(DateTime.MinValue));
Project project = new Project("New Project.mpp");
// Display project version
Console.WriteLine("Project Version : " + project.Get(Prj.SaveVersion).ToString());
Console.WriteLine("Last Saved : " + project.Get(Prj.LastSaved).ToShortDateString());
Project project = new Project("New Project.mpp");
// Display currency properties
Console.WriteLine("Currency Code : " + project.Get(Prj.CurrencyCode).ToString());
Console.WriteLine("<br>Currency Digits : " + project.Get(Prj.CurrencyDigits).ToString());
Console.WriteLine("<br>Currency Symbol : " + project.Get(Prj.CurrencySymbol).ToString());
Console.WriteLine("Currency Symbol Position" + project.Get(Prj.CurrencySymbolPosition).ToString());
// Create project
Project project = new Project("New Project.mpp");
// Display default properties
Console.WriteLine("New Task Default Start: " + project.Get(Prj.DefaultStartTime).ToShortDateString());
Console.WriteLine("New Task Default Type: " + project.Get(Prj.DefaultTaskType));
Console.WriteLine("Resource Default Standard Rate: " + project.Get(Prj.DefaultStandardRate).ToString());
Console.WriteLine("Resource Default Overtime Rate: " + project.Get(Prj.DefaultOvertimeRate).ToString());
Console.WriteLine("Default Task EV Method: " + project.Get(Prj.DefaultTaskEVMethod).ToString());
Console.WriteLine("Default Cost Accrual: " + project.Get(Prj.DefaultFixedCostAccrual).ToString());
// Create a project instance
Project project = new Project("New Project.mpp");
// Display fiscal year properties
Console.WriteLine("Fiscal Year Start Date : " + project.Get(Prj.FyStartDate).ToString());
Console.WriteLine("Fiscal Year Numbering : " + project.Get(Prj.FiscalYearStart).ToString());
// Create a project reader instance
Project project = new Project("New Project.mpp");
// custom properties are available through the typed collection
foreach (var property in project.CustomProps)
{
Console.WriteLine(property.Type);
Console.WriteLine(property.Name);
Console.WriteLine(property.Value);
}
// built-in properties are available directly
Console.WriteLine(project.BuiltInProps.Author);
Console.WriteLine(project.BuiltInProps.Title);
// or as an item of built-in property collection
foreach (var property in project.BuiltInProps)
{
Console.WriteLine(property.Name);
Console.WriteLine(property.Value);
}
// Create a project reader instance
Project project = new Project("New Project.mpp");
// Display project information
if (project.Get(Prj.ScheduleFromStart))
Console.WriteLine("Project Finish Date : " + project.Get(Prj.StartDate).ToShortDateString());
else
Console.WriteLine("Project Finish Date : " + project.Get(Prj.FinishDate).ToShortDateString());
Console.WriteLine(project.Get(Prj.Author));
Console.WriteLine(project.Get(Prj.LastAuthor));
Console.WriteLine(project.Get(Prj.Revision));
Console.WriteLine(project.Get(Prj.Keywords));
Console.WriteLine(project.Get(Prj.Comments));
Console.WriteLine("The program has run successfully");
Project project = new Project("New Project.mpp");
// Display week days properties
Console.WriteLine("Week Start Date : " + project.Get(Prj.WeekStartDay).ToString());
Console.WriteLine("Days Per Month : " + project.Get(Prj.DaysPerMonth).ToString());
Console.WriteLine("Minutes Per Day : " + project.Get(Prj.MinutesPerDay).ToString());
Console.WriteLine("Minutes Per Week : " + project.Get(Prj.MinutesPerWeek).ToString());
// Create a project instance Set new task property and Save the project as XML project file
Project project = new Project();
project.Set(Prj.NewTaskStartDate, TaskStartDateType.CurrentDate);
project.Save("SetAttributesForNewTasks_out.xml", SaveFileFormat.XML);
// Display Status.
Console.WriteLine("New Task created with start date successfully.");
// Create a project instance
Project project = new Project("New Project.mpp");
// Set currency properties
project.Set(Prj.CurrencyCode, "AUD");
project.Set(Prj.CurrencyDigits, 2);
project.Set(Prj.CurrencySymbol, "$");
project.Set(Prj.CurrencySymbolPosition, CurrencySymbolPositionType.After);
project.Save("WriteCurrencyProperties_out.xml", SaveFileFormat.XML);
// Create a project instance and Set default properties
Project project = new Project();
project.Set(Prj.ScheduleFromStart, true);
project.Set(Prj.StartDate, DateTime.Now);
project.Set(Prj.DefaultStartTime, project.Get(Prj.StartDate));
project.Set(Prj.DefaultTaskType, TaskType.FixedDuration);
project.Set(Prj.DefaultStandardRate, 15);
project.Set(Prj.DefaultOvertimeRate, 12);
project.Set(Prj.DefaultTaskEVMethod, EarnedValueMethodType.PercentComplete);
project.Set(Prj.DefaultFixedCostAccrual, CostAccrualType.Prorated);
project.Save("WriteDefaultProperties_out.xml", SaveFileFormat.XML);
// Create a project instance
Project project = new Project("New Project.mpp");
// Set fiscal year properties
project.Set(Prj.FyStartDate, Month.July);
project.Set(Prj.FiscalYearStart, true);
project.Save("WriteFiscalYearProperties_out.mpp", SaveFileFormat.MPP);
// Instantiate Project class
Project project = new Project("New Project.mpp");
// Set project summary
project.Set(Prj.Author, "Author");
project.Set(Prj.LastAuthor, "Last Author");
project.Set(Prj.Revision, 15);
project.Set(Prj.Keywords, "MSP Aspose");
project.Set(Prj.Comments, "Comments");
project.Save("WriteMPPProjectSummary_out.mpp", SaveFileFormat.MPP);
// Create project from template file
Project project = new Project("New Project.mpp");
// Set project information
project.Set(Prj.Author, "Author");
project.Set(Prj.LastAuthor, "Last Author");
project.Set(Prj.Revision, 15);
project.Set(Prj.Keywords, "MSP Aspose");
project.Set(Prj.Comments, "Comments");
project.Save("WriteProjectInfo_out.mpp", SaveFileFormat.MPP);
// Create a project instance
Project project = new Project("New Project.mpp");
// Set week days properties
project.Set(Prj.WeekStartDay, DayType.Monday);
project.Set(Prj.DaysPerMonth, 24);
project.Set(Prj.MinutesPerDay, 540);
project.Set(Prj.MinutesPerWeek, 3240);
project.Save("WriteWeekdayProperties_out.xml", SaveFileFormat.XML);
Project project = new Project("New Project.mpp");
Task task = project.RootTask.Children.Add("New Activity");
// Define new custom attribute
ExtendedAttributeDefinition text1Definition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Text1, null);
project.ExtendedAttributes.Add(text1Definition);
// Add custom text attribute to created task.
task.ExtendedAttributes.Add(text1Definition.CreateExtendedAttribute("Activity attribute"));
// Customize table by adding text attribute field
TableField attrField = new TableField();
attrField.Field = Field.TaskText1;
attrField.Width = 20;
attrField.Title = "Custom attribute";
attrField.AlignTitle = StringAlignment.Center;
attrField.AlignData = StringAlignment.Center;
Table table = project.Tables.ToList()[0];
table.TableFields.Insert(3, attrField);
project.Save("ConfigureGanttChart_out.mpp", new MPPSaveOptions() { WriteViewData = true });
Project project = new Project("New Project.mpp");
// Create a new project task
Task task = project.RootTask.Children.Add("New Activity");
// Define new custom attribute
ExtendedAttributeDefinition text1Definition = ExtendedAttributeDefinition.CreateTaskDefinition(ExtendedAttributeTask.Text1, null);
project.ExtendedAttributes.Add(text1Definition);
// Add custom text attribute to created task.
task.ExtendedAttributes.Add(text1Definition.CreateExtendedAttribute("Activity attribute"));
// Customize table by adding text attribute field
TableField attrField = new TableField();
attrField.Field = Field.TaskText1;
attrField.Width = 20;
attrField.Title = "Custom attribute";
attrField.AlignTitle = StringAlignment.Center;
attrField.AlignData = StringAlignment.Center;
Table table = project.Tables.ToList()[0];
table.TableFields.Insert(3, attrField);
project.Save("ConfigureTheGantChartViewShowSelectedColumnFields_out.mpp", new MPPSaveOptions() { WriteViewData = true });
Project project = new Project("New Project.mpp");
// Add task links
project.TaskLinks.Add(project.RootTask.Children.Add("Task 1"), project.RootTask.Children.Add("Task 2"));
GanttChartView view = (GanttChartView)project.DefaultView;
// This code is added for better visualization
view.MiddleTimescaleTier.Unit = TimescaleUnit.Months;
project.Set(Prj.TimescaleStart, new DateTime(2012, 8, 6));
// Customize middle tier dates
view.MiddleTimescaleTier.DateTimeConverter =
date => new[] { "Янв.", "Фев.", "Мар.", "Апр.", "Май", "Июнь", "Июль", "Авг.", "Сен.", "Окт.", "Ноя.", "Дек." }[date.Month - 1];
project.Save("CustomizeTimescaleTierLabels_out.pdf", SaveFileFormat.PDF);
Project project = new Project("New Project.mpp");
GanttChartView view = project.Views.ToList()[0] as GanttChartView;
Console.WriteLine("Is Bar Rounding: " + view.BarRounding);
Console.WriteLine("Show Bar Splits? : " + view.ShowBarSplits);
Console.WriteLine("Show Drawings? : " + view.ShowDrawings);
Console.WriteLine("Roll Up Gantt Bars? " + view.RollUpGanttBars);
Console.WriteLine("Hide Rollup Bars When Summary Expa0nded: " + view.HideRollupBarsWhenSummaryExpanded);
Console.WriteLine("Bar Size: " + view.BarSize.ToString());
Console.WriteLine("Bar Style: " + view.BarStyles.Count);
Console.WriteLine("************************ RETREIVING BAR STYLES INFORMATION FROM THE VIEW *********************");
int i = 0;
foreach (GanttBarStyle barStyle in view.BarStyles)
{
Console.WriteLine("Name: " + barStyle.Name);
Console.WriteLine("ShowFor: " + barStyle.ShowFor.ToString());
Console.WriteLine("Row: " + barStyle.Row);
Console.WriteLine("From: " + barStyle.From);
Console.WriteLine("To: " + barStyle.To);
Console.WriteLine("MiddleShape: " + barStyle.MiddleShape);
Console.WriteLine("MiddleShapeColor: " + barStyle.MiddleShapeColor);
Console.WriteLine("StartShape: " + barStyle.StartShape);
Console.WriteLine("EndShape: " + barStyle.EndShape);
Console.WriteLine("EndShapeColor: " + barStyle.EndShapeColor);
i++;
}
Console.WriteLine("Grid Lines Count: " + view.Gridlines.Count);
Gridlines gridlines = view.Gridlines[0];
Console.WriteLine("************************ RETREIVING GRID LINES PROPERTIES *********************");
Console.WriteLine("GridLine Type: " + gridlines.Type);
Console.WriteLine("Gridlines Internval: " + gridlines.Interval);
Console.WriteLine("Gridlines Color: " + gridlines.NormalColor);
Console.WriteLine("Gridlines NormalPattern: " + gridlines.NormalPattern);
Console.WriteLine("Gridlines IntervalPattern: " + gridlines.IntervalPattern);
Console.WriteLine("Gridlines IntervalColor: " + gridlines.IntervalColor);
Console.WriteLine("************************ RETREIVING PROGRESS LINES PROPERTIES *********************");
Console.WriteLine("ProgressLInes.BeginAtDate: ", view.ProgressLines.BeginAtDate);
Console.WriteLine("ProgressLines.isBaselinePlan: " + view.ProgressLines.IsBaselinePlan);
Console.WriteLine("ProgressLines.DisplaySelected: " + view.ProgressLines.DisplaySelected);
Console.WriteLine("ProgressLines.SelectedDates.Count: " + view.ProgressLines.SelectedDates.Count);
Console.WriteLine("ProgressLines.SelectedDates[0]: " + view.ProgressLines.SelectedDates[0]);
Console.WriteLine("ProgressLines.SelectedDates[1]: " + view.ProgressLines.SelectedDates[1]);
Console.WriteLine("ProgressLines.SelectedDates[2]: " + view.ProgressLines.SelectedDates[2]);
Console.WriteLine("ProgressLines.DisplayAtRecurringIntervals: " + view.ProgressLines.DisplayAtRecurringIntervals);
Console.WriteLine("ProgressLines.RecurringInterval.Interval: " + Interval.Weekly, view.ProgressLines.RecurringInterval.Interval);
Console.WriteLine("ProgressLines.RecurringInterval.WeeklyDays.Count" + view.ProgressLines.RecurringInterval.WeeklyDays.Count);
Console.WriteLine("Recurring Interval.WeeklyDays: " + view.ProgressLines.RecurringInterval.WeeklyDays);
Console.WriteLine("Recurring Interval.DayType.Saturday: " + view.ProgressLines.RecurringInterval.WeeklyDays);
Console.WriteLine("Recurring Interval.DayType.Sunday: " + view.ProgressLines.RecurringInterval.WeeklyDays);
Console.WriteLine("ProgressLines.ShowDate: " + view.ProgressLines.ShowDate);
Console.WriteLine("ProgressLines.ProgressPointShape: " + view.ProgressLines.ProgressPointShape.ToString());
Console.WriteLine("ProgressLines.ProgressPointColor: " + view.ProgressLines.ProgressPointColor);
Console.WriteLine("ProgressLines.LineColor: " + Color.Red, view.ProgressLines.LineColor);
Console.WriteLine("ProgressLines.LinePattern: " + LinePattern.Solid, view.ProgressLines.LinePattern);
Console.WriteLine("ProgressLines.OtherProgressPointShape: " + view.ProgressLines.OtherProgressPointShape.ToString());
Console.WriteLine("ProgressLines.OtherProgressPointColor: " + view.ProgressLines.OtherProgressPointColor.ToString());
Console.WriteLine("ProgressLines.OtherLineColor: " + view.ProgressLines.OtherLineColor);
Console.WriteLine("************************ BOTTOM TIMESCALE IFORMATION ******************");
Console.WriteLine("BottomTimescaleTier.Count:" + view.BottomTimescaleTier.Count);
Console.WriteLine("BottomTimescaleTier.Unit:" + TimescaleUnit.Days, view.BottomTimescaleTier.Unit.ToString());
Console.WriteLine("BottomTimescaleTier.UsesFiscalYear: " + view.BottomTimescaleTier.UsesFiscalYear);
Console.WriteLine("BottomTimescaleTier.Alignment: " + StringAlignment.Center, view.BottomTimescaleTier.Alignment.ToString());
Console.WriteLine("BottomTimescaleTier.ShowTicks: " + view.BottomTimescaleTier.ShowTicks.ToString());
Console.WriteLine("BottomTimescaleTier.Label:" + DateLabel.DayDi, view.BottomTimescaleTier.Label);
Console.WriteLine("************************ MIDDLE TIMESCALE IFORMATION ******************");
Console.WriteLine("MiddleTimescaleTier.Count:" + view.MiddleTimescaleTier.Count);
Console.WriteLine("MiddleTimescaleTier.Unit:" + TimescaleUnit.Days, view.MiddleTimescaleTier.Unit.ToString());
Console.WriteLine("MiddleTimescaleTier.UsesFiscalYear: " + view.MiddleTimescaleTier.UsesFiscalYear);
Console.WriteLine("MiddleTimescaleTier.Alignment: " + StringAlignment.Center, view.MiddleTimescaleTier.Alignment.ToString());
Console.WriteLine("MiddleTimescaleTier.ShowTicks: " + view.MiddleTimescaleTier.ShowTicks.ToString());
Console.WriteLine("MiddleTimescaleTier.Label:" + DateLabel.DayDi, view.MiddleTimescaleTier.Label);
Console.WriteLine("************************ TOP TIMESCALE IFORMATION ******************");
Console.WriteLine("TopTimescaleTier.Unit:" + TimescaleUnit.Days, view.TopTimescaleTier.Unit.ToString());
Console.WriteLine("TopTimescaleTier.UsesFiscalYear: " + view.TopTimescaleTier.UsesFiscalYear);
Console.WriteLine("TopTimescaleTier.Alignment: " + StringAlignment.Center, view.TopTimescaleTier.Alignment.ToString());
Console.WriteLine("TopTimescaleTier.ShowTicks: " + view.TopTimescaleTier.ShowTicks.ToString());
Console.WriteLine("TopTimescaleTier.Label: ", view.TopTimescaleTier.Label.ToString());
Project project = new Project("New Project.mpp");
View view = null;
foreach (var v in project.Views)
{
if (v.Name == "&Gantt Chart")
{
view = v;
}
}
// set default view
project.DefaultView = view;
project.Save("DefaultGanttChartView_out.mpp", new MPPSaveOptions() { WriteViewData = true });
Project project = new Project();
// Init Gantt Chart View
GanttChartView view = new GanttChartView();
// Set Time Scale count
view.BottomTimescaleTier.Count = 2;
view.BottomTimescaleTier.ShowTicks = false;
view.MiddleTimescaleTier.Count = 2;
view.MiddleTimescaleTier.ShowTicks = false;
// Add Gantt Chart View to project
project.Views.Add(view);
// Add some test data to project
Task task1 = project.RootTask.Children.Add("Task 1");
Task task2 = project.RootTask.Children.Add("Task 2");
task1.Set(Tsk.Duration, task1.ParentProject.GetDuration(24, TimeUnitType.Hour));
task2.Set(Tsk.Duration, task1.ParentProject.GetDuration(40, TimeUnitType.Hour));
project.Save("SetTimeScaleCount_out.pdf", SaveFileFormat.PDF);
Project project = new Project("New Project.mpp");
GanttChartView ganttChartView = project.Views.ToList()[0] as GanttChartView;
if (ganttChartView != null)
{
ganttChartView.TableTextStyles.Clear();
ganttChartView.TableTextStyles.Add(new TableTextStyle(1) { Color = Color.Red, Field = Field.TaskName });
ganttChartView.TableTextStyles.Add(new TableTextStyle(1) { Color = Color.Gray, Field = Field.TaskDurationText });
ganttChartView.TableTextStyles.Add(new TableTextStyle(2) { Color = Color.Blue, FontStyle = FontStyle.Bold | FontStyle.Italic | FontStyle.Underline });
}
// Create new project
Project project = new Project("New Project.mpp");
// Assign resource "1 TRG: Trade Group" to the "TASK 1" by creating a ResourceAssignment object.
Resource resource = project.Resources.GetById(1);
Task task = project.RootTask.Children.GetById(1);
ResourceAssignment assignment = project.ResourceAssignments.Add(task, resource);
// Create custom attribute definition with lookup.
ExtendedAttributeDefinition resCostAttr = ExtendedAttributeDefinition.CreateLookupResourceDefinition(
CustomFieldType.Cost,
ExtendedAttributeResource.Cost5,
"My lookup resource cost");
project.ExtendedAttributes.Add(resCostAttr);
var value1 = new Value { NumberValue = 1500, Description = "Val 1", Id = 1, Val = "1500" };
resCostAttr.AddLookupValue(value1);
resCostAttr.AddLookupValue(new Value { NumberValue = 2500, Description = "Val 2", Id = 2 });
// This value can be seen in "Resource usage" view of MS Project.
var attributeValue = resCostAttr.CreateExtendedAttribute(value1);
assignment.ExtendedAttributes.Add(attributeValue);
// Create custom attribute definition with lookup.
ExtendedAttributeDefinition taskCostAttr = ExtendedAttributeDefinition.CreateLookupTaskDefinition(
ExtendedAttributeTask.Cost4,
"My lookup task cost");
project.ExtendedAttributes.Add(taskCostAttr);
var taskLookupValue1 = new Value { NumberValue = 18, Description = "Task val 1", Id = 3, Val = "18" };
taskCostAttr.AddLookupValue(taskLookupValue1);
resCostAttr.AddLookupValue(new Value { NumberValue = 30, Description = "Task val 2", Id = 4 });
// This value can be seen in "Task usage" view of MS Project.
assignment.ExtendedAttributes.Add(taskCostAttr.CreateExtendedAttribute(taskLookupValue1));
project.Save("AddExtendedAttributesToRAWithLookUp_out.mpp", SaveFileFormat.MPP);
// Create new project
Project project = new Project("New Project.mpp");
// Add new task and resource
Task task = project.RootTask.Children.Add("Task");
Resource resource = project.Resources.Add("Rsc");
// Assign the resource to the desired task
ResourceAssignment assignment = project.ResourceAssignments.Add(task, resource);
// Custom attributes which is visible in "Resource Usage" view can be created with ExtendedAttributeDefinition.CreateResourceDefinition method.
{
ExtendedAttributeDefinition resCostAttributeDefinition = ExtendedAttributeDefinition.CreateResourceDefinition(
CustomFieldType.Cost,
ExtendedAttributeResource.Cost5,
"My cost");
project.ExtendedAttributes.Add(resCostAttributeDefinition);
var value = resCostAttributeDefinition.CreateExtendedAttribute();
// The type of the attribute is "Cost", so we need to use "NumericValue" property.
value.NumericValue = 1500;
assignment.ExtendedAttributes.Add(value);
}
// Custom attributes which is visible in "Task Usage" view can be created with ExtendedAttributeDefinition.CreateTaskDefinition method
{
ExtendedAttributeDefinition taskCostAttributeDefinition = ExtendedAttributeDefinition.CreateTaskDefinition(
CustomFieldType.Cost,
ExtendedAttributeTask.Cost5,
"My cost for task");
project.ExtendedAttributes.Add(taskCostAttributeDefinition);
var value = taskCostAttributeDefinition.CreateExtendedAttribute();
// The type of the attribute is "Cost", so we need to use "NumericValue" property.
value.NumericValue = 2300;
assignment.ExtendedAttributes.Add(value);
}
project.Save("AddExtendedAttributesToResourceAssignment_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp")
{
CalculationMode = CalculationMode.Automatic
};
project.Set(Prj.DateFormat, DateFormat.DateDddMmDdYy);
project.Set(Prj.StartDate, new DateTime(2019, 9, 16, 9, 0, 0));
project.Set(Prj.NewTasksAreManual, false);
project.Set(Prj.ActualsInSync, false);
Resource workResource = project.Resources.Add("Servente (Work)");
workResource.Set(Rsc.Name, "Servente (Work)");
workResource.Set(Rsc.Initials, "S");
workResource.Set(Rsc.Type, ResourceType.Work);
workResource.Set(Rsc.StandardRateFormat, RateFormatType.Hour);
workResource.Set(Rsc.Code, "1503");
Resource materialResource = project.Resources.Add("Tijolo (Material)");
materialResource.Set(Rsc.Name, "Tijolo (Material)");
materialResource.Set(Rsc.Initials, "T");
materialResource.Set(Rsc.Type, ResourceType.Material);
materialResource.Set(Rsc.StandardRateFormat, RateFormatType.MaterialResourceRate);
materialResource.Set(Rsc.Code, "21341");
Task task1 = project.RootTask.Children.Add("Task - 01");
task1.Set(Tsk.IsRollup, new NullableBool(true));
task1.Set(Tsk.IsPublished, new NullableBool(false));
Task task2 = task1.Children.Add("Task - 01.01");
task2.Set(Tsk.IsRollup, new NullableBool(true));
task2.Set(Tsk.IsPublished, new NullableBool(false));
Task task3 = task2.Children.Add("Task - 01.01.001");
task3.Set(Tsk.IsEstimated, new NullableBool(false));
task3.Set(Tsk.Start, new DateTime(2019, 9, 16, 9, 0, 0));
task3.Set(Tsk.Duration, project.GetDuration(10, TimeUnitType.Day));
task3.Set(Tsk.Work, project.GetDuration(10, TimeUnitType.Day));
task3.Set(Tsk.IsRollup, new NullableBool(true));
task3.Set(Tsk.IsPublished, new NullableBool(false));
ResourceAssignment assignment1 = project.ResourceAssignments.Add(task3, materialResource);
assignment1.Set(Asn.Delay, project.GetDuration(40, TimeUnitType.Hour));
assignment1.Set(Asn.Start, new DateTime(2019, 9, 23, 9, 0, 0));
assignment1.Set(Asn.Finish, new DateTime(2019, 9, 27, 18, 0, 0));
ResourceAssignment assignment2 = project.ResourceAssignments.Add(task3, workResource);
assignment2.Set(Asn.Work, project.GetDuration(56, TimeUnitType.Hour));
assignment2.Set(Asn.Start, new DateTime(2019, 9, 16, 9, 0, 0));
assignment2.Set(Asn.Finish, new DateTime(2019, 9, 24, 18, 0, 0));
// to match expected MPP fully
assignment2.Set(Asn.WorkContour, WorkContourType.Contoured);
task3.Set(Tsk.IsManual, new NullableBool(true));
task1.Set(Tsk.IsManual, new NullableBool(true));
project.Save("Assignment_Dates.mpp", SaveFileFormat.MPP);
// Create empty project
Project project = new Project();
// Add new task and resource
Task task = project.RootTask.Children.Add("Task");
Resource resource = project.Resources.Add("Rsc");
// Assign the resource desired task
ResourceAssignment assignment = project.ResourceAssignments.Add(task, resource);
Project project = new Project("New Project.mpp");
// Get the first task of the Project
Task task = project.RootTask.Children.GetById(1);
// Get the First Resource Assignment of the Project
ResourceAssignment firstRA = project.ResourceAssignments.ToList()[0];
// Flat contour is default contour
Console.WriteLine("Flat contour");
var tdList = task.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate));
foreach (TimephasedData td in tdList)
{
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value);
}
// Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.Turtle);
Console.WriteLine("Turtle contour");
tdList = task.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate));
foreach (TimephasedData td in tdList)
{
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value);
}
// Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.BackLoaded);
Console.WriteLine("BackLoaded contour");
tdList = task.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate));
foreach (TimephasedData td in tdList)
{
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value);
}
// Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.FrontLoaded);
Console.WriteLine("FrontLoaded contour");
tdList = task.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate));
foreach (TimephasedData td in tdList)
{
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value);
}
// Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.Bell);
Console.WriteLine("Bell contour");
tdList = task.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate));
foreach (TimephasedData td in tdList)
{
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value);
}
// Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.EarlyPeak);
Console.WriteLine("EarlyPeak contour");
tdList = task.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate));
foreach (TimephasedData td in tdList)
{
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value);
}
// Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.LatePeak);
Console.WriteLine("LatePeak contour");
tdList = task.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate));
foreach (TimephasedData td in tdList)
{
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value);
}
// Change contour
firstRA.Set(Asn.WorkContour, WorkContourType.DoublePeak);
Console.WriteLine("DoublePeak contour");
tdList = task.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate));
foreach (TimephasedData td in tdList)
{
Console.WriteLine(td.Start.ToShortDateString() + " " + td.Value);
}
Project project = new Project("New Project.mpp");
// Print general resource assignment properties
foreach (ResourceAssignment ra in project.ResourceAssignments)
{
Console.WriteLine(ra.Get(Asn.Uid));
Console.WriteLine(ra.Get(Asn.Start).ToShortDateString());
Console.WriteLine(ra.Get(Asn.Finish).ToShortDateString());
}
Project project = new Project("New Project.mpp");
// Print assignment budget cost and budget work
foreach (ResourceAssignment ra in project.ResourceAssignments)
{
Console.WriteLine(ra.Get(Asn.BudgetCost));
Console.WriteLine(ra.Get(Asn.BudgetWork).ToString());
}
Project project = new Project("New Project.mpp");
// Print resource assignment costs
foreach (ResourceAssignment ra in project.ResourceAssignments)
{
Console.WriteLine(ra.Get(Asn.Cost));
Console.WriteLine(ra.Get(Asn.ACWP));
Console.WriteLine(ra.Get(Asn.BCWP));
Console.WriteLine(ra.Get(Asn.BCWS));
}
Project project = new Project("New Project.mpp");
// Print assignment overtimes
foreach (ResourceAssignment ra in project.ResourceAssignments)
{
Console.WriteLine(ra.Get(Asn.OvertimeCost));
Console.WriteLine(ra.Get(Asn.OvertimeWork).ToString());
Console.WriteLine(ra.Get(Asn.RemainingCost));
Console.WriteLine(ra.Get(Asn.RemainingOvertimeCost));
Console.WriteLine(ra.Get(Asn.RemainingOvertimeWork).ToString());
Console.WriteLine(ra.Get(Asn.RemainingOvertimeWork).ToString());
}
Project project = new Project("New Project.mpp");
// Print assignment percent completion
foreach (ResourceAssignment ra in project.ResourceAssignments)
{
Console.WriteLine(ra.Get(Asn.PercentWorkComplete).ToString());
}
Project project = new Project("New Project.mpp");
// Print resource assignment's stop and resume dates
foreach (ResourceAssignment ra in project.ResourceAssignments)
{
if (ra.Get(Asn.Stop).ToShortDateString() == "1/1/2000")
Console.WriteLine("NA");
else
Console.WriteLine(ra.Get(Asn.Stop).ToShortDateString());
if (ra.Get(Asn.Resume).ToShortDateString() == "1/1/2000")
Console.WriteLine("NA");
else
Console.WriteLine(ra.Get(Asn.Resume).ToShortDateString());
}
Project project = new Project("New Project.mpp");
// Print assignment variances
foreach (ResourceAssignment ra in project.ResourceAssignments)
{
Console.WriteLine(ra.Get(Asn.WorkVariance));
Console.WriteLine(ra.Get(Asn.CostVariance));
Console.WriteLine(ra.Get(Asn.StartVariance));
Console.WriteLine(ra.Get(Asn.FinishVariance));
}
Project project = new Project("New Project.mpp");
Task task = project.RootTask.Children.Add("t1");
Resource materialResource = project.Resources.Add("materialResource");
materialResource.Set(Rsc.Type, ResourceType.Material);
Resource nonMaterialResource = project.Resources.Add("nonMaterialResource");
nonMaterialResource.Set(Rsc.Type, ResourceType.Work);
ResourceAssignment materialResourceAssignment = project.ResourceAssignments.Add(task, materialResource);
materialResourceAssignment.Set(Asn.RateScale, RateScaleType.Week);
ResourceAssignment nonMaterialResourceAssignment = project.ResourceAssignments.Add(task, nonMaterialResource);
nonMaterialResourceAssignment.Set(Asn.RateScale, RateScaleType.Week);
project.Save("output.mpp", SaveFileFormat.MPP);
project = new Project("output.mpp");
ResourceAssignment materialResourceAssignment2 = project.ResourceAssignments.GetByUid(1);
Console.WriteLine(materialResourceAssignment2.Get(Asn.RateScale));
// only material resource assignments can have non-zero rate scale value.
ResourceAssignment nonMaterialResourceAssignment2 = project.ResourceAssignments.GetByUid(2);
// Create empty project
Project project = new Project();
// Add new task and resource
Task task = project.RootTask.Children.Add("Task");
Resource resource = project.Resources.Add("Rsc");
resource.Set(Rsc.StandardRate, 10);
resource.Set(Rsc.OvertimeRate, 15);
// Assign the resource desired task
ResourceAssignment assignment = project.ResourceAssignments.Add(task, resource);
Project project = new Project("New Project.mpp");
Task task = project.RootTask.Children.GetById(1);
Resource resource = project.Resources.GetById(1);
// Create resource assignment
ResourceAssignment assignment = project.ResourceAssignments.Add(task, resource);
assignment.Set(Asn.Notes, "Newly added assignment");
project.Save("UpdateResourceAssignment_out.mpp", SaveFileFormat.MPP);
Project project = new Project();
// Add resources
Resource resource = project.Resources.Add("Rsc");
project.Save("CreateResources_out.xml", SaveFileFormat.XML);
Project project = new Project("New Project.mpp");
// Display base calendar name for all resources
foreach (Resource res in project.Resources)
{
if (res.Get(Rsc.Name) != null)
{
Console.WriteLine(res.Get(Rsc.Calendar).BaseCalendar.Name);
}
}
Project project = new Project("New Project.mpp");
// Display all resources costs
foreach (Resource res in project.Resources)
{
if (res.Get(Rsc.Name) != null)
{
Console.WriteLine(res.Get(Rsc.Cost));
Console.WriteLine(res.Get(Rsc.ACWP));
Console.WriteLine(res.Get(Rsc.BCWS));
Console.WriteLine(res.Get(Rsc.BCWP));
}
}
Project project = new Project("New Project.mpp");
// Display overtime related parameters for all resources
foreach (Resource res in project.Resources)
{
if (res.Get(Rsc.Name) != null)
{
Console.WriteLine(res.Get(Rsc.OvertimeCost));
Console.WriteLine(res.Get(Rsc.OvertimeWork).ToString());
Console.WriteLine(res.Get(Rsc.OvertimeRateFormat).ToString());
}
}
Project project = new Project("New Project.mpp");
// Display work percentage completion for all resources
foreach (Resource res in project.Resources)
{
if (res.Get(Rsc.Name) != null)
{
Console.WriteLine(res.Get(Rsc.PercentWorkComplete));
}
}
Project project = new Project("New Project.mpp");
foreach (ResourceAssignment ra in project.ResourceAssignments)
{
Resource resource = ra.Get(Asn.Resource);
double d = resource.Get(Rsc.WorkVariance);
Console.WriteLine(d);
}
Project project = new Project("New Project.mpp");
// Get the Resource by its ID
Resource resource = project.Resources.GetByUid(1);
// Print Timephased data of ResourceWork
Console.WriteLine("Timephased data of ResourceWork");
foreach (TimephasedData td in resource.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate)))
{
Console.Write("Start: " + td.Start.ToShortDateString());
Console.Write(" Work: " + td.Value + Environment.NewLine);
}
// Print Timephased data of ResourceCost
Console.WriteLine("Timephased data of ResourceCost");
foreach (TimephasedData td in resource.GetTimephasedData(project.Get(Prj.StartDate), project.Get(Prj.FinishDate), TimephasedDataType.ResourceCost))
{
Console.Write("Start: " + td.Start.ToShortDateString());
Console.Write(" Cost: " + td.Value + Environment.NewLine);
}
Project project = new Project("New Project.mpp");
// Set the Presentation Format to Resource Sheet
PresentationFormat format = PresentationFormat.ResourceSheet;
// Define rendering options
SaveOptions options = new PdfSaveOptions();
options.PresentationFormat = format;
project.Save("ResourceSheetView_out.pdf", options);
Project project = new Project("New Project.mpp");
// Define the SaveOptions with required TimeScale settings as Days
SaveOptions options = new PdfSaveOptions();
options.Timescale = Timescale.Days;
// Set the Presentation format to ResourceUsage
options.PresentationFormat = PresentationFormat.ResourceUsage;
project.Save("result_ResourceUsageView_days_out.pdf", options);
// Set the Timescale settings to ThirdsOfMonths and save the Project
options.Timescale = Timescale.ThirdsOfMonths;
project.Save("result_ResourceUsageView_thirdsOfMonths_out.pdf", options);
// Set the Timescale settings to Months and save the Project
options.Timescale = Timescale.Months;
project.Save("result_ResourceUsageView_months_out.pdf", options);
public class ResourcePrefixForNestedResources : ICssSavingCallback, IFontSavingCallback, IImageSavingCallback
{
public static void Run()
{
Project project = new Project("New Project.mpp");
HtmlSaveOptions options = GetSaveOptions(1);
project.Save("document.html", options);
}
public void CssSaving(CssSavingArgs args)
{
FileStream stream = new FileStream("css/" + args.FileName, FileMode.Create);
args.Stream = stream;
args.KeepStreamOpen = false;
args.Uri = "css/" + args.FileName;
}
public void FontSaving(FontSavingArgs args)
{
FileStream stream = new FileStream("fonts/" + args.FileName, FileMode.Create);
args.Stream = stream;
args.KeepStreamOpen = false;
args.Uri = "fonts/" + args.FileName;
}
public void ImageSaving(ImageSavingArgs args)
{
if (args.FileName.EndsWith("png"))
{
FileStream stream1 = new FileStream("resources/nestedResources/" + args.FileName, FileMode.Create);
args.Stream = stream1;
args.KeepStreamOpen = false;
args.Uri = "resources/" + args.FileName;
args.NestedUri = "nestedResources/" + args.FileName;
}
else
{
FileStream stream2 = new FileStream("resources/" + args.FileName, FileMode.Create);
args.Stream = stream2;
args.KeepStreamOpen = false;
args.Uri = "resources/" + args.FileName;
}
}
private static HtmlSaveOptions GetSaveOptions(int pageNumber)
{
HtmlSaveOptions options = new HtmlSaveOptions
{
Pages = new List<int>(),
IncludeProjectNameInPageHeader = false,
IncludeProjectNameInTitle = false,
PageSize = PageSize.A3,
Timescale = Timescale.ThirdsOfMonths,
ReduceFooterGap = true,
FontFaceTypes = FontFaceType.Ttf,
ExportCss = ResourceExportType.AsFile,
ExportFonts = ResourceExportType.AsFile,
ExportImages = ResourceExportType.AsFile
};
ResourcePrefixForNestedResources program = new ResourcePrefixForNestedResources();
options.FontSavingCallback = program;
options.CssSavingCallback = program;
options.ImageSavingCallback = program;
options.Pages.Clear();
options.Pages.Add(pageNumber);
if (!Directory.Exists("fonts"))
{
Directory.CreateDirectory("fonts");
}
if (!Directory.Exists("resources"))
{
Directory.CreateDirectory("resources");
}
if (!Directory.Exists("nestedResources"))
{
Directory.CreateDirectory("resources/nestedResources");
}
if (!Directory.Exists("css"))
{
Directory.CreateDirectory("css");
}
return options;
}
}
// Add resources
Resource resource = project.Resources.Add("Rsc");
// Set resource properties, Resource properties are represented by static class Rsc
resource.Set(Rsc.StandardRate, 15);
resource.Set(Rsc.OvertimeRate, 20);
Project project = new Project();
Resource res = project.Resources.Add("Resource1");
// Add standard calendar and assign to resource
Calendar cal = project.Calendars.Add("Resource1");
res.Set(Rsc.Calendar, cal);
Project project = new Project("New Project.mpp");
// Define extended attribute
ExtendedAttributeDefinition myNumber1 = project.ExtendedAttributes.GetById((int)ExtendedAttributeTask.Number1);
if (myNumber1 == null)
{
myNumber1 = ExtendedAttributeDefinition.CreateResourceDefinition(ExtendedAttributeResource.Number1, "Age");
project.ExtendedAttributes.Add(myNumber1);
}
// Create extended attribute and set its value
ExtendedAttribute number1Resource = myNumber1.CreateExtendedAttribute();
number1Resource.NumericValue = 30.5345m;
// Add a new resource and its extended attribute
Resource resource = project.Resources.Add("R1");
resource.ExtendedAttributes.Add(number1Resource);
project.Save("ResourceExtendedAttributes_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
// Add resource and set some properties
Resource resource = project.Resources.Add("Rsc");
resource.Set(Rsc.StandardRate, 30);
resource.Set(Rsc.OvertimeRate, 45);
resource.Set(Rsc.Group, "Workgroup1");
project.Save("UpdateResourceData_out.mpp", SaveFileFormat.MPP);
Project project = new Project();
// Creating TaskBaseline:
Task task = project.RootTask.Children.Add("Task");
// Set baseline for specified tasks and entire project
project.SetBaseline(BaselineType.Baseline, new Task[] { task });
project.SetBaseline(BaselineType.Baseline);
Project project = new Project();
// Creating TaskBaseline
Task task = project.RootTask.Children.Add("Task");
project.SetBaseline(BaselineType.Baseline);
// Display task baseline duration
TaskBaseline baseline = task.Baselines.ToList()[0];
Console.WriteLine("Baseline duration is 1 day: {0}", baseline.Duration.ToString().Equals("1 day"));
Console.WriteLine("BaselineStart is same as Task Start: {0}", baseline.Start.Equals(task.Get(Tsk.Start)));
Console.WriteLine("BaselineFinish is same as Task Finish: {0}", baseline.Finish.Equals(task.Get(Tsk.Finish)));
Project project = new Project();
// Creating TaskBaseline
Task task = project.RootTask.Children.Add("Task");
project.SetBaseline(BaselineType.Baseline);
// Display task baseline schedule
TaskBaseline baseline = task.Baselines.ToList()[0];
Console.WriteLine("Baseline duration is 1 day: {0}", baseline.Duration.ToString().Equals("1 day"));
Console.WriteLine("BaselineStart is same as Task Start: {0}", baseline.Start.Equals(task.Get(Tsk.Start)));
Console.WriteLine("BaselineFinish is same as Task Finish: {0}", baseline.Finish.Equals(task.Get(Tsk.Finish)));
// Create new project
Project project = new Project("New Project.mpp");
// Create an Extended Attribute Definition of Text1 type
var taskExtendedAttributeText1Definition = ExtendedAttributeDefinition.CreateTaskDefinition(CustomFieldType.Text, ExtendedAttributeTask.Text1, "Task City Name");
// Add it to the project's Extended Attributes collection
project.ExtendedAttributes.Add(taskExtendedAttributeText1Definition);
// Add a task to the project
Task task = project.RootTask.Children.Add("Task 1");
// Create an Extended Attribute from the Attribute Definition
var taskExtendedAttributeText1 = taskExtendedAttributeText1Definition.CreateExtendedAttribute();
// Assign a value to the generated Extended Attribute. The type of the attribute is "Text", the "TextValue" property should be used.
taskExtendedAttributeText1.TextValue = "London";
// Add the Extended Attribute to task
task.ExtendedAttributes.Add(taskExtendedAttributeText1);
project.Save("PlainTextExtendedAttribute_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
// Create an Extended Attribute Definition of Text2 type
var taskExtendedAttributeText2Definition = ExtendedAttributeDefinition.CreateLookupTaskDefinition(CustomFieldType.Text, ExtendedAttributeTask.Text2, "Task Towns Name");
// Add lookup values for the extended attribute definition
taskExtendedAttributeText2Definition.AddLookupValue(new Value { Id = 1, StringValue = "Town1", Description = "This is Town1" });
taskExtendedAttributeText2Definition.AddLookupValue(new Value { Id = 2, StringValue = "Town2", Description = "This is Town2" });
// Add it to the project's Extended Attributes collection
project.ExtendedAttributes.Add(taskExtendedAttributeText2Definition);
// Add a task to the project
var task2 = project.RootTask.Children.Add("Task 2");
// Crate an Extended Attribute from the Text2 Lookup Definition for Id 1
var taskExtendedAttributeText2 = taskExtendedAttributeText2Definition.CreateExtendedAttribute(taskExtendedAttributeText2Definition.ValueList[1]);
// Add the Extended Attribute to task
task2.ExtendedAttributes.Add(taskExtendedAttributeText2);
project.Save("TextExtendedAttributeWithLookup_out.mpp", SaveFileFormat.MPP);
Project project2 = new Project("New Project.mpp");
// Create an Extended Attribute Definition of Duration2 type
var taskExtendedAttributeDuration2Definition = ExtendedAttributeDefinition.CreateLookupTaskDefinition(CustomFieldType.Duration, ExtendedAttributeTask.Duration2, "Some duration");
// Add lookup values for extended attribute definition
taskExtendedAttributeDuration2Definition.AddLookupValue(new Value { Id = 2, Duration = project2.GetDuration(4, TimeUnitType.Hour), Description = "4 hours" });
taskExtendedAttributeDuration2Definition.AddLookupValue(new Value { Id = 3, Duration = project2.GetDuration(1, TimeUnitType.Day), Description = "1 day" });
taskExtendedAttributeDuration2Definition.AddLookupValue(new Value { Id = 4, Duration = project2.GetDuration(1, TimeUnitType.Hour), Description = "1 hour" });
taskExtendedAttributeDuration2Definition.AddLookupValue(new Value { Id = 7, Duration = project2.GetDuration(10, TimeUnitType.Day), Description = "10 days" });
// Add the definition to the project's Extended Attributes collection
project2.ExtendedAttributes.Add(taskExtendedAttributeDuration2Definition);
// Add a task to the project
var task3 = project2.RootTask.Children.Add("Task 3");
// Create an Extended Attribute from the Duration2 Lookup Definition for Id 3
var taskExtendedAttributeDuration2 = taskExtendedAttributeDuration2Definition.CreateExtendedAttribute(taskExtendedAttributeDuration2Definition.ValueList[3]);
// Add the Extended Attribute to task
task3.ExtendedAttributes.Add(taskExtendedAttributeDuration2);
project2.Save("DurationExtendedAttributeWithLookup_out.mpp", SaveFileFormat.MPP);
Project project3 = new Project("New Project.mpp");
// Create an Extended Attribute Definition of Finish2 Type
var taskExtendedAttributeFinish2Definition = ExtendedAttributeDefinition.CreateLookupTaskDefinition(CustomFieldType.Finish, ExtendedAttributeTask.Finish2, "Some finish");
// Add lookup values for extended attribute defintion
taskExtendedAttributeFinish2Definition.AddLookupValue(new Value { Id = 2, DateTimeValue = new DateTime(1984, 01, 01, 00, 00, 01), Description = "This is Value2" });
taskExtendedAttributeFinish2Definition.AddLookupValue(new Value { Id = 3, DateTimeValue = new DateTime(1994, 01, 01, 00, 01, 01), Description = "This is Value3" });
taskExtendedAttributeFinish2Definition.AddLookupValue(new Value { Id = 4, DateTimeValue = new DateTime(2009, 12, 31, 00, 00, 00), Description = "This is Value4" });
taskExtendedAttributeFinish2Definition.AddLookupValue(new Value { Id = 7, DateTimeValue = DateTime.Now, Description = "This is Value6" });
// Add the definition to the project's Extended Attributes collection
project3.ExtendedAttributes.Add(taskExtendedAttributeFinish2Definition);
// Add a task to the project
var task4 = project3.RootTask.Children.Add("Task 4");
// Create an Extended Attribute from the Finish2 Lookup Definition for Id 3
var taskExtendedAttributeFinish2 = taskExtendedAttributeFinish2Definition.CreateExtendedAttribute(taskExtendedAttributeFinish2Definition.ValueList[3]);
// Add the Extended Attribute to task
task4.ExtendedAttributes.Add(taskExtendedAttributeFinish2);
project3.Save("FinishExtendedAttributeWithLookup_out.mpp", SaveFileFormat.MPP);
Project proj = new Project();
proj.WBSCodeDefinition = new WBSCodeDefinition();
proj.WBSCodeDefinition.GenerateWBSCode = true;
proj.WBSCodeDefinition.VerifyUniqueness = true;
proj.WBSCodeDefinition.CodePrefix = "CRS-";
WBSCodeMask mask = new WBSCodeMask();
mask.Length = 2;
mask.Separator = "-";
mask.Sequence = WBSSequence.OrderedNumbers;
proj.WBSCodeDefinition.CodeMaskCollection.Add(mask);
mask = new WBSCodeMask();
mask.Length = 1;
mask.Separator = "-";
mask.Sequence = WBSSequence.OrderedUppercaseLetters;
proj.WBSCodeDefinition.CodeMaskCollection.Add(mask);
Task task = proj.RootTask.Children.Add("Task 1");
Task child = task.Children.Add("Task 2");
proj.Recalculate();
proj.Save("AddWBSCodes_out.xml", SaveFileFormat.XML);
Project project = new Project("New Project.mpp");
// Find a split task
Task splitTask = project.RootTask.Children.GetByUid(4);
// Find the project calendar
Calendar calendar = project.Get(Prj.Calendar);
// Calculate task's finish date with different durations
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 8 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(8, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 16 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(16, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 24 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(24, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 28 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(28, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 32 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(32, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 46 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(46, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 61 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(61, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 75 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(75, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 80 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(80, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 120 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(120, 0, 0)));
Console.WriteLine("Start Date: " + splitTask.Get(Tsk.Start).ToShortDateString() + "Duration 150 hours Finish Date: " + calendar.GetTaskFinishDateFromDuration(splitTask, new TimeSpan(150, 0, 0)));
Project project = new Project("New Project.mpp");
// Get a task to calculate its duration in different formats
Task task = project.RootTask.Children.GetById(1);
// Get the duration in Minutes, Days, Hours, Weeks and Months
double mins = task.Get(Tsk.Duration).Convert(TimeUnitType.Minute).ToDouble();
Console.WriteLine("Duration in Mins: {0}", mins);
double days = task.Get(Tsk.Duration).Convert(TimeUnitType.Day).ToDouble();
Console.WriteLine("Duration in Days: {0}", days);
double hours = task.Get(Tsk.Duration).Convert(TimeUnitType.Hour).ToDouble();
Console.WriteLine("Duration in Hours: {0}", hours);
double weeks = task.Get(Tsk.Duration).Convert(TimeUnitType.Week).ToDouble();
Console.WriteLine("Duration in Weeks: {0}", weeks);
double months = task.Get(Tsk.Duration).Convert(TimeUnitType.Month).ToDouble();
Console.WriteLine("Duration in Months: {0}", months);
Project project = new Project();
Console.WriteLine("Project Calculation mode is Automatic: {0}", project.CalculationMode.Equals(CalculationMode.Automatic));
Task task = project.RootTask.Children.Add("Task");
task.Set(Tsk.Duration, project.GetDuration(2));
task.Set(Tsk.PercentComplete, 50);
Project project = new Project("New Project.mpp");
RecurringTaskParameters parameters = new RecurringTaskParameters
{
TaskName = "Recurring task",
Duration = project.GetDuration(1, TimeUnitType.Day),
RecurrencePattern =
new WeeklyRecurrencePattern
{
Repetition = new WeeklyRepetition
{
RepetitionInterval = 2,
WeekDays = WeekdayType.Sunday | WeekdayType.Monday | WeekdayType.Friday,
},
RecurrenceRange =
new EndByRecurrenceRange
{
Start = new DateTime(2018, 7, 1, 8, 0, 0),
Finish = new DateTime(2018, 7, 20, 17, 0, 0),
}
}
};
project.RootTask.Children.Add(parameters);
// Create new project
Project splitTaskProject = new Project();
// Get a standard calendar
Calendar calendar = splitTaskProject.Get(Prj.Calendar);
// Set project's calendar settings
splitTaskProject.Set(Prj.StartDate, new DateTime(2000, 3, 15, 8, 0, 0));
splitTaskProject.Set(Prj.FinishDate, new DateTime(2000, 4, 21, 17, 0, 0));
// Add a new task to root task
Task rootTask = splitTaskProject.RootTask;
rootTask.Set(Tsk.Name, "Root");
Task taskToSplit = rootTask.Children.Add("Task1");
taskToSplit.Set(Tsk.Duration, splitTaskProject.GetDuration(3));
// Create a new resource assignment and generate timephased data
ResourceAssignment splitResourceAssignment = splitTaskProject.ResourceAssignments.Add(taskToSplit, null);
splitResourceAssignment.TimephasedDataFromTaskDuration(calendar);
// Split the task into 3 parts.
// Provide start date and finish date arguments to SplitTask method which will be used for split
splitResourceAssignment.SplitTask(new DateTime(2000, 3, 16, 8, 0, 0), new DateTime(2000, 3, 16, 17, 0, 0), calendar);
splitResourceAssignment.SplitTask(new DateTime(2000, 3, 18, 8, 0, 0), new DateTime(2000, 3, 18, 17, 0, 0), calendar);
splitResourceAssignment.Set(Asn.WorkContour, WorkContourType.Contoured);
splitTaskProject.Save("CreateSplitTasks_out.xml", SaveFileFormat.XML);
Project project = new Project("New Project.mpp");
// Add task
Task task = project.RootTask.Children.Add("Task 1");
// Setting new subproject link
task.Set(Tsk.SubprojectName, "subProject.mpp");
project.Save("SubProjectTask_out.mpp", SaveFileFormat.MPP);
Project project = new Project();
// Add task, sub task and save project
Task task = project.RootTask.Children.Add("Summary1");
Task subtask = task.Children.Add("Subtask1");
project.Save("CreateTasks_out.xml", SaveFileFormat.XML);
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Parse through all the collected tasks
foreach (Task task in collector.Tasks)
{
string strED = task.Get(Tsk.IsEffortDriven) ? "EffortDriven" : "Non-EffortDriven";
string strCrit = task.Get(Tsk.IsCritical) ? "Critical" : "Non-Critical";
Console.WriteLine(task.Get(Tsk.Name) + " : " + strED);
Console.WriteLine(task.Get(Tsk.Name) + " : " + strCrit);
}
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Parse through all the collected tasks
foreach (Task task in collector.Tasks)
{
string strEst = (task.Get(Tsk.IsEstimated)) ? "Estimated" : "Non-Estimated";
string strMileStone = (task.Get(Tsk.IsMilestone)) ? "Milestone" : "Non-Milestone";
Console.WriteLine(task.Get(Tsk.Name) + " : " + strEst);
Console.WriteLine(task.Get(Tsk.Name) + " : " + strMileStone);
}
Project project = new Project("New Project.mpp");
// Move tasks with id 2 to the end of the collection
Task task = project.RootTask.Children.GetById(2);
task.MoveToSibling(-1);
project.Save("MoveTaskAtTheEnd_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
project.CalculationMode = CalculationMode.Automatic;
// Get Tasks by Ids
Task task1 = project.RootTask.Children.GetByUid(6);
Task task2 = project.RootTask.Children.GetByUid(3);
// Adding Task 6 to another parent
task2.Children.Add(task1);
project.Save("MoveTaskUnderAnotherParent_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
// Move tasks with id 5 before task with id 3
Task task = project.RootTask.Children.GetById(5);
task.MoveToSibling(3);
project.Save("MoveTaskUnderSameParent_out.mpp", SaveFileFormat.MPP);
// Create Project instance
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Parse through all the collected tasks
foreach (Task task in collector.Tasks)
{
Console.WriteLine("Task Name : " + task.Get(Tsk.Name));
Console.WriteLine("Actual Start: " + task.Get(Tsk.ActualStart).ToLongDateString());
Console.WriteLine("Actual Finish: " + task.Get(Tsk.ActualFinish).ToLongDateString());
Console.WriteLine("Actual Duration: " + task.Get(Tsk.ActualDuration).TimeSpan.Hours.ToString());
Console.WriteLine("Actual Cost: " + task.Get(Tsk.ActualCost).ToString());
Console.WriteLine("---------------------------------------------");
}
Project project = new Project("New Project.mpp");
// Display budget work and budget cost for project summary task
Task projSummary = project.RootTask;
Console.WriteLine("projSummary.BudgetWork = " + projSummary.Get(Tsk.BudgetWork).ToString());
Console.WriteLine("projSummary.BudgetCost = " + projSummary.Get(Tsk.BudgetCost).ToString());
// Display resource budget work
Resource resource = project.Resources.GetByUid(6);
Console.WriteLine("Resource BudgetWork = " + resource.Get(Rsc.BudgetWork).ToString());
// Display resource budget cost
resource = project.Resources.GetByUid(7);
Console.WriteLine("Resource BudgetCost = " + resource.Get(Rsc.BudgetCost).ToString());
// Display assignment budget work and budget cost
foreach (ResourceAssignment assignment in projSummary.Assignments)
{
if (assignment.Get(Asn.Resource).Get(Rsc.Type) == ResourceType.Work)
Console.WriteLine("Assignment BudgetWork = " + assignment.Get(Asn.BudgetWork).ToString());
else
Console.WriteLine("Assignment BudgetCost = " + assignment.Get(Asn.BudgetCost).ToString());
}
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Parse through all the collected tasks
foreach (Task task in collector.Tasks)
{
Console.WriteLine(task.Get(Tsk.Name));
}
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Check Stop and Resume dates for all tasks
foreach (Task task in collector.Tasks)
{
if (task.Get(Tsk.Stop).ToShortDateString() == "1/1/2000")
Console.WriteLine("Stop: NA");
else
Console.WriteLine("Stop: " + task.Get(Tsk.Stop).ToShortDateString());
if (task.Get(Tsk.Resume).ToShortDateString() == "1/1/2000")
Console.WriteLine("Resume: NA");
else
Console.WriteLine("Resume: " + task.Get(Tsk.Resume).ToShortDateString());
}
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);
// Parse all the recursive children
foreach (Task task in collector.Tasks)
{
Calendar cal = task.Get(Tsk.Calendar);
Console.WriteLine("Task calendar name: {0}", cal == null ? "None" : cal.Name);
}
// Create new project
Project project = new Project();
// Add task and set cost
Task task = project.RootTask.Children.Add("Task");
task.Set(Tsk.Cost, 800);
// Display cost related properties of task
Console.WriteLine(task.Get(Tsk.RemainingCost));
Console.WriteLine(task.Get(Tsk.FixedCost));
Console.WriteLine(task.Get(Tsk.CostVariance));
Console.WriteLine(project.RootTask.Get(Tsk.Cost));
Console.WriteLine(project.RootTask.Get(Tsk.FixedCost));
Console.WriteLine(project.RootTask.Get(Tsk.RemainingCost));
Console.WriteLine(project.RootTask.Get(Tsk.CostVariance));
Project project = new Project("New Project.mpp");
// Read extended attributes for tasks
foreach (Task task in project.RootTask.Children)
{
foreach (ExtendedAttribute ea in task.ExtendedAttributes)
{
Console.WriteLine(ea.FieldId);
Console.WriteLine(ea.ValueGuid);
switch (ea.AttributeDefinition.CfType)
{
case CustomFieldType.Date:
case CustomFieldType.Start:
case CustomFieldType.Finish:
Console.WriteLine(ea.DateValue);
break;
case CustomFieldType.Text:
Console.WriteLine(ea.TextValue);
break;
case CustomFieldType.Duration:
Console.WriteLine(ea.DurationValue.ToString());
break;
case CustomFieldType.Cost:
case CustomFieldType.Number:
Console.WriteLine(ea.NumericValue);
break;
case CustomFieldType.Flag:
Console.WriteLine(ea.FlagValue);
break;
}
}
}
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Parse through all the collected tasks
foreach (Task task in collector.Tasks)
{
Console.WriteLine(task.Get(Tsk.Name) + " - Outline Level : " + task.Get(Tsk.OutlineLevel));
Console.WriteLine(task.Get(Tsk.Name) + " - Outline Number : " + task.Get(Tsk.OutlineNumber));
}
Project project = new Project("New Project.mpp");
// Read overtime and percentage completion for tasks
foreach (Task task in project.RootTask.Children)
{
Console.WriteLine(task.Get(Tsk.OvertimeCost));
Console.WriteLine(task.Get(Tsk.OvertimeWork).ToString());
Console.WriteLine(task.Get(Tsk.PercentComplete));
Console.WriteLine(task.Get(Tsk.PercentWorkComplete).ToString());
Console.WriteLine(task.Get(Tsk.PhysicalPercentComplete).ToString());
// Set percent complete
task.Set(Tsk.PercentComplete, 100);
}
Project project = new Project("TaskPercentageCompletion.mpp");
// Access tasks and display percentage completion
foreach (Task task in project.RootTask.Children)
{
Console.WriteLine(task.Get(Tsk.PercentComplete));
Console.WriteLine(task.Get(Tsk.PercentWorkComplete).ToString());
Console.WriteLine(task.Get(Tsk.PhysicalPercentComplete).ToString());
}
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Display Priorities for all tasks
foreach (Task task in collector.Tasks)
{
Console.WriteLine(task.Get(Tsk.Name) + " - Priority : " + task.Get(Tsk.Priority).ToString());
}
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Parse through all the collected tasks
foreach (Task task in collector.Tasks)
{
Console.WriteLine("Task Id: {0}", task.Get(Tsk.Id));
Console.WriteLine("Task Uid: {0}", task.Get(Tsk.Uid));
Console.WriteLine("Task Name: {0}", task.Get(Tsk.Name));
Console.WriteLine("Task Start: {0}", task.Get(Tsk.Start));
Console.WriteLine("Task Finish: {0}", task.Get(Tsk.Finish));
}
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Parse through all the collected tasks
foreach (Task task in collector.Tasks)
{
Console.WriteLine(task.Get(Tsk.WBS));
Console.WriteLine(task.Get(Tsk.WBSLevel));
// Set custom WBS
task.Set(Tsk.WBS, "custom wbs" + task.Get(Tsk.WBS));
}
Project project = new Project("New Project.mpp");
// Set project properties
project.Set(Prj.StartDate, new DateTime(2013, 10, 30, 9, 0, 0));
project.Set(Prj.NewTasksAreManual, false);
// Add task and resources
Task task = project.RootTask.Children.Add("Task");
Resource resource = project.Resources.Add("Rsc");
// Set resource rates and task duration
resource.Set(Rsc.StandardRate, 10);
resource.Set(Rsc.OvertimeRate, 15);
task.Set(Tsk.Duration, project.GetDuration(6));
// Create resource assignment
ResourceAssignment assignment = project.ResourceAssignments.Add(task, resource);
assignment.Set(Asn.Stop, DateTime.MinValue);
assignment.Set(Asn.Resume, DateTime.MinValue);
// Set Backloaded contour, it increases task duration from 6 to 10 days
assignment.Set(Asn.WorkContour, WorkContourType.BackLoaded);
project.SetBaseline(BaselineType.Baseline);
task.Set(Tsk.PercentComplete, 50);
// Read timephased data
List<TimephasedData> td = assignment.GetTimephasedData(assignment.Get(Asn.Start), assignment.Get(Asn.Finish), TimephasedDataType.AssignmentRemainingWork).ToList();
Console.WriteLine(td.Count);
foreach(TimephasedData timePhasedValue in td)
{
Console.WriteLine(timePhasedValue.Value);
}
Project project = new Project("New Project.mpp");
// Set presentation format Task Sheet and save project as PDF
SaveOptions options = new PdfSaveOptions();
options.PresentationFormat = PresentationFormat.TaskSheet;
project.Save("TaskSheetView_out.pdf", options);
Project project = new Project("New Project.mpp");
// Define the SaveOptions with required TimeScale settings as Days
SaveOptions options = new PdfSaveOptions();
options.Timescale = Timescale.Days;
// Set the Presentation format to ResourceUsage
options.PresentationFormat = PresentationFormat.TaskUsage;
project.Save("TaskUsageView_result_days_out.pdf", options);
// Set the Timescale settings to ThirdsOfMonths
options.Timescale = Timescale.ThirdsOfMonths;
project.Save("TaskUsageView_result_thirdsOfMonths_out.pdf", options);
// Set the Timescale settings to Months
options.Timescale = Timescale.Months;
project.Save("TaskUsageView_result_months_out.pdf", options);
Project project = new Project("New Project.mpp");
// Get Default view
UsageView view = project.DefaultView as TaskUsageView;
// Details header column will not be displayed
view.DisplayDetailsHeaderColumn = false;
view.RepeatDetailsHeaderOnAllRows = false;
view.AlignDetailsData = StringAlignment.Near;
project.Save("task usage1_out.pdf", SaveFileFormat.PDF);
// Display details header column
view.DisplayDetailsHeaderColumn = true;
// Repeat details header on all assignments rows
view.RepeatDetailsHeaderOnAllRows = true;
view.AlignDetailsData = StringAlignment.Far;
project.Save("task usage2_out.pdf", SaveFileFormat.PDF);
Project project = new Project("New Project.mpp");
Console.WriteLine("WBS codes before: ");
// output: ""; "1"; "2"; "4"
foreach (Task task in project.RootTask.SelectAllChildTasks())
{
Console.WriteLine("\"" + task.Get(Tsk.WBS) + "\"" + "; ");
}
project.RenumberWBSCode(new List<int> { 1, 2, 3 });
// project.RenumberWBSCode(); // this overload can be used instead
Console.WriteLine("WBS codes after: ");
// output: ""; "1"; "2"; "3"
foreach (Task task in project.RootTask.SelectAllChildTasks())
{
Console.WriteLine("\"" + task.Get(Tsk.WBS) + "\"" + "; ");
}
Project project = new Project("New Project.mpp");
Task task = project.RootTask.Children.GetById(1);
Console.WriteLine(task.Get(Tsk.Warning));
Project project = new Project("New Project.mpp");
// Set project start date
project.Set(Prj.StartDate, new DateTime(2012, 07, 29, 8, 0, 0));
// Add summary task and set its properties
Task summary = project.RootTask.Children.Add("Summary task");
Task task = summary.Children.Add("First task");
task.Set(Tsk.Duration, project.GetDuration(3));
task.Set(Tsk.Deadline, task.Get(Tsk.Start).AddDays(10));
task.Set(Tsk.NotesText, "The first task.");
task.Set(Tsk.DurationFormat, TimeUnitType.MinuteEstimated);
task.Set(Tsk.ConstraintType, ConstraintType.FinishNoLaterThan);
task.Set(Tsk.ConstraintDate, task.Get(Tsk.Deadline).AddDays(-1));
// Create 10 new sub tasks for summary task
for (int i = 0; i < 10; i++)
{
Task subTask = summary.Children.Add(string.Format("Task{0}", i + 2));
subTask.Set(Tsk.Duration, task.Get(Tsk.Duration).Add(project.GetDuration(i + 1)));
subTask.Set(Tsk.DurationFormat, TimeUnitType.Day);
subTask.Set(Tsk.Deadline, task.Get(Tsk.Deadline).AddDays(i + 1));
}
project.Save("UpdateTaskData_out.mpp", SaveFileFormat.MPP);
Project project = new Project("New Project.mpp");
// Access task
Task splitTask = project.RootTask.Children.GetById(4);
// Display split parts of task
SplitPartCollection collection = splitTask.SplitParts;
foreach (SplitPart splitPart in collection)
{
Console.WriteLine("Index: " + splitPart.Index + " Start: " + splitPart.Start + " Finish: " + splitPart.Finish);
}
Project project = new Project("New Project.mpp");
// Create a ChildTasksCollector instance
ChildTasksCollector collector = new ChildTasksCollector();
// Collect all the tasks from RootTask using TaskUtils
TaskUtils.Apply(project.RootTask, collector, 0);
// Parse through all the collected tasks
foreach (Task task in collector.Tasks)
{
if (task.Get(Tsk.ConstraintDate).ToShortDateString() == "1/1/2000")
Console.WriteLine("NA");
else
Console.WriteLine(task.Get(Tsk.ConstraintDate).ToShortDateString());
Console.WriteLine(task.Get(Tsk.ConstraintType).ToString());
}
// Set constraint As Late As Possible for task with Id 11
Task wallBoard = project.RootTask.Children.GetById(11);
wallBoard.Set(Tsk.ConstraintType, ConstraintType.AsLateAsPossible);
SaveOptions options = new PdfSaveOptions();
options.StartDate = project.Get(Prj.StartDate);
options.Timescale = Timescale.ThirdsOfMonths;
project.Save("AsLateAsPossible_out.pdf", options);
// Set constraint Finish No Earlier Than on task with Id 2
Task first = project.RootTask.Children.GetById(2);
first.Set(Tsk.ConstraintType, ConstraintType.FinishNoEarlierThan);
first.Set(Tsk.ConstraintDate, new DateTime(2016, 12, 1, 18, 0, 0));
SaveOptions options = new PdfSaveOptions();
options.StartDate = project.Get(Prj.StartDate);
options.Timescale = Timescale.ThirdsOfMonths;
project.Save("FinishNoEarlierThan_out.pdf", options);
// Set constraint Must Finish On for task with Id 15
Task task = project.RootTask.Children.GetById(15);
task.Set(Tsk.ConstraintType, ConstraintType.MustFinishOn);
task.Set(Tsk.ConstraintDate, new DateTime(2017, 3, 1, 18, 0, 0));
SaveOptions options = new PdfSaveOptions();
options.StartDate = project.Get(Prj.StartDate);
options.Timescale = Timescale.ThirdsOfMonths;
project.Save("MustFinishOn_out.pdf", options);
// Set constraint Must Start On for task with Id 5
Task roof = project.RootTask.Children.GetById(5);
roof.Set(Tsk.ConstraintType, ConstraintType.MustStartOn);
roof.Set(Tsk.ConstraintDate, new DateTime(2017, 1, 1, 9, 0, 0));
SaveOptions options = new PdfSaveOptions();
options.StartDate = project.Get(Prj.StartDate);
options.Timescale = Timescale.ThirdsOfMonths;
project.Save("MustStartOn_out.pdf", options);
Project project = new Project("New Project.mpp");
// Set constraint Start No Earlier Than on task with Id 1
Task summary = project.RootTask.Children.GetById(1);
summary.Set(Tsk.ConstraintType, ConstraintType.StartNoEarlierThan);
summary.Set(Tsk.ConstraintDate, new DateTime(2016, 12, 1, 9, 0, 0));
SaveOptions o = new PdfSaveOptions();
o.StartDate = project.Get(Prj.StartDate);
o.Timescale = Timescale.ThirdsOfMonths;
project.Save("StartNoEarlierThan_out.pdf", o);
Project project = new Project();
// Add task
Task task = project.RootTask.Children.Add("Task1");
// Create calendar and assign to task
Calendar cal = project.Calendars.Add("TaskCal1");
task.Set(Tsk.Calendar, cal);
// Create a new project and add a new task
Project project = new Project();
Task task = project.RootTask.Children.Add("Task");
// Task duration in days (default time unit)
Duration duration = task.Get(Tsk.Duration);
Console.WriteLine("Duration equals 1 day: {0}", duration.ToString().Equals("1 day"));
// Convert to hours time unit
duration = duration.Convert(TimeUnitType.Hour);
Console.WriteLine("Duration equals 8 hrs: {0}", duration.ToString().Equals("8 hrs"));
// Get wrapped TimeSpan instance
Console.WriteLine("Duration TimeSpan equals to TimeSpan of 8 hrs: {0}", duration.TimeSpan.Equals(TimeSpan.FromHours(8)));
// Increase task duration to 1 week and display if duration is updated successfully
task.Set(Tsk.Duration, project.GetDuration(1, TimeUnitType.Week));
Console.WriteLine("Duration equals 1 wk: {0}", task.Get(Tsk.Duration).ToString().Equals("1 wk"));
// Decrease task duration and display if duration is updated successfully
task.Set(Tsk.Duration, task.Get(Tsk.Duration).Subtract(0.5));
Console.WriteLine("Duration equals 0.5 wks: {0}", task.Get(Tsk.Duration).ToString().Equals("0.5 wks"));
Project project = new Project();
// Add task and set task properties
Task task = project.RootTask.Children.Add("Task1");
task.Set(Tsk.Start, project.RootTask.Get(Tsk.Start).AddDays(1));
task.Set(Tsk.Name, "new name");
Project project = new Project("New Project.mpp");
VbaProject vbaProject = project.VbaProject;
IVbaModule vbaModule = vbaProject.Modules.ToList()[0];
Console.WriteLine("Attributes Count: " + vbaModule.Attributes.Count);
Console.WriteLine("VB_Name: " + vbaModule.Attributes.ToList()[0].Key);
Console.WriteLine("Module1: " + vbaModule.Attributes.ToList()[0].Value);
Project project = new Project("New Project.mpp");
VbaProject vbaProject = project.VbaProject;
Console.WriteLine("Total Modules Count: " + vbaProject.Modules.Count);
IVbaModule vbaModule = vbaProject.Modules.ToList()[0];
Console.WriteLine("Module Name: " + vbaModule.Name);
Console.WriteLine("Source Code: " + vbaModule.SourceCode);
Project project = new Project("New Project.mpp");
VbaProject vbaProject = project.VbaProject;
VbaReferenceCollection references = vbaProject.References;
Console.WriteLine("Reference count ", references.Count);
VbaReference reference = vbaProject.References.ToList()[0];
Console.WriteLine("Identifier: " + reference.LibIdentifier);
Console.WriteLine("Name: " + reference.Name);
reference = vbaProject.References.ToList()[1];
Console.WriteLine("Identifier: " + reference.LibIdentifier);
Console.WriteLine("Name: " + reference.Name);
reference = vbaProject.References.ToList()[2];
Console.WriteLine("Identifier: " + reference.LibIdentifier);
Console.WriteLine("Name: " + reference.Name);
Project project = new Project("New Project.mpp");
VbaProject vbaProject = project.VbaProject;
Console.WriteLine("VbaProject.Name " + vbaProject.Name);
Console.WriteLine("VbaProject.Description " + vbaProject.Description);
Console.WriteLine("VbaProject.CompilationArguments " + vbaProject.CompilationArguments);
Console.WriteLine("VbaProject.HelpContextId " + vbaProject.HelpContextId);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment