Compartir a través de


de la propiedad DraftProject.FieldValues

Obtiene los valores de campo personalizado para el proyecto de borrador.

Espacio de nombres:  Microsoft.ProjectServer.Client
Ensamblado:  Microsoft.ProjectServer.Client (en Microsoft.ProjectServer.Client.dll)

Sintaxis

'Declaración
Public ReadOnly Property FieldValues As Dictionary(Of String, Object)
    Get
'Uso
Dim instance As DraftProject
Dim value As Dictionary(Of String, Object)

value = instance.FieldValues
public Dictionary<string, Object> FieldValues { get; }

Valor de propiedad

Tipo: System.Collections.Generic.Dictionary<String, Object>
Un conjunto de pares de clave y valor para los valores de campo personalizado, donde la clave es el nombre interno de campo personalizado y el valor es el valor del campo personalizado o el nombre interno de una entrada de tabla de consulta.

Ejemplos

En el ejemplo de código siguiente se retira el proyecto de empresa especificado y, a continuación, consulta el proyecto de borrador para su colección de campos personalizados. El ejemplo de código muestra el GUID y el nombre del proyecto, el nombre y el valor de cada campo personalizado y el nombre interno de cada campo personalizado del proyecto como clave en un par de clave y valor. Si el campo usa una tabla de consulta, el elemento FieldValues contiene el nombre interno de la entrada de la tabla de consulta. Si el campo personalizado es un campo de texto con varios valores, el ejemplo muestra el valor y el nombre interno de cada entrada de la tabla de consulta para el campo personalizado en el proyecto. Si el campo personalizado no utiliza una tabla de búsqueda, el valor es simplemente el valor del campo personalizado.

El nombre interno de un campo personalizado es una cadena con el valor "Custom_ de [GUID]", por ejemplo, Custom_9d77d62aa92e4d40adc8446c90eb7456. El nombre interno de una entrada de tabla de búsqueda es una cadena con el valor "Entry_ de [GUID]", por ejemplo, Entry_4a2750309d91e21193f90021704e28a0.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ProjectServer.Client;
using Microsoft.SharePoint.Client;

namespace GetDraftProjectFieldValues
{
    class Program
    {
        private const string pwaPath = "https://ServerName/pwa";    // Change the path for Project Web App.
        private static string projName = string.Empty;

        // Set the Project Server client context.
        private static ProjectContext projContext;

        static void Main(string[] args)
        {
            if (!ParseCommandLine(args))
            {
                Usage();
                ExitApp(string.Empty);
            }

            Dictionary<string, object> projDict = new Dictionary<string, object>();
            projContext = new ProjectContext(pwaPath);

            // Get the list of published projects in Project Web App.
            var pubProjects = projContext.LoadQuery(projContext.Projects
                .Where(p => p.IsEnterpriseProject == true
                         && p.Name == projName));
            projContext.ExecuteQuery();

            if (pubProjects.Count() < 1)
            {
                ExitApp("No enterprise project name: " + projName);
            }

            Console.WriteLine("\t\tDraft project ID\t:\tProject name");

            foreach (PublishedProject pubProj in pubProjects)
            {
                // Check out the project.
                if (!pubProj.IsCheckedOut)
                {
                    DraftProject draftProj = pubProj.CheckOut().IncludeCustomFields;
                    projContext.Load(draftProj);
                    projContext.Load(draftProj.IncludeCustomFields);
                    projContext.ExecuteQuery();

                    Console.WriteLine("\n{0} :\t{1}", draftProj.Id.ToString(), draftProj.Name);

                    projDict = draftProj.FieldValues;

                    // Initialize variables to compare with custom field types:
                    string textValue = "";                  // TEXT - no lookup table
                    String[] lutTextValues = { "" };        // TEXT - lookup table
                    DateTime dateValue = DateTime.MinValue; // DATE - no lookup table

                    foreach (KeyValuePair<string, object> kvp in projDict)
                    {
                        object oVal = kvp.Value;
                        string keyStr = kvp.Key;

                        var projCFs = projContext.LoadQuery(draftProj.CustomFields
                            .Where(cf => cf.InternalName == keyStr));
                        projContext.ExecuteQuery();

                        WriteCustomFieldName(projCFs.First().Name);
                        Console.WriteLine("; FieldType = {0};\n\tInternalName = {1}",
                            projCFs.First().FieldType.ToString(), keyStr);

                        // Check whether the custom field is a simple text field.
                        if (object.ReferenceEquals(oVal.GetType(), textValue.GetType()))
                        {
                            textValue = (string)oVal;
                            Console.WriteLine("\tSingle-line string value = {0}", textValue.ToString());
                        }
                        // Check whether the custom field is a text (or multivalue text) field from a lookup table.
                        else if (object.ReferenceEquals(oVal.GetType(), lutTextValues.GetType()))
                        {
                            projContext.Load(projCFs.First().LookupTable);
                            projContext.ExecuteQuery();
                            string lutName = projCFs.First().LookupTable.Name;

                            WriteLookupTableName(lutName);

                            var luts = projContext.LoadQuery(projContext.LookupTables
                                .Where(lut => lut.Name == lutName));
                            projContext.ExecuteQuery();

                            lutTextValues = (string[])oVal;

                            for (var j = 0; j < lutTextValues.Count(); j++)
                            {
                                var entries = projContext.LoadQuery(luts.First().Entries
                                    .Where(e => e.InternalName == lutTextValues[j]));
                                projContext.ExecuteQuery();
                                Console.WriteLine("\t    Entry({0}): String value = {1};\n\t\t  InternalName = {2}",
                                    j, entries.First().FullValue, lutTextValues[j]);
                            }
                        }
                        // Check whether the custom field is a date.
                        else if (object.ReferenceEquals(oVal.GetType(), dateValue.GetType()))
                        {
                            dateValue = (DateTime)oVal;

                            Console.WriteLine("\tDate value = {0}", dateValue.ToString());
                        }
                        // Add other cases for cost, duration, flag, and number custom fields. 
                    }

                    // Check in and publish the project.
                    draftProj.Publish(true);
                    projContext.ExecuteQuery();
                }
                ExitApp(string.Empty);
            }
        }

