silverlight. to oob or not to oob

Post on 13-Jan-2015

2.252 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

Eugenie Zharkov speech at Ciklum .NET Saturday (Kharkov 21.05.2011)

TRANSCRIPT

Silverlight. To OOB or not to OOB

Евгений ЖарковSilverlight MVP/MCTS

Windows Phone 7ПК

Silverlight

Браузер Вне браузера

Out of browser (OOB)

• Управление окном• Настройка внешнего вида окна• Размещения HTML внутри приложения• Окна уведомлений• Digital Rights Management (DRM)• Расширенные права• Доступ к файловой системе• COM• Интегрированная возможность обновления

Активация OOB

Конфигурация OOB

Инсталляция

Довели до ума

Elevated trust

Доступ к буферу обмена

Прямой доступ к

папке User

COM

Кросс-доменные

запросы

Установка доверенных приложений

Подпись XAP

/uninstall  – Uninstalls the application specified in /origin. This is the same /origin value that was used to install the app originally./origin:"xapURI" – same as /origin for the install case

Тихая установка XAP

/install:"xapFile" – where xapFile is the file name/file path to the .xap file., E.g. /install:"c:\temp\sample.xap"/origin:"xapURI" – where xapURI is the URI where the .xap file would've come from if not installed at the commandline

e.g. /origin:"http://example.com/sample.xap" . This URI will be used as the site of origin for security purposes. For example, for sandboxed applications, Silverlight networking requires a policy file check when making network requests to domains other than the site of origin. The origin also serves as a unique ID for the application. The xapURI must be an absolute URI not a relative URI, and must start with http:, https:, or file:.

/overwrite -- (optional) Overwrites any previously installed .xap with that xapURI.

Инсталляция

Деинсталляция

sllauncher.exe /install:"{LocalPathToXapFile}\Yourfile.xap" /origin:"{urltoxapfile}/Yourfile.xap" /shortcut:desktop+startmenu

Тихая установка XAP

Установка

"%ProgramFiles%\Microsoft Silverlight\sllauncher.exe" /emulate:"Yourfile.xap" /origin:"http://blabla.com/Yourfile.xap"

Автозапуск

"%ProgramFiles%\Microsoft Silverlight\sllauncher.exe" /uninstall /origin:"http://blabla.com/Yourfile.xap"

Деинсталляция

Тихая установка Silverlight

/q -  quiet install or upgrade. This installs or upgrades Silverlight without seeing the GUI. When Silverlight is installed quietly, by default privacy related features such as DRM protected media playback and the Silverlight auto-update feature will be configured to prompt the user for permission on 1st use of the respective features. The Silverlight auto-update feature requires administrative rights so non-admin users will not be prompted./doNotRequireDRMPrompt - turns off the 1st use prompt allowing content protected by Digital Rights Management (DRM) to play without requiring any end-user intervention. When Silverlight is installed quietly, DRM Playback is set to prompt on 1st use by default./ignorewarnings - non-fatal warnings will not be reflected in the quiet installer return code but will instead return zero indicating success./noupdate - disables the Silverlight internal auto-updater./qu - quiet uninstall. This uninstalls Silverlight without seeing the GUI.

Тихая установка Silverlight

Silverlight.exe /q /doNotRequireDRMPrompt

Результирующая строка

NSIS Script ExampleName “Test Out of Browser Installer"OutFile “TextOOBInstaller.exe"InstallDir "$PROGRAMFILES\TestOOB"

XPStyle on

Section SetOutPath "$INSTDIR" SetOverwrite ifnewer File "Silverlight.exe" ExecWait "$INSTDIR\Silverlight.exe /q /doNotRequireDRMPrompt" File “TestOOB.xap" ExecWait '"$PROGRAMFILES\Microsoft Silverlight\sllauncher.exe"

/install:"$INSTDIR\TestOOB.xap" /origin:"http://blabla.com/TestOOB.xap" /shortcut:desktop+startmenu'

SectionEnd

