|
|
Не забывайте про записи докладчика!
Не забывайте про записи докладчика!
ASP.NET AJAX Improvements: New ASP.NET AJAX features in the ASP.NET 3.5 Extensions release include better browser history support (back/forward button integration, and server-side history management support), improved AJAX content linking support with permalinks, and additional JavaScript library improvements. ASP.NET MVC: This model view controller (MVC) framework for ASP.NET provides a structured model that enables a clear separation of concerns within web applications, and makes it easier to unit test your code and support a TDD workflow. It also helps provide more control over the URLs you publish in your applications, and more control over the HTML that is emitted from them. ASP.NET Dynamic Data Support: The ASP.NET 3.5 Extensions release delivers new features that enable faster creation of data driven web sites. It provides a rich scaffolding framework, and will enable rapid data driven site development using both ASP.NET WebForms and ASP.NET MVC. ASP.NET Silverlight Support: With the ASP.NET 3.5 Extensions release we'll deliver support for easily integrating Silverlight within your ASP.NET applications. Included will be new controls that make it easy to integrate Silverlight video/media and interactive content within your sites. ADO.NET Data Services: In parallel with the ASP.NET Extensions release we will also be releasing the ADO.NET Entity Framework. This provides a modeling framework that enables developers to define a conceptual model of a database schema that closely aligns to a real world view of the information. We will also be shipping a new set of data services (codename "Astoria") that make it easy to expose REST based API endpoints from within your ASP.NET applications.
Смешивается конструирование UI, навигация по UI и бизнес-логика
Back in 1979, Trygve Reenskaug came up with a new architecture for developing interactive applications. In his design, applications were broken into three types of components: models, views, and controllers. The model is responsible for maintaining the state of the application. Sometimes this state is transient, lasting for just a couple of interactions with the user. Sometimes the state is permanent and will be stored outside the application, often in a database. A model is more than just data; it enforces all the business rules that apply to that data. For example, if a discount shouldn’t be applied to orders of less than $20, the model will enforce the constraint. This makes sense; by putting the implementation of these business rules in the model, we make sure that nothing else in the application can make our data invalid. The model acts as both a gatekeeper and a data store. The view is responsible for generating a user interface, normally based on data in the model. For example, an online store will have a list of products to be displayed on a catalog screen. This list will be accessible via the model, but it will be a view that accesses the list from the model and formats it for the end user. Although the view may present the user with various ways of inputting data, the view itself never handles incoming data. The view’s work is done once the data is displayed. There may well be many views that access the same model data, often for different purposes. In the online store, there’ll
Например eShop
P&P = Patterns & Practices. В основе WCSF лежит MVP pattern, а это означает полноценное использование Web-Forms, PostBack etc. Не PostBack, не ViewState нет в MVC. *См. След. слайд*
· MVP Pattern o View is more loosely coupled to the model. The presenter is responsible for binding the model to the view. o Easier to unit test because interaction with the view is through an interface o Usually view to presenter map one to one. Complex views may have multi presenters. · MVC Pattern o Controller are based on behaviors and can be shared across views o Can be responsible for determining which view to display (Front Controller Pattern)
.
Не забывайте про записи докладчика!
DSL = Domain Specific Languages
С помощью System.Web.Abstractions мы можем полностью эмулировать работу IIS-а, заменяя ее часть на фейк.
The term 'Mock Objects' has become a popular one to describe special case objects that mimic real objects for testing. Most language environments now have frameworks that make it easy to create mock objects. What's often not realized, however, is that mock objects are but one form of special case test object, one that enables a different style of testing. In this article I'll explain how mock objects work, how they encourage testing based on behavior verification, and how the community around them uses them to develop a different style of testing.
Visual Studio 2008 - новое в разработке веб-приложений и Microsoft ASP.NET MVC Framework Евгений Марченков Эксперт по технологиям разработки ПО Отдел стратегических технологий Microsoft Corporation
Visual Studio 2008 Новые возможности для Web VS 2008 HTML Designer ASP.NET Data Controls ASP.NET AJAX ASP.NET AJAX Control Toolkit ASP.NET 3.5 Extensions
DEMO Новые возможности для Web
VS 2008 HTML Designer Улучшенный HTML designer Такой же WYSIWYG designer как и в Expression Web Новые возможности: Быстрое переключение между Source/Design view Split view Вложенные Master Pages в Design View Поддержка редактирования CSS Позволяет значительно лучше взаимодействовать дизайнеру с разработчиком
ASP.NET Data Controls ListView Объединяет возможности Repeater и DataGrid: Поддержка большого набора шаблонов Контроль генерируемого HTML DataPager Расширяет функциональность существующих компонент, добавляя paging LinqDataSource LINQ как источник данных
Поддержка AJAX в VS 2008 JavaScript IntelliSense IntelliSense для client-side JavaScript IntelliSense для JSON .asmx веб-сервисов Проверка синтаксиса в build-time-е Отладка и профаилинг JavaScript Улучшенный механизм распознавания JavaScript Breakpoints в .aspx файлах Новый механизм отображения значений переменных Поддержка AJAX Extender Control Во время дизайна можно добавлять extender-ы Все возможности ASP.NET AJAX 1.0 включены в .NET 3.5
ASP.NET AJAX Control Toolkit Отдельный пакет для ASP.NET AJAX Библиотека бесплатных ASP.NET AJAX контролов Скачать можно с http://ajax.asp.net/ Разработана с помощью collaborative source model Все исходные коды доступны бесплатно. Для изменения кода существует специальная лицензия. Писать код могут как сотрудники Microsoft, так и не сотрудники Microsoft Уже сейчас содержит 40 контролов!
ASP.NET 3.5 Extensions Расширение ASP.NET и .NET 3.5 Улучшения ASP.NET AJAX History control ASP.NET MVC Framework ASP.NET Dynamic Data ASP.NET Silverlight Интеграция Новые контролы ADO.NET Data Services (“Astoria”) ADO.NET Entity Framework
MVC Framework
Чем плох данный код? private void OnNewOrderClicked( object sender, EventArgs e ) { TreeNode customerNode = treeView.SelectedNode; Customer customer = customerNode.Tag as Customer; // Create a new order. Order newOrder = new Order(); newOrder.CustomerID = customer.CustomerID; // Show the order form. OrderForm orderForm = new OrderForm( newOrder ); if (orderForm.ShowDialog() == DialogResult.OK) { // Check value of order. if (newOrder.OrderTotal > 1000.0) newOrder.PendingApproval = true; // Create an order node under the customer. TreeNode orderNode = new TreeNode( newOrder.OrderNo ); orderNode.Tag = newOrder; customerNode.Nodes.Add( orderNode ); } }
MVC Design Pattern MVC = Model View Controller Приложение разбивается на 3 компоненты: Model отвечает за бизнес-логику и работу с БД View отвечает за формирование UI Controller Взаимодействует с пользователем Обрабатывает команды пользовательского ввода Взаимодействует с Model Формирует запрос к View и передает данные, полученные с Model
MVC Design Pattern Model Controller View DB 1 2 3 4 Браузер шлет запрос Контроллер взаимодействует с моделью Контроллер вызывает представление Представление формирует новый экран
Page Controller Реализовано в WebForms View - *.aspx Controller – code behind *.cs Model – Business Objects Сложно тестировать без ASP.NET Runtime
Front Controller Единая точка обработки всех обращений
Когда использовать MVC? Высокие требования к качеству Test Driven Development Поддержка нескольких платформ Windows, PDA, Сотовый Контроль над HTML кодом Верстальщики и разработчики Прозрачная навигация URL http://musica.ru/Albums/Nightwish/Once Maintainable код (+ Командная работа)
ASP.NET MVC Framework Реализует MVC Design Pattern Интеграция с ASP.NET Использование существующей инфраструктуры Сaching, session, profile Поддержка статических и динамических языков C#, Ruby.NET… Интеграция с Visual Studio 2008 Intellisense, Refactoring, Debugging Project Templates .aspx View можно удобно редактировать в дизайнере Visual Studio
ASP.NET MVC Framework Это не WebForms 4.0 Построен на ASP.NET 2.0 Позволяет использовать подход Test Driven Development (TDD) Хорошо взаимодействует с другими решениями: nHibernate для создания моделей Brail для создания представления Фундаментальная поддержка в System.Web уже есть!
DEMO Hello World!
MVC Framework Как это работает?
MVC
Немного больше деталей... Web Server получает запрос с браузера Определяется путь к Controller-у Controller активизируется Вызывается метод на Controller-е Controller взаимодействует с моделью и пользовательским вводом Controller создает View, передавая ViewData, на основе которой и формируется View Все URL-ы на View ссылаются на Controller-ы и их Action-ы
Еще больше деталей - Request Flow Каждый этап под контролем
Пример работы MVC Framework Browser Web Server (IIS) ProductsController (Controller) http://myserver.com/Products/Edit/5 ViewData ActionLink (Action = “Edit”. ID=5) List LINQ Product ViewData ActionLink (Action = “Update”. ID=5)
DEMO Жизненный цикл запроса
MVC Framework Популярные вопросы
Ух ты, здорово. Есть, что выбрать. Только что? В каких случаях я должен использовать WebForms, а не MVC?
Преимущества ASP.NET MVC Понятные URL-ы HTML под контролем Интеграция с ASP.NET Используются все те же самые provider-ы Membership, Session, Caching, и т.д. ASP.NET Designer Surface в VS2008 MVC легко расширяема Любая часть может быть заменена своей Test Driven Development
Что насчет P&P? Некоторые мои клиенты используют Web Client Software Factory (WCSF). Должны ли они переходить на MVC?
По моему я что-то подобное уже когда-то слышал? Какая разница между MVP и MVC?
MVC Model View Controller
MVP Model View Presenter View Interface
MVP vs MVC MVP Pattern Слабая связанность View с Model Более простое unit тестирование Обычно View и Presenter соотносятся 1:1, но более сложные View могут иметь несколько Presenter-ов MVC Pattern Один Controller может использоваться для нескольких View Controller может отвечать за выбор View (Front Controller)
Widget-ы? Есть ли они? Что насчет компонент для MVC?
Что насчет Microsoft AJAX Можно ли его использовать с MVC?
Что насчет Microsoft AJAX и всех его составляющих? Например UpdatePanel
DEMO AJAX TaskList
Хотим релиз! Когда выйдет MVC RTM?
Представляем… Microsoft Visual Business Enabler Studio 2008R3v2 September Technical Preview Refresh MSVBES2k8R3v2lptrczstr для краткости
Новый инсталятор…
MVC безопасен? Что насчет безопасности?
MVC масштабируем? Что насчет производительности и масштабируемости?
MVC Framework Копаем глубже
Расширяемость Views Controllers Models Routes Всё можно встраивать!
Controller URL-ы ссылаются на действия Controller-а, а не на страницы Controller исполняет логику, выбирает View Все Public методы доступны из вне public void ShowPost(int id) { Post p = PostRepository.GetPostById(id); if (p != null) { RenderView("showpost", p); } else { RenderView("nosuchpost", id); } }
Модель Для создания модели вы можете использовать любой удобный вам механизм ADO.NET LINQ to SQL nHibernate Работа с созданной моделью происходит так же, как и в простом случае обращение к DAL-у
URL маршрутизация (Routes) Разработчики добавляют пути в глобальную таблицу путей RouteTable Путь задается шаблоном, по которому формируется RouteData, состоящая из пар ключ/значение protected void Application_Start(object sender, EventArgs e) { RouteTable.Routes.Add( new Route("blog/bydate/{year}/{month}/{day}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary { {"controller", "blog"}, {"action", "show"} }, Constraints = new RouteValueDictionary { {"year", @"\d{1.4}"}, {"month", @"\d{1.2}"}, {"day", @"\d{1.2}"}} });}
ViewPage Используется для отображения информации Не для валидации входных данных Можно использовать .ascx, .aspx, .css, .master ViewPage можно заменить любой другой технологией для создания View nVelocity, Brail, NHaml и т.д. Controller задаёт данные для View Эти данные могут быть типизированные и не типизированные
ViewEngineBase View Engine генерирует View на выходе По умолчанию используются WebForms Можете написать свой View Engine У MVCContrib на CodePlex есть реализация для Brail, Nvelocity NHaml одно из интересных решений View Engines используются для: Создания своего DSL для более простого создания HTML Генерирывания View абсолютно разных mime/types Изображения, RSS, JSON, XML, OFX, VCards, и т.п.
DEMO Northwind CRUD
MVC Framework Test Driven Development
Интерфейсы и TDD Эмуляция (System.Web.Abstractions) HttpContextBase, HttpResponseBase, HttpRequestBase Расширяемость (System.Web.MVC) IController IControllerFactory IRouteHandler ViewEngineBase
Mock Frameworks Mock Object – Объект, который имитирует реальный объект с целью тестирования Популярные framework-и для .NET TypeMock Moq Rhino.Mock Реализуют эмуляцию IIS-а для MVC Framework-а
Тестируем Controller Actions Нет специальных требований для тестирования в ASP.NET runtime. Используйте RhinoMocks или TypeMock Создавайте тест версии частей runtime-а, которые вы хотите эмулировать [TestMethod] public void ShowPostsDisplayPostView() { TestPostRepository repository = new TestPostRepository(); TestViewEngine viewEngine = new TestViewEngine(); BlogController controller = new BlogController(…); controller.ShowPost(2); Assert.AreEqual("showpost",viewEngine.LastRequestedView); Assert.IsTrue(repository.GetPostByIdWasCalled); Assert.AreEqual(2, repository.LastRequestedPostId); }
DEMO Test Driven Development
Заключение Это нет Web Forms 4.0 Это альтернативное решение. Как машина в сравнении с мотоциклом. Простота и сложность варьируется вами Фундаментальная технология Является частью System.Web Хорошо взаимодействует с другими решениями: nHibernate для создания моделей Brail для создания представления Всё что вы хотите для создания контроллеров Текущая версия CTP 2 (Март 2008)
Ссылки по теме ASP.NET www.asp.net - официальный сайт ASP.NET www.asp.net/mvc - официальный сайт MVC Framework www.asp.net/downloads/3.5-extensions/ - ASP.NET 3.5 Extensions Евгений Марченков Эксперт по технологиям разработки ПО Email: evgenym@microsoft.com Блог: blogs.gotdotnet.ru/personal/emarchenkov/ http://weblogs.asp.net/scottgu/
“ScottGu”
When I was born…
“Gu”
“Его Gu-нейшество”
“Сэр” А не добавить ли нам нимб?
“Master Chief Gu”
Удачи, Пишите хороший код, и будьте на связи! evgenym@microsoft.com Евгений Марченков
© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Summary: Евгений Марченков, Дни разработчиков, весна 2008, http://www.microsoft.com/rus/msdn/events/devdays/default.mspx
| URL: |
No comments posted yet
Comments