        private static void WriteCustomFieldName(string cfName)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("\n    Custom field: '{0}'", cfName);
            Console.ResetColor();
        }

        private static void WriteLookupTableName(string lutName)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\tLookup table: {0}", lutName);
            Console.ResetColor();
        }

        // Parse the command line. Return true if there are no errors.
        private static bool ParseCommandLine(string[] args)
        {
            bool error = false;
            int argsLen = args.Length;

            try
            {
                for (int i = 0; i < argsLen; i++)
                {
                    if (error) break;
                    if (args[i].StartsWith("-") || args[i].StartsWith("/"))
                        args[i] = "*" + args[i].Substring(1).ToLower();

                    switch (args[i])
                    {
                        case "*projname":
                        case "*n":
                            if (++i >= argsLen) return false;
                            projName = args[i];
                            break;
                        //case "*timeout":
                        //case "*t":
                        //    if (++i >= argsLen) return false;
                        //    timeoutSeconds = Convert.ToInt32(args[i]);
                        //    break;
                        case "*?":
                        default:
                            error = true;
                            break;
                    }
                }
            }
            catch (FormatException)
            {
                error = true;
            }

            if (string.IsNullOrEmpty(projName)) error = true;
            return !error;
        }

        private static void Usage()
        {
            string example = "Usage: -projName | -p \"Project name\"";
            example += "\nExample: -p \"My New Project\"";
            Console.WriteLine(example);
        }

        private static void ExitApp(string reason)
        {
            if (reason != string.Empty) Console.WriteLine(reason);
            Console.Write("\nPress any key to exit... ");
            Console.ReadKey(true);
            Environment.Exit(0);
        }
    }
}

Por ejemplo, un proyecto denominado TestProject9 tiene un valor de campo personalizado de departamentos de los proyectos, un campo personalizado de texto de múltiples valores con tres valores de entrada de tabla de búsqueda, un campo de texto personalizado y un campo de fecha personalizado. Como departamentos de los proyectos es un campo personalizado incorporado, el GUID para el campo personalizado de departamentos de los proyectos de forma predeterminada en las instancias de Project Web App es 9d77d62a-a92e-4d40-adc8-446c90eb7456. A continuación es el resultado de la aplicación de ejemplo de GetProjectFieldValues :

        Draft project ID        :       Project name

b846e947-29e0-43eb-b5c6-5ddeaf08d5c0 :  CSOM Project9

    Custom field: 'Project Departments'; FieldType = TEXT;
        InternalName = Custom_9d77d62aa92e4d40adc8446c90eb7456
        Lookup table: Department
            Entry(0): String value = Test Dept 1;
                  InternalName = Entry_bbc07ff5b06de21193f40021704e28a0

    Custom field: 'ProjectMVText'; FieldType = TEXT;
        InternalName = Custom_9295a8759d91e21193f90021704e28a0
        Lookup table: TestTextMV
            Entry(0): String value = First.001;
                  InternalName = Entry_4a2750309d91e21193f90021704e28a0
            Entry(1): String value = Second.002;
                  InternalName = Entry_4d2750309d91e21193f90021704e28a0
            Entry(2): String value = Third;
                  InternalName = Entry_4f2750309d91e21193f90021704e28a0

    Custom field: 'Test Project Date'; FieldType = DATE;
        InternalName = Custom_37f61601a991e21193f90021704e28a0
        Date value = 3/29/2013 8:00:00 AM

    Custom field: 'Test project simple text'; FieldType = TEXT;
        InternalName = Custom_8bf7eed5cc94e21193f90021704e28a0
        Single-line string value = This is a line of text

Press any key to exit...

Vea también

Referencia

clase DraftProject

Miembros DraftProject

Espacio de nombres Microsoft.ProjectServer.Client