Partager via


Extrait de code : implémentation d’un connecteur personnalisé

Dernière modification : lundi 17 mai 2010

S’applique à : SharePoint Server 2010

Dans cet article
Description
Pour utiliser cet exemple
Code

Description

L’exemple de code suivant montre comment implémenter l’interface ISystemUtility fournie par le Service BDC (Business Data Connectivity) pour implémenter un connecteur personnalisé. Cet exemple fournit un connecteur au système de fichiers. Notez que seule l’interface ISystemUtility est obligatoire. Cet exemple remplace le gestionnaire de connexion par défaut en implémentant l’interface IConnectionManager. Cet exemple implémente également l’interface IAdministrableSystem pour assurer la prise en charge de la gestion des propriété de l’interface utilisateur d’administration.

Pour utiliser cet exemple

  1. Démarrez un nouveau projet de classe Microsoft Visual Studio, puis nommez-le FileSystemConnector.

  2. Remplacez le code généré automatiquement dans le fichier .cs par le code C# fourni ci-dessous.

  3. Compilez l’assembly, puis ajoutez-le au GAC.

  4. Obtenez le jeton de clé publique pour l’assembly.

  5. Copiez l’exemple de modèle BDC de l’Exemple de modèle BDC : connexion à un connecteur de système de fichiers personnalisé dans un fichier XML. Nommez-le FileSystemConnectorSample.xml.

  6. Mettez à jour la ligne 9 du fichier XML avec les nouvelles informations de l’assembly.

  7. Mettez à jour la ligne 22 du fichier XML pour indiquer le répertoire dans lequel se trouve des fichiers.

  8. Importez le fichier XML dans le BDC.

  9. À ce stade, vous devriez être en mesure de créer des listes externes et de voir les données à partir du système de fichiers.

Code

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.BusinessData.Infrastructure;
using Microsoft.BusinessData.Runtime;
using Microsoft.BusinessData.MetadataModel;
using Microsoft.BusinessData.MetadataModel.Collections;
using System.Collections;



namespace MS.Internal.Motif.Office.Lobi.ConnectorTest
{
    class FileSystemConnector : ISystemUtility, IDisposable, IConnectionManager, IAdministrableSystem
      {
        #region private variables
        String DirectoryPath;
        String DirectoryPropertyName = "Directory";
        String FileIDName = "FileName";

        #endregion
        #region IAdministrableSystem Members

        public IList<AdministrableProperty> AdministrableLobSystemProperties
        {
            get
            {
                return new List<AdministrableProperty>()
                {
                    new AdministrableProperty("SystemUtilityTypeName","Name of the custom connector  utility",typeof(string),"SystemUtilityTypeName", typeof(string),true), 
                    new AdministrableProperty("SystemUtilityInstallDate","Date custom connector was installed",typeof(DateTime),"SystemUtilityInstallDate", typeof(DateTime),false)
                };
            }
        }

        public IList<AdministrableProperty> AdministrableLobSystemInstanceProperties
        {
            get
            {
                return new List<AdministrableProperty>()
                {
                   new AdministrableProperty("ServerName","Name of server where filesystem exists",typeof(string),"ServerName", typeof(string),false)  
                };
            }
        }
        #endregion

        #region ISystemUtility Members

        public void ExecuteStatic(IMethodInstance methodInstance, ILobSystemInstance lobSystemInstance, object[] methodSignatureArgs, IExecutionContext context)
        {
            if (methodInstance == null)
            {
                throw (new ArgumentNullException("methodInstance"));
            }
            if (lobSystemInstance == null)
            {
                throw (new ArgumentNullException("lobSystemInstance"));
            }
            if (methodSignatureArgs == null)
            {
                throw (new ArgumentNullException("args"));
            }

            Dictionary<String, object> propertyValues = new Dictionary<string, object>();

            if (context != null)
            {
                if (context.IsPropertyDefined("FullPath"))
                    propertyValues.Add("FullPath", context["FullPath"]);

                if (context.IsPropertyDefined("Count"))
                {
                    context["Count"] = (Int32)context["Count"] + 1;
                    propertyValues.Add("Count", context["Count"]);
                }

                if(context.IsPropertyDefined("CountInMethod"))
                    propertyValues.Add("CountInMethod", context["CountInMethod"]);
            }
                      
            DirectoryPath = GetFullPath(methodInstance);
            ExecuteInternal(DirectoryPath, methodInstance, methodSignatureArgs,propertyValues);

        }

