2015-09-11 24 views
6

Nel codice lato server SharePoint, è possibile scrivere qualcosa di simile:Come estrarre il tipo da un campo?

field.fieldvalueType 

Che a volte vi darà il tipo (DateTime, o qualsiasi altra cosa). Fastidiosamente, a volte, restituisce semplicemente Null (ad esempio, il campo ID).

In CSOM, non si dispone di quel campo. Tuttavia, c'è TypeAsString che dà i tipi di SharePoint, quali:

  • Computerizzata
  • Integer
  • Nota

Quello che mi piacerebbe fare è afferrare questa huge table from MSDN:

ed estratto "Int32" quando so che ho a che fare con un campo "Integer" ed estrai "System.String" dalla nota di SharePoint.

Questo funziona un pò, ma è la madre di tutte le hack:

var myTempItem = list.AddItem(new ListItemCreationInformation()); 
myTempItem.Update(); 
context.ExecuteQuery(); 

context.Load(myTempItem); 
context.ExecuteQuery(); 

Dopo la creazione, è possibile utilizzare:

myTempItemCreated[fieldImTryingToGetTypeOf.Title].GetType().FullName -> Gives->System.Int32

Ora, qual è la corretta modo di farlo? Spero solo che la risposta non sia una dichiarazione di un interruttore di dieci piedi di lunghezza.

risposta

3

Poiché non v'è alcun SPField.FieldValueType property controparti in SharePoint CSOM API, il seguente metodo di estensione dimostra come eseguire esso:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using Microsoft.SharePoint.Client; 
using Field = Microsoft.SharePoint.Client.Field; 

namespace SharePoint.Client.Extensions 
{ 
    public static class FieldExtensions 
    { 


     public static Type GetFieldValueType(this Field field) 
     { 
      var table = new Dictionary<FieldType, Type>(); 
      table[FieldType.Guid] = typeof(Guid); 
      table[FieldType.Attachments] = typeof(bool); 
      table[FieldType.Boolean] = typeof(bool); 
      table[FieldType.Choice] = typeof (string); 
      table[FieldType.CrossProjectLink] = typeof(bool); 
      table[FieldType.DateTime] = typeof(DateTime); 
      table[FieldType.Lookup] = typeof(FieldLookupValue); 
      table[FieldType.ModStat] = typeof(int); 
      table[FieldType.MultiChoice] = typeof(string[]); 
      table[FieldType.Number] = typeof(double); 
      table[FieldType.Recurrence] = typeof(bool); 
      table[FieldType.Text] = typeof(string); 
      table[FieldType.URL] = typeof(FieldUrlValue); 
      table[FieldType.URL] = typeof(FieldUrlValue); 
      table[FieldType.User] = typeof(FieldUserValue); 
      table[FieldType.WorkflowStatus] = typeof(int); 
      table[FieldType.ContentTypeId] = typeof(ContentTypeId); 
      table[FieldType.Note] = typeof(string); 
      table[FieldType.Counter] = typeof(int); 
      table[FieldType.Computed] = typeof(string); 
      table[FieldType.Integer] = typeof(int); 
      table[FieldType.File] = typeof(string); 

      if (!table.ContainsKey(field.FieldTypeKind)) 
       throw new NotSupportedException(string.Format("Unknown field type: {0}", field.FieldTypeKind)); 
      return table[field.FieldTypeKind]; 
     } 
    } 
} 

Uso

var list = ctx.Web.Lists.GetByTitle(listTitle); 
var fields = list.Fields; 
ctx.Load(fields); 
ctx.ExecuteQuery(); 

foreach (var field in fields) 
{ 
    if (field.FieldTypeKind != FieldType.Invalid) 
    { 
     var fieldValueType = field.GetFieldValueType(); 
     Console.WriteLine("{0} : {1}", field.InternalName, fieldValueType);  
    }   
} 
+0

Suppongo, a volte, semplicemente non ci sia una via di uscita pigra. http://www.quote2day.com/wp-content/uploads/Photo-35.jpg – David

+1

:) Mi considero anche una persona pigra, ma in questo caso particolare sembra essere l'unico modo .. –

-1

È possibile ottenere il tipo di campo utilizzando il seguente frammento:

item.Fields["Title"].FieldValueType.FullName 
+0

Ciao, hai letto la domanda per favore? – David

+0

Scusa se sono confuso su cosa è richiesto?Desideri ottenere il valore del campo? io, e: basta chiamare un metodo per ottenere il valore e restituisce il valore in base al suo tipo? – ibrahims

+1

Scusa ma la domanda è abbastanza chiara. La tua risposta è * letteralmente * la seconda riga della domanda (che è ovviamente davvero frustrante). Devo ottenere il tipo di campo senza creare una voce di elenco. Leggi la domanda per una spiegazione del motivo per cui il tuo frammento non funziona. – David

0

In generale, è necessario fare la mappatura lei descrive, non il metodo myTempItemCreated[fieldImTryingToGetTypeOf.Title].GetType().FullName .

Il motivo è, myTempItemCreated[fieldImTryingToGetTypeOf.Title].GetType().FullName fallirà nello scenario in cui il valore del campo (ad esempio Title) è nullo per quel particolare oggetto ListItem. (Mentre Title non è generalmente nullo, altri campi possono essere e sono nulli). E ovviamente null non ti dà un oggetto su cui puoi chiamare il metodo GetType() (ovviamente otterrai una NullReferenceException).

Quindi, per una soluzione generale del problema, è necessario mappare la stringa restituita da TypeAsString del campo elenco, chiamando dal campo elenco oggetti/elenco e non dall'elemento elenco.

1

Ampliando @ risposta di Vadim, qui è una versione che non costruisce un nuovo dizionario ogni volta che viene chiamato il metodo di estensione;

namespace SharePoint.Client.Extensions 
{ 
    public static class FieldExtensions 
    { 
     private static Dictionary<FieldType, Type> _fieldTypes = new Dictionary<FieldType, Type>() 
     { 
      { FieldType.Guid, typeof(Guid) }, 
      { FieldType.Attachments, typeof(bool)}, 
      {FieldType.Boolean, typeof(bool)}, 
      {FieldType.Choice, typeof(string)}, 
      {FieldType.CrossProjectLink, typeof(bool)}, 
      {FieldType.DateTime, typeof(DateTime)}, 
      {FieldType.Lookup, typeof(FieldLookupValue)}, 
      {FieldType.ModStat, typeof(int)}, 
      {FieldType.MultiChoice, typeof(string[])}, 
      {FieldType.Number, typeof(double)}, 
      {FieldType.Recurrence, typeof(bool)}, 
      {FieldType.Text, typeof(string)}, 
      {FieldType.URL, typeof(FieldUrlValue)}, 
      {FieldType.User, typeof(FieldUserValue)}, 
      {FieldType.WorkflowStatus, typeof(int)}, 
      {FieldType.ContentTypeId, typeof(ContentTypeId)}, 
      {FieldType.Note, typeof(string)}, 
      {FieldType.Counter, typeof(int)}, 
      {FieldType.Computed, typeof(string)}, 
      {FieldType.Integer, typeof(int)}, 
      {FieldType.File, typeof(string)} 
     }; 

     public static Type GetFieldValueType(this Field field) 
     { 
      if (!_fieldTypes.ContainsKey(field.FieldTypeKind)) 
       throw new NotSupportedException(string.Format("Unknown field type: {0}", field.FieldTypeKind)); 
      return _fieldTypes[field.FieldTypeKind]; 
     } 
    } 
} 
Problemi correlati