Travailler avec des projets

Aspose.Tasks pour .NET vous permet de travailler avec les fichiers Microsoft Project (MPP / XML) sans installer Microsoft Project ou à l’aide de Microsoft Office Automation. Une API puissante et flexible, Aspose.Tasks vous fait gagner du temps et des efforts en vous donnant les outils dont vous avez besoin pour écrire du code efficace pour manipuler les fichiers de projet.

Aspose.Tasks peut ouvrir des fichiers existants, mais il peut également créer de nouveaux fichiers. Cet article explique comment créer un fichier de projet nouveau et vide à partir du flux à l’aide de la classe de projet. ainsi que ouvrir les fichiers existants.

Création d’un fichier de projet vide

La classe Project est la classe principale d’Aspose.Tasks utilisés pour définir et obtenir des propriétés associées à un projet, ainsi qu’un comportement. La méthode de sauvegarde offerte par cette classe permet de rendre le projet à divers formats de sortie tels que XML, MPP, PDF, HTML, etc. avec un seul appel API. Cette méthode accepte un flux de fichiers ou un nom de fichier, et l’une des valeurs fournies par le type d’énumération SaveFileFormat.

Les lignes de code suivantes créent un fichier de projet simple au format XML.

Créez un projet vide et enregistrant en tant que fichier XML

1Project project = new Project();
2project.Save("EmptyProjectSaveXML_out.xml", SaveFileFormat.XML);

The resulting XML project file can be opened in Microsoft Project using the following steps:

  1. On the File menu, select Open.
  2. Select the XML format (*.xml) option from the file types and browse to the output XML file.
  3. On the Project menu, select Project Information

Create an Empty Project and Save to Stream

1// Create a project instance
2Project newProject = new Project();
3
4// Create a file stream
5using (FileStream stream = new FileStream("EmptyProjectSaveStream_out.xml", FileMode.Create, FileAccess.Write))
6{
7    // Write the stream into XML format
8    newProject.Save(stream, SaveFileFormat.XML);
9}

Create an Empty Project and Save to MPP

1// there is no more need to load MPP template to save it into MPP
2// add tasks, resources, etc.
3Project project = new Project();
4
5// !The project will be saved into MPP by using internal MPP template.
6project.Save("New Project.mpp", SaveFileFormat.MPP);

Reading a Project File

Aspose.Tasks for .NET lets you read existing project in different formats: XML, MPP, MPT, MPX, XER, Primavera P6 XML, etc and save these back in MPP or another format after updating. The following snippets show how a project file can be read using the Project class’s constructor.

Reading Project Files as a Template

1// Read existing project template file
2Project project = new Project("New Project.mpp");

Reading Project File from Stream

1// Read the project xml into file stream
2using (FileStream stream = new FileStream("ReadProjectFileFromStream.xml", FileMode.Open))
3{
4    // Create project using file stream
5    Project project = new Project(stream);
6}

Importing Project Data From Microsoft Project Server Database

We plan to retire the importing of project data from Microsoft Project Server Database in a future release. Instead you can use import \ export of project data using Microsoft Project Server’s PWA API.

See documentation for ProjectServerManager class for more details.

 1// Create connection string
 2SqlConnectionStringBuilder sqlConnectionString = new SqlConnectionStringBuilder();
 3sqlConnectionString.DataSource = "192.168.56.2,1433";
 4sqlConnectionString.Encrypt = true;
 5sqlConnectionString.TrustServerCertificate = true;
 6sqlConnectionString.InitialCatalog = "ProjectServer_Published";
 7sqlConnectionString.NetworkLibrary = "DBMSSOCN";
 8sqlConnectionString.UserID = "sa";
 9sqlConnectionString.Password = "*****";
10
11// Use Aspose.Tasks.Connectivity namespace
12MspDbSettings settings = new MspDbSettings(sqlConnectionString.ConnectionString, new Guid("E6426C44-D6CB-4B9C-AF16-48910ACE0F54"));
13Project project = new Project(settings);

Import Project Data from MPD (Microsoft Project Database) File

1DbSettings settings = new MpdSettings("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + "MpdFileToRead.mpd", 1);
2Project project = new Project(settings);

Ignoring invalid characters during loading Project

Some files may have invalid characters in the custom fields. Microsoft Project does not allow invalid character so the files have been created or manipulated with automation or some other tools. If these be loaded using the API, they may lead to an exception. In order to ignore such invalid characters, the overloaded constructor of Project class can be used with the delegate method ParseErrorCallBack.

 1static void Run()
 2{
 3    // Open modified xml stream
 4    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(GetModifiedXml())))
 5    {
 6        Project project = new Project(stream, new ParseErrorCallback(CustomDurationHandler));
 7    }
 8}
 9
10static string GetModifiedXml()
11{
12    // Open valid xml file and modify it
13    using (TextReader reader = new StreamReader("IgnoreInvalidCharacters.xml"))
14    {
15        string xml = reader.ReadToEnd();
16        Regex regex = new Regex("PT(\\d+)H(\\d+)M(\\d+)S");
17        return regex.Replace(xml, "**$1Hrs$2Mins$3Secs**");
18    }
19}
20
21static object CustomDurationHandler(object sender, ParseErrorArgs args)
22{
23    Regex regex = new Regex("[*]{2}(\\d+)Hrs(\\d+)Mins(\\d+)Secs[*]{2}");
24    if (args.FieldType == typeof(TimeSpan))
25    {
26        Debug.Print("Object field : {0}, Invalid value : {1}", args.FieldName, args.InvalidValue);
27        string duration = regex.Replace(args.InvalidValue, "PT$1H$2M$3S");
28        TimeSpan newValue = Duration.ParseTimeSpan(duration);
29        Debug.Print("New value : {0}", newValue);
30        return newValue;
31    }
32    // Here we handle only TimeSpan instances, so rethrow original exception with other types
33    throw args.Exception;
34}

Working With Encodings

Aspose.Tasks for .NET provides support for the encoding of MPX files. The following code example shows the encoding settings.

1// Specify Encodings
2using (StreamReader streamReader = new StreamReader("Project.mpx", System.Text.Encoding.GetEncoding("ISO-8859-1")))
3{
4    Project project = new Project(streamReader.BaseStream);
5}
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.