Batch Script:: Is this a 64-bit machine?@echo offif exist "%ProgramFiles(x86)%" (:: We're on 64-bit set sllauncherlocation="%ProgramFiles(x86)%\Microsoft Silverlight\sllauncher.exe") else (::We're on 32-bit set sllauncherlocation="%ProgramFiles%\Microsoft Silverlight\sllauncher.exe"):: run SL%sllauncherlocation% /overwrite /emulate:“TestOOB.xap" /origin:"http://blabla/TestOOB.xap"

Мои документы

Мои документы

My Documents

Documents

Eigene Dateien

Mes documents

我的文件

Τα έγγραφά

μου

Batch Script User Folder

FOR /F "tokens=3 delims= " %%G IN ('REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "Personal"') DO (SET docsdir=%%G)

Извлекаем правильный адрес директории “Мои документы” из реестра

Многоязычный интерфейс

Добавление поддерживаемых культур в файл проекта

<?xml version="1.0" encoding="utf-8"?><Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <!– настройки --> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion> <SilverlightApplication>true</SilverlightApplication>

<SupportedCultures>en-US,ru-RU,uk-UA</SupportedCultures>

<XapOutputs>true</XapOutputs>

Многоязычный интерфейс

Добавляем ресурсы с локализованным

текстом

Многоязычный интерфейс

Установить модификатор доступа

в Public

Многоязычный интерфейс

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:MyApplication" x:Class=“MyApplication.App"> <Application.Resources> <local:LocalizationResource x:Key="Localization" /> </Application.Resources></Application>

Регистрация ресурса

Многоязычный интерфейс

public class LocalizationResource : INotifyPropertyChanged { private static Localization.Strings resource = new Localization.Strings();

public Localization.Strings Strings { get { return resource; } set { OnPropertyChanged("Strings"); } }

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }

#endregion }

Регистрация ресурса

Многоязычный интерфейс

Thread.CurrentThread.CurrentUICulture = new CultureInfo("uk-UA"); ((LocalizationResource)Application.Current.Resources["Localization"]).Strings = new MyApplication.Localization.Strings();

Переключение языка UI

COM

using System.Runtime.InteropServices.Automation;

Подключаем пространство имен

using (dynamic fsoCom = AutomationFactory.CreateObject("Scripting.FileSystemObject")){ dynamic file = fsoCom.CreateTextFile(@"c:\test.txt", true); file.WriteLine("Bloody Hell!"); file.WriteLine("Silverlight is writing to C:\\"); file.Close();}

Создаем файлы в любом месте на ПК

COM

using (dynamic ShellApplication = ComAutomationFactory.CreateObject("Shell.Application")){ dynamic commonPrograms = ShellApplication.NameSpace(23); string allUsersPath = commonPrograms.Self.Path;

dynamic directory = ShellApplication.NameSpace(allUsersPath + @"\Accessories"); dynamic link = directory.ParseName("Calculator.lnk");

dynamic verbs = link.Verbs(); for (int i = 0; i < verbs.Count(); i++) { dynamic verb = verbs.Item(i); if (verb.Name.Replace(@"&", string.Empty).ToLower() == "pin to taskbar") { verb.DoIt(); } }}

Пиним приложение на панель задач

COM