        public virtual IEnumerator
            CreateEntityInstanceDataEnumerator(Object rawAdapterEntityInstanceStream, ISharedEntityState sharedEntityState)
        {
           
                return ((IEnumerable)rawAdapterEntityInstanceStream).GetEnumerator();
           
            
        }
        #endregion
        #region ITypeReflector
        public ITypeReflector DefaultTypeReflector
        {
            get
            {
                return null;
            }
        }

#endregion

        #region DefaultConnectionManager
        public IConnectionManager DefaultConnectionManager
        {
            get
            {
                return null;
            }
        }
        #endregion

        #region IConnectionManager Members

        public void CloseConnection(object connection)
        {

        }

        public void FlushConnections()
        {

        }

        public object GetConnection()
        {
            return null;
        }

        public void Initialize(ILobSystemInstance properties)
        {

        }

        #endregion
        #region IDisposable Members

        public void Dispose()
        {
       
            
        }
        #endregion

        #region private methods
        private String GetFullPath(IMethodInstance methodInstance)
        {
            IDataClass dataClass = methodInstance.GetMethod().GetDataClass();
            return (string)dataClass.GetProperties()[DirectoryPropertyName];
        }

        private void ExecuteInternal(
            string directory, /* SP List Name */
           IMethodInstance methodInstance,
           object[] args,
           Dictionary<String,object> propertyBag)
        {
            String methodName = methodInstance.GetMethod().Name;
            String path;
            DynamicType dynamicParameter = new DynamicType();

            switch (methodName)
            {
                case "ReadFile":
                    String[] fields = GetFieldValues(methodInstance);
                    path = directory + @"\" + args[0];
                    if (!File.Exists(path))
                        throw new Exception(" The file does not exist for the FindSpecific");
                    else
                    {
                        foreach (String field in fields)
                        {
                            switch (field)
                            {
                                case "FileName":
                                    if (propertyBag.ContainsKey("FullPath"))
                                    {
                                        if ((Boolean)propertyBag["FullPath"])
                                            dynamicParameter.Add("FileName", path);
                                        else
                                            dynamicParameter.Add("FileName", args[0]);
                                    }
                                    else
                                        dynamicParameter.Add("FileName", args[0]);
                                    break;

                                case "Date Modified":
                                    dynamicParameter.Add("Date Modified", File.GetLastWriteTime(path));
                                    break;

                                case "Attributes":
                                    FileAttributes attributes = File.GetAttributes(path);                    
                                    
                                    dynamicParameter.Add("Attributes", attributes);
                                    break;

                                case "Date Created":
                                    dynamicParameter.Add("Date Created", File.GetCreationTime(path));
                                    break;

                                case "Date Accessed":
                                    dynamicParameter.Add("Date Accessed",File.GetLastAccessTime(path));
                                    break;

                                case "Type":
                                    FileStream stream = File.Open(path, FileMode.Open);
                                    dynamicParameter.Add("Type", stream.GetType().ToString());
                                    stream.Close();
                                    stream.Dispose();
                                    break;

                                default:
                                    throw new Exception(" Field does not belong to File");

                            }

                        }
                    }  
                    args[1] = dynamicParameter;
                    break;

               case "CreateFile":
                    Dictionary<string, object> createValues = new Dictionary<string, object>();
                    int count = 0;

                    //
                    // Get the method parameters.
                    //
                    IParameterCollection parameterCollection = methodInstance.GetMethod().GetParameters();
                    foreach (IParameter parameter in parameterCollection)
                    {
                        if (parameter.Direction == DirectionType.In
                            || parameter.Direction == DirectionType.InOut)
                        {
                            createValues.Add(parameter.Name, args[count]);
                        }
                        count++;
                    }

                    path = directory + @"\" + args[0];
                    FileStream stream1 = File.Create(path);
                    stream1.Close();
                    stream1.Dispose();
                    args[args.Length - 1] = args[0];

                    break;
                    
                case "DeleteFile":
                    path = directory + @"\" + args[0];
                    if (!File.Exists(path))
                        throw new Exception("File does not exist to Delete");
                    File.Delete(path);
                    break;

                case "ReadFiles":
                    String[] fieldValues = GetFieldValues(methodInstance);
                    List<DynamicType> returnParameters = new List<DynamicType>();
                   // path = directory + @"\" + args[0];
                    if (!Directory.Exists(directory))
                        throw new Exception(" The directory does not exist for the Finder");
                    else
                    {
                        string[] Files = Directory.GetFiles(directory);
                        foreach(string FileName in Files)
                        {
                            DynamicType paraValue = new DynamicType();                                                      
                            foreach (String fieldValue in fieldValues)
                            {
                                
                                switch (fieldValue)
                                {
                                       
                                    case "FileName":
                                        FileInfo info = new FileInfo(FileName);
                                      
                                        paraValue.Add("FileName", info.Name);
                                        break;

                                    case "Date Modified":
                                        paraValue.Add("Date Modified", File.GetLastWriteTime(FileName));
                                        break;

                                    case "Attributes":
                                        FileAttributes attributes = File.GetAttributes(FileName);

                                        paraValue.Add("Attributes", attributes);
                                        break;

                                    case "Date Created":
                                        paraValue.Add("Date Created", File.GetCreationTime(FileName));
                                        break;

                                    case "Date Accessed":
                                        paraValue.Add("Date Accessed", File.GetLastAccessTime(FileName));
                                        break;

                                    case "Type":
                                        FileStream stream = File.Open(FileName, FileMode.Open);
                                        paraValue.Add("Type", stream.GetType().ToString());
                                        stream.Close();
                                        stream.Dispose();
                                        break;

                                    default:
                                        throw new Exception(" Field does not belong to File");

                                }
                            }
                            returnParameters.Add(paraValue);

                        }
                    }
                    args[1] = returnParameters.ToArray();
                    break;

                case "UpdateFile":
                   
                    Microsoft.BusinessData.Runtime.DynamicType updatedValues = args[0] as Microsoft.BusinessData.Runtime.DynamicType;
                    path = directory + @"\" + updatedValues[FileIDName];
                    if (!File.Exists(path))
                        throw new Exception("File does not exist to update");
                    foreach (KeyValuePair<string, object> kvp in updatedValues)
                    {
                        switch(kvp.Key)
                        {
                            case "FileName":                                 
                                break;

                            case "Date Modified":
                                File.SetLastWriteTime(path,(DateTime) kvp.Value);
                                break;

                            case "Attributes":
                                FileAttributes updatedAttribs = (FileAttributes)kvp.Value;
                                File.SetAttributes(path, updatedAttribs);                                
                                break;

                            case "Date Created":
                                File.SetCreationTime(path,(DateTime)kvp.Value);
                                break;

                            case "Date Accessed":
                                File.SetLastWriteTime(path,(DateTime)kvp.Value);
                                break;

                           default:
                                throw new Exception(" Field does not belong to File");



                        }
                    }
                    break; 

                default:
                    throw new Exception("Method Not Implemented called");
                }
            } 
     
