Monthly Archives: August 2012

Top-Down Design or Bottom-up Design, That is the Question

topdown3

 

When it comes to brand new data applications, there are two broad ways to approach building the application: design the object model first and the database later, or build the database first and the object model later. The first option is often referred to as top-down design, because you’re building application components first that sit on top of other layers including the database. The second option is bottom-up design because the underlying foundation of the application, the database, comes first. Top-down design places the business rules and architecture of the application as the highest value, and bottom-up design puts the emphasis on strong data organization. Neither methodology is necessarily better than the other: each one fits some development teams better than the other, and even some applications better than others. A project dominated by DBAs is likely to favor a bottom-up design methodology, while one dominated by developers is somewhat more likely to favor a top-down design, depending on how comfortable they are with data design. If you are building a new application that will use an existing production database, you’re inherently taking the bottom-up approach because the database already exists.
Entity Framework supports both methodologies, although not at the same time in an application. It provides three ways to build an application, one that supports bottom-first design and two that support top-first design.

  • Database-first design, available with the initial release of Entity Framework. This is the technique you used when you created the AdventureWorksLibrary project earlier in this chapter, based on objects in the existing AdventureWorksLT database. The Entity Data Model Wizard obtained the database schema and created the entity data objects for the tables you selected. The existing database schema shapes the entity objects using this technique, although you can modify the resulting objects extensively.
  • Model-first design, introduced in version 4 of Entity Framework. If the database doesn’t yet exist, you can create an Entity Data Model using the designer in Visual Studio from scratch, or you can write the XML for the .edmx file directly, if you’re so inclined. When you’re ready, you can have Entity Framework create a new database that corresponds to the model you’ve designed, shaping the data and storage to the model. If you later make changes to the model, the designer in Visual Studio supports recreating the database with the changes.
  • Code-first design, sometimes called code-only design. This is a new option released with version 4.1 of the Entity Framework. Here you write Plain Old CLR Objects (POCOs), which are regular .NET class objects, and Entity Framework will create the data store from these objects. Code-first works with an implied model at runtime, so there is no need for an .edmx model file. This technique is the purest form of top-down design, because you design your POCOs with no foresight about how the data will be persisted in a data store.

4 Benefits of Object-Relational Mapping (ORM)

ldn-bbluetry

Object-relational mapping, in the purest sense, is a programming technique that supports the conversion of incompatible types in object-oriented programming languages, specifically between a data store and programming objects. You can use an ORM framework to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form.

TIP: Nicknames and acronyms used for “object-relational mapping” include ORM, OR/M, and O/R mapping. Although ORM seems to be the term most commonly used in the .NET world, you’ll often see the others in books and articles. We’ll stick with ORM, mostly because it is the easiest to type!

The key feature of ORM is the mapping it uses to bind an object to its data in the database. Mapping expresses how an object and its properties and behaviors are related to one or more tables and their fields in the database. An ORM uses this mapping information to manage the process of converting data between its database and object forms, and generating the SQL for a relational database to insert, update, and delete data in response to changes the application makes to data objects.

ORM performs the rather amazing task of managing the application’s interactions with the database. Once you’ve used an ORM’s tools to create mappings and objects for use in an application, those objects completely manage the application’s data access needs. You won’t have to write any other low-level data access code. Strictly speaking, you could still write low-level data access code to supplement the ORM data objects, but this adds a significant layer of complexity to an application that we’ve rarely found necessary when using a robust ORM tool. It is better to stick to one or the other and keep the application simpler and more maintainable.

There are a number of benefits to using an ORM for development of databased applications and here’s four:

  1. Productivity: The data access code is usually a significant portion of a typical application, and the time needed to write that code can be a significant portion of the overall development schedule. When using an ORM tool, the amount of code is unlikely to be reduced—in fact, it might even go up—but the ORM tool generates 100% of the data access code automatically based on the data model you define, in mere moments.
  2. Application design: A good ORM tool designed by very experienced software architects will implement effective design patterns that almost force you to use good programming practices in an application. This can help support a clean separation of concerns and independent development that allows parallel, simultaneous development of application layers.
  3. Code Reuse: If you create a class library to generate a separate DLL for the ORM-generated data access code, you can easily reuse the data objects in a variety of applications. This way, each of the applications that use the class library need have no data access code at all.
  4. Application Maintainability: All of the code generated by the ORM is presumably well-tested, so you usually don’t need to worry about testing it extensively. Obviously you need to make sure that the code does what you need, but a widely used ORM is likely to have code banged on by many developers at all skill levels. Over the long term, you can refactor the database schema or the model definition without affecting how the application uses the data objects.

