SlideShare a Scribd company logo
Silverlight 4, есть ли жизнь на десктопе?Евгений ЖарковMCTS: Silverlight 4, Development
SilverlightWindows Phone 7ПКБраузерВне браузера
Out of browser (OOB)Управление окномНастройка внешнего вида окнаРазмещения HTML внутри приложенияОкна уведомленийDigital Rights Management (DRM)Расширенные праваДоступ к файловой системеCOMИнтегрированная возможность обновления
Активация OOB
КонфигурацияOOB
ИнсталляцияДовели до ума
Silverlight 4, есть ли жизнь на десктопе?
Установка доверенных приложений
Подпись XAP
Тихая установка 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 commandlinee.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.Деинсталляция/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Установкаsllauncher.exe /install:"{LocalPathToXapFile}\Yourfile.xap" /origin:"{urltoxapfile}/Yourfile.xap" /shortcut:desktop+startmenuАвтозапуск"%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 onSectionSetOutPath "$INSTDIR"SetOverwriteifnewer    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 DocumentsEigeneDateienMes documentsDocumentsМои документыΤα έγγραφά μου
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)
Многоязычный интерфейсДобавление поддерживаемых культур в файл проекта<?xmlversion="1.0"encoding="utf-8"?><ProjectToolsVersion="4.0"DefaultTargets="Build"xmlns="http://schemas.microsoft.com/developer/msbuild/2003">  <PropertyGroup>    <ConfigurationCondition=" '$(Configuration)' == '' ">Debug</Configuration>    <PlatformCondition=" '$(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
Многоязычный интерфейсРегистрация ресурса<Applicationxmlns="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>
Многоязычный интерфейсРегистрация ресурса    publicclassLocalizationResource : INotifyPropertyChanged    {privatestaticLocalization.Strings resource = newLocalization.Strings();publicLocalization.Strings Strings        {get { return resource; }set { OnPropertyChanged("Strings"); }        }        #regionINotifyPropertyChanged MemberspubliceventPropertyChangedEventHandlerPropertyChanged;privatevoidOnPropertyChanged(stringpropertyName)        {if (PropertyChanged != null)            {PropertyChanged(this, newPropertyChangedEventArgs(propertyName));            }        }        #endregion}
Многоязычный интерфейсПереключение языка UIThread.CurrentThread.CurrentUICulture = newCultureInfo("uk-UA");            ((LocalizationResource)Application.Current.Resources["Localization"]).Strings = newMyApplication.Localization.Strings();
COMПодключаем пространство именusingSystem.Runtime.InteropServices.Automation;Создаем файлы в любом месте на ПКusing (dynamicfsoCom = 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 (dynamicShellApplication = ComAutomationFactory.CreateObject("Shell.Application")){dynamiccommonPrograms = ShellApplication.NameSpace(23);stringallUsersPath = 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Добавляем OOB-приложение в автозагрузкуusing (dynamicShellApplication = ComAutomationFactory.CreateObject("Shell.Application")){dynamiccommonPrograms = ShellApplication.NameSpace(11);stringallUsersPath = commonPrograms.Self.Path;dynamic directory = ShellApplication.NameSpace(allUsersPath + @"\Programs");dynamic link = directory.ParseName(Deployment.Current.OutOfBrowserSettings.ShortName + ".lnk");stringOOBLink = link.Path;using (dynamicWShell = 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.");    }}
COMРабота с ODBCusing (dynamicIDbConnection = ComAutomationFactory.CreateObject("ADODB.Connection"))using (dynamicIDbCommand = 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();}
Тихая установка MSSQLExpresssqlexpr32.exe -q /norebootchk /qnREBOOT=ReallySuppressINSTANCENAME="name" ADDLOCAL=ALLSECURITYMODE=SQL 	SAPWD="password" SQLAUTOSTART=1 DISABLENETWORKPROTOCOLS=0Compact Editionmsiexec /quit /i SSCERuntime-ENU-x86.msi
Silverlight COM Toolkithttp://silverlightcom.codeplex.com/
Silverlight COM ToolkitCopyComToolkit.IO.File.Copy(@"c:\AnyDir\AnyFile.ext", @"c:\AnyDir\AnyFile2.ext", true);Existsbool exist = ComToolkit.IO.File.Exists(@"c:\AnyDir\AnyFile.ext");WriteAllBytesstring[] contents = //some lines of text...ComToolkit.IO.File.WriteAllLines(@"c:\AnyDir\AnyFile.ext", bytes);OpenAdoFileStream stream = ComToolkit.IO.File.Open(@"c:\AnyDir\AnyFile.ext", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);http://silverlightcom.codeplex.com/
Silverlight COM ToolkitComToolkit.DatastringconnectionString = @"Provider=SQLOLEDB;DataSource=servername\sqlexpress;InitialCatalog=databasename;User ID=username; Password=password";using (var connection = newComToolkit.Data.AdoConnection(connectionString)) { connection.Open(); varcommand = connection.CreateCommand(); command.CommandText= "SELECT MyColumn FROM MyTable"; varreader = command.ExecuteReader(); while(reader.Read()) { objectbyindex = reader[0]; objectbystring = reader["MyColumn"]; //для работы с динамическими свойства reader должен быть объявленкак dynamic//object bydynamic = reader.MyColumn;} }http://silverlightcom.codeplex.com/
Silverlight COM ToolkitАсинхронный ComToolkit.DataprivateComToolkit.Data.AdoConnection connection; privatevoidExecuteReaderAsyncSample() {connection = newComToolkit.Data.AdoConnection(connectionString); connection.Open(); varcommand = connection.CreateCommand(); command.CommandText= "SELECT MyColumn FROM MyTable";command.ExecuteReaderCompleted+= newEventHandler<ComToolkit.Data.ExecuteReaderCompletedEventArgs>(command_ExecuteReaderCompleted); command.ExecuteReaderAsync(); } voidcommand_ExecuteReaderCompleted(object sender, ComToolkit.Data.ExecuteReaderCompletedEventArgs e) { //TODO: обрабатываем результат}http://silverlightcom.codeplex.com/
Работа с документами
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)Пример обработки Word документаusing(dynamic word = AutomationFactory.CreateObject("Word.Application")){intwdFormatWebArchive = 9; // MHT fileformatintwdDoNotSaveChanges = 0; // WdSaveOptions do not save valueusing(dynamic document = word.Documents.Open(tempDoc))    {document.SaveAs("C:\t.doc", refwdFormatWebArchive);    }word.Quit(refwdDoNotSaveChanges);}
События Office Пример обработки Word документаdynamic word = AutomationFactory.CreateObject("Word.Application");word.Visible = true;AutomationEventsearchEvent = AutomationFactory.GetEvent(word, "Quit");searchEvent.EventRaised += (s, a) =>{MessageBox.Show("Quit");};dynamic document = word.Documents.Open("C:\test.doc");
Потоки и BackgroundWorkervarbw = newBackgroundWorker();bw.WorkerReportsProgress = true;bw.DoWork+= (s, a) => {varworker = sender asBackgroundWorker;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(newDictionary<string, object> {         { "file", "test.doc"},        { "region", "Ukraine"}    });
Navigation FrameworkПодключение пространства имен в XAML<UserControlxmlns="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">
Navigation FrameworkДобавление Frame<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>Переход на другую страницуNavigationService.Navigate(newUri("/INeedThisPage", UriKind.Relative));
Управление окномОграничение размера окна// App.xamlprivatevoidApplication_Startup(object sender, StartupEventArgs e){this.RootVisual= newMainPage();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 = newTextBlock();block.Text = "Wassup!";varnw = newNotificationWindow();nw.Height = 50;nw.Width = 300;nw.Content = block;nw.Show(3000);
Поздравляю, вы пережили этот докладЕвгений Жарковeu.zharkov@gmail.com@2j2eСлушай подкаст2Гига

More Related Content

PPTX
06 net saturday eugene zharkov ''silverlight. to oob or not to oob''
PPT
Alexander manuhin selenium_php_v2.0
PPT
ZFConf 2011: Воюем за ресурсы: Повышение производительности Zend Framework пр...
PPTX
Selenium, а давай подождем?
PDF
Контроль качества верстки или как начать делать Makeup
PPTX
Selenium vs AJAX
PPTX
Типичные ошибки начинающих писать тесты на WebDriver
PPTX
Automation testing desktop applications
06 net saturday eugene zharkov ''silverlight. to oob or not to oob''
Alexander manuhin selenium_php_v2.0
ZFConf 2011: Воюем за ресурсы: Повышение производительности Zend Framework пр...
Selenium, а давай подождем?
Контроль качества верстки или как начать делать Makeup
Selenium vs AJAX
Типичные ошибки начинающих писать тесты на WebDriver
Automation testing desktop applications

What's hot (20)

ODP
ZFConf 2010: Zend Framework and Doctrine
PPTX
Презентация «WebMarkupMin – HTML-минификатор для платформы .NET» с MskDotNet ...
PDF
Автоматизация UI тестирования под Windows и Windows Phone
PDF
The Old New ASP.NET
PPTX
Микрофреймворки PHP
PDF
Пользователь точно оценит! Повышение производительности мобильных приложений ...
PDF
Let’s talk about Atlas
PDF
Анджей Гужовский "Riot.JS, или как приготовить современные Web Components"
PPT
Client Side Autotesting Flash
PPT
Positive Hack Days. Гольцев. Мастер - класс: Уязвимости Web – сложные случаи.
PDF
Cоздание приложений со знанием Perl
PDF
Svyatoslav Login "How to test authentication and authorization for security"
PPTX
Vipolnenie komand na servere
PPTX
XPath локаторы в Selenium WebDriver
PPT
Selenium 2.0: обзор новых возможностей
PDF
Автоматизация функционального тестирования REST API
PDF
Превышаем скоростные лимиты с Angular 2
PPT
Js Http Request дмитрий котеров
PPTX
Ловля сетями. Инструменты отладки сетевых запросов приложений / Дмитрий Рыбак...
PPT
Опыт тестирования API САПР платформы
ZFConf 2010: Zend Framework and Doctrine
Презентация «WebMarkupMin – HTML-минификатор для платформы .NET» с MskDotNet ...
Автоматизация UI тестирования под Windows и Windows Phone
The Old New ASP.NET
Микрофреймворки PHP
Пользователь точно оценит! Повышение производительности мобильных приложений ...
Let’s talk about Atlas
Анджей Гужовский "Riot.JS, или как приготовить современные Web Components"
Client Side Autotesting Flash
Positive Hack Days. Гольцев. Мастер - класс: Уязвимости Web – сложные случаи.
Cоздание приложений со знанием Perl
Svyatoslav Login "How to test authentication and authorization for security"
Vipolnenie komand na servere
XPath локаторы в Selenium WebDriver
Selenium 2.0: обзор новых возможностей
Автоматизация функционального тестирования REST API
Превышаем скоростные лимиты с Angular 2
Js Http Request дмитрий котеров
Ловля сетями. Инструменты отладки сетевых запросов приложений / Дмитрий Рыбак...
Опыт тестирования API САПР платформы

Similar to Silverlight 4, есть ли жизнь на десктопе? (20)

PPTX
Silverlight 4, есть ли жизнь на десктопе
PDF
Устройство фреймворка symfony 2 (http://frontend-dev.ru)
ODP
Saint Perl 2009: CGI::Ajax demo
PDF
Phalcon. Что нового?
PPT
Движение по хрупкому дну / Сергей Караткевич (servers.ru)
PDF
Mobile automation uamobile
PPTX
iOS and Android Mobile Test Automation
PPT
Rich UI on Dojo Toolkit and Zend Framework
PPTX
Использование Open Source инструментов для автоматизации тестирования
PPTX
Alexei Sintsov - "Between error and vulerability - one step"
PPT
Browser Persistence Bynet
PPTX
Node.js введение в технологию, КПИ #ITmeetingKPI
PPT
WAF наше все?!
PDF
Изоморфные приложения и Python - Виталий Глибин, Huntflow
PDF
Александр Сычев "Статика и динамика. Как фреймворки помогут прокачать ваше пр...
PPTX
XSS. Обходы фильтров и защит.
PPT
Catalyst – MVC framework на Perl (RIT 2008)
PPT
Drupal Vs Other
PPT
Adobe Flex константин ковалев
Silverlight 4, есть ли жизнь на десктопе
Устройство фреймворка symfony 2 (http://frontend-dev.ru)
Saint Perl 2009: CGI::Ajax demo
Phalcon. Что нового?
Движение по хрупкому дну / Сергей Караткевич (servers.ru)
Mobile automation uamobile
iOS and Android Mobile Test Automation
Rich UI on Dojo Toolkit and Zend Framework
Использование Open Source инструментов для автоматизации тестирования
Alexei Sintsov - "Between error and vulerability - one step"
Browser Persistence Bynet
Node.js введение в технологию, КПИ #ITmeetingKPI
WAF наше все?!
Изоморфные приложения и Python - Виталий Глибин, Huntflow
Александр Сычев "Статика и динамика. Как фреймворки помогут прокачать ваше пр...
XSS. Обходы фильтров и защит.
Catalyst – MVC framework на Perl (RIT 2008)
Drupal Vs Other
Adobe Flex константин ковалев

More from Eugene Zharkov (20)

PDF
Monorepo: React + React Native. React Alicante
PDF
Monorepo: React Web & React Native
PDF
Create React Native App vs Expo vs Manually
PDF
Build automation with Fastlane
PDF
GraphQL and/or REST
PDF
React Native Animation
PDF
React Native: Hurdle Race
PDF
Burn your grass with react native
PDF
Фронтенд сказки
PDF
How to be a good frontend developer
PDF
Cycle.js: Functional and Reactive
PDF
Что там в summary
PDF
Elm: give it a try
PDF
Switch to React.js from AngularJS developer
PDF
AngularJS: Good parts
PDF
Mobile applications in a new way with React Native
PDF
Angular 2: Всех переиграл
PDF
Angular 2.0: Brighter future?
PDF
Как объяснить на платьях процесс разработки?
PDF
Angular.JS: Do it right
Monorepo: React + React Native. React Alicante
Monorepo: React Web & React Native
Create React Native App vs Expo vs Manually
Build automation with Fastlane
GraphQL and/or REST
React Native Animation
React Native: Hurdle Race
Burn your grass with react native
Фронтенд сказки
How to be a good frontend developer
Cycle.js: Functional and Reactive
Что там в summary
Elm: give it a try
Switch to React.js from AngularJS developer
AngularJS: Good parts
Mobile applications in a new way with React Native
Angular 2: Всех переиграл
Angular 2.0: Brighter future?
Как объяснить на платьях процесс разработки?
Angular.JS: Do it right

Silverlight 4, есть ли жизнь на десктопе?

  • 1. Silverlight 4, есть ли жизнь на десктопе?Евгений ЖарковMCTS: Silverlight 4, Development
  • 3. Out of browser (OOB)Управление окномНастройка внешнего вида окнаРазмещения HTML внутри приложенияОкна уведомленийDigital Rights Management (DRM)Расширенные праваДоступ к файловой системеCOMИнтегрированная возможность обновления
  • 10. Тихая установка 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 commandlinee.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.Деинсталляция/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
  • 11. Тихая установка XAPУстановкаsllauncher.exe /install:"{LocalPathToXapFile}\Yourfile.xap" /origin:"{urltoxapfile}/Yourfile.xap" /shortcut:desktop+startmenuАвтозапуск"%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"
  • 12. Тихая установка 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.
  • 13. Тихая установка SilverlightРезультирующая строкаSilverlight.exe /q /doNotRequireDRMPrompt
  • 14. NSIS Script ExampleName “Test Out of Browser Installer"OutFile“TextOOBInstaller.exe"InstallDir "$PROGRAMFILES\TestOOB"XPStyle onSectionSetOutPath "$INSTDIR"SetOverwriteifnewer 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
  • 15. 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"
  • 17. 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)
  • 18. Многоязычный интерфейсДобавление поддерживаемых культур в файл проекта<?xmlversion="1.0"encoding="utf-8"?><ProjectToolsVersion="4.0"DefaultTargets="Build"xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <ConfigurationCondition=" '$(Configuration)' == '' ">Debug</Configuration> <PlatformCondition=" '$(Platform)' == '' ">AnyCPU</Platform><!– настройки --><TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion> <SilverlightApplication>true</SilverlightApplication> <SupportedCultures>en-US,ru-RU,uk-UA</SupportedCultures> <XapOutputs>true</XapOutputs>
  • 22. Многоязычный интерфейсРегистрация ресурса publicclassLocalizationResource : INotifyPropertyChanged {privatestaticLocalization.Strings resource = newLocalization.Strings();publicLocalization.Strings Strings {get { return resource; }set { OnPropertyChanged("Strings"); } } #regionINotifyPropertyChanged MemberspubliceventPropertyChangedEventHandlerPropertyChanged;privatevoidOnPropertyChanged(stringpropertyName) {if (PropertyChanged != null) {PropertyChanged(this, newPropertyChangedEventArgs(propertyName)); } } #endregion}
  • 23. Многоязычный интерфейсПереключение языка UIThread.CurrentThread.CurrentUICulture = newCultureInfo("uk-UA"); ((LocalizationResource)Application.Current.Resources["Localization"]).Strings = newMyApplication.Localization.Strings();
  • 24. COMПодключаем пространство именusingSystem.Runtime.InteropServices.Automation;Создаем файлы в любом месте на ПКusing (dynamicfsoCom = 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();}
  • 25. COMПиним приложение на панель задачusing (dynamicShellApplication = ComAutomationFactory.CreateObject("Shell.Application")){dynamiccommonPrograms = ShellApplication.NameSpace(23);stringallUsersPath = 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(); } }}
  • 26. COMДобавляем OOB-приложение в автозагрузкуusing (dynamicShellApplication = ComAutomationFactory.CreateObject("Shell.Application")){dynamiccommonPrograms = ShellApplication.NameSpace(11);stringallUsersPath = commonPrograms.Self.Path;dynamic directory = ShellApplication.NameSpace(allUsersPath + @"\Programs");dynamic link = directory.ParseName(Deployment.Current.OutOfBrowserSettings.ShortName + ".lnk");stringOOBLink = link.Path;using (dynamicWShell = 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."); }}
  • 27. COMРабота с ODBCusing (dynamicIDbConnection = ComAutomationFactory.CreateObject("ADODB.Connection"))using (dynamicIDbCommand = 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();}
  • 28. Тихая установка MSSQLExpresssqlexpr32.exe -q /norebootchk /qnREBOOT=ReallySuppressINSTANCENAME="name" ADDLOCAL=ALLSECURITYMODE=SQL SAPWD="password" SQLAUTOSTART=1 DISABLENETWORKPROTOCOLS=0Compact Editionmsiexec /quit /i SSCERuntime-ENU-x86.msi
  • 30. Silverlight COM ToolkitCopyComToolkit.IO.File.Copy(@"c:\AnyDir\AnyFile.ext", @"c:\AnyDir\AnyFile2.ext", true);Existsbool exist = ComToolkit.IO.File.Exists(@"c:\AnyDir\AnyFile.ext");WriteAllBytesstring[] contents = //some lines of text...ComToolkit.IO.File.WriteAllLines(@"c:\AnyDir\AnyFile.ext", bytes);OpenAdoFileStream stream = ComToolkit.IO.File.Open(@"c:\AnyDir\AnyFile.ext", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);http://silverlightcom.codeplex.com/
  • 31. Silverlight COM ToolkitComToolkit.DatastringconnectionString = @"Provider=SQLOLEDB;DataSource=servername\sqlexpress;InitialCatalog=databasename;User ID=username; Password=password";using (var connection = newComToolkit.Data.AdoConnection(connectionString)) { connection.Open(); varcommand = connection.CreateCommand(); command.CommandText= "SELECT MyColumn FROM MyTable"; varreader = command.ExecuteReader(); while(reader.Read()) { objectbyindex = reader[0]; objectbystring = reader["MyColumn"]; //для работы с динамическими свойства reader должен быть объявленкак dynamic//object bydynamic = reader.MyColumn;} }http://silverlightcom.codeplex.com/
  • 32. Silverlight COM ToolkitАсинхронный ComToolkit.DataprivateComToolkit.Data.AdoConnection connection; privatevoidExecuteReaderAsyncSample() {connection = newComToolkit.Data.AdoConnection(connectionString); connection.Open(); varcommand = connection.CreateCommand(); command.CommandText= "SELECT MyColumn FROM MyTable";command.ExecuteReaderCompleted+= newEventHandler<ComToolkit.Data.ExecuteReaderCompletedEventArgs>(command_ExecuteReaderCompleted); command.ExecuteReaderAsync(); } voidcommand_ExecuteReaderCompleted(object sender, ComToolkit.Data.ExecuteReaderCompletedEventArgs e) { //TODO: обрабатываем результат}http://silverlightcom.codeplex.com/
  • 34. XML Paper Specification(XPS)Позитивные факторыВ основе лежит ZIP, XML, XAML. Разработан Microsoft и Ecma International, 2006 годВозможность относительно легкой конвертации в XAMLРодная поддержка в Windows Vista/7Негативные факторыWindows XP SP2 требует наличие .NET Framework 3 иXPS Document Viewer
  • 35. PDFПозитивные факторыБесплатные компоненты для обработки PDF-документаВозможность разместить документ в WebBrowserпри наличии Adobe Acrobat плагинаНегативные факторыПлатные компоненты для обработки и отображения в Silverlight-приложении
  • 36. HTMLПозитивные факторыВозможно разместить внутри элемента управления WebBrowserНегативные факторыНевозможно открывать локальные файлы внутри WebBrowserНевозможно задать заголовочную информацию в WebBrowserНевозможно открыть MHT-файлыСледует собирать все ресурсы в единый HTML-файл, включая изображения, используя Data URI, который имеет ограничение в 32КБ
  • 37. Microsoft Office (Word, Excel, PowerPoint)Позитивные факторыРабота с документами через COMНегативные факторыОтсутствует родная поддержкав Silverlight
  • 38. Microsoft Office (Word, Excel, PowerPoint)Пример обработки Word документаusing(dynamic word = AutomationFactory.CreateObject("Word.Application")){intwdFormatWebArchive = 9; // MHT fileformatintwdDoNotSaveChanges = 0; // WdSaveOptions do not save valueusing(dynamic document = word.Documents.Open(tempDoc)) {document.SaveAs("C:\t.doc", refwdFormatWebArchive); }word.Quit(refwdDoNotSaveChanges);}
  • 39. События Office Пример обработки Word документаdynamic word = AutomationFactory.CreateObject("Word.Application");word.Visible = true;AutomationEventsearchEvent = AutomationFactory.GetEvent(word, "Quit");searchEvent.EventRaised += (s, a) =>{MessageBox.Show("Quit");};dynamic document = word.Documents.Open("C:\test.doc");
  • 40. Потоки и BackgroundWorkervarbw = newBackgroundWorker();bw.WorkerReportsProgress = true;bw.DoWork+= (s, a) => {varworker = sender asBackgroundWorker;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(newDictionary<string, object> { { "file", "test.doc"}, { "region", "Ukraine"} });
  • 41. Navigation FrameworkПодключение пространства имен в XAML<UserControlxmlns="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">
  • 42. Navigation FrameworkДобавление Frame<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>Переход на другую страницуNavigationService.Navigate(newUri("/INeedThisPage", UriKind.Relative));
  • 43. Управление окномОграничение размера окна// App.xamlprivatevoidApplication_Startup(object sender, StartupEventArgs e){this.RootVisual= newMainPage();App.Current.Host.Content.Resized += (s, a) => {App.Current.MainWindow.Height = 650;App.Current.MainWindow.Width = 1000; };}Развернуть окноApp.Current.MainWindow.WindowState= WindowState.Maximized;
  • 44. Notification Windowvar block = newTextBlock();block.Text = "Wassup!";varnw = newNotificationWindow();nw.Height = 50;nw.Width = 300;nw.Content = block;nw.Show(3000);
  • 45. Поздравляю, вы пережили этот докладЕвгений Жарковeu.zharkov@gmail.com@2j2eСлушай подкаст2Гига