       private String[] GetFieldValues(IMethodInstance methodInstance)
        {
           List<String> fieldsList = new List<string>();
            IMethod method = methodInstance.GetMethod();
            ITypeDescriptor typeDescriptor;
                
               typeDescriptor = method.GetParameters()[1].GetRootTypeDescriptor();
               ITypeDescriptor childTypeDescriptor = typeDescriptor.GetChildTypeDescriptors()[0];

               if (methodInstance.MethodInstanceType == MethodInstanceType.Finder)
               {
                   foreach (ITypeDescriptor childDescpritor in childTypeDescriptor.GetChildTypeDescriptors())
                   {

                       fieldsList.Add(childDescpritor.Name);

                   }
               }
               else
               {

                   foreach (ITypeDescriptor childDescpritor in typeDescriptor.GetChildTypeDescriptors())
                   {
                       fieldsList.Add(childDescpritor.Name);
                   }
               }
            return fieldsList.ToArray();
        }

        private String[] GetUpdateFieldValues(IMethodInstance methodInstance)
        {
            List<String> fieldsList = new List<string>();
            IMethod method = methodInstance.GetMethod();
            ITypeDescriptor typeDescriptor = method.GetParameters()[0].GetRootTypeDescriptor();

            foreach (ITypeDescriptor childDescpritor in typeDescriptor.GetChildTypeDescriptors())
            {
                fieldsList.Add(childDescpritor.Name);
            }
            return fieldsList.ToArray();
        }

       
        }

        #endregion

    }

Voir aussi

Référence

AdministrableProperty

ISystemUtility

ITypeReflector

IConnectionManager

IAdministrableSystem

IMethodInstance

GetMethod()

IDataClass

ILobSystemInstance

IExecutionContext

IsPropertyDefined(String)

ISharedEntityState

DynamicType

Add(String, Object)

IParameterCollection

GetParameters()

IParameterCollection

IParameter

Direction

GetRootTypeDescriptor()

ITypeDescriptor

GetChildTypeDescriptors()

MethodInstanceType

MethodInstanceType

Concepts

Exemple de modèle BDC : connexion à un connecteur de système de fichiers personnalisé