Опубликован: 01.03.2010 | Доступ: свободный | Студентов: 958 / 46 | Оценка: 4.38 / 4.31 | Длительность: 09:26:00
Лекция 6:

Вставка приложений Silverlight в web приложения

< Лекция 5 || Лекция 6: 1234 || Лекция 7 >

Вставка приложений Silverlight в Office SharePoint Server

Для работы Silverlight на портале Office SharePoint Server необходимы следующие компоненты:

  • Windows SharePoint Services 3.0 Service Pack 1.
  • .NET Framework 3.5 для Silverlight
  • Настройки Internet Information Server
  • Visual Studio 2008 Silverlight 3.0 Tools + Silverlight 3.0 SDK
  • Expression Blend 3.0 (если нужен дизайн)
  • Плагин Silverlight 3.0 для браузера

Приложение Silverlight в портале SharePoint находится:

  • Внутри веб-части (Web-part), которую можно назвать SilverPart
  • ASP.NET страницы узла
  • Пользовательские типы полей списков
  • Навигационные элементы управления

Обмен данными между приложением Silverlight и порталом Office SharePoint Server можно осуществлять с помощью:

  • Веб-сервисов
  • WCF - Windows Communication Foundation
  • Скрытых полей HTML (hidden fields)
  • Свойства initParams
  • Параметры элементов управления Silverlight конфигурируются через свойства веб-части

Когда могут использоваться приложения Silverlight в портале SharePoint:

  • Сложные (может быть интерактивные) представления данных в виде графиков, многотабличных отчетов и т.д.
  • Красивое отображение медиа данных из библиотеки SharePoint (см. раздел 0 Smooth Streaming и Expression Encoder)
  • Нестандартная навигация
  • Перенос нагрузки на клиента
  • Асинхронные операции

Создание веб-части Silverlight

Создается проект пор шаблону Visual C# Class Library и добавляется класс BasicSilverLightWebPart.

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Globalization;
namespace SilverLightWebParts
{
  [DefaultProperty("Text"),
    ToolboxData("<{0}:BasicSilverLightWebPart 
    runat=server></{0}:BasicSLWebPart>"),
    XmlRoot(Namespace = "http://SilverLightWebParts")
  ]
  public class BasicSilverLightWebPart : WebPart
  {
    //Constructor
    public BasicSilverLightWebPart()
    {
    }
  }
}
Листинг 6.7.

В класс добавляются переменные:

#region Private Variables

private string _JSPath = "";
private const string defaultText = "";
private string text = defaultText;
private string _SLCtlHeight = "100%";
private string _SLCtlWidth = "100%";
private string _MainCtlJS = "Default_html";
private string _XAMLPageName = "Page";

#endregion
Листинг 6.8.

В класс добавляются свойства, которые устанавливают путь к файлам *.js и *.xaml. Можно добавить собственные свойства для улучшения функциональности

#region Properties

[Browsable(true),Personalizable(), WebBrowsable,
  Category("Custom Settings"), DefaultValue(defaultText),
  Description("Text Property")]
public string Text
{
  get
  {
    return text;
  }
  set
  {
    text = value;
  }
}

[Browsable(true),Personalizable(), WebBrowsable,
  Category("Custom Settings"), DefaultValue("100%"),
  Description("Silverlight Control Width")]
public string SLControlWidth
{
  get
  {
    return _SLCtlWidth;
  }

  set
  {
    _SLCtlWidth = value;
  }
}

[Browsable(true),Personalizable(), WebBrowsable,
  Category("Custom Settings"), DefaultValue("100%"),
  Description("Silverlight Control Height")]
public string SLControlHeight
{
  get
  {
    return _SLCtlHeight;
  }

  set
  {
    _SLCtlHeight = value;
  }
}

[Browsable(true),Personalizable(), WebBrowsable,
  Category("Custom Settings"), DefaultValue(""),
  Description("Javascript file path")]
public string JSPath
{
  get
  {
    return _JSPath;
  }

  set
  {
    _JSPath = value;
  }
}

[Browsable(true),Personalizable(), WebBrowsable,
  Category("Custom Settings"), DefaultValue(""),
  Description("Main JS file Name")]
public string MainCtlJS
{
  get
  {
    return _MainCtlJS;
  }

  set
  {
    _MainCtlJS = value;
  }
}

[Browsable(true),Personalizable(), WebBrowsable,
  Category("Custom Settings"), DefaultValue("Page"),
  Description("Xaml FileName")]
public string XAMLPageName
{
  get
  {
    return _XAMLPageName;
  }

  set
  {
    _XAMLPageName = value;
  }
}
#endregion
Листинг 6.9.

Регистрируются 3 файла со скриптами Jscript и JavaScript. Это стандартные скрипты любого приложения Silverlight:

  • silverlight.js. Скрипт обнаруживает установлен ли плагин Silverlight в браузер. Если нет, то скрипт покажет иконку-ссылку на странцу, с которой можно его установить.
  • Default_html.js. Скрипт содержит функцию createSilverlight
  • Page.xaml.js. Содержит слушателей событий.
protected override void OnPreRender(EventArgs e)
{

  String JSString;

  // Register the webpart specfic script (Each different type of webpart needs its own main, 
  multiple instances of the same webpart on a page 
   reference the same script
  JSString = "<script type=\"text/javascript\" src=\"" 
            + _JSPath + _MainCtlJS + ".js\"></script>\n";
  if (!Page.ClientScript.IsClientScriptBlockRegistered("SilverlightWebPartScript"))
  Page.ClientScript.RegisterClientScriptBlock(this.GetType(), 
        "SilverlightDefaultScript", JSString);

  // Register the general scripts (Two web parts can use this same script blocks as they are generic)
  JSString = "<script type=\"text/javascript\" src=\"" 
            + _JSPath + "Silverlight.js\"></script>\n";

  JSString += "<script type=\"text/javascript\" src=\"" 
            + _JSPath + "Page.xaml.js\"></script>\n";
  if (!Page.ClientScript.IsClientScriptBlockRegistered("GeneralSilverlightScripts"))
  Page.ClientScript.RegisterClientScriptBlock(this.GetType(), 
        "GeneralSilverlightScripts", JSString);
}
Листинг 6.10.

Добавляется код, который генерирует таг <div>, где объект Silverlight будет вставлен в веб-часть

protected override void RenderContents(HtmlTextWriter writer)
{
  EnsureChildControls();
  HtmlTextWriter textWriter = new HtmlTextWriter(new StringWriter(CultureInfo.InvariantCulture));

  try
  {
    string width, height;

    width = "400px"; height = "300px";
    if (this.SLControlWidth.Length > 0)
    width = _SLCtlWidth;

    if (this.SLControlHeight.Length > 0)
    height = _SLCtlHeight;


    textWriter.WriteLine("<TABLE class='ms-summarycustombody' cellpadding='0' cellspacing='0' border='0'>");
    textWriter.WriteLine("<tr><td width='95%'>");
    textWriter.WriteLine("<div id='SilverlightControlHost" + 
          this.ClientID + "' Class=''>");
    textWriter.WriteLine("<script type=\"text/javascript\"> ");
    textWriter.WriteLine("var localScene=new SilverlightTest1.Page();");
    textWriter.WriteLine("createSilverlight('SilverlightControlHost" + this.ClientID + 
          "', '" + _XAMLPageName + 
          "', 'SilverlightControl" + this.ClientID + 
          "','" + width + "','" + height + 
          "', localScene);  ");
    textWriter.WriteLine("</script></div>");
    textWriter.WriteLine("</td></tr></TABLE>");
  }
  catch
  {
    textWriter = new HtmlTextWriter(new StringWriter(CultureInfo.InvariantCulture));
    textWriter.WriteLine("<TABLE class='ms-summarycustombody' 
        cellpadding='0' cellspacing='0' border='0'>");
    textWriter.WriteLine("<TR><TD>There was an error creating this web part</TD></TR>");
    textWriter.WriteLine("</TABLE>");
  }
  
  writer.Write(textWriter.InnerWriter.ToString());
}
Листинг 6.11.

Создается файл Default_html.js file и в него копируется код модифицированной функции createSilverlight.

function createSilverlight(controlHost, xamlSource, controlName, controlWidth, controlHeight)
{
  var SLObj = new SilverlightTest1.Page();
  Silverlight.createObjectEx(
  {
    source: xamlSource,
    parentElement: document.getElementById(controlHost),
    id: controlName,
    properties: 
    {
      width: controlWidth,
      height: controlHeight,
      version: "1.0"
    },
    events: 
    {
      onLoad: Silverlight.createDelegate(SLObj,  SLObj.handleLoad)
    }
  });
}

if (!window.Silverlight) 
  window.Silverlight = {};

Silverlight.createDelegate = function(instance, method) 
{
  return function() 
  {
    return method.apply(instance, arguments);
  }
Листинг 6.12.

Создание XAML

Создается Page.xaml файл:

<Canvas
  xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="640" Height="480"
  Background="White"
  x:Name="Page"
  >
  <TextBlock Width="247" Height="72" Canvas.Left="197" Canvas.Top="121" Text="This is great" TextWrapping="Wrap"/>
</Canvas>

Развертывание веб-части Silverlight на Office SharePoint Server

Развертывание веб-части Silverlight на Office SharePoint Server 2007 выполняется в следующей последовательности:

  1. Устанавливается последняя версия плагина Silverlight. Если плагина нет, отображается ссылка на страницу установки
  2. Копируется сборка *.dll в каталог _app_bin приложения SharePoint ( C:\Inetpub\wwwroot\wss\VirtualDirectories\80\_app_bin ). Файл можно установить в global assembly cache (GAC)
  3. Копируются файлы default_html.js, Page.xaml, Page.xaml.js и SilverLight.js в корневую директорию. Укажите этот же путь в свойствах JSPath веб-части
  4. Добавить строку в web.config файл
    <SafeControl Assembly="SilverLightWebPart2005"
    Namespace="SilverLightWebParts" 
    TypeName="*" Safe="True" />
  5. Зайти на галерею веб-частей и добавить веб-часть BasicSilverLightWebPart в список.
  6. Зайти на сайт SharePoint и добавить на страницу созданную веб-часть
  7. Убедиться, что в строке custom properties указан полный либо относительный путь к файлу Page.xaml, например /Page.xaml.

Файлы Page.xaml.js и Default_html.js

Файлы Page.xaml.js и Default_html.js должны содержать следующий код.

Page.xaml.js
if (!window.SilverlightTest1)
  window.SilverlightTest1 = {};

SilverlightTest1.Page = function() 
{
}

SilverlightTest1.Page.prototype =
{
  handleLoad: function(control, userContext, rootElement) 
  {
    this.control = control;
    
    // Sample event hookup:  
    rootElement.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleMouseDown));
  },
  
  // Sample event handler
  handleMouseDown: function(sender, eventArgs) 
  {
    // The following line of code shows how to find an element by name and call a method on it.
    // this.control.content.findName("Timeline1").Begin();
  }
}
Default_html_js
function createSilverlight()
{
  var scene = new SilverlightTest1.Page();
  Silverlight.createObjectEx({
    source: "Page.xaml",
    parentElement: document.getElementById("SilverlightControlHost"),
    id: "SilverlightControl",
    properties: {
      width: "100%",
      height: "100%",
      version: "1.0"
    },
    events: {
      onLoad: Silverlight.createDelegate(scene, scene.handleLoad)
    }
  });
}



function createSilverlight(controlHost, xamlSource, controlName, controlWidth, controlHeight)
{
  var SLObj = new SilverlightTest1.Page();
  Silverlight.createObjectEx({
    source: xamlSource,
    parentElement: document.getElementById(controlHost),
    id: controlName,
    properties: {
      width: controlWidth,
      height: controlHeight,
      version: "1.0"
    },
    events: {
      onLoad: Silverlight.createDelegate(SLObj, SLObj.handleLoad)
    }
  });
}


if (!window.Silverlight) 
  window.Silverlight = {};

Silverlight.createDelegate = function(instance, method) {
  return function() {
    return method.apply(instance, arguments);
  }
}
Листинг 6.13.

Заключение

С помощью веб-частей Silverlight можно создавать очень сложные веб-части и публиковать их на портале Office SharePoint Server.

< Лекция 5 || Лекция 6: 1234 || Лекция 7 >