ASP.NET 4.0 in Practice phần 2 ppsx

50 796 0
ASP.NET 4.0 in Practice phần 2 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

25TECHNIQUE 2 Form validation mind that they’re activated only if a value is present in the field that the validator is associated with. Remember, you always need to include a RequiredFieldValidator if you want to make sure an empty value won’t bypass your controls. Validator controls use adaptive rendering, so they’ll send client-side JavaScript code to recognized browsers. You need to access the IsValid property of the Page class to ensure that validation is also done server side, as shown in the following listing. Markup: Your first name: <asp:textbox runat="server" ID="FirstName" /> <asp:RequiredFieldValidator runat="server" ID="FirstNameValidator" ControlToValidate="FirstName" ErrorMessage="First name is required" Text="*" /> <br /> <asp:ValidationSummary ID="MyValidationSummary" runat="server" HeaderText="You need to check:" /> C#: void HandleSubmit(Object sender, EventArgs e) { if (Page.IsValid) { } } VB: Sub HandleSubmit(sender as Object, e as EventArgs) If Page.IsValid then#3 End If End Sub ValidationSummary has a boolean property called ShowMessageBox that pops up an alert message when the validation isn’t passed. If you set this property to true and ShowSummary to false , you can display only this alert. Default values are respectively false and true . Figure 1.10 shows you the results of the code in listing 1.3 if the user has omitted the value for the field “Your first name” and PostBack has been invoked. Other controls in this group do about the same thing; the difference is only in the property you will use. If you need more examples of validator controls, check out the ones included in the MSDN documentation at http://msdn.microsoft.com/en-us/ library/aa310913(VS.71).aspx. Listing 1.3 Validation controls at work Control to act against Summary of validation errors Collection to bind to Your code logic here 26 CHAPTER 1 Getting acquainted with ASP.NET 4.0 DISCUSSION Input validation is a key factor in today applications. Both the client-side and server- side validation offered by validator controls in Web Forms is a killer feature for web applications, and you get it by default. It’s just one of the free services the ASP.NET infrastructure lets you use to enhance your UI. Now that you’ve validated the form, the next step is to manipulate the page charac- teristics, such as the header (title, meta, or keywords), style, and CSS. Page header, styling, and CSS Programmatic access to the page header can help when you need to set some proper- ties via code. A common problem when dealing with a dynamic page is that often the page is composed of data coming from a database. In situations like this, you need to set the page headers programmatically. By manipulating page headers you can dynamically set the title, style sheets, or syndication feeds. PROBLEM You need to access the page headers from your code and programmatically set the val- ues that correspond to the kind of header you’re manipulating. SOLUTION Starting with ASP.NET 2.0, you can manipulate page headers if you add a runat="server" attribute to the <head /> tag. If you need to set the page title, the Title property on the Page class lets you access Page.Header.Title and programmat- ically set this information. Version 4.0 lets you set meta tags for search engines. You have to use the Page.Keywords and Page.Description properties to set the meta keywords and description respectively, as in the following listing. C#: Page.Title = "My Page title"; Page.Keywords = "list separated by commas"; Page.Description = "Page description, shown by search engines."; Listing 1.4 Dynamically setting page headers Figure 1.10 A Web Form with validator controls. As you can see, the validator generates a warning (dis- played in red, by default) and blocks the form from being submitted. TECHNIQUE 3 27TECHNIQUE 3 Page header, styling, and CSS VB: Page.Title = "My Page title" Page.Keywords = "list separated by commas" Page.Description = "Page description, shown by search engines." The strongly typed model provided by the Page class is powerful. You can manipulate the corresponding headers using a simple approach, from anywhere in your page, before the whole page is rendered. This code is especially helpful when you’re dealing with dynamic content coming from a database. Styling and CSS All web controls use a common approach to styling because they all derive from the WebControl class. You can modify some properties directly, using properties like Back- Color , ForeColor , BorderColor , or Font . When you need to apply styles to controls, it’s always better to rely on a CSS for formatting from a centralized point. WebControl (and derived controls, like Label and TextBox ) offers a CssClass prop- erty, which is a string containing the CSS class that you’re going to use. If you’re using CSS IDs as a way to add style to your markup, you need to take a look at the new features for ClientID that are included in ASP.NET 4.0 (which we’ll discuss in chapter 5). In any case, it’s better to use CSS classes than CSS IDs; if multiple pieces of markup are being generated by iteration (such as data coming from a database into a page list), you’ll probably end up with autogenerated IDs anyway. Unfortunately, ASP.NET doesn’t provide a mechanism to register an external CSS directly. You can always create an instance of the HtmlLink class and add the new control to the Controls collection of the Page.Header property, as shown in the fol- lowing listing. C#: HtmlLink cssLink = new HtmlLink(); cssLink.Href = "/styles/styles.css"; cssLink.Attributes.Add("rel", "stylesheet"); cssLink.Attributes.Add("type", "text/css"); Page.Header.Controls.Add(cssLink); VB: Dim cssLink As New HtmlLink() cssLink.Href = "/styles/styles.css" cssLink.Attributes.Add("rel", "stylesheet") cssLink.Attributes.Add("type", "text/css") Page.Header.Controls.Add(cssLink) As previously noted, this technique is useful when you don’t know the path to the CSS file, and you have to determine it at runtime. An example is when you need to person- alize a link based on user preference. Registering RSS feeds Remember that you can use the code shown in listing 1.5 to add other kinds of HtmlLink controls, such as a reference to Internet Explorer (IE) Web Slice or an RSS (Really Simple Syndication) feed. Listing 1.5 Registering a CSS 28 CHAPTER 1 Getting acquainted with ASP.NET 4.0 RSS or Atom feeds are quite popular these days in web applications because they let users subscribe to updates and receive them in their news aggregator. This process is similar to what mail readers do. RSS differs from Atom in terms of format, but both are XML based. You can dynamically register the path to RSS or Atom feeds by using code similar to that shown in the following listing. C#: HtmlLink rssLink = new HtmlLink(); rssLink.Href = "/rss.aspx"; rssLink.Attributes.Add("rel", "alternate"); rssLink.Attributes.Add("type", "application/rss+xml"); Page.Header.Controls.Add(rssLink); VB: Dim cssLink As New HtmlLink() rssLink.Href = "/rss.aspx" rssLink.Attributes.Add("rel", "alternate") rssLink.Attributes.Add("type", "application/rss+xml") Page.Header.Controls.Add(rssLink) If you’re using Web Slice, you need to set the rel attribute to default-slice and type to application/x-hatom . Web Slice is a special feature of IE 8.0+; for more infor- mation, go to http://www.ieaddons.com/. DISCUSSION You’ll usually need to generate and add controls at runtime in the page header when you want to provide additional interactions to users visiting your pages. Syndication feeds, page title or page description, and dynamic CSS are used to leverage the dynamic nature of ASP.NET and let your user get what he needs to fully use your web application, but with his own personalization. 1.6 Summary Almost everything we’ve talked about in this chapter applies to all versions of ASP.NET. That said, ASP.NET 4.0 does introduce some interesting features, but the pillars of this technology are the same as those that were used in the first version. If you’re relatively new to ASP.NET, this chapter should have helped you visualize the big picture sur- rounding this technology. ASP.NET is built on top of .NET Framework and gains a lot of its features from this base. .NET Framework is full of interesting technologies, such as the Entity Frame- work, WCF, and ADO.NET, and you can leverage them in your web application to enhance functionalities. If you don’t know about these yet, you’ll find specific exam- ples of each of them in the upcoming chapters. Keep in mind that ASP.NET is built with extensibility as a pillar, so the succeeding chapters will contain advanced implementations of what you’ve learned in this one. Listing 1.6 Programmatically adding an RSS feed to the current page application/atom+ xml for Atom 29Summary You’ll find concepts like Web Forms, PostBack, ViewState, HttpRuntime , and IIS inte- gration in every new step you’ll take. This chapter didn’t contain a lot of examples, but don’t worry. In the following chapters, you’ll find plenty of tips and code to implement the most common scenarios in web applications. Now you’re ready for chapter 2. We’re going to delve into an analysis of the data access options available in . NET Framework 4.0 and specifically for ASP.NET 4.0. 30 Data access reloaded: Entity Framework When databases are in place, accessing data becomes a key concern. The way you communicate with the database and, more importantly, the way you represent data inside your application becomes one thing that can shift your application from one that works to a real success. You have a lot of options. The first option is to use ADO.NET objects, like con- nections, adapters, readers, and datasets. This approach is easy to understand and enables you to immediately start writing code. Another option is to use ADO.NET classes to interact with the database and then create your own classes (object model) to represent data inside the application. The initial learning curve with such a pattern is higher compared with the previous one, but in the long run, this pattern ensures higher maintainability. This chapter covers ■ Designing an application ■ Understanding an ORM ■ Learning Entity Framework ■ Reading and updating data with Entity Framework 31Designing an application The last option is to use an ORM tool, which hides the complexity of using ADO.NET classes and lets you work only with objects in your application. An ORM tool includes the best of the previous approaches because it offers immediate and sustained productivity. Microsoft has developed an ORM whose name is Entity Framework. Microsoft touts Entity Framework as its best practice for data access. That’s why we focus on Entity Framework only in this chapter. If you want to take a look at how to perform data access using the classic ADO.NET approach, take a look at appendix A. Understanding data access using Entity Framework is vital because it lays the foun- dation for the next chapter and for the rest of the book. We’ll be using Entity Framework in the chapters about data binding, authentication, authorization, and performance. If you’re an experienced Entity Framework developer, you can skip this chapter and go straight to chapter 3. If you’re new to this topic, you’ll find this chapter to be a good starting point to build on. Before delving into the details of using Entity Framework, let’s take a step back and analyze the pattern you should follow when you develop an application. By looking at the pattern up close, you’ll clearly understand where Entity Framework stands in your application design. 2.1 Designing an application In this chapter, you’ll create an application that handles orders for the Northwind database (more information about it is in the sidebar). This database contains data about customers and products stored in several tables: Orders, Customers, Order Details, and Products. The tables that contain this data are Orders, Customers, Order Details, and Products. You need to create an internal network of classes (the object model) that holds data that can be filled from a query in the database. These classes also need to handle data that updates the database. The classes are Order , Customer , Order_Detail , and Product . They contain properties that represent data on the database and that are useful for business. These classes hide the complexity of the database structure from the business code (also known as the Business Logic Layer or BLL), let- ting the code communicate only with them and with a specific layer that will be responsible for interacting with the database (the Data Access Layer or DAL). The Business Logic Layer knows nothing about the database and interacts only with the four classes. The DAL is responsible for communicating with the database. With this nifty organization, the classes we create become the business Logic Layer database. Fig- ure 2.1 shows an example of this design. Database Business layer Data access layer Order Customer Model OrderDetail Product Figure 2.1 The Business Logic Layer uses classes in the model and then persists modifications through the Data Access Layer. The business code doesn’t communicate with the database. 32 CHAPTER 2 Data access reloaded: Entity Framework Separating the code inside isolated layers is a technique that guarantees faster devel- opment and, maybe more important, easier maintenance. So far, we’ve said that the model contains classes that in turn contain data that is persisted into the database. But how do you make a model? What techniques do you need to use to build it? The answer is: it depends. 2.1.1 What’s an object model? In many, possibly most, applications, a model can be a simple set of classes that con- tain data coming from a database and that have only a little behavior. This kind of model is known as an object model. Let’s look at a few of the characteristics of the object model classes. DATA VALIDATION One of the behaviors that an object model class contains is data validation. For instance, the Customer class has the CustomerID property. Because it’s the key of the class (and the primary key in the Customers table), this property can’t be null or empty. Placing validation code in the property setter makes sense because it prevents the property from being set with an invalid value. PROPERTY JOINING Another behavior that is commonly added to an object model class is property join- ing. You often need the full customer address in a single string. Writing a piece of code that joins all address-related properties into a string every time you need the cus- tomer’s full address is feasible, but it’s repetitive and error prone. The Customer class contains an additional property, FullAddress , which internally joins the address prop- erties and returns them as a string so you don’t have to write the code to retrieve the full address every time you need it. Why the Northwind database? In this chapter and throughout the rest of the book, we’ll use the Northwind database. Although it’s a simple database, it has lots of useful characteristics. First of all, it represents a real-world scenario but exposes it in a manner that’s pretty easy to un- derstand. Secondly, it’s been around for a long time, and it’s probably the most used demo database in the world. We’ve attended countless conferences and courses and this database is always used. With the advent of SQL Server 2005, Microsoft introduced the AdventureWorks data- base. This database represents a complex scenario and uses lots of SQL server fea- tures. It also has an online transaction processing (OLTP) database and a data warehouse so that every aspect of the business problem is covered. Explaining SQL Server using AdventureWorks is wonderful, but we’re talking about ASP.NET. We need a simpler model that allows us to focus on what matters so the complexity of the database doesn’t bog us down. 33Designing an application CONNECTING CLASSES TO EACH OTHER Classes in an object model are not standalone; they’re connected to each other. For instance, the Order class is connected to Customer and Order_Detail classes and Order_Detail is connected to Product . In a database, tables are connected by foreign key columns. In an object model, referencing another class simply by using a property that acts as a foreign key isn’t the optimal solution because you can directly reference another class using a property of the referenced class type. For example, the Order class keeps a reference to the Cus- tomer class by using the Customer property (we used the Customer name but you can use any name you like) whose type is Customer . If an object must reference multiple objects, you can create an enumeration prop- erty whose type is List<T>, where T is the type of the objects in the collection. For instance, an order must reference a list of details. To do that, The Order class contains the Order_Details property, which is of type List<Order_Detail> . NOTE You don’t have to use List<T> . You can use any other collection classes, like Collection<T> , HashSet<T> , or even the non generic ArrayList . When you’ve completed the design process for the object model relationships, you end up with the model shown in figure 2.2. As I said before, an object model works perfectly well in lots of applications, but its data-only nature is a limitation in complex scenarios. For some applications, you want a higher level of interaction between the object model and the environment. In other words, the object model must contain behavior. 2.1.2 The evolution of the object model: the domain model A domain model is an object model where classes have a lot more behavior. The behav- ior that’s added to domain model classes creates a broad and rich integration between the classes and the environment. Customer Class Order_Detail Class Product Class Order Class Order Details Customer Product Figure 2.2 The Order class is connected to the Customer class by the Customer property. The Order class also contains details through the Order_Details property. Eventually, each detail is connected to the product via the Product property. 34 CHAPTER 2 Data access reloaded: Entity Framework More exactly, a domain model doesn’t involve just classes and their data. It introduces a new design for your application. The classes are integrated in the BLL and commu- nicate with repository modules that are the new gateways to the database. All these classes and modules becomes a single layer: the domain model. The domain model itself doesn’t communicate directly with the database. An infra- structure layer that’s underneath the model does the actual work. This layer hides database communication. The repositories deal with the infrastructure layer, which they use to send commands that retrieve data from a database or update data in it. Fig- ure 2.3 shows the result of such a design. You probably know that because classes are aware of the repositories, they can retrieve data from the database. Because the classes can do this, they offer a brand new range of services to the developers who use them. Not only that, the domain model pattern contains lots of other features that are outside the scope of this book. If you’re interested in knowing more about the domain model, check out the book Domain Driven Design by Eric Evans. Now you know how to effectively layer an application to create a better design and more maintainable code. Layering is the foundation of every successful application and the thing to keep in mind as you progress through the rest of the book. All this discussion about object model and domain model includes a concept that has always remained the same: you have to deal with a database and with objects whose data must be persisted into it. Let’s discover how you can do that using an ORM. Database Domain Model Order Customer OrderDetail Product Infrastructure OrderRepository OrderRepository CustomerRepository Figure 2.3 The domain model comprises the model classes and the repositories. The model uses the infrastructure layer to abstract the physical interaction with the database. [...]... entity using two different contexts 60 CHAPTER 3 Context instance 1 Integrating Entity Framework and ASP.NET Page instance 1 Client Context instance 2 Page instance 2 Figure 3.3 Each time a page is processed, a new instance of the page is created Each instance uses a new context instance without reusing existing ones In this section, we want to emphasize the disconnected way of working because ASP.NET. .. following listing puts this technique into practice Listing 2. 5 Creating a new customer C#: var c = new Customer() { Address = "address", City = "City", CompanyName = "CompanyName", ContactName = "ContactName", ContactTitle = "ContactTitle", Country = "Country", CustomerID = "15455", Fax = "22 222 2", Phone = "23 33333", PostalCode = " 123 445", TECHNIQUE 7 Writing data using Entity Framework 49 Region = "Region"... time to dig deeper into it and see how you can use it in ASP.NET applications Integrating Entity Framework and ASP.NET This chapter covers ■ Handling the context in ASP NET applications ■ Optimizing persistence in ASP NET applications ■ Managing concurrency ■ Optimizing performance In the previous chapter, we talked about the different ways you can design your application We focused mainly on data access... better approach: one context per ASP.NET request 57 Now that we have a gateway to handle the context lifecycle, all we have to do is invoke the methods we just created in the repository CreateContext can be invoked in the page’s Init event and DestroyContext can be invoked in the page’s Unload event The following listing puts this concept into action Listing 3.3 Invoking a repository method to handle... ContextHandler().DestroyContext() End Sub End Class Placing this code in each page isn’t ideal What you can do is create a class and let it inherit from the Page class You put the code in listing 3.3 in the class and let your pages inherit from it Now all your pages can handle context without you having to do it each time The following listing shows how this way makes things simpler Listing 3.4 Invoking repository methods via... CustomerID = "15455", _ Fax = "22 222 2", _ Phone = "23 33333", _ PostalCode = " 123 445", _ Region = "Region" _ } ctx.Customers.AddObject(customer) ctx.SaveChanges() The AddObject method adds the customer instance to the context and marks the instance as Added SaveChanges transforms the added object into a new row in the database Updating the customer is equally simple You can do it in one of two ways You can... classes inherit from the base class Introducing Entity Framework 37 In the database, the concept of inheritance doesn’t exist at all What you can do is create an artifact to simulate inheritance You can create inheritance in the database using one of three methods: ■ ■ ■ Table-per-hierarchy (TPH)—One table contains the data for all the classes in the inheritance hierarchy and usually uses a discriminator... the page is responsible for creating and destroying the context Wouldn’t it be better if the data access code could manage the context instantiation and destruction without us having to write anything in the page or in its base class? That’s the subject of the next section TECHNIQUE 10 Instantiating the context using modules Invoking context creation and disposal methods in the page creates dangerous... the events of the ASP.NET execution pipeline so that you can plug in your logic In our case, we can subscribe to the BeginRequest event to create the context and to the EndRequest event to destroy it You can place the module in the data access assembly, eliminating every circular dependency The following listing shows the code for HttpModule Listing 3.5 Creating the module for handling context lifecycle... perform a LINQ to Entities query against an entity set LINQ to Entities is just a dialect of LINQ that triggers the process that transforms the LINQ query in SQL (instead of performing an in- memory search) Now that you have the fundamentals, let’s start writing the query that returns orders The first search parameter is the shipping city Applying this type of filter is extremely simple C#: using (var . in web applications. Now you’re ready for chapter 2. We’re going to delve into an analysis of the data access options available in . NET Framework 4. 0 and specifically for ASP. NET 4. 0. 30 Data. personalization. 1.6 Summary Almost everything we’ve talked about in this chapter applies to all versions of ASP. NET. That said, ASP. NET 4. 0 does introduce some interesting features, but the pillars of. (Really Simple Syndication) feed. Listing 1.5 Registering a CSS 28 CHAPTER 1 Getting acquainted with ASP. NET 4. 0 RSS or Atom feeds are quite popular these days in web applications because they let

