Tag Archives: visual C# tutorial

The WPF Layout System – Visual C#

Layout in WPF is flow-based, but it also includes automatic resizing and repositioning of controls if the user changes screen resolution or resizes the window containing controls or adds or removes controls at runtime. As you will see in this chapter, this provides resolution and size independent user interfaces.

A window can contain one element, or control. That element will almost always be a container. A container contains controls and, optionally, other containers. All container controls derive from the System.Windows.Controls.Panel class. Layout in WPF is a recursive process. The .NET Framework runtime makes two passes before drawing elements.

In the Measure pass, the runtime queries each element to determine the element’s size and location. In the Arrange pass, the runtime determines the actual size and position for each element. Elements may or may not be sized and located where they requested, depending on the number of elements, the screen resolution, the size of the window, etc.

Layout is not only a recursive process, but it is also an iterative process. The entire layout process occurs each time the user resizes the window or your code adds or removes elements. You should keep this in mind as you design user interfaces.

How does the layout system determine how to size each element? Each element on a window is surrounded by a bounding box, as shown in Figure 1. This represents the space allocated to the element, and therefore represents the maximum size of the element.

helloworld

Figure 1 Each element on a window is surrounded by a bounding box.

The layout system determines the actual size of an element by taking into account the following:

  •  The available screen space.
  • The size of any constraints, such as maximum or minimum height or width.
  •  Layout-specific properties, such as alignment, margins, padding, etc.
  •  The behavior of the parent container.

As needed, the layout system can shrink, grow, or move elements on a window.

Alignment, Margins, and Padding

All elements have four properties that are important to understand, as these play a key role in determining the position of elements in a window. These properties are HorizontalAlignment, VerticalAlignment, Margin, and Padding. Alignment refers to how child elements should be positioned within a parent element’s allocated layout space. The HorizontalAlignment property determines how an element is positioned horizontally within a container. The possible values for this property are Left, Right, Center, and Stretch, as shown in Figure 2. If this property is set to Stretch, which is the default, the control will expand to its maximum available width.

WPFLayoutSystem2

 Figure 2  The HorizontalAlignment property determines how an element is positioned horizontally within a container.

The VerticalAlignment property determines how an element is positioned vertically within a container. The possible values for this property are Top, Bottom, Center, and Stretch, as shown in Figure 3. If this property is set to Stretch, which is the default, the control will expand to its maximum available height.

WPFLayoutSystem3

Figure 3. The VerticalAlignment property determines how an element is
positioned vertically within a container.

The Margin property determines the distance between an element and its child or peers. This property consists of four parts: the left margin, the top margin, the right margin, and the bottom margin. The following XAML sets the margin for an element following this pattern:

<Button Margin=”0,10,0,10″…

The previous code specifies that there should be no additional space on the left and right, but there should be a ten pixel space on the top and bottom. If you want the same margin on all four sides, you only need to specify one value. The following XAML sets the margin to ten on all sides:

<Button Margin=”10″…

The Padding property is similar to the Margin property, however it is only available for certain controls, including Border, Button, and TextBlock. The property adds space between the edge of a control and its content.

Figure 4 shows the use of the Margin and Padding properties, along with horizontal alignment, to control the layout of elements.

WPFLayoutSystem4

Figure 4. You can use the Margin and Padding properties, along with horizontal
alignment, to control the layout of elements.

Containers

As mentioned earlier, each window can contain a single element. This element will typically be a container control. This chapter covers the following containers:

  • StackPanel: Stacks elements horizontally or vertically.
  • WrapPanel: Places elements in rows and columns that wrap as needed.
  • DockPanel: Aligns elements along an edge.
  • Grid: Places elements in rows and columns.
  • Canvas: Places elements according to coordinates.

This post is an excerpt from the online courseware Windows Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

Introducing Windows Presentation Foundation – C# 2010

Modern applications require a modern user interface. On the other hand, applications you create using Windows Forms, the standard user interface design package that Visual Studio has provided for past versions, look little different than applications written using tools you might have used in 1995.

No matter how you dress them up, forms created using the Windows Forms package generally look pretty much the same, as shown in Figure 1. Although you can create other types of applications, using Windows Forms, you’re on your own—the tools exist to create more creative forms, but you must write all the code for each application. You can create non-rectangular forms; you can create forms that scale. But you’ll write a lot of code to make it happen.

WPF1
Figure 1. It’s an attractive form, but it looks like every other form.

