Фрагмент кода. Установка объекта параметров перед вызовом GenericInvoker
Дата последнего изменения: 6 мая 2010 г.
Применимо к: SharePoint Server 2010
В следующем примере кода показано, как установить объект Parameters перед вызовом GenericInvoker.
Необходимые компоненты:
Microsoft SharePoint Server 2010 или Microsoft SharePoint Foundation 2010.
Microsoft .NET Framework 3.5 и Microsoft Visual Studio.
Использование этого примера
Запустите Visual Studio и создайте проект консольного приложения C#. При создании проекта выберите .NET Framework 3.5.
В меню Вид выберите Страницы свойств, чтобы вывести свойства проекта.
На вкладке Построение в качестве Целевой платформы выберите Любой ЦП.
Закройте окно свойств проекта
В обозревателе решений в разделе Ссылки удалите все ссылки проекта кроме System и System.Core.
Добавьте в проект следующие ссылки:
Microsoft.BusinessData
Microsoft.SharePoint
System.Data
System.Web
System.Xml
Замените автоматически созданный код в файле Program.cs на код, приведенный в конце этой процедуры.
Введите допустимые значения параметров siteUrl, nameSpace, entityName и methodInstanceName.
Измените код для этапов 4, 5 и 6, указанный ниже, соответствующим образом. Данные, введенные на этапах 4, 5 и 6, должны совпадать с параметрами и типами, определенными для метода универсального вызывающего в модели BDC.
Чтобы построить решение, нажмите клавишу F6.
Нажмите CTRL+F5, чтобы запустить пример.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.BusinessData.MetadataModel;
using Microsoft.BusinessData.Runtime;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Web;
using Microsoft.BusinessData.MetadataModel.Collections;
using Microsoft.BusinessData.Infrastructure;
namespace Microsoft.SDK.Sharepoint.Samples
{
class Program
{
static void Main(string[] args)
{
string siteURL = "<siteUrl>";
string entityNS = "<nameSpace>";
string entityName = "<entityName>";
string methodInstanceName = "<methodInstanceName>";
using (SPSite site = new SPSite(siteURL))
{
using (new Microsoft.SharePoint.SPServiceContextScope(
SPServiceContext.GetContext(site)))
{
BdcService service =
SPFarm.Local.Services.GetValue<BdcService>
(String.Empty);
IMetadataCatalog catalog =
service.GetDatabaseBackedMetadataCatalog(
SPServiceContext.Current);
IEntity entity =
catalog.GetEntity(entityNS, entityName);
ILobSystemInstance LobSysteminstance =
entity.GetLobSystem().
GetLobSystemInstances()[0].Value;
// Step 1: Obtain the MethodInstance from Entity.
IMethodInstance myGenericInvoker =
entity.GetMethodInstance(
methodInstanceName,
MethodInstanceType.GenericInvoker);
// Step 2: Obtain the Parameters using the Method.
IParameterCollection parameters =
myGenericInvoker.GetMethod().GetParameters();
// Step 3: Create the Object[] that needs
// to be passed in.
Object[] rawParameters =
new Object[parameters.Count];
// Step 4: For simple types and known types you can
// just create the instance and assign it to the
// parameter.
// Known types are the types that are known to you at
// compile time. These are the types that are in .NET Framework,
// BDC, or assemblies in the global assembly cache. The types that are
// defined in your proxy are NOT known types, as BDC
// will generate another proxy for the Web service.
rawParameters[0] = 32;
rawParameters[1] = "A";
rawParameters[2] = new System.Data.DataTable("X");
// Step 5: For "unknown types" (such as types defined
// in your proxy), you need to access to the type
// reflector to instantiate the complex types
// defined in your proxy.
ITypeReflector reflector = parameters[3].TypeReflector;
ITypeDescriptor rootTypeDescriptor =
parameters[3].GetRootTypeDescriptor();
Object instance = reflector.Instantiate(
rootTypeDescriptor);
// Or if you want to have the instance object
// use default values
// defined in your model, use the following:
// Object instance =
// reflector.Instantiate(
// rootTypeDescriptor, myGenericInvoker);
// Or if the root of the parameter is a collection,
// use the following:
// Object instance =
// reflector.Instantiate(rootTypeDescriptor, 55);
// Or if the root of the parameter is a collection
// and you want to use default values,
// use the following:
// Object instance =
// reflector.Instantiate(
// rootTypeDescriptor, 55, myGenericInvoker);
rawParameters[3] = instance;
// Step 6: To set values in the complex object
// you’ve just created, you can use the Set
// method on TypeReflector.
ITypeDescriptor child =
rootTypeDescriptor.GetChildTypeDescriptors()[3];
// Alternatively you can look over them and
// check the name,
// but since you are using generic invoker,
// it is most likely that you have intimate
// knowledge of the method.
// If your object is a structure:
reflector.Set(
child, rootTypeDescriptor, ref instance, "value");
// Or if your object is a collection:
// reflector.Set(
// child, rootTypeDescriptor, ref instance,
// "value", /*index*/ 2);
// If you want to set values in deeper parts of
// the structure, you’ll need to navigate to the
// relevant type descriptors,
// and provide the corresponding root object,
// parent type descriptor and child type descriptor.
// You can also create instances of deeper
// TypeDescriptors and assign the created instances
// to parts of the structure using the Set method.
// NOTE: Repeat steps 5 and 6 for all the values
// you need to create and set.
}
}
}
}
}
Полезный способ — использовать метод IMethodInstance.GetMethod().CreateDefaultParameterInstances(IMethodInstance), который возвращает массив Object[] экземпляров внутренних аргументов на основе значений модели по умолчанию, а затем заменяет эти значения с помощью TypeReflector, как показано в следующем примере кода. CreateDefaultParameterInstances() — это быстрый способ выполнения этапов 3-5.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.BusinessData.MetadataModel;
using Microsoft.BusinessData.Runtime;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Web;
namespace Microsoft.SDK.Sharepoint.Samples
{
class Program
{
static void Main(string[] args)
{
string siteURL = ""<siteUrl>";
string entityNS = "<nameSpace>";
string entityName = "<entityName>";
string methodInstanceName = "<methodInstanceName>";
using (SPSite site = new SPSite(siteURL))
{
using (new Microsoft.SharePoint.SPServiceContextScope(
SPServiceContext.GetContext(site)))
{
BdcService service =
SPFarm.Local.Services.GetValue<BdcService>(
String.Empty);
IMetadataCatalog catalog =
service.GetDatabaseBackedMetadataCatalog(
SPServiceContext.Current);
IEntity entity = catalog.GetEntity(
entityNS, entityName);
ILobSystemInstance LobSysteminstance =
entity.GetLobSystem().GetLobSystemInstances()
[0].Value;
// Step 1: Obtain the MethodInstance from the entity.
IMethodInstance myGenericInvoker =
entity.GetMethodInstance(
methodInstanceName, MethodInstanceType.GenericInvoker);
// Step 2: Obtain the Parameters using the Method.
IParameterCollection parameters =
myGenericInvoker.GetMethod().
CreateDefaultParameterInstances(IMethodInstance);
}
}
}
}
}
См. также
Ссылка
GetDatabaseBackedMetadataCatalog(SPServiceContext)