Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

06 net saturday eugene zharkov ''silverlight. to oob or not to oob''


Published on

Published in: Technology, Business
  • Be the first to comment

  • Be the first to like this

06 net saturday eugene zharkov ''silverlight. to oob or not to oob''

  1. 1. Silverlight. To OOB or not to OOB<br />Евгений Жарков<br />Silverlight MVP/MCTS<br />
  2. 2. Silverlight<br />Windows Phone 7<br />ПК<br />Браузер<br />Вне браузера <br />
  3. 3. Out of browser (OOB)<br />Управление окном<br />Настройка внешнего вида окна<br />Размещения HTML внутри приложения<br />Окна уведомлений<br />Digital Rights Management (DRM)<br />Расширенные права<br />Доступ к файловой системе<br />COM<br />Интегрированная возможность обновления<br />
  4. 4. Активация OOB<br />
  5. 5. КонфигурацияOOB<br />
  6. 6. Инсталляция<br />Довели до ума<br />
  7. 7.
  8. 8. Установка доверенных приложений<br />
  9. 9. Подпись XAP<br />
  10. 10. Тихая установка XAP<br />Инсталляция<br />/install:"xapFile" – where xapFile is the file name/file path to the .xap file., E.g. /install:"c:tempsample.xap"<br />/origin:"xapURI" – where xapURI is the URI where the .xap file would've come from if not installed at the commandline<br />e.g. /origin:"" .  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:.<br />/overwrite -- (optional) Overwrites any previously installed .xap with that xapURI.<br />Деинсталляция<br />/uninstall  – Uninstalls the application specified in /origin. This is the same /origin value that was used to install the app originally.<br />/origin:"xapURI" – same as /origin for the install case<br />
  11. 11. Тихая установка XAP<br />Установка<br />sllauncher.exe <br />/install:"{LocalPathToXapFile}Yourfile.xap" <br />/origin:"{urltoxapfile}/Yourfile.xap" <br />/shortcut:desktop+startmenu<br />Автозапуск<br />"%ProgramFiles%Microsoft Silverlightsllauncher.exe" <br />/emulate:"Yourfile.xap" <br />/origin:""<br />Деинсталляция<br />"%ProgramFiles%Microsoft Silverlightsllauncher.exe" <br />/uninstall <br />/origin:""<br />
  12. 12. Тихая установка Silverlight<br />/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.<br />/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.<br />/ignorewarnings - non-fatal warnings will not be reflected in the quiet installer return code but will instead return zero indicating success.<br />/noupdate - disables the Silverlight internal auto-updater.<br />/qu - quiet uninstall. This uninstalls Silverlight without seeing the GUI.<br />
  13. 13. Тихая установка Silverlight<br />Результирующая строка<br />Silverlight.exe /q /doNotRequireDRMPrompt<br />
  14. 14. NSIS Script Example<br />Name “Test Out of Browser Installer"<br />OutFile “TextOOBInstaller.exe"<br />InstallDir "$PROGRAMFILESTestOOB"<br />XPStyle on<br />Section<br />SetOutPath "$INSTDIR"<br />SetOverwriteifnewer<br /> File "Silverlight.exe"<br />ExecWait "$INSTDIRSilverlight.exe /q /doNotRequireDRMPrompt"<br /> File “TestOOB.xap"<br />ExecWait '"$PROGRAMFILESMicrosoft Silverlightsllauncher.exe" /install:"$INSTDIRTestOOB.xap" <br /> /origin:"" <br /> /shortcut:desktop+startmenu'<br />SectionEnd<br />
  15. 15. Batch Script<br />:: Is this a 64-bit machine?<br />@echo off<br />if exist "%ProgramFiles(x86)%" (<br />:: We're on 64-bit<br /> set sllauncherlocation="%ProgramFiles(x86)%Microsoft Silverlightsllauncher.exe"<br />) else (<br />::We're on 32-bit<br /> set sllauncherlocation="%ProgramFiles%Microsoft Silverlightsllauncher.exe"<br />)<br />:: run SL<br />%sllauncherlocation% /overwrite /emulate:“TestOOB.xap" /origin:"http://blabla/TestOOB.xap"<br />
  16. 16. Мои документы<br />我的文件<br />My Documents<br />EigeneDateien<br />Mes documents<br />Documents<br />Мои документы<br />Τα έγγραφά μου<br />
  17. 17. Batch Script User Folder<br />Извлекаем правильный адрес директории “Мои документы” из реестра<br />FOR /F "tokens=3 delims= " %%G IN ('REG QUERY "HKCUSoftwareMicrosoftWindowsCurrentVersionExplorerShell Folders" /v "Personal"') DO (SET docsdir=%%G)<br />
  18. 18. Многоязычный интерфейс<br />Добавление поддерживаемых культур в файл проекта<br /><?xmlversion="1.0"encoding="utf-8"?><br /><ProjectToolsVersion="4.0"DefaultTargets="Build"xmlns=""><br /> <PropertyGroup><br /> <ConfigurationCondition=" '$(Configuration)' == '' ">Debug</Configuration><br /> <PlatformCondition=" '$(Platform)' == '' ">AnyCPU</Platform><br /><!– настройки --><br /><TargetFrameworkVersion>v4.0</TargetFrameworkVersion><br /> <SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion><br /> <SilverlightApplication>true</SilverlightApplication><br /> <SupportedCultures>en-US,ru-RU,uk-UA</SupportedCultures><br /> <XapOutputs>true</XapOutputs><br />
  19. 19. Многоязычный интерфейс<br />Добавляем ресурсы с локализованным текстом<br />
  20. 20. Многоязычный интерфейс<br />Установить модификатор доступа в Public<br />
  21. 21. Многоязычный интерфейс<br />Регистрация ресурса<br /><Application<br />xmlns=""<br />xmlns:x=""<br />xmlns:local="clr-namespace:MyApplication"<br />x:Class=“MyApplication.App"><br /> <Application.Resources><br /><local:LocalizationResource x:Key="Localization" /><br /> </Application.Resources><br /></Application><br />
  22. 22. Многоязычный интерфейс<br />Регистрация ресурса<br /> publicclassLocalizationResource : INotifyPropertyChanged<br /> {<br />privatestaticLocalization.Strings resource = newLocalization.Strings();<br />publicLocalization.Strings Strings<br /> {<br />get { return resource; }<br />set { OnPropertyChanged("Strings"); }<br /> }<br /> #regionINotifyPropertyChanged Members<br />publiceventPropertyChangedEventHandlerPropertyChanged;<br />privatevoidOnPropertyChanged(stringpropertyName)<br /> {<br />if (PropertyChanged != null)<br /> {<br />PropertyChanged(this, newPropertyChangedEventArgs(propertyName));<br /> }<br /> }<br /> #endregion<br />}<br />
  23. 23. Многоязычный интерфейс<br />Переключение языка UI<br />Thread.CurrentThread.CurrentUICulture = newCultureInfo("uk-UA");<br /> ((LocalizationResource)Application.Current.Resources["Localization"]).Strings = newMyApplication.Localization.Strings();<br />
  24. 24. COM<br />Подключаем пространство имен<br />usingSystem.Runtime.InteropServices.Automation;<br />Создаем файлы в любом месте на ПК<br />using (dynamicfsoCom = AutomationFactory.CreateObject("Scripting.FileSystemObject"))<br />{<br />dynamic file = fsoCom.CreateTextFile(@"c:test.txt", true);<br />file.WriteLine("Bloody Hell!");<br />file.WriteLine("Silverlight is writing to C:");<br />file.Close();<br />}<br />
  25. 25. COM<br />Пиним приложение на панель задач<br />using (dynamicShellApplication = ComAutomationFactory.CreateObject("Shell.Application"))<br />{<br />dynamiccommonPrograms = ShellApplication.NameSpace(23);<br />stringallUsersPath = commonPrograms.Self.Path;<br />dynamic directory = ShellApplication.NameSpace(allUsersPath + @"Accessories");<br />dynamic link = directory.ParseName("Calculator.lnk");<br />dynamic verbs = link.Verbs();<br />for (int i = 0; i < verbs.Count(); i++)<br /> {<br />dynamic verb = verbs.Item(i);<br />if (verb.Name.Replace(@"&", string.Empty).ToLower() == "pin to taskbar")<br /> {<br />verb.DoIt();<br /> }<br /> }<br />}<br />
  26. 26. COM<br />Добавляем OOB-приложение в автозагрузку<br />using (dynamicShellApplication = ComAutomationFactory.CreateObject("Shell.Application"))<br />{<br />dynamiccommonPrograms = ShellApplication.NameSpace(11);<br />stringallUsersPath = commonPrograms.Self.Path;<br />dynamic directory = ShellApplication.NameSpace(allUsersPath + @"Programs");<br />dynamic link = directory.ParseName(Deployment.Current.OutOfBrowserSettings.ShortName + ".lnk");<br />stringOOBLink = link.Path;<br />using (dynamicWShell = ComAutomationFactory.CreateObject("WScript.Shell"))<br /> {<br />WShell.RegWrite(@"HKLMSoftwareMicrosoftWindowsCurrentVersionRun"<br />+ Deployment.Current.OutOfBrowserSettings.ShortName,<br />OOBLink);<br />MessageBox.Show("Please restart your machine and this application will load on startup.");<br /> }<br />}<br />
  27. 27. COM<br />Работа с ODBC<br />using (dynamicIDbConnection = ComAutomationFactory.CreateObject("ADODB.Connection"))<br />using (dynamicIDbCommand = ComAutomationFactory.CreateObject("ADODB.Command"))<br />{<br />IDbConnection.ConnectionString = "driver={SQL Server};"+ "server=.;uid=sa;pwd=password;database=Northwind";<br />IDbConnection.Open();<br />IDbCommand.ActiveConnection = IDbConnection;<br />IDbCommand.CommandText =<br />@"INSERT INTO [Northwind].[dbo].[Region] <br />                   ([RegionID], [RegionDescription]) VALUES (10, 'BLa')";<br />IDbCommand.Execute();<br />}<br />
  28. 28. Тихая установка MSSQL<br />Express<br />sqlexpr32.exe -q /norebootchk /qnREBOOT=ReallySuppressINSTANCENAME="name" ADDLOCAL=ALLSECURITYMODE=SQL SAPWD="password" SQLAUTOSTART=1 DISABLENETWORKPROTOCOLS=0<br />Compact Edition<br />msiexec /quit /i SSCERuntime-ENU-x86.msi<br />
  29. 29. Silverlight COM Toolkit<br /><br />
  30. 30. Silverlight COM Toolkit<br />Copy<br />ComToolkit.IO.File.Copy(@"c:AnyDirAnyFile.ext", @"c:AnyDirAnyFile2.ext", true);<br />Exists<br />bool exist = ComToolkit.IO.File.Exists(@"c:AnyDirAnyFile.ext");<br />WriteAllBytes<br />string[] contents = //some lines of text...ComToolkit.IO.File.WriteAllLines(@"c:AnyDirAnyFile.ext", bytes);<br />Open<br />AdoFileStream stream = ComToolkit.IO.File.Open(@"c:AnyDirAnyFile.ext", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);<br /><br />
  31. 31. Silverlight COM Toolkit<br />ComToolkit.Data<br />stringconnectionString = @"Provider=SQLOLEDB;DataSource=servernamesqlexpress;InitialCatalog=databasename;User ID=username; Password=password";<br />using (var connection = newComToolkit.Data.AdoConnection(connectionString)) { <br />connection.Open(); <br />varcommand = connection.CreateCommand(); <br />command.CommandText= "SELECT MyColumn FROM MyTable"; <br />varreader = command.ExecuteReader(); <br />while(reader.Read()) { <br />objectbyindex = reader[0]; <br />objectbystring = reader["MyColumn"]; <br />//для работы с динамическими свойства reader должен быть объявлен<br />как dynamic<br />//object bydynamic = reader.MyColumn;<br />} }<br /><br />
  32. 32. Silverlight COM Toolkit<br />Асинхронный ComToolkit.Data<br />privateComToolkit.Data.AdoConnection connection; <br />privatevoidExecuteReaderAsyncSample() {<br />connection = newComToolkit.Data.AdoConnection(connectionString); <br />connection.Open(); <br />varcommand = connection.CreateCommand(); <br />command.CommandText= "SELECT MyColumn FROM MyTable";<br />command.ExecuteReaderCompleted+= new<br />EventHandler<ComToolkit.Data.ExecuteReaderCompletedEventArgs>(command_ExecuteReaderCompleted); <br />command.ExecuteReaderAsync(); } <br />voidcommand_ExecuteReaderCompleted(object sender, ComToolkit.Data.ExecuteReaderCompletedEventArgs e) { <br />//TODO: обрабатываем результат<br />}<br /><br />
  33. 33. Работа с документами<br />
  34. 34. XML Paper Specification(XPS)<br />Позитивные факторы<br />В основе лежит ZIP, XML, XAML. Разработан Microsoft и Ecma International, 2006 год<br />Возможность относительно легкой конвертации в XAML<br />Родная поддержка в Windows Vista/7<br />Негативные факторы<br />Windows XP SP2 требует наличие .NET Framework 3 иXPS Document Viewer<br />
  35. 35. PDF<br />Позитивные факторы<br />Бесплатные компоненты для обработки PDF-документа<br />Возможность разместить документ в WebBrowserпри наличии Adobe Acrobat плагина<br />Негативные факторы<br />Платные компоненты для обработки и отображения в Silverlight-приложении<br />
  36. 36. HTML<br />Позитивные факторы<br />Возможно разместить внутри элемента управления WebBrowser<br />Негативные факторы<br />Невозможно открывать локальные файлы внутри WebBrowser<br />Невозможно задать заголовочную информацию в WebBrowser<br />Невозможно открыть MHT-файлы<br />Следует собирать все ресурсы в единый HTML-файл, включая изображения, используя Data URI, который имеет ограничение в 32КБ<br />
  37. 37. Microsoft Office (Word, Excel, PowerPoint)<br />Позитивные факторы<br />Работа с документами через COM<br />Негативные факторы<br />Отсутствует родная поддержкав Silverlight<br />
  38. 38. Microsoft Office (Word, Excel, PowerPoint)<br />Пример обработки Word документа<br />using(dynamic word = AutomationFactory.CreateObject("Word.Application"))<br />{<br />intwdFormatWebArchive = 9; // MHT fileformat<br />intwdDoNotSaveChanges = 0; // WdSaveOptions do not save value<br />using(dynamic document = word.Documents.Open(tempDoc))<br /> {<br />document.SaveAs("C:t.doc", refwdFormatWebArchive);<br /> }<br />word.Quit(refwdDoNotSaveChanges);<br />}<br />
  39. 39. События Office <br />Пример обработки Word документа<br />dynamic word = AutomationFactory.CreateObject("Word.Application");<br />word.Visible = true;<br />AutomationEventsearchEvent = AutomationFactory.GetEvent(word, "Quit");<br />searchEvent.EventRaised += (s, a) =><br />{<br />MessageBox.Show("Quit");<br />};<br />dynamic document = word.Documents.Open("C:test.doc");<br />
  40. 40. Потоки и BackgroundWorker<br />varbw = newBackgroundWorker();<br />bw.WorkerReportsProgress = true;<br />bw.DoWork+= (s, a) => {<br />varworker = sender asBackgroundWorker;<br />worker.ReportProgress(0, "Сейчас начнем");<br />MessageBox.Show("Работаем");<br />worker.ReportProgress(100, «Закончили");<br />};<br />bw.ProgressChanged+= (s, a) =>{<br />MessageBox.Show("Current state" + a.ProgressPercentage.ToString());<br />// сложные объекты могут передаваться в e.UserState<br /> };<br />bw.RunWorkerCompleted+= (s, a) => {<br />MessageBox.Show("Done");<br />};<br />bw.RunWorkerAsync(newDictionary<string, object> { <br /> { "file", "test.doc"},<br /> { "region", "Ukraine"}<br /> });<br />
  41. 41. Navigation Framework<br />Подключение пространства имен в XAML<br /><UserControl<br />xmlns=""<br />xmlns:x=""<br />xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"<br />xmlns:uriMapper="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation"><br />
  42. 42. Navigation Framework<br />Добавление Frame<br /><navigation:Frame x:Name="ContentFrame" Source="/Action"><br /><navigation:Frame.UriMapper><br /><uriMapper:UriMapper><br /><uriMapper:UriMapping Uri=""MappedUri="/Pages/Action.xaml"/><br /><uriMapper:UriMapping Uri="/{pageName}"MappedUri="/Pages/{pageName}.xaml"/><br /></uriMapper:UriMapper><br /></navigation:Frame.UriMapper><br /></navigation:Frame><br />Переход на другую страницу<br />NavigationService.Navigate(newUri("/INeedThisPage", UriKind.Relative));<br />
  43. 43. Управление окном<br />Ограничение размера окна<br />// App.xaml<br />privatevoidApplication_Startup(object sender, StartupEventArgs e)<br />{<br />this.RootVisual= newMainPage();<br />App.Current.Host.Content.Resized += (s, a) => <br /> {<br />App.Current.MainWindow.Height = 650;<br />App.Current.MainWindow.Width = 1000;<br /> };<br />}<br />Развернуть окно<br />App.Current.MainWindow.WindowState= WindowState.Maximized;<br />
  44. 44. Notification Window<br />var block = newTextBlock();<br />block.Text = "Wassup!";<br />varnw = newNotificationWindow();<br />nw.Height = 50;<br />nw.Width = 300;<br />nw.Content = block;<br />nw.Show(3000);<br />
  45. 45. Хочу работать с архивами<br /><br />ZipOutputStreamzipOutStream = newZipOutputStream(File.Create(""));<br />ZipEntryfileZipEntry = newZipEntry(name); <br />zipOutStream.PutNextEntry(fileZipEntry); <br />FileStreamfileStream= File.Open(filePath, FileMode.Open); <br />byte[] buffer = newbyte[fileStream.Length]; <br />fileStream.Read(buffer, 0, buffer.Length); <br />zipOutStream.Write(buffer, 0, buffer.Length); <br />zipOutStream.CloseEntry(); <br />
  46. 46. Silverlight 5<br />
  47. 47. Поздравляю, вы пережили этот доклад<br />Вопросы<br />?<br />Слушай подкаст<br />2Гига<br />Евгений Жарков<br /><br />@2j2e<br />