Although Windows Forms provide a rich set of tools for creating business applications, the package leaves a great deal to be desired for building intricate, rich, modern graphically oriented applications.

What if you want to create an application that uses a completely new type of interface? Perhaps you don’t want rectangular controls, but rather, would like to use your own styles?

One thing is for sure: If you’ve ever seen anyone use a computer interface in a movie or television show, you can be assured that you weren’t seeing an application created using Windows Forms. As you know, creating a visually appealing application using Windows Forms can be challenging. To be honest, up until recently, computer graphics hardware really wasn’t powerful enough for a forms package richer than Windows Forms. You can certainly use Windows Forms to create interfaces as you might see in a movie, but it’s not easy, and each application you write would require its own set of tools.

In addition, using Windows Forms, three-dimensional graphics were extremely difficult without using external libraries. Even then, your code was at the mercy of hardware that might not provide the power necessary to perform the required mathematical calculations. In addition, the underlying graphics engine, built into Windows for many years, is extremely limited.

Windows Presentation Foundation (WPF) provides a new design medium. WPF has been created from the ground up to take advantage of hardware power, and provides a consistent, powerful graphics platform. WPF includes an integrated, vector-based (as opposed to pixel-based) composition engine, which utilizes the power of the computer throughout the graphics stack. In other words, it takes advantage of both the processing power of the computer, and of the GPU (Graphics Processing Unit) built into the graphics hardware. WPF provides full support for resolution independence—as you move from one screen resolution to another, your WPF applications scale appropriately.

WPF introduces a unified approach to user interface, documents, and media: it provides full support for mixing all types of user interaction in a single application. Retrieve input from a user, display a movie, render the contents of a newspaper, all within a WPF application using native controls and rendering support.

From a programmer’s perspective, WPF makes rich document integration part of the development experience. Unlike Windows Forms, where you can bolt on media support, this support is simply part of WPF. In addition, WPF fully supports separation of design and code, allowing you to bring designers directly into the development process. Because you can use declarative coding to create your WPF applications, designers can create the user interface with either Visual Studio or other WPF-enabled tools (such as Microsoft’s Expressions products), and then you, as a developer, can add the programmatic functionality later. Finally, deployment of WPF applications is easy; it allows administrators to deploy and manage applications securely.

This post is an excerpt from the online courseware Developing Applications with Entity Framework 4.1 Using C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

The Decline of the IT Generalist

vsBack in the good old days – say, 20 years ago – many small companies had what was considered an “IT generalist.” They pretty much did everything. They set up and managed the e-mail, fixed computers, kept an eye on the network, and managed small projects.

They were, of course, “the IT guy.” And even in companies with larger IT staffs, many of the IT workers had a hand in all different types of technology. They even dabbled in programming; it wasn’t abnormal for IT workers to be mildly proficient in Windows, Cisco, Perl, etc.

Well, now we’re approaching the age of “specialists.” Many companies have a separate “expert” in network management, help desk, project management, etc. And this trend is particularly acute in the programming world. The list of languages, of course, is a long one: Java, VB, C#, Ruby, Python, etc.

More and more companies are looking for language-specific specialists, and that’s good news for job seekers. Check out our Java, C#, or Visual C# tutorials and become a “specialist.”

Thumbnail for 628

Thousands of developers worldwide use LearnNowOnline to gain the technical skills they need to succeed on the job and advance their career.

Dependency Resolution and Hosting: Dependency Injection

There’s a sense in which the entire idea behind having consumable services such as the ASP.NET Web API provides is a decoupled, reusable architecture. You want to have a body of data and business logic decoupled from a client application so it can be used by a variety of client applications. Testability is also an important architectural issue. A unit of code must be decoupled from its dependencies in order to write automated tests against it.

Practices like Test Driven Development (TDD) virtually force writing code this way. In software development, all code should be written with these principles in mind, including our client applications and the services, themselves.

Dependency Injection is one way to help achieve decoupling, reusability, and testability in Web API services. With this in mind, the Web API framework was designed to facilitate this technique.

Inversion of Control

In a broad sense, Inversion of Control is the concept of allowing something outside of a system to control it. In other words, the system doesn’t run itself but something or someone on the outside invokes it when it is needed. In a very broad sense, things like a web-based interface over a database could be an example of Inversion of Control. In object-oriented software development, Inversion of Control means that, instead of tightly coupling objects to other objects in code, objects are pulled together at runtime by some outside mechanism.