Ngày đăng: 12/08/2014, 15:23

Từ khóa liên quan

Mục lục

  • Part 1: ASP.NET Fundamentals

    • Getting acquainted with ASP.NET 4.0

      • 1.5 ASP.NET Web Forms in practice

        • Technique 3: Page header, styling, and CSS

        • 1.6 Summary

        • Data access reloaded: Entity Framework

          • 2.1 Designing an application

            • 2.1.1 What’s an object model?

            • 2.1.2 The evolution of the object model: the domain model

            • 2.2 Using an ORM to build a data layer

              • 2.2.1 The granularity mismatch

              • 2.2.2 The relationship mismatch

              • 2.2.3 The inheritance mismatch

              • 2.3 Introducing Entity Framework

                • Technique 4: Creating a model using Entity Framework

                • Technique 5: Generating POCO code

                • Technique 6: Reading data using Entity Framework

                • Technique 7: Writing data using Entity Framework

                • 2.4 Summary

                • Integrating Entity Framework and ASP.NET

                  • 3.1 Understanding context lifetime

                    • Technique 8: First approach: one context per method

                    • Technique 9: A better approach: one context per ASP.NET request

                    • Technique 10: Instantiating the context using modules

                    • 3.2 Using the context the right way

                      • Technique 11: Persisting entity modifications

                      • Technique 12: Persisting only selected properties

                      • Technique 13: Persisting an entity using ViewState

                      • Technique 14: Keep concurrency in mind

                      • 3.3 Optimizing performance in an ASP.NET environment

                        • Technique 15: Optimizing fetching

Tài liệu cùng người dùng

Tài liệu liên quan