One potential downside to using an ORM is performance. It is very likely that the data access code generated by the ORM is more complex than you’d typically write for an application. This is because most ORMs are designed to handle a wide variety of data-use scenarios, far more than any single application is ever likely to use. Complex code generally means slower performance, but a well-designed ORM is likely to generate well-tuned code that minimizes the performance impact. Besides, in all but the most data-intensive applications the time spent interacting with the database is a relatively small portion of the time the user spends using the application. Nevertheless, we’ve never found a case where the small performance hit wasn’t worth the other benefits of using an ORM. You should certainly test it for your data and applications to make sure that the performance is acceptable.

There are a number of ORM tools available for .NET applications (see the “List of object-relational mapping software” topic in Wikipedia in the .NET section for an exhaustive list). Before Microsoft introduced Entity Framework, the open source NHibernate was probably the dominant ORM tool. NHibernate is ported from Hibernate, a Java ORM tool that has been available for years. But because Microsoft now bundles Entity Framework with the .NET Framework and incorporates extensive support for it in Visual Studio, Entity Framework has become the dominant ORM in the Microsoft development world.

Start training on .NET!

Staying Up-To-Date In The C# World

Thumbnail for 666Experienced C# developers understand the importance of sharpening their skills and staying up-to-date on the latest developments in their field. This typically involves enrolling in periodic training workshops or taking additional courses. However, the decision to continue your education requires time and money.

Some C# developers work full-time in demanding positions, which allows little time for school. Fortunately, there are online programs to help professionals in this predicament. They can enroll in a C# video course and sharpen their skills online.

A C# video course is perfect for anyone who doesn’t have time to sit in a classroom each week. LearnNowOnline offers a host of video tutorials led by expert instructors. You can benefit from live learning in the comfort of your home or office. And the best part, you can access video courses at an affordable price. Why pay hundreds or thousands of dollars for a single course or workshop?

LearnNowOnline is one of the most cost-effective and convenient ways to gain access to a C# video course, which can open the door to advance job opportunities and a higher salary.

Start training on C#!

See, Learn, Develop

uva_online-525x335

 

Out of the four learning styles that we cover in our online training courses – visual, aural, read/write and kinesthetic – this blog will look at visual learning, or learning by seeing.

As a dominant learning style, there’s a good chance that many developers looking to further their training and education are visual learners. Hence, they should look to visual learning methods when going about learning a new development technology.

Due to its visual makeup, online learning courses and tutorials are extremely well suited to the visual learner. From simple graphics to animated graphics, rollovers and videos, the visuals used in online learning courses help emphasize important pieces of information.

The process of integrating images into instructional strategies can benefit all developer students, including those who might not otherwise be classified as visual learners. For example, images aid in retention by delivering new information to students through both verbal and visual communication. Images that reference previous material can also aid comprehension by linking a new concept to one already mastered. Diagrams and graphs can help individuals to understand mathematical data and statistics. Images can also help to reveal previously unrealized relationships or patterns within data sets.

The online video courses at LearnNowOnline, completely visual in their makeup, are a great learning tool for the developer that learns by seeing!

In the following video, you can see many aspects of visual learning! This snippet is part of our course on “ASP.NET Using Knockout.js: Getting Started and Observables.”

Food for thought:

  • Are you a visual learner?
  • Do you use tools to help you learn efficiently and effectively?

Developers, Let’s talk $uccess

7568209-crown-icon-on-computer-keyboard-original-illustrationIt is plain common sense that a developer will succeed and advance in their career, and therefore benefit financially from their success, if they are known as an expert in the technology they work in. As a Visual Web Developer or Visual Studio Developer, would you do better in your career if you were average or if you were an expert? Clearly, that is an easy answer… of course you will do better if you are known as an expert.

