Поделиться через


Фрагмент кода: импорт модели подключения к бизнес-данным в хранилище метаданных

Дата последнего изменения: 13 мая 2010 г.

Применимо к: SharePoint Server 2010

В примере ниже показывается, как импортировать модель подключения к бизнес-данным в каталог фермы.

Необходимые компоненты:

  • Microsoft SharePoint Server 2010 или Microsoft SharePoint Foundation 2010.

  • Microsoft .NET Framework 3.5.

Использование этого примера

  1. Запустите Visual Studio и создайте проект консольного приложения C#. При создании проекта выберите .NET Framework 3.5.

  2. В меню Вид выберите Страницы свойств, чтобы отобразить свойства проекта.

  3. На вкладке Построение в качестве значения Целевая платформа выберите Любой ЦП.

  4. Закройте окно свойств проекта

  5. В обозревателе решений в разделе Ссылки удалите все ссылки проекта кроме System и System.Core.

  6. Добавьте в проект следующие ссылки:

    1. Microsoft.BusinessData

    2. Microsoft.SharePoint

    3. System.Web

  7. Замените код в файле Program.cs на код, приведенный в конце этой процедуры.

  8. Сохраните проект.

  9. Замените значения strModelName и strXmlFile2Import именем и полным путем к файлу модели соответственно.

  10. Замените значение strSomeSite URL-адресом веб-сайта в используемой ферме.

  11. Скомпилируйте и запустите проект.

  12. Откройте браузер Internet Explorer и перейдите в центр администрирования фермы.

  13. В браузере щелкните Управление приложениями-службами.

  14. Щелкните Служба подключения к бизнес-данным.

    ПримечаниеПримечание

    Business Data Connectivity Service — это имя службы BDC по умолчанию. Если администратор назвал службу BDC иначе, на веб-странице центра администрирования появится другое имя.

    Отобразится импортированная модель.

using System;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.BusinessData.Administration;
using Microsoft.SharePoint.BusinessData.Parser;
using Microsoft.SharePoint.BusinessData.SharedService;

namespace Microsoft.SDK.Sharepoint.Samples
{
    class Program
    {
        static void Main(string[] args)
        {
            # region declarations and initializations

            // The model name is used to compose its file name 
            // and also to check hits existence in the catalog.
            string strModelName = "testBCSimport";

            // The full path to the XML model to import.
            string strXmlFile2Import = @".\" + strModelName + ".xml";

            // A site in the farm is used as a reference point 
            // to the farm.
            string strSomeSite = "http://intranet.contoso.com/";

            // The model definition file is the XML data to import.
            string strXmlData2Import;

            // An array to gather the non-critical errors encountered 
            // during the import process.
            string[] strarrNoncriticalErrors;

            // Specify what to import: {"All", "InlineProxies", 
            // "LocalizedNames", "Model", "None", "Permissions", 
            // "Properties"}.
            PackageContents packageContentsImportFlags = 
                PackageContents.All;

            // Setting to use when obtaining resources to 
            // import the model.
            string strResourcesSettingId = "";

            // If blUpdateExistingModel is true, the model definition 
            // that was already in the database is updated 
            // to contain only the external content types 
            // in the given XML. 
            // This method throws an exception if the model 
            // is not in the database. 
            // If blUpdateExistingModel is false, the model is
            // created for the first time, 
            // and this method throws an exception if the 
            // model already exists in the database. 
            // When the model is being updated, the external 
            // content types that were previously in the model 
            // are not deleted. 
            //   The caller must clean them up separately.
            bool blUpdateExistingModel = false;

            // A GUID that is used to track this import process.
            Guid guidJobId = 
                new Guid("C6E88A92-31C2-4D02-9890-5DC2ADB36EA9");

            # endregion declarations and initializations

            # region import

            try
            {
                // Get the model.
                strXmlData2Import = File.ReadAllText(strXmlFile2Import);

                // Identify the farm using a site in the farm.
                using (SPSite site = new SPSite(strSomeSite))
                {
                    // Reference the farm to host the BCS definitions.
                    using (new Microsoft.SharePoint.SPServiceContextScope(
                        SPServiceContext.GetContext(site)))
                    {
                        // Reference the BDC service.
                        BdcService service = 
                            SPFarm.Local.Services.GetValue<BdcService>
                            (String.Empty);

                        // Get the catalog of the referenced BDC service.
                        AdministrationMetadataCatalog cat = 
                            service.GetAdministrationMetadataCatalog(
                            SPServiceContext.Current);

                        // Import the XML definition.
                        Model bcsadminModel = cat.ImportPackage(
                            strXmlData2Import,
                            out strarrNoncriticalErrors,
                            packageContentsImportFlags,
                            strResourcesSettingId,
                            blUpdateExistingModel,
                            guidJobId);

                        Console.Out.NewLine = "\n\r\n\r";
                        int iNumOfNoncriticalErrors = 
                            strarrNoncriticalErrors.Length;
                        if (iNumOfNoncriticalErrors > 0)
                        {
                            Console.WriteLine("Noncritical Errors");
                            for (int iCtr = 0; 
                                iCtr < iNumOfNoncriticalErrors; 
                                iCtr++)
                            {
                                Console.WriteLine(
                                    strarrNoncriticalErrors[iCtr]);
                            }
                        }
                        Console.WriteLine(
                            "Import completed successfully");
                        // Now go to the farm's central administration, 
                        // click Manage service applications,
                        // click Business Data Connectivity 
                        // (the name of the BDC service) 
                        // and enjoy the newly imported model.
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.Read();
            }

            # endregion import
        }
    }
}

См. также

Ссылка

PackageContents

BdcService

Services

AdministrationMetadataCatalog

GetAdministrationMetadataCatalog(SPServiceContext)

ImportPackage(String, [], PackageContents, String, Boolean, Guid)

Model