using (dynamic ShellApplication = ComAutomationFactory.CreateObject("Shell.Application")){ dynamic commonPrograms = ShellApplication.NameSpace(11); string allUsersPath = commonPrograms.Self.Path;

dynamic directory = ShellApplication.NameSpace(allUsersPath + @"\Programs"); dynamic link = directory.ParseName(Deployment.Current.OutOfBrowserSettings.ShortName + ".lnk"); string OOBLink = link.Path;

using (dynamic WShell = ComAutomationFactory.CreateObject("WScript.Shell")) { WShell.RegWrite(@"HKLM\Software\Microsoft\Windows\CurrentVersion\Run\"+ Deployment.Current.OutOfBrowserSettings.ShortName, OOBLink); MessageBox.Show("Please restart your machine and this application will load on startup."); }}

Добавляем OOB-приложение в автозагрузку

COM

using (dynamic IDbConnection = ComAutomationFactory.CreateObject("ADODB.Connection"))using (dynamic IDbCommand = ComAutomationFactory.CreateObject("ADODB.Command")){ IDbConnection.ConnectionString = "driver={SQL Server};" + "server=.\\;uid=sa;pwd=password;database=Northwind";

IDbConnection.Open(); IDbCommand.ActiveConnection = IDbConnection;

IDbCommand.CommandText = @"INSERT INTO [Northwind].[dbo].[Region]                    ([RegionID], [RegionDescription]) VALUES (10, 'BLa')";

IDbCommand.Execute();}

Работа с ODBC

Тихая установка MSSQL

sqlexpr32.exe -q /norebootchk /qn REBOOT=ReallySuppress INSTANCENAME="name" ADDLOCAL=ALL SECURITYMODE=SQL SAPWD="password" SQLAUTOSTART=1 DISABLENETWORKPROTOCOLS=0

Express

msiexec /quit /i SSCERuntime-ENU-x86.msi

Compact Edition

Silverlight COM Toolkit

http://silverlightcom.codeplex.com/

Silverlight COM Toolkit

http://silverlightcom.codeplex.com/

ComToolkit.IO.File.Copy(@"c:\AnyDir\AnyFile.ext", @"c:\AnyDir\AnyFile2.ext", true);

Copy

string[] contents = //some lines of text... ComToolkit.IO.File.WriteAllLines(@"c:\AnyDir\AnyFile.ext", bytes);

WriteAllBytes

bool exist = ComToolkit.IO.File.Exists(@"c:\AnyDir\AnyFile.ext");

Exists

AdoFileStream stream = ComToolkit.IO.File.Open(@"c:\AnyDir\AnyFile.ext", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);

Open

Silverlight COM Toolkit

http://silverlightcom.codeplex.com/

string connectionString = @"Provider=SQLOLEDB;Data Source=servername\sqlexpress;Initial Catalog=databasename;User ID=username; Password=password";using (var connection = new ComToolkit.Data.AdoConnection(connectionString)) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = "SELECT MyColumn FROM MyTable"; var reader = command.ExecuteReader(); while (reader.Read()) { object byindex = reader[0]; object bystring = reader["MyColumn"]; // для работы с динамическими свойства reader должен быть объявлен

как dynamic //object bydynamic = reader.MyColumn; } }

ComToolkit.Data

Silverlight COM Toolkit

http://silverlightcom.codeplex.com/

private ComToolkit.Data.AdoConnection connection; private void ExecuteReaderAsyncSample() { connection = new ComToolkit.Data.AdoConnection(connectionString); connection.Open(); var command = connection.CreateCommand(); command.CommandText = "SELECT MyColumn FROM MyTable"; command.ExecuteReaderCompleted += new EventHandler<ComToolkit.Data.ExecuteReaderCompletedEventArgs>(command_ExecuteReaderCompleted); command.ExecuteReaderAsync(); }

void command_ExecuteReaderCompleted(object sender, ComToolkit.Data.ExecuteReaderCompletedEventArgs e) { //TODO: обрабатываем результат}

Асинхронный ComToolkit.Data

Работа с документами

Desktop Application

PDF

Microsoft Office

HTML

XPS

XML Paper Specification (XPS)

• В основе лежит ZIP, XML, XAML. Разработан Microsoft и Ecma International, 2006 год

• Возможность относительно легкой конвертации в XAML• Родная поддержка в Windows Vista/7

Позитивные факторы

• Windows XP SP2 требует наличие .NET Framework 3 и XPS Document Viewer

Негативные факторы

PDF

• Бесплатные компоненты для обработки PDF-документа• Возможность разместить документ в WebBrowser при

наличии Adobe Acrobat плагина

Позитивные факторы

• Платные компоненты для обработки и отображения в Silverlight-приложении

Негативные факторы

HTML

• Возможно разместить внутри элемента управления WebBrowser

Позитивные факторы

• Невозможно открывать локальные файлы внутри WebBrowser• Невозможно задать заголовочную информацию в WebBrowser• Невозможно открыть MHT-файлы• Следует собирать все ресурсы в единый HTML-файл, включая

изображения, используя Data URI, который имеет ограничение в 32КБ

Негативные факторы

Microsoft Office (Word, Excel, PowerPoint)

• Работа с документами через COMПозитивные факторы

• Отсутствует родная поддержка в Silverlight

Негативные факторы

Microsoft Office (Word, Excel, PowerPoint)

using (dynamic word = AutomationFactory.CreateObject("Word.Application")){ int wdFormatWebArchive = 9; // MHT fileformat int wdDoNotSaveChanges = 0; // WdSaveOptions do not save value

using (dynamic document = word.Documents.Open(tempDoc)) {

document.SaveAs("C:\t.doc", ref wdFormatWebArchive); } word.Quit(ref wdDoNotSaveChanges);}

Пример обработки Word документа

События Office

dynamic word = AutomationFactory.CreateObject("Word.Application");word.Visible = true;

AutomationEvent searchEvent = AutomationFactory.GetEvent(word, "Quit");searchEvent.EventRaised += (s, a) =>{ MessageBox.Show("Quit");};

dynamic document = word.Documents.Open("C:\test.doc");

Пример обработки Word документа

Потоки и BackgroundWorkervar bw = new BackgroundWorker();bw.WorkerReportsProgress = true;

bw.DoWork += (s, a) => {var worker = sender as BackgroundWorker;worker.ReportProgress(0, "Сейчас начнем");

MessageBox.Show("Работаем");worker.ReportProgress(100, «Закончили");

};bw.ProgressChanged += (s, a) => { MessageBox.Show("Current state" + a.ProgressPercentage.ToString()); // сложные объекты могут передаваться в e.UserState };bw.RunWorkerCompleted += (s, a) => { MessageBox.Show("Done"); };bw.RunWorkerAsync(new Dictionary<string, object> { { "file", "test.doc" }, { "region", "Ukraine"} });

Navigation Framework

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation" xmlns:uriMapper="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation">

Подключение пространства имен в XAML

Navigation Framework

<navigation:Frame x:Name="ContentFrame" Source="/Action"> <navigation:Frame.UriMapper> <uriMapper:UriMapper> <uriMapper:UriMapping Uri="" MappedUri="/Pages/Action.xaml"/> <uriMapper:UriMapping Uri="/{pageName}"

MappedUri="/Pages/{pageName}.xaml"/> </uriMapper:UriMapper> </navigation:Frame.UriMapper></navigation:Frame>

Добавление Frame

NavigationService.Navigate(new Uri("/INeedThisPage", UriKind.Relative));

Переход на другую страницу

Управление окном

// App.xamlprivate void Application_Startup(object sender, StartupEventArgs e){ this.RootVisual = new MainPage(); App.Current.Host.Content.Resized += (s, a) => { App.Current.MainWindow.Height = 650; App.Current.MainWindow.Width = 1000; };}

Ограничение размера окна

App.Current.MainWindow.WindowState = WindowState.Maximized;

Развернуть окно

Notification Windowvar block = new TextBlock();block.Text = "Wassup!";

var nw = new NotificationWindow();nw.Height = 50;nw.Width = 300;nw.Content = block;nw.Show(3000);

Хочу работать с архивами

http://slsharpziplib.codeplex.com/

ZipOutputStream zipOutStream = new ZipOutputStream(File.Create("my.zip"));

ZipEntry fileZipEntry = new ZipEntry(name); zipOutStream.PutNextEntry(fileZipEntry); FileStream fileStream = File.Open(filePath, FileMode.Open); byte[] buffer = new byte[fileStream.Length]; fileStream.Read(buffer, 0, buffer.Length); zipOutStream.Write(buffer, 0, buffer.Length); zipOutStream.CloseEntry();

Silverlight 5

Поздравляю, вы пережили этот доклад

Евгений Жарковeu.zharkov@gmail.com

@2j2e

Слушай подкаст2Гига

Вопросы?

top related