Beyond being a so-called expert, what must you do in order to succeed, advance your career and make more money as a developer?

Learn the right technologies!

Would you do better if you were an expert in Fortran or Cobol? Or would you do better if you were an expert in Visual Studio, Visual C#, .NET, Microsoft SharePoint, SQL Server, mobile development or Java? In the short term you can’t do them all, so it’s very important to pick the right ones! Success lies in being an expert in the hottest technologies at the moment, so choose wisely and then use a proven method to learn the technology.

According to Dice.com, Java developers remain the most difficult tech pros to land, followed by mobile developers and .NET developers. Hiring managers and recruiters cite these positions 2-3 times more frequently than other skill sets in the employment marketplace!

Given the above, I suggest becoming an expert in Java, Mobile Development or .NET programming.

Once you’ve chosen a technology to become an expert in, the next step is finding the best materials to learn the technology. At LearnNowOnline.com we build the highest quality video tutorials in the technologies you need and desire. We have Java Video tutorials, Mobile development video tutorials including development in iOS, Android and .NET and we have .NET programming video tutorials! In addition to our online video tutorials, you can add on sample code, full courseware and hands on labs to provide additional resources for your learning.

Happy Learning,

Craig

Does your Help need Help?

Writing a ton of HTML code to support almost any kind of application, particularly one that maintains data, can be breathtakingly tedious. You’ll need to pepper the view with code nuggets, snippets of code embedded in the view to read from and write to the view’s model and perhaps ViewData. Although it is simpler and more efficient to write this kind of code in MVC and ASP.NET than it was in classic ASP, it is still tedious.

IntelliSense

It would be nice if Microsoft were to provide a middle ground, a feature that retains for the developer a high degree of control over the HTML, but lessens the tedium of writing reams of HTML code and makes intelligent decisions about the HTML to emit. A middle ground between the two extremes would be nice!

Fortunately, they did. (Bet you saw that coming!) The feature is called HTML helpers, or just helpers or helper methods. These are methods in the framework that emit markup for the most common HTML elements, and help create wellformed, valid markup.

In this article we’ll discuss the different types of HTML helper methods used in MVC.

Types of HTML Helper Methods

MVC includes three broad classes of HTML helper methods: untyped helper methods, strongly-typed helper methods, and templated helpers. The untyped helper methods first appeared in the initial release of MVC, version 1, and generally take a string with the name of the property to which it is bound at runtime. The following code is an example of using a regular HTML helper to display a label, text box, and validation message to edit a Name property of the view model object, using the Label, TextBox, and ValidationMessage helper methods.

A strongly-typed helper has “For” appended to the name of the method and takes a lambda expression that binds the helper to a model property at design time. This is in contrast to a regular helper that takes a string parameter. Strongly-typed helpers have the benefit of catching many kinds of problems at compile time instead of runtime, and IntelliSense fully supports them when you write code. The following code is an example of using strongly-typed
helpers for the same Name property of the previous code, using the LabelFor, TextBoxFor, and ValidationMessageFor methods. Notice that each takes a lambda expression to bind the helper at design time.

Using a lambda expression lets you pass both the field that the helper is binding to and the value of the field. The strongly-typed helper method uses this information to intelligently determine how to display the data. It really is a rather elegant way to pass the information to the helper method.

TIP: Try misspelling a field name to see what happens. Specifically, misspell one
of the field names in one of the TextBox helper methods in the Edit view of
the DogApp project, such as changing “Age” to “Ag.” You’ll find that when
you edit a dog’s data any existing age doesn’t appear, and when you save the
data it stores it as zero, no matter what you put in the text box.

Code that uses strongly-typed methods looks a bit more complex and requires more typing than the untyped versions, but only a little. And because the fields you are using are strongly typed, IntelliSense can help you where it couldn’t with just strings, as shown in Figure 1. Another benefit of using strongly-typed helper methods is that refactoring tools can update the views if you change field names.

Figure 1. IntelliSense provides a list of the properties of the Dog object.