If you go to a pizza restaurant, you’ll see people making pizzas. What you probably won’t see are people growing tomatoes for the sauce, milking cows to make the cheese, or processing cardboard to make the pizza boxes. The pizza shop needs all those things, but they are not responsible for creating them. Someone else creates them and gives them to the pizza shop to use to get their job done. This is roughly analogous to Inversion of Control in software development.

For instance, if you are writing a repository class that will save products to the database, it will need some kind of data access object to perform the database operations. One way to do this is simply to instantiate a data access object in your repository code. However, this will tightly couple your repository code to that data access object.

With Inversion of Control, you code the repository to an abstraction (usually an interface) that represents the data access object and you rely on some outside mechanism to instantiate a data access object and give it to your repository at runtime. By doing this, your repository is now decoupled from any particular data access object. This allows you to reuse the repository code with various data access components as well as making it testable (by giving the repository a “mock” data access object).

There are various techniques that give you Inversion of Control in software development and one of the more common and prominent ones is Dependency Injection.

Using Dependency Injection

Many classes that you write need other objects to do their jobs, and nowhere is this more true than in a services layer. Many services need objects to access data, process business rules, perform validation, handle logging, and a wide array of functionality that the services layer tends to coordinate.

With Dependency Injection, programmers code their classes assuming that these objects will be instantiated from an entity outside their class and passed into it. Sometimes, this is done by exposing properties that can be set from the outside. A very common way to set up for Dependency Injection, however, is to handle it in the constructor.

In the previous example, there is a Logger class that needs a file writer object. In tightly-coupled code, the Logger would just instantiate its own file writer:

However, this would bind the Logger class to a specific FileWriter object. By allowing an object that implements IFileWriter to be passed into the constructor, you can now reuse this class for various kinds of file writers. Also, this code is very testable because you can pass in a fake file writer for testing purposes—perhaps one that writes to a test file or even does nothing at all.

If code is written to receive its dependencies from the outside, these objects have to come from somewhere. Something on the outside needs to instantiate these objects and pass them into the objects that require them. Some mechanism needs to inject these dependencies. There’s more than one way to do this, but this is such a common issue in software development that common libraries have been written to solve this problem. They are often called IoC (Inversion of Control) Containers or DI (Dependency Injection) frameworks.

This post is an excerpt from the online courseware for our ASP.NET Web API Hosting and Dependency Resolution course written by expert Philip Ledgerwood.

ldn-pledgerwoodPhilip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

Requesting Other MIME Types

MIME originally stood for Multipurpose Internet Mail Extensions to refer to the fact that emails would sometimes carry data that wasn’t text, such as attached graphics or spreadsheets. MIME types were a way for email clients to recognize the different types of data coming across and handle them appropriately.

When dealing with web applications today, MIME types (also referred to as Content-Types) refer to all kinds of data that web clients access over the Internet. A common MIME type is text/html, but there’s also text/css, application/xml, and even non-textual types such as application/pdf or image/gif.

JSON is the default MIME type that Web API services return, and it might fit a great many needs for web services, but what if your application needs to get XML from a service, or a comma-delimited file, or even a graphic or a spreadsheet?

XML

XML is an extremely common data exchange format for web services and, as such, the Web API can support returning XML data with no code changes. All that needs to happen is that the HTTP request has to specify a Content-Type of application/xml.

If a Web API service gets an HTTP request with a Content-Type of application/xml, it will automatically serialize and return data as XML rather than JSON. Nothing special needs to be done to make this happen unless you want to provide a different XML serializer.

NOTE: At the time of this writing, the ASP.NET Web API uses the DataContractSerializer in the .NET Framework behind the scenes to do XML serialization. You can set a different serializer in the Web API’s configuration.

Other MIME Types

JSON and XML are the only MIME types the Web API handles out of the box. However, the Web API can send back virtually any MIME type out there. If you want a Web API service to return something besides JSON or XML, you must first write your own “serializer” for the data you want to return. In Web API parlance, this is called a Media Formatter. This Media Formatter needs to be registered in the Web API configuration. Once this is done, any requests for that data that have a Content-Type of the MIME type of the appropriate Media Formatter will receive that type of data back from the service.

ldn-pledgerwoodThis post is an excerpt from the online courseware for our ASP.NET Web API Model Binding and Media Formats course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

Model Binding: HTML Templates

url4

 