Templated helpers take the methods to an entirely different level, using built-in and custom templates to give you fine control over the HTML generated based on various templates. You can even throw an entire custom object at a templated helper, and the helper will use reflection to render all its properties—including nested properties—based on the templates defined for each data type, and reverting to a text box for any data types for which it has no template. The following code is an example of using a template helper to edit an entire view model, not just a single property of the object, using the EditorForModel method.

For the most part, you’ll want to avoid using untyped helpers because they rely on string parameters and so tend to be error prone. Whenever you can, let MVC, Visual Studio, and the language compiler help you write good quality code!

Get more training on ASP.NET MVC 2 & 3!

ldn-bbluetry

ASP.NET MVC 3 – OutputCache Action Filter

ASP.NET has had robust output caching features since the very first version back near the beginning of the millennium. It has a rich set of features that let you control the cache by duration, characteristics of the request such as by various parameters, and even based on data changes in an underlying data store. You can cache full pages, parts of pages, or individual objects such as Datasets. And each new version of ASP.NET brings improvements and new features. In MVC 3 you can apply the OutputCache attribute to an action method that you call using either the Html.Action or Html.RenderAction helper methods. The effect is to cache the output of the child action method independently of the page. This is an example of one of the built-in action and result filters. OutputCache has properties that hook into virtually all of the ASP.NET caching features, with the exception of the VaryByControl property, which wouldn’t make sense in MVC since a server control is a bit of an irrelevant concept.
cached page

Using the OutputCache is simple. The Dog controller in the sample application has a CacheThis action method that simply returns the CacheThis view. It sets the output cache to expire every 10 seconds, and specifies that the cache will not depend on any property values. You must include the VaryByParam property in this usage.

The CacheThis page simply displays the current time, as shown in the following code. When you run the application and click the View Cached Page link on the Index view of the Dog controller, you’ll see the page shown in Figure 16. Keep refreshing the page. For 10 seconds the time won’t change, but after 10 seconds the time will update.

Figure 16. The cached page.

One nice option of the OutputCache filter is that instead of defining the characteristics of the cache for every action method where you want to use caching, you can define one or more profiles in web.config. This way, when you have to change the caching characteristics, you can change them in one place rather than throughout the application.

The sample application has this caching element defined in web.config to define a single CacheProfile (you can define as many as you want):

Then you can configure the OutputCache filter to use that profile:

When you run the application again, you’ll get the same behavior as before, with the view cached for 10 seconds. And now the application is much more maintainable.

TIP: You can’t use the regular ASP.NET @OutputCache attribute in the Page
directive in a view. The reason is that the action method executes before a
view is even selected. The @OutputCache will work to cache the contents of
the view, but the action method will still run every time. Since the method is
where all of the action happens with extracting and manipulating data, the
benefit of caching will be negligible if you just cache the view.

Get more training on ASP.NET MVC 2 & 3!

ldn-bbluetry

ASP.NET MVC – Content Result

At one extreme, many MVC views consists entirely of static content. But on the opposite end, you have the option to use a ContentResult object to entirely define the content of a Web page within an action method. Strictly speaking, this isn’t a feature of MVC views, since there is no view involved in this technique. But when you need to create a Web page that has to be entirely dynamic, this is a good option.

A ContentResult has three properties. Content takes the content you want to display, ContentEncoding defines the encoding of the content, and ContentType tells the browser what the content consists of so that it can render it correctly to the user. Common settings for the content type are text/plain, text/xml, and application/json, but there are many others.

For example, say you have some XML data in a file on the server that you want to send to the browser as XML and let the browser deal with displaying it. One way to do this is to read the data from the file in an action method, and use a ContentResult to send it to the browser, like this:

TIP: Hamlet.xml can be downloaded from iBiblio.org using the following link http://goo.gl/3OIgp.

When you invoke the ReadHamlet action method, the raw XML of the entire play Hamlet displays in the browser. If you use Internet Explorer or another browser that understands XML you can collapse and expand different sections of the play, as shown in Figure 7.

Figure 7. Hamlet displayed as XML in the browser.

The important thing to understand about using ContentResult is that you define the entire contents of what the Web page will display. Alternatively, you can provide data for updating a portion of a page, such as when the page makes an Ajax request for JSON data.

Get more training on ASP.NET MVC 2 & 3!

ASP.NET MVC Request Validation Protection: AllowHtml Attribute

MVC has always included the same kind of request validation protection that is turned on by default, although you could turn it off by using the ValidateInput attribute with an argument of false. But that has proven to be too blunt a tool for many applications. If you had a single property of a model that could legitimately contain HTML markup—and you protected against crosssite scripting attacks programmatically—you had to turn off request validation for the entire action method.

In MVC 3, there is a better way: the AllowHtml attribute, which you can apply to individual properties of a model. This makes the attribute behave more like other model property-based validation attributes, and gives you very granular control over how request validation is applied. The sample application has a Notes property on the Dog class. If you use the default request validation behavior and add HTML markup to the contents of the Notes field as shown in Figure 22, when you submit the form the application will throw an HttpRequestValidationException as shown in Figure 23. This is a trappable exception that a real application should handle more gracefully than letting the user see a yellow screen of death.

Figure 22. Entering markup in a text field.

Edit Action Method

Figure 23. HttpRequestValidationException as a result of request validation in an MVC application.

If you want to allow HTML markup in the Notes field, simply decorate the property in the Dog model class with the AllowHtml attribute as shown in the following code. With that in place, the application will save the data as regular string data. If you then view the details for the dog, as shown in Figure 24, you’ll see the markup, although the “Irish Setter” part of the text will not appear in bold. Why not?

html markup

Figure 24. HTML markup displayed for a dog in the Notes field.

The good news here is that this view encodes all strings displayed on the page. If you view the page source for the Details view shown in Figure 24, you’ll see the following HTML. This is why the text isn’t bolded and you see the markup.

The Razor view engine encodes all text automatically for you, and if you use the Web forms view engine you can use the special code nugget delimiters <%: %> to encode text. This encoding in the view provides another layer of protection against cross-site scripting attacks, in this case against script and markup that are already infesting the data.

To turn off request validation for the entire model for an action method, you can still use the ValidateInput attribute with a value of false, as shown in the following code. This will allow markup in any of the text fields, as shown in Figure 25. This is not something you want to do lightly!

Edit Action Method

Figure 25. The result of turning off request validation for the entire model in the Edit action method.

Get more training on ASP.NET MVC 2 & 3!


ASP.NET MVC Controllers: HttpNotFoundResult

The controller in an MVC application is the traffic cop that keeps everything working smoothly. A controller is responsible for responding to user input and managing the overall flow of the application.

In short, the controller is responsible for doing whatever is necessary to service requests from users, using the tools at its disposal: models and views. You can think of a controller as being responsible for application logic, how the application itself works.

In this article you’ll learn about the features, specifically HttpNotFoundResult, on ASP.NET MVC that can simplify the controller code you write.

HttpNotFoundResult

HttpNotFoundResult is useful when you want to indicate that a requested resource is not available. It can be useful to handle situations where a user hacks a URL to request an out of bounds ID value. The action result returns an HTTP 404 status code, which can mask an exception the user would otherwise get that can inadvertently leak information about how the Web site works to an attacker.

For example, the Index view of the Home controller has the following code, which provides two links. Assuming that you have created at least one dog using the DogController, the first link displays the Details view for the dog. The code uses the ActionLink HTML helper method to build the link, providing the id value using the route values parameter. The second link attempts to view the details for a dog with the id value of 10000, which, unless you have entered a lot of dogs manually in the sample application, doesn’t exist. Under normal circumstances, the second link will cause an exception when the view attempts to display a null dog, which you can handle using ASP.NET exception handling either locally or globally. But this kind of problem really is a resource not found error, and an HTTP 404 status is ideally suited for this situation.

The Dog controller also has a SeedDogs action method that adds three dogs to the dogs collection, saving you the trouble of manually adding a few dogs before trying out the code in this section.

The following code implements the Details action method called by the ActionLink URL. If the dog object is null after trying to retrieve the selected Dog object from the dogs list, the code returns the HttpNotFound action result. This results in the 404 HTTP status code, and you can produce a custom page to show the user.

Requesting such an out of bounds value might cause an exception in an action method, so this way the user gets an exception that really does indicate the correct situation. It also prevents an attacker from probing the application and learning potentially damaging information.

Get more training on ASP.NET MVC 2 & 3!