The client-side migration revolution has not left markup untouched. Given thatclients making service calls and rendering the results has become such a common way for web applications to work with data, especially as mobile application use is on the rise, a good deal of attention has been given to the rendering aspect of using service data.
The standard way of dealing with data returned via AJAX was to use JavaScript to concatenate the data into strings of HTML and then dynamically write that HTML into the DOM. Although the basic principle is the same, mechanisms have been developed in recent years to make this process easier and more modular. Binding data to HTML templates is a popular way to do this, and using it has even given rise to a pattern commonly called MVVM.

MVVM

MVVM stands for Model-View-ViewModel and describes a client rendering design pattern.

  • The Model represents your actual data, such as might be pulled from a database or a service.
  • The View is the actual UI that renders the ViewModel, which will generally be HTML in the case of typical web application development.
  • The ViewModel is Model data that has been shaped specifically with the goal of binding this to a View that will render the data.

This may not sound all that different from the MVC or MVP patterns, but one of the things that makes the MVVM pattern a little more exciting is that changes to the ViewModel can update the View and the Model immediately.

Let’s consider the traditional client-server way of editing data. If you want to add a new customer in a web application:

  1. Pull up an HTML form and make changes to the form.
  2. >Click Submit so the page posts this data to code that writes it into the database.
  3. The page refreshes with any new information such as Customer Id.

Now let’s consider using MVVM to edit data. With the MVVM pattern, a ViewModel sits between the View (the form) and the Model (the data from the database), which gives you flexibility on when and how these updates happen >and renders the changes in real-time. If you want to add a new customer using MVVM:

  1. Fill out the Add Customer form.
  2. Click Submit, which adds the customer to the ViewModel.
  3. This change automatically updates an Added Customers grid at the bottom of the page with no refresh.

At this point you can decide if you want the new customer to be saved directlyto the database. If you do, then as soon as your server-side code saves the customer and gets the Id, it can put the Id into the ViewModel which automatically updates any UI elements bound to it.

You could also keep the “Added Customers” in the ViewModel but not save any of them until the user clicks the Commit Changes button. This allows theuser to add, update, or delete all kinds of operations on that data with a UI thatresponds immediately to changes but doesn’t commit anything to the database until it’s told to.

The main point is that in MVVM, the ViewModel is directly bound to the View, so any changes to it automatically update the View. This adds a huge level of responsiveness and options when writing web applications. Some applications are referred to as Single-Page Applications because the MVVMpattern enables users to do everything on a single page bound to a modifiable ViewModel.

Binding ViewModels to HTML

Much like AJAX, there are a number of JavaScript libraries that have already been written to help you with the process of binding an HTML UI to a ViewModel. The basic principle behind them all is that you create a snippet of HTML and use attributes or JavaScript functions to mark off the dynamic partsthat will get their data from the ViewModel.

When a web page containing an HTML template is requested, an AJAX operation gets data from a service. This data either directly becomes or is incorporated into a JSON ViewModel, and the JavaScript binds this ViewModel to the corresponding places marked off in your HTML. Any changes to the JSON ViewModel will automatically update the UI pieces that are bound to them.

Like AJAX, there’s nothing stopping you from writing all the code for this process yourself, but a number of libraries exist that already do this. One popular library for binding JSON ViewModels to HTML templates is Knockout.js, and Microsoft includes it by default in Web API projects. There are other options however, such as Pure, Mustache, or JTemplates. Also like AJAX, no Microsoft-specific technologies or platforms are required to use HTML templates. On the client/consumer end of HTTP web services, you are free to use whatever you like, all the way from static HTML to PHP to JSP to anything in between. It’s all HTML and JavaScript at this point.


ldn-pledgerwoodThis post is an excerpt from the online courseware for our
ASP.NET Web API Model Binding and Media Formats course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

ASP.NET Web API: Client-Side Pipeline

power-sass-multi-deviceMicrosoft .NET Framework technologies that support a request-response pattern typically use a pipeline, which is a sequence of events that fire to process a request and send back an appropriate response.

Pipelines are important because they allow developers to run code at various stages of processing a request.

The ASP.NET Web API has a pipeline and, by taking advantage of how the API processes HTTP messages, you can easily add some very useful functionality. The Web API has a processing pipeline for both the client and >the server, and this article will focus on the Client-Side Pipeline!

Client-Side Pipeline

The Web API pipeline has two “sides” to it: the client-side and the server-side. Understanding the client-side pipeline is useful as virtually any application can harness the client-side objects to make calls to a Web API. The objects available in the client-side pipeline are especially useful when creating applications that need to access Web API services directly from application code and consume the results.

HttpClient

The HttpClient object represents the client making the request. You can instantiate the object in code, use it to generate an HttpRequestMessage, and send it asynchronously to a URL to be handled by a Web API application. The HttpClient then receives an HttpResponseMessage and handles the contentsaccordingly.

The HttpClient only has four properties, and its methods are primarily concerned with various ways to send an HTTP request and receive a response. The HttpClient is somewhat analogous to AJAX frameworks that essentially facilitate sending requests and receiving responses, leaving it to other code to unpack the response and use the data meaningfully. In the same way, the bulk of the logic dealing with a service response will operate on the HttpResponseMessage object, which will contain the actual data that the requestor needed.

NOTE: With the popularity of various AJAX libraries, many applications will make client-side calls to the Web API directly, but if you have a need to make these calls using server-side code, the HttpClient object will beuseful.

HttpMessageHandler

The HttpMessageHandler object sends the HttpRequestMessage generated by the HttpClient to the right place and listens for an HttpResponseMessage. When a response is received, the HttpMessageHandler is the first object to process it before handing it back to the HttpClient.

HttpMessageHandler is actually a base class for all such handlers. The default implementation for the client-side pipeline is the HttpClientHandler, which satisfies most basic usages of the Web API. However, you are free to write your own implementation of the HttpMessageHandler. This might be useful if you want to perform a uniform task for every request or response that comes through, such as adding a security key to the header or examining incoming responses for a correct format.

You must use caution when adding custom code to your HttpMessageHandler on the client-side, however. The idea behind a Web API service is that the functionality can be called by a wide variety of clients. Putting too much logic about the transaction on the client-side may require replicating that code on every client that uses the service. This is something that you should generally avoid, or at the very least, clients should have other ways to provide that information to the service other than requiring a custom HttpMessageHandler on the client-side.


ldn-pledgerwoodThis post is an excerpt from the online courseware for our
ASP.NET Web API HTTP Pipeline course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

ASP.NET Web API’s: Default Mapping

Web API Routing

If you have used the MVC pattern in your web applications, you are already familiar with the concept of URL routing. The ASP.NET MVC framework, for instance, knows which controller action to call by looking at pieces of the URL and using those pieces to identify the controller and the controller action.

Web API routing works in a similar way, except that the action is not specified in the URL. Instead, the action is selected based on the HTTP method used in the request.

Default Mapping

Like the ASP.NET MVC framework, you can find the default routing table for the Web API in Global.asax.

Contrast this with the default routing table for ASP.NET MVC controllers:

The differences in the properties that are set and the URL mapping pattern may seem subtle, but they are important. Not only do the two mapping schemes they also capture the primary differences between a RESTful API and something that maps to method names in a URL.

The first difference is the MapHttpRoute method. This method is used to map API routes as opposed to the MapRoute method, which is used for ASP.NET MVC routing tables.

The second difference is that “api” is a hard-coded value in the Web API map for URLs. This prevents mapping conflicts with the ASP.NET MVC framework. It’s quite possible for both your MVC controllers and your Web API controllers to have the same names, so having “api” as part of all Web API URLs makes sure your routing table uses the right controller for a request.

The third difference is that the routeTemplate does not have an action parameter like the ASP.NET MVC framework routes do. In ASP.NET MVC, the URL specifies the action that should be called. In the Web API, the API decides which action should be called based on the HTTP method handled bythe controller.

In order to map a request to a controller action, Web API routing goes through the following steps:

  1. Checks for an “api” in the beginning. If there isn’t one, it is handled by MVC routing, instead.
  2. Adds the word “Controller” to the value found in the {controller} parameter of the URL and uses this to find the appropriate Web API controller
  3. Looks for an action with a name that begins with the HTTP method used in the request. For instance, if a GET method is used, Web API will look for an action name that starts with the word “Get,” a POST method willtrigger an action that starts with the word “Post,” and so on.
  4. Maps any additional parameters to action parameters.

Table 1 shows how the HTTP method and the URL pattern will map to actions by default. Once again, remember that the action name only has to begin with the HTTP method name; everything else is irrelevant and can be whatever you want.

HTTP Method URL Matching Action
GET api/books GetAllBooks()
GET api/books/2 GetBook(int id)
POST api/books PostNewBook()
PUT api/books/2 DeleteBook(int id)
DELETE api/books/2 DeleteBook(int id)

Table 1. Example HTTP requests mapping to controller actions.

This post is an excerpt from the online courseware for our ASP.NET Web API Basics course written by expert Philip Ledgerwood.

ldn-pledgerwoodPhilip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.