Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .NET+Framework/under-the-hood-of-net-memory-management.pdf.txt +0 -0
- APL/APL2_at_a_Glance_-_Brown_Pakin_Polivka.pdf.txt +1 -0
- APL2_at_a_Glance_-_Brown_Pakin_Polivka.pdf.txt +1 -0
- ASP.NET+Core/LittleAspNetCoreBook.pdf.txt +0 -0
- ASP.NET/DotNETFrameworkNotesForProfessionals.pdf.txt +0 -0
- ASP.NET/Introducing%20ASP.NET%20Web%20Pages%202.pdf.txt +0 -0
- ASP.NET/Introducing%2520ASP.NET%2520Web%2520Pages%25202.pdf.txt +0 -0
- ASP.NET/intro%20to%20asp.net%20mvc%204%20with%20visual%20studio%20-%20beta.pdf.txt +3442 -0
- ASP.NET/intro%2520to%2520asp.net%2520mvc%25204%2520with%2520visual%2520studio%2520-%2520beta.pdf.txt +3442 -0
- Ada/.ipynb_checkpoints/Ada_for_the_C_or_Java_Developer-cc.pdf-checkpoint.txt +0 -0
- Ada/AdaDistilled07-27-2003.pdf.txt +0 -0
- Ada/Ada_for_the_C_or_Java_Developer-cc.pdf.txt +0 -0
- Ada/RM-Final.pdf.txt +0 -0
- Ada/guide-c2ada.pdf.txt +0 -0
- Angular/Angular2NotesForProfessionals.pdf.txt +0 -0
- AngularJS/AngularJSNotesForProfessionals.pdf.txt +0 -0
- Arduino/Arduino_-_MakeUseOf.com.pdf.txt +1283 -0
- Arduino/Arduino_Projects_Book.pdf.txt +0 -0
- Arduino/arduino-tips-tricks-and-techniques.pdf.txt +996 -0
- Arduino/arduino.pdf.txt +0 -0
- Assembly+Language/ARMBook.pdf.txt +0 -0
- Assembly+Language/ProgrammingGroundUp-1-0-booksize.pdf.txt +0 -0
- Assembly+Language/asl.pdf.txt +0 -0
- Assembly+Language/wizardcode4.pdf.txt +0 -0
- Bash/LinuxShellScriptingWithBash-Sams.pdf.txt +0 -0
- Bash/bash.pdf.txt +0 -0
- Bash/bashguide.pdf.txt +0 -0
- Basic/gambas-beginner-guide.pdf.txt +0 -0
- BeanShell/bshmanual.pdf.txt +0 -0
- C/EssentialC.pdf.txt +2747 -0
- C/arm-baremetal-ebook.pdf.txt +0 -0
- C/book.pdf.txt +0 -0
- C/c17_updated_proposed_fdis.pdf.txt +0 -0
- C/ctut.pdf.txt +0 -0
- C/gnu-c-manual.pdf.txt +0 -0
- C/gsl_stats.pdf.txt +0 -0
- C/learning_gnu_c.pdf.txt +0 -0
- C/pointers.pdf.txt +2742 -0
- COBOL/GNU_Cobol_Programmers_Guide_2.1.pdf.txt +0 -0
- COBOL/OpenCOBOL%2520Programmers%2520Guide.pdf.txt +0 -0
- COBOL/sc092539.pdf.txt +0 -0
- CUDA/CUDA_C_Best_Practices_Guide.pdf.txt +0 -0
- CUDA/CUDA_C_Programming_Guide.pdf.txt +0 -0
- CUDA/NVIDIA_OpenCL_ProgrammingGuide.pdf.txt +0 -0
- CakePHP/CakePHPCookbook.pdf.txt +0 -0
- Clojure/clojure.pdf.txt +0 -0
- Codename+One/developer-guide.pdf.txt +0 -0
- ColdFusion/coldfusion.pdf.txt +3002 -0
- Cool/cool-manual.pdf.txt +1787 -0
- DBMS/DATABASE%2520MANAGEMENT%2520SYSTEMS.pdf.txt +0 -0
.NET+Framework/under-the-hood-of-net-memory-management.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
APL/APL2_at_a_Glance_-_Brown_Pakin_Polivka.pdf.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
APL2_at_a_Glance_-_Brown_Pakin_Polivka.pdf.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
ASP.NET+Core/LittleAspNetCoreBook.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ASP.NET/DotNETFrameworkNotesForProfessionals.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ASP.NET/Introducing%20ASP.NET%20Web%20Pages%202.pdf.txt
ADDED
The diff for this file is too large to render.
See raw di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40 |
+
e basics of
|
41 |
+
|
42 |
+
building an
|
43 |
+
|
44 |
+
n ASP.NET M
|
45 |
+
|
46 |
+
MVC Web
|
47 |
+
|
48 |
+
applicat
|
49 |
+
|
50 |
+
ion using M
|
51 |
+
|
52 |
+
Microsoft Vi
|
53 |
+
|
54 |
+
isual Studio
|
55 |
+
|
56 |
+
o 11 Express
|
57 |
+
|
58 |
+
s Beta for W
|
59 |
+
|
60 |
+
Web, which
|
61 |
+
|
62 |
+
is a free
|
63 |
+
|
64 |
+
version o
|
65 |
+
|
66 |
+
of Microsof
|
67 |
+
|
68 |
+
ft Visual Stu
|
69 |
+
|
70 |
+
udio.
|
71 |
+
|
72 |
+
Categor
|
73 |
+
|
74 |
+
ry: Step-By
|
75 |
+
|
76 |
+
-Step
|
77 |
+
|
78 |
+
Applies
|
79 |
+
|
80 |
+
to: ASP.NE
|
81 |
+
|
82 |
+
ET MVC 4 B
|
83 |
+
|
84 |
+
eta, Visual
|
85 |
+
|
86 |
+
Studio 11 B
|
87 |
+
|
88 |
+
Beta
|
89 |
+
|
90 |
+
Source:
|
91 |
+
|
92 |
+
ASP.NET si
|
93 |
+
|
94 |
+
te (link to s
|
95 |
+
|
96 |
+
source cont
|
97 |
+
|
98 |
+
tent)
|
99 |
+
|
100 |
+
E-book
|
101 |
+
|
102 |
+
publicatio
|
103 |
+
|
104 |
+
on date: Ma
|
105 |
+
|
106 |
+
ay 2012
|
107 |
+
|
108 |
+
115 pag
|
109 |
+
|
110 |
+
es
|
111 |
+
|
112 |
+
|
113 |
+
|
114 |
+
|
115 |
+
|
116 |
+
|
117 |
+
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
|
122 |
+
|
123 |
+
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
Copyright © 2012 by Microsoft Corporation
|
129 |
+
|
130 |
+
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means
|
131 |
+
without the written permission of the publisher.
|
132 |
+
|
133 |
+
Microsoft and the trademarks listed at
|
134 |
+
http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the
|
135 |
+
Microsoft group of companies. All other marks are property of their respective owners.
|
136 |
+
|
137 |
+
The example companies, organizations, products, domain names, email addresses, logos, people, places, and events
|
138 |
+
depicted herein are fictitious. No association with any real company, organization, product, domain name, email address,
|
139 |
+
logo, person, place, or event is intended or should be inferred.
|
140 |
+
|
141 |
+
This book expresses the author’s views and opinions. The information contained in this book is provided without any
|
142 |
+
express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will
|
143 |
+
be held liable for any damages caused or alleged to be caused either directly or indirectly by this book.
|
144 |
+
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
|
150 |
+
|
151 |
+
|
152 |
+
|
153 |
+
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
Contents
|
159 |
+
Getting Started ........................................................................................................................................ 3
|
160 |
+
|
161 |
+
What You'll Build ........................................................................................................................... 3
|
162 |
+
|
163 |
+
Skills You'll Learn ........................................................................................................................... 5
|
164 |
+
|
165 |
+
Getting Started .............................................................................................................................. 6
|
166 |
+
|
167 |
+
Creating Your First Application .................................................................................................... 7
|
168 |
+
|
169 |
+
Adding a Controller ............................................................................................................................ 13
|
170 |
+
|
171 |
+
Adding a View ..................................................................................................................................... 20
|
172 |
+
|
173 |
+
Changing Views and Layout Pages ............................................................................................ 25
|
174 |
+
|
175 |
+
Passing Data from the Controller to the View ........................................................................... 31
|
176 |
+
|
177 |
+
Adding a Model .................................................................................................................................. 37
|
178 |
+
|
179 |
+
Adding Model Classes................................................................................................................. 37
|
180 |
+
|
181 |
+
Creating a Connection String and Working with SQL Server LocalDB .................................... 41
|
182 |
+
|
183 |
+
Accessing Your Model's Data from a Controller ............................................................................... 43
|
184 |
+
|
185 |
+
Creating a Movie ......................................................................................................................... 46
|
186 |
+
|
187 |
+
Examining the Generated Code.................................................................................................. 48
|
188 |
+
|
189 |
+
Strongly Typed Models and the @model Keyword .................................................................. 49
|
190 |
+
|
191 |
+
Working with SQL Server LocalDB ............................................................................................. 53
|
192 |
+
|
193 |
+
Examining the Edit Methods and Edit View ...................................................................................... 58
|
194 |
+
|
195 |
+
Processing the POST Request ..................................................................................................... 65
|
196 |
+
|
197 |
+
Adding a Search Method and Search View ............................................................................... 67
|
198 |
+
|
199 |
+
Displaying the SearchIndex Form ............................................................................................... 67
|
200 |
+
|
201 |
+
Adding Search by Genre ............................................................................................................. 77
|
202 |
+
|
203 |
+
Adding Markup to the SearchIndex View to Support Search by Genre .................................. 79
|
204 |
+
|
205 |
+
Adding a New Field to the Movie Model and Table ......................................................................... 80
|
206 |
+
|
207 |
+
Adding a Rating Property to the Movie Model ......................................................................... 80
|
208 |
+
|
209 |
+
Managing Model and Database Schema Differences ............................................................... 82
|
210 |
+
|
211 |
+
Automatically Re-Creating the Database on Model Changes .................................................. 85
|
212 |
+
|
213 |
+
Adding Validation to the Model ........................................................................................................ 95
|
214 |
+
|
215 |
+
Keeping Things DRY .................................................................................................................... 95
|
216 |
+
|
217 |
+
Adding Validation Rules to the Movie Model ........................................................................... 95
|
218 |
+
|
219 |
+
Validation Error UI in ASP.NET MVC .......................................................................................... 97
|
220 |
+
|
221 |
+
How Validation Occurs in the Create View and Create Action Method ................................ 100
|
222 |
+
|
223 |
+
Adding Formatting to the Movie Model.................................................................................. 108
|
224 |
+
|
225 |
+
Examining the Details and Delete Methods .................................................................................... 111
|
226 |
+
|
227 |
+
Examining the Details and Delete Methods ............................................................................ 111
|
228 |
+
|
229 |
+
Wrapping Up ............................................................................................................................. 113
|
230 |
+
|
231 |
+
|
232 |
+
|
233 |
+
|
234 |
+
Getting Started
|
235 |
+
By Rick Anderson and Scott Hanselman
|
236 |
+
|
237 |
+
This tutorial will teach you the basics of building an ASP.NET MVC Web application using Microsoft Visual
|
238 |
+
|
239 |
+
Studio 11 Express Beta for Web, which is a free version of Microsoft Visual Studio. Before you start, make sure
|
240 |
+
|
241 |
+
you've installed the prerequisites listed below. You can install all of them by clicking the following link: Web
|
242 |
+
|
243 |
+
Platform Installer.
|
244 |
+
|
245 |
+
If you're using Visual Studio 11 Beta instead of Visual Studio 11 Express Beta for Web , install the prerequisites
|
246 |
+
|
247 |
+
by clicking the following link: Web Platform Installer
|
248 |
+
|
249 |
+
A Visual Web Developer project with C# source code is available to accompany this topic. Download the C#
|
250 |
+
|
251 |
+
version.
|
252 |
+
|
253 |
+
What You'll Build
|
254 |
+
|
255 |
+
You'll implement a simple movie-listing application that supports creating, editing, searching and listing movies
|
256 |
+
|
257 |
+
from a database. Below are two screenshots of the application you’ll build. It includes a page that displays a list
|
258 |
+
|
259 |
+
of movies from a database:
|
260 |
+
|
261 |
+
|
262 |
+
|
263 |
+
|
264 |
+
The application also lets you add, edit, and delete movies, as well as see details about individual ones. All data-
|
265 |
+
|
266 |
+
entry scenarios include validation to ensure that the data stored in the database is correct.
|
267 |
+
|
268 |
+
|
269 |
+
Skills You'll Learn
|
270 |
+
|
271 |
+
Here's what you'll learn:
|
272 |
+
|
273 |
+
• How to create a new ASP.NET MVC project.
|
274 |
+
|
275 |
+
|
276 |
+
• How to create ASP.NET MVC controllers and views.
|
277 |
+
|
278 |
+
• How to create a new database using the Entity Framework Code First paradigm.
|
279 |
+
|
280 |
+
• How to retrieve and display data.
|
281 |
+
|
282 |
+
• How to edit data and enable data validation.
|
283 |
+
|
284 |
+
Getting Started
|
285 |
+
|
286 |
+
Start by running Visual Web Developer 11 Express Beta("Visual Web Developer" or VWD for short) and select
|
287 |
+
|
288 |
+
New Project from the Start page.
|
289 |
+
|
290 |
+
Visual Web Developer is an IDE, or integrated development environment. Just like you use Microsoft Word to
|
291 |
+
|
292 |
+
write documents, you'll use an IDE to create applications. In Visual Web Developer there's a toolbar along the
|
293 |
+
|
294 |
+
top showing various options available to you. There's also a menu that provides another way to perform tasks
|
295 |
+
|
296 |
+
in the IDE. (For example, instead of selecting New Project from the Start page, you can use the menu and
|
297 |
+
|
298 |
+
select File>New Project.)
|
299 |
+
|
300 |
+
Creating Your First Application
|
301 |
+
|
302 |
+
You can create applications using either Visual Basic or Visual C# as the programming language. Select Visual
|
303 |
+
|
304 |
+
C# on the left and then select ASP.NET MVC 4 Web Application. Name your project "MvcMovie" and then
|
305 |
+
|
306 |
+
click OK.
|
307 |
+
|
308 |
+
|
309 |
+
In the New ASP.NET MVC 4 Project dialog box, select Internet Application. LeaveRazor as the default view
|
310 |
+
|
311 |
+
engine.
|
312 |
+
|
313 |
+
|
314 |
+
Click OK. Visual Web Developer used a default template for the ASP.NET MVC project you just created, so you
|
315 |
+
|
316 |
+
have a working application right now without doing anything! This is a simple "Hello World!" project, and it's a
|
317 |
+
|
318 |
+
good place to start your application.
|
319 |
+
|
320 |
+
|
321 |
+
From the Debug menu, select Start Debugging.
|
322 |
+
|
323 |
+
|
324 |
+
Notice that the keyboard shortcut to start debugging is F5.
|
325 |
+
|
326 |
+
|
327 |
+
F5 causes Visual Web Developer to start IIS Express and run your web application. Visual Web Developer then
|
328 |
+
|
329 |
+
launches a browser and opens the application's home page. Notice that the address bar of the browser says
|
330 |
+
|
331 |
+
localhost and not something like example.com. That's becauselocalhost always points to your own local
|
332 |
+
|
333 |
+
computer, which in this case is running the application you just built. When Visual Web Developer runs a web
|
334 |
+
|
335 |
+
project, a random port is used for the web server. In the image below, the port number is 41788. When you run
|
336 |
+
|
337 |
+
the application, you'll probably see a different port number.
|
338 |
+
|
339 |
+
Right out of the box this default template gives you Home, Contact and About pages. It also provides support
|
340 |
+
|
341 |
+
to register and log in, and links to Facebook and Twitter. The next step is to change how this application works
|
342 |
+
|
343 |
+
and learn a little bit about ASP.NET MVC. Close your browser and let's change some code.
|
344 |
+
|
345 |
+
|
346 |
+
|
347 |
+
|
348 |
+
Adding a Controller
|
349 |
+
|
350 |
+
MVC stands formodel-view-controller. MVC is a pattern for developing applications that are well
|
351 |
+
architected, testable and easy to maintain. MVC-based applications contain:
|
352 |
+
• Models: Classes that represent the data of the application and that use validation logic to enforce
|
353 |
+
|
354 |
+
business rules for that data.
|
355 |
+
|
356 |
+
• Views: Template files that your application uses to dynamically generate HTML responses.
|
357 |
+
|
358 |
+
• Controllers: Classes that handle incoming browser requests, retrieve model data, and then specify
|
359 |
+
|
360 |
+
view templates that return a response to the browser.
|
361 |
+
|
362 |
+
We'll be covering all these concepts in this tutorial series and show you how to use them to build an
|
363 |
+
application.
|
364 |
+
|
365 |
+
Let's begin by creating a controller class. InSolution Explorer, right-click theControllersfolder and then
|
366 |
+
selectAdd Controller.
|
367 |
+
|
368 |
+
Name your new controller "HelloWorldController". Leave the default template asEmpty controllerand
|
369 |
+
clickAdd.
|
370 |
+
|
371 |
+
|
372 |
+
Notice inSolution Explorerthat a new file has been created namedHelloWorldController.cs. The file is
|
373 |
+
open in the IDE.
|
374 |
+
|
375 |
+
|
376 |
+
Replace the contents of the file with the following code.
|
377 |
+
|
378 |
+
usingSystem.Web;
|
379 |
+
usingSystem.Web.Mvc;
|
380 |
+
|
381 |
+
namespaceMvcMovie.Controllers
|
382 |
+
{
|
383 |
+
publicclassHelloWorldController:Controller
|
384 |
+
{
|
385 |
+
//
|
386 |
+
// GET: /HelloWorld/
|
387 |
+
|
388 |
+
|
389 |
+
|
390 |
+
publicstringIndex()
|
391 |
+
{
|
392 |
+
return"This is my <b>default</b> action...";
|
393 |
+
}
|
394 |
+
|
395 |
+
//
|
396 |
+
// GET: /HelloWorld/Welcome/
|
397 |
+
|
398 |
+
publicstringWelcome()
|
399 |
+
{
|
400 |
+
return"This is the Welcome action method...";
|
401 |
+
}
|
402 |
+
}
|
403 |
+
}
|
404 |
+
|
405 |
+
The controller methods will return a string of HTML as an example. The controller is
|
406 |
+
namedHelloWorldControllerand the first method above is namedIndex. Let’s invoke it from a browser.
|
407 |
+
Run the application (press F5 or Ctrl+F5). In the browser, append "HelloWorld" to the path in the address
|
408 |
+
bar. (For example, in the illustration below, it'shttp://localhost:1234/HelloWorld.) The page in the browser
|
409 |
+
will look like the following screenshot. In the method above, the code returned a string directly. You told
|
410 |
+
the system to just return some HTML, and it did!
|
411 |
+
|
412 |
+
ASP.NET MVC invokes different controller classes (and different action methods within them) depending
|
413 |
+
on the incoming URL. The default URL routing logic used by ASP.NET MVC uses a format like this to
|
414 |
+
determine what code to invoke:
|
415 |
+
|
416 |
+
/[Controller]/[ActionName]/[Parameters]
|
417 |
+
The first part of the URL determines the controller class to execute. So/HelloWorldmaps to the
|
418 |
+
HelloWorldControllerclass. The second part of the URL determines the action method on the class to
|
419 |
+
|
420 |
+
|
421 |
+
|
422 |
+
|
423 |
+
|
424 |
+
execute. So/HelloWorld/Indexwould cause theIndexmethod of theHelloWorldControllerclass to
|
425 |
+
execute. Notice that we only had to browse to/HelloWorldand theIndexmethod was used by default. This
|
426 |
+
is because a method named Indexis the default method that will be called on a controller if one is not
|
427 |
+
explicitly specified.
|
428 |
+
Browse tohttp://localhost:xxxx/HelloWorld/Welcome. TheWelcomemethod runs and returns the string "This
|
429 |
+
is the Welcome action method...". The default MVC mapping
|
430 |
+
is/[Controller]/[ActionName]/[Parameters]. For this URL, the controller
|
431 |
+
isHelloWorldandWelcomeis the action method. You haven't used the[Parameters]part of the URL yet.
|
432 |
+
|
433 |
+
Let's modify the example slightly so that you can pass some parameter information from the URL to the
|
434 |
+
controller (for example,/HelloWorld/Welcome?name=Scott&numtimes=4). Change yourWelcomemethod
|
435 |
+
to include two parameters as shown below. Note that the code uses the C# optional-parameter feature to
|
436 |
+
indicate that the numTimesparameter should default to 1 if no value is passed for that parameter.
|
437 |
+
|
438 |
+
publicstringWelcome(string name,int numTimes =1){
|
439 |
+
returnHttpUtility.HtmlEncode("Hello "+ name +", NumTimes is: "+ numTimes);
|
440 |
+
}
|
441 |
+
|
442 |
+
Run your application and browse to the example URL
|
443 |
+
(http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4). You can try different values
|
444 |
+
fornameandnumtimesin the URL. The ASP.NET MVC model binding system automatically maps the named
|
445 |
+
parameters from the query string in the address bar to parameters in your method.
|
446 |
+
|
447 |
+
|
448 |
+
In both these examples the controller has been doing the "VC" portion of MVC — that is, the view and
|
449 |
+
controller work. The controller is returning HTML directly. Ordinarily you don't want controllers returning
|
450 |
+
HTML directly, since that becomes very cumbersome to code. Instead we'll typically use a separate view
|
451 |
+
template file to help generate the HTML response. Let's look next at how we can do this.
|
452 |
+
|
453 |
+
|
454 |
+
|
455 |
+
|
456 |
+
Adding a View
|
457 |
+
|
458 |
+
In this section you're going to modify the HelloWorldController class to use view template files to cleanly
|
459 |
+
|
460 |
+
encapsulate the process of generating HTML responses to a client.
|
461 |
+
|
462 |
+
You'll create a view template file using theRazor view engine introduced with ASP.NET MVC 3. Razor-based
|
463 |
+
|
464 |
+
view templates have a .cshtml file extension, and provide an elegant way to create HTML output using C#. Razor
|
465 |
+
|
466 |
+
minimizes the number of characters and keystrokes required when writing a view template, and enables a fast,
|
467 |
+
|
468 |
+
fluid coding workflow.
|
469 |
+
|
470 |
+
Start by creating a view template with the Index method in theHelloWorldController class. Currently the
|
471 |
+
|
472 |
+
Index method returns a string with a message that is hard-coded in the controller class. Change the Index
|
473 |
+
|
474 |
+
method to return a View object, as shown in the following code:
|
475 |
+
|
476 |
+
publicActionResultIndex()
|
477 |
+
|
478 |
+
{
|
479 |
+
|
480 |
+
returnView();
|
481 |
+
|
482 |
+
}
|
483 |
+
|
484 |
+
The Index method above uses a view template to generate an HTML response to the browser. Controller
|
485 |
+
|
486 |
+
methods (also known asaction methods), such as the Index method above, generally return anActionResult (or a
|
487 |
+
|
488 |
+
class derrived fromActionResult), not primitive types like string.
|
489 |
+
|
490 |
+
In the project, add a view template that you can use with the Index method. To do this, right-click inside the
|
491 |
+
|
492 |
+
Index method and clickAdd View.
|
493 |
+
|
494 |
+
|
495 |
+
The Add View dialog box appears. Leave the defaults the way they are and click the Add button:
|
496 |
+
|
497 |
+
The MvcMovie\Views\HelloWorld folder and the MvcMovie\Views\HelloWorld\Index.cshtml file are created. You
|
498 |
+
|
499 |
+
can see them in Solution Explorer:
|
500 |
+
|
501 |
+
|
502 |
+
The following shows the Index.cshtml file that was created:
|
503 |
+
|
504 |
+
|
505 |
+
Add the following HTML under the <h2> tag.
|
506 |
+
|
507 |
+
<p>Hello from our View Template!</p>
|
508 |
+
|
509 |
+
The complete MvcMovie\Views\HelloWorld\Index.cshtml file is shown below.
|
510 |
+
|
511 |
+
@{
|
512 |
+
|
513 |
+
ViewBag.Title = "Index";
|
514 |
+
|
515 |
+
}
|
516 |
+
|
517 |
+
|
518 |
+
<h2>Index</h2>
|
519 |
+
|
520 |
+
<p>Hello from our View Template!</p>
|
521 |
+
|
522 |
+
In solution explorer, right click the Index.cshtml file and selectView in Page Inspector.
|
523 |
+
|
524 |
+
ThePage Inspector tutorial has more information about this new tool.
|
525 |
+
|
526 |
+
|
527 |
+
|
528 |
+
|
529 |
+
Alternatively, run the application and browse to the HelloWorld controller (http://localhost:xxxx/HelloWorld).
|
530 |
+
|
531 |
+
The Index method in your controller didn't do much work; it simply ran the statement return View(), which
|
532 |
+
|
533 |
+
specified that the method should use a view template file to render a response to the browser. Because you
|
534 |
+
|
535 |
+
didn't explicitly specify the name of the view template file to use, ASP.NET MVC defaulted to using the
|
536 |
+
|
537 |
+
Index.cshtml view file in the \Views\HelloWorld folder. The image below shows the string hard-coded in the
|
538 |
+
|
539 |
+
view.
|
540 |
+
|
541 |
+
Looks pretty good. However, notice that the browser's title bar shows "Index My ASP.NET A" and the big link on
|
542 |
+
|
543 |
+
the top of the page says "your logo here." Below the "your logo here." link are registration and log in links, and
|
544 |
+
|
545 |
+
below that links to Home, About and Contact pages. Let's change some of these.
|
546 |
+
|
547 |
+
Changing Views and Layout Pages
|
548 |
+
|
549 |
+
First, you want to change the "your logo here." title at the top of the page. That text is common to every page.
|
550 |
+
|
551 |
+
It's actually implemented in only one place in the project, even though it appears on every page in the
|
552 |
+
|
553 |
+
application. Go to the /Views/Shared folder in Solution Explorer and open the _Layout.cshtml file. This file is
|
554 |
+
|
555 |
+
called a layout page and it's the shared "shell" that all other pages use.
|
556 |
+
|
557 |
+
|
558 |
+
|
559 |
+
Layout templates allow you to specify the HTML container layout of your site in one place and then apply it
|
560 |
+
|
561 |
+
across multiple pages in your site. Find the@RenderBody() line. RenderBody is a placeholder where all the
|
562 |
+
|
563 |
+
view-specific pages you create show up, "wrapped" in the layout page. For example, if you select the About link,
|
564 |
+
|
565 |
+
the Views\Home\About.cshtml view is rendered inside the RenderBody method.
|
566 |
+
|
567 |
+
Change the site-title heading in the layout template from "your logo here" to "MVC Movie".
|
568 |
+
|
569 |
+
<divclass="float-left">
|
570 |
+
|
571 |
+
<pclass="site-title">@Html.ActionLink("MVC Movie", "Index", "Home")</p>
|
572 |
+
|
573 |
+
</div>
|
574 |
+
|
575 |
+
Replace the contents of the title element with the following markup:
|
576 |
+
|
577 |
+
<title>@ViewBag.Title - Movie App</title>
|
578 |
+
|
579 |
+
The ViewBag is a zzz (dict object) Run the application and notice that it now says "MVC Movie ". Click theAbout
|
580 |
+
|
581 |
+
link, and you see how that page shows "MVC Movie", too. We were able to make the change once in the layout
|
582 |
+
|
583 |
+
template and have all pages on the site reflect the new title.
|
584 |
+
|
585 |
+
The complete _Layout.cshtml file is shown below:
|
586 |
+
|
587 |
+
<!DOCTYPE html>
|
588 |
+
|
589 |
+
<htmllang="en">
|
590 |
+
|
591 |
+
<head>
|
592 |
+
|
593 |
+
<metacharset="utf-8"/>
|
594 |
+
|
595 |
+
<title>@ViewBag.Title - Movie App</title>
|
596 |
+
|
597 |
+
<linkhref="~/favicon.ico"rel="shortcut icon"type="image/x-icon"/>
|
598 |
+
|
599 |
+
<linkhref="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/c
|
600 |
+
|
601 |
+
ss")"rel="stylesheet"type="text/css"/>
|
602 |
+
|
603 |
+
<linkhref="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/t
|
604 |
+
|
605 |
+
hemes/base/css")"rel="stylesheet"type="text/css"/>
|
606 |
+
|
607 |
+
<scriptsrc="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/
|
608 |
+
|
609 |
+
js")"></script>
|
610 |
+
|
611 |
+
<metaname="viewport"content="width=device-width"/>
|
612 |
+
|
613 |
+
</head>
|
614 |
+
|
615 |
+
|
616 |
+
<body>
|
617 |
+
|
618 |
+
<header>
|
619 |
+
|
620 |
+
<divclass="content-wrapper">
|
621 |
+
|
622 |
+
<divclass="float-left">
|
623 |
+
|
624 |
+
<pclass="site-title">@Html.ActionLink("MVC Movie", "Index", "Home")</p>
|
625 |
+
|
626 |
+
</div>
|
627 |
+
|
628 |
+
<divclass="float-right">
|
629 |
+
|
630 |
+
<sectionid="login">
|
631 |
+
|
632 |
+
@Html.Partial("_LoginPartial")
|
633 |
+
|
634 |
+
</section>
|
635 |
+
|
636 |
+
<nav>
|
637 |
+
|
638 |
+
<ulid="menu">
|
639 |
+
|
640 |
+
<li>@Html.ActionLink("Home", "Index", "Home")</li>
|
641 |
+
|
642 |
+
<li>@Html.ActionLink("About", "About", "Home")</li>
|
643 |
+
|
644 |
+
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
|
645 |
+
|
646 |
+
</ul>
|
647 |
+
|
648 |
+
</nav>
|
649 |
+
|
650 |
+
</div>
|
651 |
+
|
652 |
+
</div>
|
653 |
+
|
654 |
+
</header>
|
655 |
+
|
656 |
+
<divid="body">
|
657 |
+
|
658 |
+
@RenderSection("featured", required: false)
|
659 |
+
|
660 |
+
<sectionclass="content-wrapper main-content clear-fix">
|
661 |
+
|
662 |
+
@RenderBody()
|
663 |
+
|
664 |
+
</section>
|
665 |
+
|
666 |
+
</div>
|
667 |
+
|
668 |
+
<footer>
|
669 |
+
|
670 |
+
<divclass="content-wrapper">
|
671 |
+
|
672 |
+
<divclass="float-left">
|
673 |
+
|
674 |
+
<p>© @DateTime.Now.Year - My ASP.NET MVC Application</p>
|
675 |
+
|
676 |
+
</div>
|
677 |
+
|
678 |
+
<divclass="float-right">
|
679 |
+
|
680 |
+
<ulid="social">
|
681 |
+
|
682 |
+
<li><ahref="http://facebook.com"class="facebook">Facebook</a></li>
|
683 |
+
|
684 |
+
<li><ahref="http://twitter.com"class="twitter">Twitter</a></li>
|
685 |
+
|
686 |
+
</ul>
|
687 |
+
|
688 |
+
</div>
|
689 |
+
|
690 |
+
</div>
|
691 |
+
|
692 |
+
</footer>
|
693 |
+
|
694 |
+
</body>
|
695 |
+
|
696 |
+
</html>
|
697 |
+
|
698 |
+
Now, let's change the title of the Index view.
|
699 |
+
|
700 |
+
Open MvcMovie\Views\HelloWorld\Index.cshtml. There are two places to make a change: first, the text that
|
701 |
+
|
702 |
+
appears in the title of the browser, and then in the secondary header (the <h2> element). You'll make them
|
703 |
+
|
704 |
+
slightly different so you can see which bit of code changes which part of the app.
|
705 |
+
|
706 |
+
@{
|
707 |
+
|
708 |
+
ViewBag.Title = "Movie List";
|
709 |
+
|
710 |
+
}
|
711 |
+
|
712 |
+
<h2>My Movie List</h2>
|
713 |
+
|
714 |
+
<p>Hello from our View Template!</p>
|
715 |
+
|
716 |
+
To indicate the HTML title to display, the code above sets a Title property of the ViewBag object (which is in
|
717 |
+
|
718 |
+
the Index.cshtml view template). If you look back at the source code of the layout template, you’ll notice that
|
719 |
+
|
720 |
+
the template uses this value in the <title> element as part of the <head> section of the HTML that we
|
721 |
+
|
722 |
+
modified previously. Using this ViewBag approach, you can easily pass other parameters between your view
|
723 |
+
|
724 |
+
template and your layout file.
|
725 |
+
|
726 |
+
Run the application and browse to http://localhost:xx/HelloWorld. Notice that the browser title, the primary
|
727 |
+
|
728 |
+
heading, and the secondary headings have changed. (If you don't see changes in the browser, you might be
|
729 |
+
|
730 |
+
viewing cached content. Press Ctrl+F5 in your browser to force the response from the server to be loaded.) The
|
731 |
+
|
732 |
+
browser title is created with the ViewBag.Title we set in the Index.cshtml view template and the additional "-
|
733 |
+
|
734 |
+
Movie App" added in the layout file.
|
735 |
+
|
736 |
+
Also notice how the content in the Index.cshtml view template was merged with the _Layout.cshtml view
|
737 |
+
|
738 |
+
template and a single HTML response was sent to the browser. Layout templates make it really easy to make
|
739 |
+
|
740 |
+
changes that apply across all of the pages in your application.
|
741 |
+
|
742 |
+
|
743 |
+
|
744 |
+
Our little bit of "data" (in this case the "Hello from our View Template!" message) is hard-coded, though. The
|
745 |
+
|
746 |
+
MVC application has a "V" (view) and you've got a "C" (controller), but no "M" (model) yet. Shortly, we'll walk
|
747 |
+
|
748 |
+
through how create a database and retrieve model data from it.
|
749 |
+
|
750 |
+
Passing Data from the Controller to the View
|
751 |
+
|
752 |
+
Before we go to a database and talk about models, though, let's first talk about passing information from the
|
753 |
+
|
754 |
+
controller to a view. Controller classes are invoked in response to an incoming URL request. A controller class is
|
755 |
+
|
756 |
+
where you write the code that handles the incoming browser requests, retrieves data from a database, and
|
757 |
+
|
758 |
+
ultimately decides what type of response to send back to the browser. View templates can then be used from a
|
759 |
+
|
760 |
+
controller to generate and format an HTML response to the browser.
|
761 |
+
|
762 |
+
Controllers are responsible for providing whatever data or objects are required in order for a view template to
|
763 |
+
|
764 |
+
render a response to the browser. A best practice: A view template should never perform business logic or
|
765 |
+
|
766 |
+
interact with a database directly. Instead, a view template should work only with the data that's provided to it
|
767 |
+
|
768 |
+
by the controller. Maintaining this "separation of concerns" helps keep your code clean, testable and more
|
769 |
+
|
770 |
+
maintainable.
|
771 |
+
|
772 |
+
|
773 |
+
Currently, the Welcome action method in the HelloWorldController class takes a name and a numTimes
|
774 |
+
|
775 |
+
parameter and then outputs the values directly to the browser. Rather than have the controller render this
|
776 |
+
|
777 |
+
response as a string, let’s change the controller to use a view template instead. The view template will generate
|
778 |
+
|
779 |
+
a dynamic response, which means that you need to pass appropriate bits of data from the controller to the view
|
780 |
+
|
781 |
+
in order to generate the response. You can do this by having the controller put the dynamic data (parameters)
|
782 |
+
|
783 |
+
that the view template needs in a ViewBag object that the view template can then access.
|
784 |
+
|
785 |
+
Return to the HelloWorldController.cs file and change the Welcome method to add a Message and NumTimes
|
786 |
+
|
787 |
+
value to the ViewBag object. ViewBag is a dynamic object, which means you can put whatever you want in to
|
788 |
+
|
789 |
+
it; the ViewBag object has no defined properties until you put something inside it. TheASP.NET MVC model
|
790 |
+
|
791 |
+
binding system automatically maps the named parameters (nameand numTimes) from the query string in the
|
792 |
+
|
793 |
+
address bar to parameters in your method. The completeHelloWorldController.cs file looks like this:
|
794 |
+
|
795 |
+
usingSystem.Web;
|
796 |
+
|
797 |
+
usingSystem.Web.Mvc;
|
798 |
+
|
799 |
+
namespaceMvcMovie.Controllers
|
800 |
+
|
801 |
+
{
|
802 |
+
|
803 |
+
publicclassHelloWorldController:Controller
|
804 |
+
|
805 |
+
{
|
806 |
+
|
807 |
+
publicActionResultIndex()
|
808 |
+
|
809 |
+
{
|
810 |
+
|
811 |
+
returnView();
|
812 |
+
|
813 |
+
}
|
814 |
+
|
815 |
+
publicActionResultWelcome(string name,int numTimes =1)
|
816 |
+
|
817 |
+
{
|
818 |
+
|
819 |
+
ViewBag.Message="Hello "+ name;
|
820 |
+
|
821 |
+
ViewBag.NumTimes= numTimes;
|
822 |
+
|
823 |
+
returnView();
|
824 |
+
|
825 |
+
}
|
826 |
+
|
827 |
+
}
|
828 |
+
|
829 |
+
}
|
830 |
+
|
831 |
+
Now the ViewBag object contains data that will be passed to the view automatically.
|
832 |
+
|
833 |
+
|
834 |
+
|
835 |
+
|
836 |
+
Next, you need a Welcome view template! In the Build menu, select Build MvcMovie to make sure the project
|
837 |
+
|
838 |
+
is compiled.
|
839 |
+
|
840 |
+
Then right-click inside the Welcome method and click Add View.
|
841 |
+
|
842 |
+
|
843 |
+
|
844 |
+
Here's what the Add View dialog box looks like:
|
845 |
+
|
846 |
+
Click Add, and then add the following code under the < h2> element in the new Welcome.cshtml file. You'll
|
847 |
+
|
848 |
+
create a loop that says "Hello" as many times as the user says it should. The completeWelcome.cshtml file is
|
849 |
+
|
850 |
+
shown below.
|
851 |
+
|
852 |
+
@{
|
853 |
+
|
854 |
+
ViewBag.Title = "Welcome";
|
855 |
+
|
856 |
+
}
|
857 |
+
|
858 |
+
<h2>Welcome</h2>
|
859 |
+
|
860 |
+
<ul>
|
861 |
+
|
862 |
+
|
863 |
+
|
864 |
+
|
865 |
+
@for (int i=0; i < ViewBag.NumTimes; i++) {
|
866 |
+
|
867 |
+
<li>@ViewBag.Message</li>
|
868 |
+
|
869 |
+
}
|
870 |
+
|
871 |
+
</ul>
|
872 |
+
|
873 |
+
Run the application and browse to the following URL:
|
874 |
+
|
875 |
+
http://localhost:xx/HelloWorld/Welcome?name=Scott&numtimes=4
|
876 |
+
|
877 |
+
Now data is taken from the URL and passed to the controller using themodel binder. The controller packages
|
878 |
+
|
879 |
+
the data into a ViewBag object and passes that object to the view. The view then displays the data as HTML to
|
880 |
+
|
881 |
+
the user.
|
882 |
+
|
883 |
+
Well, that was a kind of an "M" for model, but not the database kind. Let's take what we've learned and create a
|
884 |
+
|
885 |
+
database of movies.
|
886 |
+
|
887 |
+
|
888 |
+
|
889 |
+
|
890 |
+
Adding a Model
|
891 |
+
|
892 |
+
In this section you'll add some classes for managing movies in a database. These classes will be the "model"
|
893 |
+
|
894 |
+
part of the ASP.NET MVC application.
|
895 |
+
|
896 |
+
You’ll use a .NET Framework data-access technology known as the Entity Framework to define and work with
|
897 |
+
|
898 |
+
these model classes. The Entity Framework (often referred to as EF) supports a development paradigm called
|
899 |
+
|
900 |
+
Code First. Code First allows you to create model objects by writing simple classes. (These are also known as
|
901 |
+
|
902 |
+
POCO classes, from "plain-old CLR objects.") You can then have the database created on the fly from your
|
903 |
+
|
904 |
+
classes, which enables a very clean and rapid development workflow.
|
905 |
+
|
906 |
+
Adding Model Classes
|
907 |
+
|
908 |
+
In Solution Explorer, right click the Models folder, select Add, and then select New Item.
|
909 |
+
|
910 |
+
|
911 |
+
In the Add New Item dialog, select Class then name the class "Movie".
|
912 |
+
|
913 |
+
|
914 |
+
Add the following five properties to the Movie class:
|
915 |
+
|
916 |
+
publicclassMovie
|
917 |
+
|
918 |
+
{
|
919 |
+
|
920 |
+
publicint ID {get;set;}
|
921 |
+
|
922 |
+
publicstringTitle{get;set;}
|
923 |
+
|
924 |
+
publicDateTimeReleaseDate{get;set;}
|
925 |
+
|
926 |
+
publicstringGenre{get;set;}
|
927 |
+
|
928 |
+
publicdecimalPrice{get;set;}
|
929 |
+
|
930 |
+
|
931 |
+
}
|
932 |
+
|
933 |
+
We'll use the Movie class to represent movies in a database. Each instance of a Movie object will correspond to
|
934 |
+
|
935 |
+
a row within a database table, and each property of the Movie class will map to a column in the table.
|
936 |
+
|
937 |
+
In the same file, add the following MovieDBContext class:
|
938 |
+
|
939 |
+
publicclassMovieDBContext:DbContext
|
940 |
+
|
941 |
+
{
|
942 |
+
|
943 |
+
publicDbSet<Movie>Movies{get;set;}
|
944 |
+
|
945 |
+
}
|
946 |
+
|
947 |
+
The MovieDBContext class represents the Entity Framework movie database context, which handles fetching,
|
948 |
+
|
949 |
+
storing, and updating Movie class instances in a database. The MovieDBContext derives from theDbContext
|
950 |
+
|
951 |
+
base class provided by the Entity Framework. For more information about DbContext and DbSet,
|
952 |
+
|
953 |
+
seeProductivity Improvements for the Entity Framework.
|
954 |
+
|
955 |
+
In order to be able to reference DbContext and DbSet, you need to add the following using statement at the
|
956 |
+
|
957 |
+
top of the file:
|
958 |
+
|
959 |
+
usingSystem.Data.Entity;
|
960 |
+
|
961 |
+
The complete Movie.cs file is shown below. (Several using statements that are not needed have been removed.)
|
962 |
+
|
963 |
+
usingSystem;
|
964 |
+
|
965 |
+
usingSystem.Data.Entity;
|
966 |
+
|
967 |
+
namespaceMvcMovie.Models
|
968 |
+
|
969 |
+
{
|
970 |
+
|
971 |
+
publicclassMovie
|
972 |
+
|
973 |
+
{
|
974 |
+
|
975 |
+
publicint ID {get;set;}
|
976 |
+
|
977 |
+
publicstringTitle{get;set;}
|
978 |
+
|
979 |
+
publicDateTimeReleaseDate{get;set;}
|
980 |
+
|
981 |
+
publicstringGenre{get;set;}
|
982 |
+
|
983 |
+
publicdecimalPrice{get;set;}
|
984 |
+
|
985 |
+
|
986 |
+
}
|
987 |
+
|
988 |
+
publicclassMovieDBContext:DbContext
|
989 |
+
|
990 |
+
{
|
991 |
+
|
992 |
+
publicDbSet<Movie>Movies{get;set;}
|
993 |
+
|
994 |
+
}
|
995 |
+
|
996 |
+
}
|
997 |
+
|
998 |
+
Creating a Connection String and Working with SQL Server LocalDB
|
999 |
+
|
1000 |
+
The MovieDBContext class you created handles the task of connecting to the database and mapping Movie
|
1001 |
+
|
1002 |
+
objects to database records. One question you might ask, though, is how to specify which database it will
|
1003 |
+
|
1004 |
+
connect to. You'll do that by adding connection information in the Web.config file of the application.
|
1005 |
+
|
1006 |
+
Open the application root Web.config file. (Not the Web.configfile in the Views folder.) Open the Web.config file
|
1007 |
+
|
1008 |
+
outlined in red.
|
1009 |
+
|
1010 |
+
Add the following connection string to the <connectionStrings> element in the Web.config file.
|
1011 |
+
|
1012 |
+
<addname="MovieDBContext"
|
1013 |
+
|
1014 |
+
|
1015 |
+
|
1016 |
+
connectionString="Data
|
1017 |
+
|
1018 |
+
Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated
|
1019 |
+
|
1020 |
+
Security=True"
|
1021 |
+
|
1022 |
+
providerName="System.Data.SqlClient"
|
1023 |
+
|
1024 |
+
/>
|
1025 |
+
|
1026 |
+
The following example shows a portion of the Web.config file with the new connection string added:
|
1027 |
+
|
1028 |
+
<connectionStrings>
|
1029 |
+
|
1030 |
+
<addname="DefaultConnection"
|
1031 |
+
|
1032 |
+
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcMovie-
|
1033 |
+
|
1034 |
+
2012213181139;Integrated Security=true"
|
1035 |
+
|
1036 |
+
providerName="System.Data.SqlClient"
|
1037 |
+
|
1038 |
+
/>
|
1039 |
+
|
1040 |
+
<addname="MovieDBContext"
|
1041 |
+
|
1042 |
+
connectionString="Data
|
1043 |
+
|
1044 |
+
Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated
|
1045 |
+
|
1046 |
+
Security=True"
|
1047 |
+
|
1048 |
+
providerName="System.Data.SqlClient"
|
1049 |
+
|
1050 |
+
/>
|
1051 |
+
|
1052 |
+
</connectionStrings>
|
1053 |
+
|
1054 |
+
This small amount of code and XML is everything you need to write in order to represent and store the movie
|
1055 |
+
|
1056 |
+
data in a database.
|
1057 |
+
|
1058 |
+
Next, you'll build a new MoviesController class that you can use to display the movie data and allow users
|
1059 |
+
|
1060 |
+
to create new movie listings.
|
1061 |
+
|
1062 |
+
|
1063 |
+
|
1064 |
+
Accessing Your Model's Data from a Controller
|
1065 |
+
|
1066 |
+
In this section, you'll create a new MoviesController class and write code that retrieves the movie data and
|
1067 |
+
|
1068 |
+
displays it in the browser using a view template.
|
1069 |
+
|
1070 |
+
Build the application before going on to the next step.
|
1071 |
+
|
1072 |
+
Right-click the Controllers folder and create a new MoviesController controller. The options below will not
|
1073 |
+
|
1074 |
+
appear until you build your application. Select the following options:
|
1075 |
+
|
1076 |
+
• Controller name: MoviesController. (This is the default. )
|
1077 |
+
|
1078 |
+
•
|
1079 |
+
|
1080 |
+
Template: Controller with read/write actions and views, using Entity Framework.
|
1081 |
+
|
1082 |
+
• Model class: Movie (MvcMovie.Models).
|
1083 |
+
|
1084 |
+
• Data context class: MovieDBContext (MvcMovie.Models).
|
1085 |
+
|
1086 |
+
• Views: Razor (CSHTML). (The default.)
|
1087 |
+
|
1088 |
+
Click Add. Visual Studio Express creates the following files and folders:
|
1089 |
+
|
1090 |
+
• A MoviesController.csfile in the project's Controllers folder.
|
1091 |
+
|
1092 |
+
|
1093 |
+
• A Movies folder in the project's Views folder.
|
1094 |
+
|
1095 |
+
• Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Movies folder.
|
1096 |
+
|
1097 |
+
|
1098 |
+
ASP.NET MVC 4 automatically created the CRUD (create, read, update, and delete) action methods and views
|
1099 |
+
|
1100 |
+
for you (the automatic creation of CRUD action methods and views is known as scaffolding). You now have a
|
1101 |
+
|
1102 |
+
fully functional web application that lets you create, list, edit, and delete movie entries.
|
1103 |
+
|
1104 |
+
Run the application and browse to the Movies controller by appending /Movies to the URL in the address bar
|
1105 |
+
|
1106 |
+
of your browser. Because the application is relying on the default routing (defined in the Global.asax file), the
|
1107 |
+
|
1108 |
+
browser request http://localhost:xxxxx/Movies is routed to the default Index action method of the Movies
|
1109 |
+
|
1110 |
+
controller. In other words, the browser request http://localhost:xxxxx/Movies is effectively the same as the
|
1111 |
+
|
1112 |
+
browser request http://localhost:xxxxx/Movies/Index. The result is an empty list of movies, because you haven't
|
1113 |
+
|
1114 |
+
added any yet.
|
1115 |
+
|
1116 |
+
Creating a Movie
|
1117 |
+
|
1118 |
+
Select the Create New link. Enter some details about a movie and then click the Create button.
|
1119 |
+
|
1120 |
+
|
1121 |
+
Clicking the Create button causes the form to be posted to the server, where the movie information is saved in
|
1122 |
+
|
1123 |
+
the database. You're then redirected to the /Movies URL, where you can see the newly created movie in the
|
1124 |
+
|
1125 |
+
listing.
|
1126 |
+
|
1127 |
+
|
1128 |
+
Create a couple more movie entries. Try the Edit, Details, and Delete links, which are all functional.
|
1129 |
+
|
1130 |
+
Examining the Generated Code
|
1131 |
+
|
1132 |
+
Open the Controllers\MoviesController.cs file and examine the generated Index method. A portion of the movie
|
1133 |
+
|
1134 |
+
controller with theIndex method is shown below.
|
1135 |
+
|
1136 |
+
publicclassMoviesController:Controller
|
1137 |
+
|
1138 |
+
{
|
1139 |
+
|
1140 |
+
privateMovieDBContext db =newMovieDBContext();
|
1141 |
+
|
1142 |
+
//
|
1143 |
+
|
1144 |
+
// GET: /Movies/
|
1145 |
+
|
1146 |
+
publicActionResultIndex()
|
1147 |
+
|
1148 |
+
{
|
1149 |
+
|
1150 |
+
returnView(db.Movies.ToList());
|
1151 |
+
|
1152 |
+
|
1153 |
+
|
1154 |
+
|
1155 |
+
}
|
1156 |
+
|
1157 |
+
The following line from the MoviesController class instantiates a movie database context, as described
|
1158 |
+
|
1159 |
+
previously. You can use the movie database context to query, edit, and delete movies.
|
1160 |
+
|
1161 |
+
privateMovieDBContext db =newMovieDBContext();
|
1162 |
+
|
1163 |
+
A request to the Movies controller returns all the entries in the Movies table of the movie database and then
|
1164 |
+
|
1165 |
+
passes the results to the Index view.
|
1166 |
+
|
1167 |
+
Strongly Typed Models and the @model Keyword
|
1168 |
+
|
1169 |
+
Earlier in this tutorial, you saw how a controller can pass data or objects to a view template using the ViewBag
|
1170 |
+
|
1171 |
+
object. The ViewBag is a dynamic object that provides a convenient late-bound way to pass information to a
|
1172 |
+
|
1173 |
+
view.
|
1174 |
+
|
1175 |
+
ASP.NET MVC also provides the ability to pass strongly typed data or objects to a view template. This strongly
|
1176 |
+
|
1177 |
+
typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Studio
|
1178 |
+
|
1179 |
+
Express editor. The scaffolding mechanism in Visual Studio Express used this approach with the
|
1180 |
+
|
1181 |
+
MoviesController class and view templates when it created the methods and views.
|
1182 |
+
|
1183 |
+
In the Controllers\MoviesController.cs file examine the generated Details method. A portion of the movie
|
1184 |
+
|
1185 |
+
controller with theDetails method is shown below.
|
1186 |
+
|
1187 |
+
publicActionResultDetails(int id =0)
|
1188 |
+
|
1189 |
+
{
|
1190 |
+
|
1191 |
+
Movie movie =db.Movies.Find(id);
|
1192 |
+
|
1193 |
+
if(movie ==null)
|
1194 |
+
|
1195 |
+
{
|
1196 |
+
|
1197 |
+
returnHttpNotFound();
|
1198 |
+
|
1199 |
+
}
|
1200 |
+
|
1201 |
+
returnView(movie);
|
1202 |
+
|
1203 |
+
}
|
1204 |
+
|
1205 |
+
An instance of the Movie model is passed to the Details view.
|
1206 |
+
|
1207 |
+
By including a @model statement at the top of the view template file, you can specify the type of object that the
|
1208 |
+
|
1209 |
+
view expects. When you created the movie controller, Visual Studio Express automatically included the
|
1210 |
+
|
1211 |
+
following@model statement at the top of the Details.cshtml file:
|
1212 |
+
|
1213 |
+
@model MvcMovie.Models.Movie
|
1214 |
+
|
1215 |
+
This @model directive allows you to access the movie that the controller passed to the view by using a Model
|
1216 |
+
|
1217 |
+
object that's strongly typed. For example, in the Details.cshtml template, the code passes each movie field to
|
1218 |
+
|
1219 |
+
the DisplayNameFor and DisplayFor HTML Helpers with the strongly typed Model object. The Create and Edit
|
1220 |
+
|
1221 |
+
methods and view templates also pass a movie model object.
|
1222 |
+
|
1223 |
+
Examine the Index.cshtml view template and the Index method in the MoviesController.cs file. Notice how the
|
1224 |
+
|
1225 |
+
code creates aList object when it calls the View helper method in the Index action method. The code then
|
1226 |
+
|
1227 |
+
passes this Movies list from the controller to the view:
|
1228 |
+
|
1229 |
+
publicActionResultIndex()
|
1230 |
+
|
1231 |
+
{
|
1232 |
+
|
1233 |
+
returnView(db.Movies.ToList());
|
1234 |
+
|
1235 |
+
}
|
1236 |
+
|
1237 |
+
When you created the movie controller, Visual Studio Express automatically included the following@model
|
1238 |
+
|
1239 |
+
statement at the top of the Index.cshtml file:
|
1240 |
+
|
1241 |
+
@model IEnumerable<MvcMovie.Models.Movie>
|
1242 |
+
|
1243 |
+
This @model directive allows you to access the list of movies that the controller passed to the view by using a
|
1244 |
+
|
1245 |
+
Model object that's strongly typed. For example, in the Index.cshtml template, the code loops through the
|
1246 |
+
|
1247 |
+
movies by doing a foreach statement over the strongly typed Model object:
|
1248 |
+
|
1249 |
+
@foreach (var item in Model) {
|
1250 |
+
|
1251 |
+
<tr>
|
1252 |
+
|
1253 |
+
<td>
|
1254 |
+
|
1255 |
+
@Html.DisplayFor(modelItem => item.Title)
|
1256 |
+
|
1257 |
+
</td>
|
1258 |
+
|
1259 |
+
<td>
|
1260 |
+
|
1261 |
+
@Html.DisplayFor(modelItem => item.ReleaseDate)
|
1262 |
+
|
1263 |
+
</td>
|
1264 |
+
|
1265 |
+
<td>
|
1266 |
+
|
1267 |
+
@Html.DisplayFor(modelItem => item.Genre)
|
1268 |
+
|
1269 |
+
</td>
|
1270 |
+
|
1271 |
+
<td>
|
1272 |
+
|
1273 |
+
@Html.DisplayFor(modelItem => item.Price)
|
1274 |
+
|
1275 |
+
</td>
|
1276 |
+
|
1277 |
+
<th>
|
1278 |
+
|
1279 |
+
@Html.DisplayFor(modelItem => item.Rating)
|
1280 |
+
|
1281 |
+
</th>
|
1282 |
+
|
1283 |
+
<td>
|
1284 |
+
|
1285 |
+
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
|
1286 |
+
|
1287 |
+
@Html.ActionLink("Details", "Details", { id=item.ID }) |
|
1288 |
+
|
1289 |
+
@Html.ActionLink("Delete", "Delete", { id=item.ID })
|
1290 |
+
|
1291 |
+
</td>
|
1292 |
+
|
1293 |
+
</tr>
|
1294 |
+
|
1295 |
+
}
|
1296 |
+
|
1297 |
+
Because the Model object is strongly typed (as an IEnumerable<Movie> object), each item object in the loop
|
1298 |
+
|
1299 |
+
is typed as Movie. Among other benefits, this means that you get compile-time checking of the code and full
|
1300 |
+
|
1301 |
+
IntelliSense support in the code editor:
|
1302 |
+
|
1303 |
+
|
1304 |
+
Working with SQL Server LocalDB
|
1305 |
+
|
1306 |
+
Entity Framework Code First detected that the database connection string that was provided pointed to a
|
1307 |
+
|
1308 |
+
Movies database that didn’t exist yet, so Code First created the database automatically. You can verify that it's
|
1309 |
+
|
1310 |
+
been created by looking in the App_Data folder. If you don't see the Movies.sdf file, click the Show All Files
|
1311 |
+
|
1312 |
+
button in theSolution Explorer toolbar, click the Refresh button, and then expand the App_Data folder.
|
1313 |
+
|
1314 |
+
|
1315 |
+
Double-click Movies.mdf to open DATABASE EXPLORER. Then expand the Tables folder to see the tables that
|
1316 |
+
|
1317 |
+
have been created in the database.
|
1318 |
+
|
1319 |
+
|
1320 |
+
|
1321 |
+
There are two tables, one for the Movie entity set and theEdmMetadata table. The EdmMetadata table is used
|
1322 |
+
|
1323 |
+
by the Entity Framework to determine when the model and the database are out of sync.
|
1324 |
+
|
1325 |
+
Right-click the Movies table and select Show Table Data to see the data you created.
|
1326 |
+
|
1327 |
+
Right-click the Movies table and select Open Table Definition to see the table structure that Entity Framework
|
1328 |
+
|
1329 |
+
Code First created for you.
|
1330 |
+
|
1331 |
+
|
1332 |
+
|
1333 |
+
Notice how the schema of the Movies table maps to the Movie class you created earlier. Entity Framework
|
1334 |
+
|
1335 |
+
Code First automatically created this schema for you based on your Movie class.
|
1336 |
+
|
1337 |
+
When you're finished, close the connection by right clicking Movies.mdf and selecting Close Connection. (If you
|
1338 |
+
|
1339 |
+
don't close the connection, you might get an error the next time you run the project).
|
1340 |
+
|
1341 |
+
|
1342 |
+
You now have the database and a simple listing page to display content from it. In the next tutorial, we'll
|
1343 |
+
|
1344 |
+
examine the rest of the scaffolded code and add a SearchIndex method and a SearchIndex view that lets
|
1345 |
+
|
1346 |
+
you search for movies in this database.
|
1347 |
+
|
1348 |
+
|
1349 |
+
|
1350 |
+
|
1351 |
+
Examining the Edit Methods and Edit View
|
1352 |
+
|
1353 |
+
In this section, you'll examine the generated action methods and views for the movie controller. Then you'll add
|
1354 |
+
|
1355 |
+
a custom search page.
|
1356 |
+
|
1357 |
+
Run the application and browse to the Movies controller by appending /Movies to the URL in the address bar
|
1358 |
+
|
1359 |
+
of your browser. Hold the mouse pointer over an Edit link to see the URL that it links to.
|
1360 |
+
|
1361 |
+
The Edit link was generated by the Html.ActionLink method in the Views\Movies\Index.cshtml view:
|
1362 |
+
|
1363 |
+
@Html.ActionLink("Edit", "Edit", new { id=item.ID })
|
1364 |
+
|
1365 |
+
|
1366 |
+
The Html object is a helper that's exposed using a property on the System.Web.Mvc.WebViewPage base class.
|
1367 |
+
|
1368 |
+
The ActionLinkmethod of the helper makes it easy to dynamically generate HTML hyperlinks that link to
|
1369 |
+
|
1370 |
+
action methods on controllers. The first argument to the ActionLink method is the link text to render (for
|
1371 |
+
|
1372 |
+
example,<a>Edit Me</a>). The second argument is the name of the action method to invoke. The final
|
1373 |
+
|
1374 |
+
argument is ananonymous object that generates the route data (in this case, the ID of 4).
|
1375 |
+
|
1376 |
+
The generated link shown in the previous image is http://localhost:xxxxx/Movies/Edit/4. The default route
|
1377 |
+
|
1378 |
+
(established in Global.asax.cs) takes the URL pattern {controller}/{action}/{id}. Therefore, ASP.NET
|
1379 |
+
|
1380 |
+
translateshttp://localhost:xxxxx/Movies/Edit/4 into a request to the Edit action method of the Movies
|
1381 |
+
|
1382 |
+
controller with the parameter ID equal to 4.
|
1383 |
+
|
1384 |
+
You can also pass action method parameters using a query string. For example, the URL
|
1385 |
+
|
1386 |
+
http://localhost:xxxxx/Movies/Edit?ID=4 also passes the parameter ID of 4 to the Edit action method of
|
1387 |
+
|
1388 |
+
theMovies controller.
|
1389 |
+
|
1390 |
+
|
1391 |
+
Open the Movies controller. The two Edit action methods are shown below.
|
1392 |
+
|
1393 |
+
//
|
1394 |
+
|
1395 |
+
// GET: /Movies/Edit/5
|
1396 |
+
|
1397 |
+
publicActionResultEdit(int id =0)
|
1398 |
+
|
1399 |
+
{
|
1400 |
+
|
1401 |
+
Movie movie =db.Movies.Find(id);
|
1402 |
+
|
1403 |
+
if(movie ==null)
|
1404 |
+
|
1405 |
+
{
|
1406 |
+
|
1407 |
+
returnHttpNotFound();
|
1408 |
+
|
1409 |
+
}
|
1410 |
+
|
1411 |
+
|
1412 |
+
|
1413 |
+
returnView(movie);
|
1414 |
+
|
1415 |
+
}
|
1416 |
+
|
1417 |
+
//
|
1418 |
+
|
1419 |
+
// POST: /Movies/Edit/5
|
1420 |
+
|
1421 |
+
[HttpPost]
|
1422 |
+
|
1423 |
+
publicActionResultEdit(Movie movie)
|
1424 |
+
|
1425 |
+
{
|
1426 |
+
|
1427 |
+
if(ModelState.IsValid)
|
1428 |
+
|
1429 |
+
{
|
1430 |
+
|
1431 |
+
db.Entry(movie).State=EntityState.Modified;
|
1432 |
+
|
1433 |
+
db.SaveChanges();
|
1434 |
+
|
1435 |
+
returnRedirectToAction("Index");
|
1436 |
+
|
1437 |
+
}
|
1438 |
+
|
1439 |
+
returnView(movie);
|
1440 |
+
|
1441 |
+
}
|
1442 |
+
|
1443 |
+
Notice the second Edit action method is preceded by the HttpPost attribute. This attribute specifies that that
|
1444 |
+
|
1445 |
+
overload of the Edit method can be invoked only for POST requests. You could apply the HttpGet attribute to
|
1446 |
+
|
1447 |
+
the first edit method, but that's not necessary because it's the default. (We'll refer to action methods that are
|
1448 |
+
|
1449 |
+
implicitly assigned the HttpGet attribute as HttpGet methods.)
|
1450 |
+
|
1451 |
+
The HttpGetEdit method takes the movie ID parameter, looks up the movie using the Entity Framework Find
|
1452 |
+
|
1453 |
+
method, and returns the selected movie to the Edit view. The ID parameter specifies a default value of zero if
|
1454 |
+
|
1455 |
+
the Edit method is called without a parameter. If a movie cannot be found, HttpNotFound is returned. When
|
1456 |
+
|
1457 |
+
the scaffolding system created the Edit view, it examined the Movie class and created code to render <label>
|
1458 |
+
|
1459 |
+
and <input> elements for each property of the class. The following example shows the Edit view that was
|
1460 |
+
|
1461 |
+
generated:
|
1462 |
+
|
1463 |
+
@model MvcMovie.Models.Movie
|
1464 |
+
|
1465 |
+
@{
|
1466 |
+
|
1467 |
+
ViewBag.Title = "Edit";
|
1468 |
+
|
1469 |
+
}
|
1470 |
+
|
1471 |
+
<h2>Edit</h2>
|
1472 |
+
|
1473 |
+
|
1474 |
+
|
1475 |
+
|
1476 |
+
|
1477 |
+
<scriptsrc="@Url.Content("~/Scripts/jquery.validate.min.js")"type="text/javascript"><
|
1478 |
+
|
1479 |
+
/script>
|
1480 |
+
|
1481 |
+
<scriptsrc="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/j
|
1482 |
+
|
1483 |
+
avascript"></script>
|
1484 |
+
|
1485 |
+
@using (Html.BeginForm()) {
|
1486 |
+
|
1487 |
+
@Html.ValidationSummary(true)
|
1488 |
+
|
1489 |
+
<fieldset>
|
1490 |
+
|
1491 |
+
<legend>Movie</legend>
|
1492 |
+
|
1493 |
+
@Html.HiddenFor(model => model.ID)
|
1494 |
+
|
1495 |
+
<divclass="editor-label">
|
1496 |
+
|
1497 |
+
@Html.LabelFor(model => model.Title)
|
1498 |
+
|
1499 |
+
</div>
|
1500 |
+
|
1501 |
+
<divclass="editor-field">
|
1502 |
+
|
1503 |
+
@Html.EditorFor(model => model.Title)
|
1504 |
+
|
1505 |
+
@Html.ValidationMessageFor(model => model.Title)
|
1506 |
+
|
1507 |
+
</div>
|
1508 |
+
|
1509 |
+
<divclass="editor-label">
|
1510 |
+
|
1511 |
+
@Html.LabelFor(model => model.ReleaseDate)
|
1512 |
+
|
1513 |
+
</div>
|
1514 |
+
|
1515 |
+
<divclass="editor-field">
|
1516 |
+
|
1517 |
+
@Html.EditorFor(model => model.ReleaseDate)
|
1518 |
+
|
1519 |
+
@Html.ValidationMessageFor(model => model.ReleaseDate)
|
1520 |
+
|
1521 |
+
</div>
|
1522 |
+
|
1523 |
+
<divclass="editor-label">
|
1524 |
+
|
1525 |
+
@Html.LabelFor(model => model.Genre)
|
1526 |
+
|
1527 |
+
</div>
|
1528 |
+
|
1529 |
+
<divclass="editor-field">
|
1530 |
+
|
1531 |
+
@Html.EditorFor(model => model.Genre)
|
1532 |
+
|
1533 |
+
@Html.ValidationMessageFor(model => model.Genre)
|
1534 |
+
|
1535 |
+
</div>
|
1536 |
+
|
1537 |
+
<divclass="editor-label">
|
1538 |
+
|
1539 |
+
|
1540 |
+
|
1541 |
+
|
1542 |
+
|
1543 |
+
|
1544 |
+
|
1545 |
+
|
1546 |
+
@Html.LabelFor(model => model.Price)
|
1547 |
+
|
1548 |
+
</div>
|
1549 |
+
|
1550 |
+
<divclass="editor-field">
|
1551 |
+
|
1552 |
+
@Html.EditorFor(model => model.Price)
|
1553 |
+
|
1554 |
+
@Html.ValidationMessageFor(model => model.Price)
|
1555 |
+
|
1556 |
+
</div>
|
1557 |
+
|
1558 |
+
<p>
|
1559 |
+
|
1560 |
+
<inputtype="submit"value="Save"/>
|
1561 |
+
|
1562 |
+
</p>
|
1563 |
+
|
1564 |
+
</fieldset>
|
1565 |
+
|
1566 |
+
}
|
1567 |
+
|
1568 |
+
<div>
|
1569 |
+
|
1570 |
+
@Html.ActionLink("Back to List", "Index")
|
1571 |
+
|
1572 |
+
</div>
|
1573 |
+
|
1574 |
+
Notice how the view template has a @model MvcMovie.Models.Movie statement at the top of the file — this
|
1575 |
+
|
1576 |
+
specifies that the view expects the model for the view template to be of type Movie.
|
1577 |
+
|
1578 |
+
The scaffolded code uses several helper methods to streamline the HTML markup. TheHtml.LabelFor helper
|
1579 |
+
|
1580 |
+
displays the name of the field ("Title", "ReleaseDate", "Genre", or "Price"). TheHtml.EditorFor helper renders
|
1581 |
+
|
1582 |
+
an HTML <input> element. TheHtml.ValidationMessageFor helper displays any validation messages
|
1583 |
+
|
1584 |
+
associated with that property.
|
1585 |
+
|
1586 |
+
Run the application and navigate to the /Movies URL. Click anEdit link. In the browser, view the source for the
|
1587 |
+
|
1588 |
+
page. The HTML for the form element is shown below.
|
1589 |
+
|
1590 |
+
<formaction="/Movies/Edit/4"method="post"><fieldset>
|
1591 |
+
|
1592 |
+
<legend>Movie</legend>
|
1593 |
+
|
1594 |
+
<inputdata-val="true"data-val-number="The field ID must be a number."data-val-
|
1595 |
+
|
1596 |
+
required="The ID field is required."id="ID"name="ID"type="hidden"value="4"/>
|
1597 |
+
|
1598 |
+
<divclass="editor-label">
|
1599 |
+
|
1600 |
+
<labelfor="Title">Title</label>
|
1601 |
+
|
1602 |
+
</div>
|
1603 |
+
|
1604 |
+
|
1605 |
+
|
1606 |
+
|
1607 |
+
|
1608 |
+
<divclass="editor-field">
|
1609 |
+
|
1610 |
+
<inputclass="text-box single-line"id="Title"name="Title"type="text"value="Rio
|
1611 |
+
|
1612 |
+
Bravo"/>
|
1613 |
+
|
1614 |
+
<spanclass="field-validation-valid"data-valmsg-for="Title"data-valmsg-
|
1615 |
+
|
1616 |
+
replace="true"></span>
|
1617 |
+
|
1618 |
+
</div>
|
1619 |
+
|
1620 |
+
<divclass="editor-label">
|
1621 |
+
|
1622 |
+
<labelfor="ReleaseDate">ReleaseDate</label>
|
1623 |
+
|
1624 |
+
</div>
|
1625 |
+
|
1626 |
+
<divclass="editor-field">
|
1627 |
+
|
1628 |
+
<inputclass="text-box single-line"data-val="true"data-val-date="The field ReleaseDate
|
1629 |
+
|
1630 |
+
must be a date."data-val-required="The ReleaseDate field is
|
1631 |
+
|
1632 |
+
required."id="ReleaseDate"name="ReleaseDate"type="text"value="4/15/1959 12:00:00
|
1633 |
+
|
1634 |
+
AM"/>
|
1635 |
+
|
1636 |
+
<spanclass="field-validation-valid"data-valmsg-for="ReleaseDate"data-valmsg-
|
1637 |
+
|
1638 |
+
replace="true"></span>
|
1639 |
+
|
1640 |
+
</div>
|
1641 |
+
|
1642 |
+
<divclass="editor-label">
|
1643 |
+
|
1644 |
+
<labelfor="Genre">Genre</label>
|
1645 |
+
|
1646 |
+
</div>
|
1647 |
+
|
1648 |
+
<divclass="editor-field">
|
1649 |
+
|
1650 |
+
<inputclass="text-box single-line"id="Genre"name="Genre"type="text"value="Western"/>
|
1651 |
+
|
1652 |
+
<spanclass="field-validation-valid"data-valmsg-for="Genre"data-valmsg-
|
1653 |
+
|
1654 |
+
replace="true"></span>
|
1655 |
+
|
1656 |
+
</div>
|
1657 |
+
|
1658 |
+
<divclass="editor-label">
|
1659 |
+
|
1660 |
+
<labelfor="Price">Price</label>
|
1661 |
+
|
1662 |
+
</div>
|
1663 |
+
|
1664 |
+
<divclass="editor-field">
|
1665 |
+
|
1666 |
+
<inputclass="text-box single-line"data-val="true"data-val-number="The field Price
|
1667 |
+
|
1668 |
+
must be a number."data-val-required="The Price field is
|
1669 |
+
|
1670 |
+
required."id="Price"name="Price"type="text"value="2.99"/>
|
1671 |
+
|
1672 |
+
<spanclass="field-validation-valid"data-valmsg-for="Price"data-valmsg-
|
1673 |
+
|
1674 |
+
replace="true"></span>
|
1675 |
+
|
1676 |
+
</div>
|
1677 |
+
|
1678 |
+
|
1679 |
+
|
1680 |
+
|
1681 |
+
<p>
|
1682 |
+
|
1683 |
+
<inputtype="submit"value="Save"/>
|
1684 |
+
|
1685 |
+
</p>
|
1686 |
+
|
1687 |
+
</fieldset>
|
1688 |
+
|
1689 |
+
</form>
|
1690 |
+
|
1691 |
+
The <input> elements are in an HTML <form> element whose action attribute is set to post to the
|
1692 |
+
|
1693 |
+
/Movies/Edit URL. The form data will be posted to the server when the Edit button is clicked.
|
1694 |
+
|
1695 |
+
Processing the POST Request
|
1696 |
+
|
1697 |
+
The following listing shows the HttpPost version of the Edit action method.
|
1698 |
+
|
1699 |
+
[HttpPost]
|
1700 |
+
|
1701 |
+
publicActionResultEdit(Movie movie)
|
1702 |
+
|
1703 |
+
{
|
1704 |
+
|
1705 |
+
if(ModelState.IsValid)
|
1706 |
+
|
1707 |
+
{
|
1708 |
+
|
1709 |
+
db.Entry(movie).State=EntityState.Modified;
|
1710 |
+
|
1711 |
+
db.SaveChanges();
|
1712 |
+
|
1713 |
+
returnRedirectToAction("Index");
|
1714 |
+
|
1715 |
+
}
|
1716 |
+
|
1717 |
+
returnView(movie);
|
1718 |
+
|
1719 |
+
}
|
1720 |
+
|
1721 |
+
The ASP.NET MVC model binder takes the posted form values and creates aMovie object that's passed as the
|
1722 |
+
|
1723 |
+
movie parameter. TheModelState.IsValid method verifies that the data submitted in the form can be used
|
1724 |
+
|
1725 |
+
to modify (edit or update) a Movie object. If the data is valid, the movie data is saved to the Movies collection
|
1726 |
+
|
1727 |
+
of the db (MovieDBContext instance). The new movie data is saved to the database by calling the
|
1728 |
+
|
1729 |
+
SaveChanges method ofMovieDBContext. After saving the data, the code redirects the user to the Index
|
1730 |
+
|
1731 |
+
action method of the MoviesController class, which displays the of movie collection, including the changes
|
1732 |
+
|
1733 |
+
just made..
|
1734 |
+
|
1735 |
+
If the posted values aren't valid, they are redisplayed in the form. TheHtml.ValidationMessageFor helpers
|
1736 |
+
|
1737 |
+
in the Edit.cshtml view template take care of displaying appropriate error messages.
|
1738 |
+
|
1739 |
+
|
1740 |
+
Note about locales If you normally work with a locale other than English, see Supporting ASP.NET MVC
|
1741 |
+
|
1742 |
+
Validation with Non-English Locales. The decimal field may require a common, not a decimal point. As a
|
1743 |
+
|
1744 |
+
temporary fix, you can add the globalization element to the projects root web.config file. The following code
|
1745 |
+
|
1746 |
+
shows the globalization element with the culture set to United States English.
|
1747 |
+
|
1748 |
+
|
1749 |
+
<system.web>
|
1750 |
+
|
1751 |
+
<globalizationculture="en-US"/>
|
1752 |
+
|
1753 |
+
<!--elements removed for clarity-->
|
1754 |
+
|
1755 |
+
</system.web>
|
1756 |
+
|
1757 |
+
All the HttpGet methods follow a similar pattern. They get a movie object (or list of objects, in the case of
|
1758 |
+
|
1759 |
+
Index), and pass the model to the view. The Create method passes an empty movie object to the Create view.
|
1760 |
+
|
1761 |
+
All the methods that create, edit, delete, or otherwise modify data do so in the HttpPost overload of the
|
1762 |
+
|
1763 |
+
method. Modifying data in an HTTP GET method is a security risk, as described in the blog post entryASP.NET
|
1764 |
+
|
1765 |
+
MVC Tip #46 – Don’t use Delete Links because they create Security Holes. Modifying data in a GET method also
|
1766 |
+
|
1767 |
+
violates HTTP best practices and the architectural REST pattern, which specifies that GET requests should not
|
1768 |
+
|
1769 |
+
change the state of your application. In other words, performing a GET operation should be a safe operation
|
1770 |
+
|
1771 |
+
that has no side effects and doesn't modify your persisted data.
|
1772 |
+
|
1773 |
+
Adding a Search Method and Search View
|
1774 |
+
|
1775 |
+
In this section you'll add a SearchIndex action method that lets you search movies by genre or name. This will
|
1776 |
+
|
1777 |
+
be available using the /Movies/SearchIndex URL. The request will display an HTML form that contains input
|
1778 |
+
|
1779 |
+
elements that a user can enter in order to search for a movie. When a user submits the form, the action method
|
1780 |
+
|
1781 |
+
will get the search values posted by the user and use the values to search the database.
|
1782 |
+
|
1783 |
+
Displaying the SearchIndex Form
|
1784 |
+
|
1785 |
+
Start by adding a SearchIndex action method to the existingMoviesController class. The method will
|
1786 |
+
|
1787 |
+
return a view that contains an HTML form. Here's the code:
|
1788 |
+
|
1789 |
+
publicActionResultSearchIndex(string searchString)
|
1790 |
+
|
1791 |
+
{
|
1792 |
+
|
1793 |
+
var movies =from m in db.Movies
|
1794 |
+
|
1795 |
+
select m;
|
1796 |
+
|
1797 |
+
if(!String.IsNullOrEmpty(searchString))
|
1798 |
+
|
1799 |
+
{
|
1800 |
+
|
1801 |
+
|
1802 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
1803 |
+
|
1804 |
+
}
|
1805 |
+
|
1806 |
+
returnView(movies);
|
1807 |
+
|
1808 |
+
}
|
1809 |
+
|
1810 |
+
The first line of the SearchIndex method creates the followingLINQ query to select the movies:
|
1811 |
+
|
1812 |
+
var movies =from m in db.Movies
|
1813 |
+
|
1814 |
+
select m;
|
1815 |
+
|
1816 |
+
The query is defined at this point, but hasn't yet been run against the data store.
|
1817 |
+
|
1818 |
+
If the searchString parameter contains a string, the movies query is modified to filter on the value of the
|
1819 |
+
|
1820 |
+
search string, using the following code:
|
1821 |
+
|
1822 |
+
if(!String.IsNullOrEmpty(searchString))
|
1823 |
+
|
1824 |
+
{
|
1825 |
+
|
1826 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
1827 |
+
|
1828 |
+
}
|
1829 |
+
|
1830 |
+
The s => s.Title code above is aLambda Expression. Lambdas are used in method-basedLINQ queries as
|
1831 |
+
|
1832 |
+
arguments to standard query operator methods such asWhere method used in the above code. LINQ queries
|
1833 |
+
|
1834 |
+
are not executed when they are defined or when they are modified by calling a method such as Where or
|
1835 |
+
|
1836 |
+
OrderBy. Instead, query execution is deferred, which means that the evaluation of an expression is delayed
|
1837 |
+
|
1838 |
+
until its realized value is actually iterated over or theToList method is called. In the SearchIndex sample, the
|
1839 |
+
|
1840 |
+
query is executed in the SearchIndex view. For more information about deferred query execution, see Query
|
1841 |
+
|
1842 |
+
Execution.
|
1843 |
+
|
1844 |
+
Now you can implement the SearchIndex view that will display the form to the user. Right-click inside the
|
1845 |
+
|
1846 |
+
SearchIndex method and then click Add View. In the Add View dialog box, specify that you're going to pass
|
1847 |
+
|
1848 |
+
a Movie object to the view template as its model class. In the Scaffold template list, choose List, then click
|
1849 |
+
|
1850 |
+
Add.
|
1851 |
+
|
1852 |
+
|
1853 |
+
When you click the Add button, the Views\Movies\SearchIndex.cshtml view template is created. Because you
|
1854 |
+
|
1855 |
+
selected List in the Scaffold template list, Visual Studio Express automatically generated (scaffolded) some
|
1856 |
+
|
1857 |
+
default markup in the view. The scaffolding created an HTML form. It examined the Movie class and created
|
1858 |
+
|
1859 |
+
code to render <label> elements for each property of the class. The listing below shows the Create view that
|
1860 |
+
|
1861 |
+
was generated:
|
1862 |
+
|
1863 |
+
@model IEnumerable<MvcMovie.Models.Movie>
|
1864 |
+
|
1865 |
+
@{
|
1866 |
+
|
1867 |
+
ViewBag.Title = "SearchIndex";
|
1868 |
+
|
1869 |
+
}
|
1870 |
+
|
1871 |
+
<h2>SearchIndex</h2>
|
1872 |
+
|
1873 |
+
|
1874 |
+
|
1875 |
+
|
1876 |
+
|
1877 |
+
<p>
|
1878 |
+
|
1879 |
+
@Html.ActionLink("Create New", "Create")
|
1880 |
+
|
1881 |
+
</p>
|
1882 |
+
|
1883 |
+
<table>
|
1884 |
+
|
1885 |
+
<tr>
|
1886 |
+
|
1887 |
+
<th>
|
1888 |
+
|
1889 |
+
Title
|
1890 |
+
|
1891 |
+
</th>
|
1892 |
+
|
1893 |
+
<th>
|
1894 |
+
|
1895 |
+
ReleaseDate
|
1896 |
+
|
1897 |
+
</th>
|
1898 |
+
|
1899 |
+
<th>
|
1900 |
+
|
1901 |
+
Genre
|
1902 |
+
|
1903 |
+
</th>
|
1904 |
+
|
1905 |
+
<th>
|
1906 |
+
|
1907 |
+
Price
|
1908 |
+
|
1909 |
+
</th>
|
1910 |
+
|
1911 |
+
<th></th>
|
1912 |
+
|
1913 |
+
</tr>
|
1914 |
+
|
1915 |
+
@foreach (var item in Model) {
|
1916 |
+
|
1917 |
+
<tr>
|
1918 |
+
|
1919 |
+
<td>
|
1920 |
+
|
1921 |
+
@Html.DisplayFor(modelItem => item.Title)
|
1922 |
+
|
1923 |
+
</td>
|
1924 |
+
|
1925 |
+
<td>
|
1926 |
+
|
1927 |
+
@Html.DisplayFor(modelItem => item.ReleaseDate)
|
1928 |
+
|
1929 |
+
</td>
|
1930 |
+
|
1931 |
+
<td>
|
1932 |
+
|
1933 |
+
@Html.DisplayFor(modelItem => item.Genre)
|
1934 |
+
|
1935 |
+
</td>
|
1936 |
+
|
1937 |
+
<td>
|
1938 |
+
|
1939 |
+
@Html.DisplayFor(modelItem => item.Price)
|
1940 |
+
|
1941 |
+
</td>
|
1942 |
+
|
1943 |
+
<td>
|
1944 |
+
|
1945 |
+
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
|
1946 |
+
|
1947 |
+
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
|
1948 |
+
|
1949 |
+
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
|
1950 |
+
|
1951 |
+
|
1952 |
+
</td>
|
1953 |
+
|
1954 |
+
</tr>
|
1955 |
+
|
1956 |
+
}
|
1957 |
+
|
1958 |
+
</table>
|
1959 |
+
|
1960 |
+
Run the application and navigate to /Movies/SearchIndex. Append a query string such as
|
1961 |
+
|
1962 |
+
?searchString=ghost to the URL. The filtered movies are displayed.
|
1963 |
+
|
1964 |
+
If you change the signature of the SearchIndex method to have a parameter named id, the id parameter will
|
1965 |
+
|
1966 |
+
match the{id} placeholder for the default routes set in the Global.asax file.
|
1967 |
+
|
1968 |
+
{controller}/{action}/{id}
|
1969 |
+
|
1970 |
+
|
1971 |
+
|
1972 |
+
The original SearchIndex method looks like this::
|
1973 |
+
|
1974 |
+
publicActionResultSearchIndex(string searchString)
|
1975 |
+
|
1976 |
+
{
|
1977 |
+
|
1978 |
+
var movies =from m in db.Movies
|
1979 |
+
|
1980 |
+
select m;
|
1981 |
+
|
1982 |
+
if(!String.IsNullOrEmpty(searchString))
|
1983 |
+
|
1984 |
+
{
|
1985 |
+
|
1986 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
1987 |
+
|
1988 |
+
}
|
1989 |
+
|
1990 |
+
returnView(movies);
|
1991 |
+
|
1992 |
+
}
|
1993 |
+
|
1994 |
+
The modified SearchIndex method would look as follows:
|
1995 |
+
|
1996 |
+
publicActionResultSearchIndex(string id)
|
1997 |
+
|
1998 |
+
{
|
1999 |
+
|
2000 |
+
string searchString = id;
|
2001 |
+
|
2002 |
+
var movies =from m in db.Movies
|
2003 |
+
|
2004 |
+
select m;
|
2005 |
+
|
2006 |
+
if(!String.IsNullOrEmpty(searchString))
|
2007 |
+
|
2008 |
+
{
|
2009 |
+
|
2010 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
2011 |
+
|
2012 |
+
}
|
2013 |
+
|
2014 |
+
returnView(movies);
|
2015 |
+
|
2016 |
+
}
|
2017 |
+
|
2018 |
+
You can now pass the search title as route data (a URL segment) instead of as a query string value.
|
2019 |
+
|
2020 |
+
|
2021 |
+
|
2022 |
+
|
2023 |
+
|
2024 |
+
However, you can't expect users to modify the URL every time they want to search for a movie. So now you
|
2025 |
+
|
2026 |
+
you'll add UI to help them filter movies. If you changed the signature of the SearchIndex method to test how
|
2027 |
+
|
2028 |
+
to pass the route-bound ID parameter, change it back so that your SearchIndex method takes a string
|
2029 |
+
|
2030 |
+
parameter named searchString:
|
2031 |
+
|
2032 |
+
publicActionResultSearchIndex(string searchString)
|
2033 |
+
|
2034 |
+
{
|
2035 |
+
|
2036 |
+
var movies =from m in db.Movies
|
2037 |
+
|
2038 |
+
select m;
|
2039 |
+
|
2040 |
+
if(!String.IsNullOrEmpty(searchString))
|
2041 |
+
|
2042 |
+
{
|
2043 |
+
|
2044 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
2045 |
+
|
2046 |
+
}
|
2047 |
+
|
2048 |
+
|
2049 |
+
|
2050 |
+
|
2051 |
+
returnView(movies);
|
2052 |
+
|
2053 |
+
}
|
2054 |
+
|
2055 |
+
Open the Views\Movies\SearchIndex.cshtml file, and just after @Html.ActionLink("Create New",
|
2056 |
+
|
2057 |
+
"Create"), add the following:
|
2058 |
+
|
2059 |
+
@using (Html.BeginForm()){
|
2060 |
+
|
2061 |
+
<p> Title: @Html.TextBox("SearchString")<br/>
|
2062 |
+
|
2063 |
+
<inputtype="submit"value="Filter"/></p>
|
2064 |
+
|
2065 |
+
}
|
2066 |
+
|
2067 |
+
The following example shows a portion of the Views\Movies\SearchIndex.cshtml file with the added filtering
|
2068 |
+
|
2069 |
+
markup.
|
2070 |
+
|
2071 |
+
@model IEnumerable<MvcMovie.Models.Movie>
|
2072 |
+
|
2073 |
+
@{
|
2074 |
+
|
2075 |
+
ViewBag.Title = "SearchIndex";
|
2076 |
+
|
2077 |
+
}
|
2078 |
+
|
2079 |
+
<h2>SearchIndex</h2>
|
2080 |
+
|
2081 |
+
<p>
|
2082 |
+
|
2083 |
+
@Html.ActionLink("Create New", "Create")
|
2084 |
+
|
2085 |
+
@using (Html.BeginForm()){
|
2086 |
+
|
2087 |
+
<p> Title: @Html.TextBox("SearchString") <br/>
|
2088 |
+
|
2089 |
+
<inputtype="submit"value="Filter"/></p>
|
2090 |
+
|
2091 |
+
}
|
2092 |
+
|
2093 |
+
</p>
|
2094 |
+
|
2095 |
+
The Html.BeginForm helper creates an opening <form> tag. The Html.BeginForm helper causes the form to
|
2096 |
+
|
2097 |
+
post to itself when the user submits the form by clicking the Filter button.
|
2098 |
+
|
2099 |
+
Run the application and try searching for a movie.
|
2100 |
+
|
2101 |
+
|
2102 |
+
|
2103 |
+
|
2104 |
+
|
2105 |
+
There's no HttpPost overload of the SearchIndex method. You don't need it, because the method isn't
|
2106 |
+
|
2107 |
+
changing the state of the application, just filtering data.
|
2108 |
+
|
2109 |
+
You could add the following HttpPost SearchIndex method. In that case, the action invoker would match
|
2110 |
+
|
2111 |
+
the HttpPost SearchIndex method, and the HttpPost SearchIndex method would run as shown in the
|
2112 |
+
|
2113 |
+
image below.
|
2114 |
+
|
2115 |
+
[HttpPost]
|
2116 |
+
|
2117 |
+
publicstringSearchIndex(FormCollection fc,string searchString)
|
2118 |
+
|
2119 |
+
{
|
2120 |
+
|
2121 |
+
return"<h3> From [HttpPost]SearchIndex: "+ searchString +"</h3>";
|
2122 |
+
|
2123 |
+
}
|
2124 |
+
|
2125 |
+
|
2126 |
+
However, even if you add this HttpPost version of the SearchIndex method, there's a limitation in how this
|
2127 |
+
|
2128 |
+
has all been implemented. Imagine that you want to bookmark a particular search or you want to send a link to
|
2129 |
+
|
2130 |
+
friends that they can click in order to see the same filtered list of movies. Notice that the URL for the HTTP
|
2131 |
+
|
2132 |
+
POST request is the same as the URL for the GET request (localhost:xxxxx/Movies/SearchIndex) -- there's no
|
2133 |
+
|
2134 |
+
search information in the URL itself. Right now, the search string information is sent to the server as a form field
|
2135 |
+
|
2136 |
+
value. This means you can't capture that search information to bookmark or send to friends in a URL.
|
2137 |
+
|
2138 |
+
The solution is to use an overload of BeginForm that specifies that the POST request should add the search
|
2139 |
+
|
2140 |
+
information to the URL and that is should be routed to the HttpGet version of the SearchIndex method.
|
2141 |
+
|
2142 |
+
Replace the existing parameterless BeginForm method with the following:
|
2143 |
+
|
2144 |
+
@using (Html.BeginForm("SearchIndex","Movies",FormMethod.Get))
|
2145 |
+
|
2146 |
+
Now when you submit a search, the URL contains a search query string. Searching will also go to the HttpGet
|
2147 |
+
|
2148 |
+
SearchIndex action method, even if you have a HttpPost SearchIndex method.
|
2149 |
+
|
2150 |
+
|
2151 |
+
|
2152 |
+
Adding Search by Genre
|
2153 |
+
|
2154 |
+
If you added the HttpPost version of the SearchIndex method, delete it now.
|
2155 |
+
|
2156 |
+
Next, you'll add a feature to let users search for movies by genre. Replace the SearchIndex method with the
|
2157 |
+
|
2158 |
+
following code:
|
2159 |
+
|
2160 |
+
publicActionResultSearchIndex(string movieGenre,string searchString)
|
2161 |
+
|
2162 |
+
{
|
2163 |
+
|
2164 |
+
varGenreLst=newList<string>();
|
2165 |
+
|
2166 |
+
varGenreQry=from d in db.Movies
|
2167 |
+
|
2168 |
+
orderby d.Genre
|
2169 |
+
|
2170 |
+
|
2171 |
+
|
2172 |
+
select d.Genre;
|
2173 |
+
|
2174 |
+
GenreLst.AddRange(GenreQry.Distinct());
|
2175 |
+
|
2176 |
+
ViewBag.movieGenre =newSelectList(GenreLst);
|
2177 |
+
|
2178 |
+
var movies =from m in db.Movies
|
2179 |
+
|
2180 |
+
select m;
|
2181 |
+
|
2182 |
+
if(!String.IsNullOrEmpty(searchString))
|
2183 |
+
|
2184 |
+
{
|
2185 |
+
|
2186 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
2187 |
+
|
2188 |
+
}
|
2189 |
+
|
2190 |
+
if(string.IsNullOrEmpty(movieGenre))
|
2191 |
+
|
2192 |
+
returnView(movies);
|
2193 |
+
|
2194 |
+
else
|
2195 |
+
|
2196 |
+
{
|
2197 |
+
|
2198 |
+
returnView(movies.Where(x => x.Genre== movieGenre));
|
2199 |
+
|
2200 |
+
}
|
2201 |
+
|
2202 |
+
}
|
2203 |
+
|
2204 |
+
This version of the SearchIndex method takes an additional parameter, namely movieGenre. The first few
|
2205 |
+
|
2206 |
+
lines of code create aList object to hold movie genres from the database.
|
2207 |
+
|
2208 |
+
The following code is a LINQ query that retrieves all the genres from the database.
|
2209 |
+
|
2210 |
+
varGenreQry=from d in db.Movies
|
2211 |
+
|
2212 |
+
orderby d.Genre
|
2213 |
+
|
2214 |
+
select d.Genre;
|
2215 |
+
|
2216 |
+
The code uses the AddRange method of the generic List collection to add all the distinct genres to the list.
|
2217 |
+
|
2218 |
+
(Without the Distinct modifier, duplicate genres would be added — for example, comedy would be added
|
2219 |
+
|
2220 |
+
twice in our sample). The code then stores the list of genres in the ViewBag object.
|
2221 |
+
|
2222 |
+
The following code shows how to check the movieGenre parameter. If it's not empty, the code further
|
2223 |
+
|
2224 |
+
constrains the movies query to limit the selected movies to the specified genre.
|
2225 |
+
|
2226 |
+
|
2227 |
+
|
2228 |
+
|
2229 |
+
|
2230 |
+
if(string.IsNullOrEmpty(movieGenre))
|
2231 |
+
|
2232 |
+
returnView(movies);
|
2233 |
+
|
2234 |
+
else
|
2235 |
+
|
2236 |
+
{
|
2237 |
+
|
2238 |
+
returnView(movies.Where(x => x.Genre== movieGenre));
|
2239 |
+
|
2240 |
+
}
|
2241 |
+
|
2242 |
+
Adding Markup to the SearchIndex View to Support Search by Genre
|
2243 |
+
|
2244 |
+
Add an Html.DropDownList helper to the Views\Movies\SearchIndex.cshtml file, just before the TextBox
|
2245 |
+
|
2246 |
+
helper. The completed markup is shown below:
|
2247 |
+
|
2248 |
+
<p>
|
2249 |
+
|
2250 |
+
@Html.ActionLink("Create New", "Create")
|
2251 |
+
|
2252 |
+
@using (Html.BeginForm("SearchIndex","Movies",FormMethod.Get)){
|
2253 |
+
|
2254 |
+
<p>Genre: @Html.DropDownList("movieGenre", "All")
|
2255 |
+
|
2256 |
+
Title: @Html.TextBox("SearchString")
|
2257 |
+
|
2258 |
+
<inputtype="submit"value="Filter"/></p>
|
2259 |
+
|
2260 |
+
}
|
2261 |
+
|
2262 |
+
</p>
|
2263 |
+
|
2264 |
+
Run the application and browse to /Movies/SearchIndex. Try a search by genre, by movie name, and by both
|
2265 |
+
|
2266 |
+
criteria.
|
2267 |
+
|
2268 |
+
In this section you examined the CRUD action methods and views generated by the framework. You created a
|
2269 |
+
|
2270 |
+
search action method and view that let users search by movie title and genre. In the next section, you'll look at
|
2271 |
+
|
2272 |
+
how to add a property to the Movie model and how to add an initializer that will automatically create a test
|
2273 |
+
|
2274 |
+
database.
|
2275 |
+
|
2276 |
+
|
2277 |
+
|
2278 |
+
Adding a New Field to the Movie Model and
|
2279 |
+
|
2280 |
+
Table
|
2281 |
+
|
2282 |
+
In this section you'll make some changes to the model classes and learn how you can update the database
|
2283 |
+
|
2284 |
+
schema to match the model changes.
|
2285 |
+
|
2286 |
+
Adding a Rating Property to the Movie Model
|
2287 |
+
|
2288 |
+
Start by adding a new Rating property to the existing Movie class. Open the Models\Movie.cs file and add the
|
2289 |
+
|
2290 |
+
Rating property like this one:
|
2291 |
+
|
2292 |
+
publicstringRating{get;set;}
|
2293 |
+
|
2294 |
+
The complete Movie class now looks like the following code:
|
2295 |
+
|
2296 |
+
publicclassMovie
|
2297 |
+
|
2298 |
+
{
|
2299 |
+
|
2300 |
+
publicint ID {get;set;}
|
2301 |
+
|
2302 |
+
publicstringTitle{get;set;}
|
2303 |
+
|
2304 |
+
publicDateTimeReleaseDate{get;set;}
|
2305 |
+
|
2306 |
+
publicstringGenre{get;set;}
|
2307 |
+
|
2308 |
+
publicdecimalPrice{get;set;}
|
2309 |
+
|
2310 |
+
publicstringRating{get;set;}
|
2311 |
+
|
2312 |
+
}
|
2313 |
+
|
2314 |
+
Recompile the application using the Build > Build Movie menu command.
|
2315 |
+
|
2316 |
+
Now that you've updated the Model class, you also need to update the \Views\Movies\Index.cshtml and
|
2317 |
+
|
2318 |
+
\Views\Movies\Create.cshtml view templates in order to display the new Rating property in the browser view.
|
2319 |
+
|
2320 |
+
Open the \Views\Movies\Index.cshtml file and add a <th>Rating</th> column heading just after the Price
|
2321 |
+
|
2322 |
+
column. Then add a <td> column near the end of the template to render the @item.Rating value. Below is
|
2323 |
+
|
2324 |
+
what the updated Index.cshtml view template looks like:
|
2325 |
+
|
2326 |
+
@model IEnumerable<MvcMovie.Models.Movie>
|
2327 |
+
|
2328 |
+
@{
|
2329 |
+
|
2330 |
+
ViewBag.Title = "Index";
|
2331 |
+
|
2332 |
+
}
|
2333 |
+
|
2334 |
+
<h2>Index</h2>
|
2335 |
+
|
2336 |
+
<p>
|
2337 |
+
|
2338 |
+
@Html.ActionLink("Create New", "Create")
|
2339 |
+
|
2340 |
+
</p>
|
2341 |
+
|
2342 |
+
<table>
|
2343 |
+
|
2344 |
+
<tr>
|
2345 |
+
|
2346 |
+
<th>
|
2347 |
+
|
2348 |
+
@Html.DisplayNameFor(model => model.Title)
|
2349 |
+
|
2350 |
+
</th>
|
2351 |
+
|
2352 |
+
<th>
|
2353 |
+
|
2354 |
+
@Html.DisplayNameFor(model => model.ReleaseDate)
|
2355 |
+
|
2356 |
+
</th>
|
2357 |
+
|
2358 |
+
<th>
|
2359 |
+
|
2360 |
+
@Html.DisplayNameFor(model => model.Genre)
|
2361 |
+
|
2362 |
+
</th>
|
2363 |
+
|
2364 |
+
<th>
|
2365 |
+
|
2366 |
+
@Html.DisplayNameFor(model => model.Price)
|
2367 |
+
|
2368 |
+
</th>
|
2369 |
+
|
2370 |
+
<th>
|
2371 |
+
|
2372 |
+
@Html.DisplayNameFor(model => model.Rating)
|
2373 |
+
|
2374 |
+
</th>
|
2375 |
+
|
2376 |
+
<th></th>
|
2377 |
+
|
2378 |
+
</tr>
|
2379 |
+
|
2380 |
+
@foreach (var item in Model) {
|
2381 |
+
|
2382 |
+
<tr>
|
2383 |
+
|
2384 |
+
<td>
|
2385 |
+
|
2386 |
+
@Html.DisplayFor(modelItem => item.Title)
|
2387 |
+
|
2388 |
+
</td>
|
2389 |
+
|
2390 |
+
<td>
|
2391 |
+
|
2392 |
+
@Html.DisplayFor(modelItem => item.ReleaseDate)
|
2393 |
+
|
2394 |
+
</td>
|
2395 |
+
|
2396 |
+
|
2397 |
+
|
2398 |
+
|
2399 |
+
|
2400 |
+
<td>
|
2401 |
+
|
2402 |
+
@Html.DisplayFor(modelItem => item.Genre)
|
2403 |
+
|
2404 |
+
</td>
|
2405 |
+
|
2406 |
+
<td>
|
2407 |
+
|
2408 |
+
@Html.DisplayFor(modelItem => item.Price)
|
2409 |
+
|
2410 |
+
</td>
|
2411 |
+
|
2412 |
+
<td>
|
2413 |
+
|
2414 |
+
@Html.DisplayFor(modelItem => item.Rating)
|
2415 |
+
|
2416 |
+
</td>
|
2417 |
+
|
2418 |
+
<td>
|
2419 |
+
|
2420 |
+
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
|
2421 |
+
|
2422 |
+
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
|
2423 |
+
|
2424 |
+
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
|
2425 |
+
|
2426 |
+
</td>
|
2427 |
+
|
2428 |
+
</tr>
|
2429 |
+
|
2430 |
+
}
|
2431 |
+
|
2432 |
+
</table>
|
2433 |
+
|
2434 |
+
Next, open the \Views\Movies\Create.cshtml file and add the following markup near the end of the form. This
|
2435 |
+
|
2436 |
+
renders a text box so that you can specify a rating when a new movie is created.
|
2437 |
+
|
2438 |
+
<divclass="editor-label">
|
2439 |
+
|
2440 |
+
@Html.LabelFor(model => model.Rating)
|
2441 |
+
|
2442 |
+
</div>
|
2443 |
+
|
2444 |
+
<divclass="editor-field">
|
2445 |
+
|
2446 |
+
@Html.EditorFor(model => model.Rating)
|
2447 |
+
|
2448 |
+
@Html.ValidationMessageFor(model => model.Rating)
|
2449 |
+
|
2450 |
+
</div>
|
2451 |
+
|
2452 |
+
Managing Model and Database Schema Differences
|
2453 |
+
|
2454 |
+
You've now updated the application code to support the new Rating property.
|
2455 |
+
|
2456 |
+
Now run the application and navigate to the /Movies URL. When you do this, though, you'll see one of the
|
2457 |
+
|
2458 |
+
following errors:
|
2459 |
+
|
2460 |
+
|
2461 |
+
|
2462 |
+
You're seeing this error because the updated Movie model class in the application is now different than the
|
2463 |
+
|
2464 |
+
schema of the Movie table of the existing database. (There's no Rating column in the database table.)
|
2465 |
+
|
2466 |
+
By default, when you use Entity Framework Code First to automatically create a database, as you did earlier in
|
2467 |
+
|
2468 |
+
this tutorial, Code First adds a table to the database to help track whether the schema of the database is in sync
|
2469 |
+
|
2470 |
+
with the model classes it was generated from. If they aren't in sync, the Entity Framework throws an error. This
|
2471 |
+
|
2472 |
+
makes it easier to track down issues at development time that you might otherwise only find (by obscure
|
2473 |
+
|
2474 |
+
|
2475 |
+
errors) at run time. The sync-checking feature is what causes the error message to be displayed that you just
|
2476 |
+
|
2477 |
+
saw.
|
2478 |
+
|
2479 |
+
There are two approaches to resolving the error:
|
2480 |
+
|
2481 |
+
1. Have the Entity Framework automatically drop and re-create the database based on the new model class
|
2482 |
+
|
2483 |
+
schema. This approach is very convenient when doing active development on a test database; it allows
|
2484 |
+
|
2485 |
+
you to quickly evolve the model and database schema together. The downside, though, is that you lose
|
2486 |
+
|
2487 |
+
existing data in the database — so you don't want to use this approach on a production database!
|
2488 |
+
|
2489 |
+
2. Explicitly modify the schema of the existing database so that it matches the model classes. The advantage
|
2490 |
+
|
2491 |
+
of this approach is that you keep your data. You can make this change either manually or by creating a
|
2492 |
+
|
2493 |
+
database change script.
|
2494 |
+
|
2495 |
+
For this tutorial, we'll use the first approach — you'll have the Entity Framework Code First automatically re-
|
2496 |
+
|
2497 |
+
create the database anytime the model changes.
|
2498 |
+
|
2499 |
+
Automatically Re-Creating the Database on Model Changes
|
2500 |
+
|
2501 |
+
Let's update the application so that Code First automatically drops and re-creates the database anytime you
|
2502 |
+
|
2503 |
+
change the model for the application.
|
2504 |
+
|
2505 |
+
Warning You should enable this approach of automatically dropping and re-creating the database only when
|
2506 |
+
|
2507 |
+
you're using a development or test database, and never on a production database that contains real data. Using
|
2508 |
+
|
2509 |
+
it on a production server can lead to data loss.
|
2510 |
+
|
2511 |
+
Stop the debugger. In Solution Explorer, right click the Models folder, select Add, and then select New Item.
|
2512 |
+
|
2513 |
+
In the Add New Item dialog, select Class then name the class "MovieInitializer". Update the
|
2514 |
+
|
2515 |
+
MovieInitializer class to contain the following code:
|
2516 |
+
|
2517 |
+
usingSystem;
|
2518 |
+
|
2519 |
+
usingSystem.Collections.Generic;
|
2520 |
+
|
2521 |
+
usingSystem.Data.Entity;
|
2522 |
+
|
2523 |
+
namespaceMvcMovie.Models{
|
2524 |
+
|
2525 |
+
publicclassMovieInitializer:DropCreateDatabaseIfModelChanges<MovieDBContext>{
|
2526 |
+
|
2527 |
+
protectedoverridevoidSeed(MovieDBContext context){
|
2528 |
+
|
2529 |
+
var movies =newList<Movie>{
|
2530 |
+
|
2531 |
+
newMovie{Title="When Harry Met Sally",
|
2532 |
+
|
2533 |
+
ReleaseDate=DateTime.Parse("1989-1-11"),
|
2534 |
+
|
2535 |
+
Genre="Romantic Comedy",
|
2536 |
+
|
2537 |
+
|
2538 |
+
|
2539 |
+
|
2540 |
+
Rating="R",
|
2541 |
+
|
2542 |
+
Price=7.99M},
|
2543 |
+
|
2544 |
+
newMovie{Title="Ghostbusters ",
|
2545 |
+
|
2546 |
+
ReleaseDate=DateTime.Parse("1984-3-13"),
|
2547 |
+
|
2548 |
+
Genre="Comedy",
|
2549 |
+
|
2550 |
+
Rating="R",
|
2551 |
+
|
2552 |
+
Price=8.99M},
|
2553 |
+
|
2554 |
+
newMovie{Title="Ghostbusters 2",
|
2555 |
+
|
2556 |
+
ReleaseDate=DateTime.Parse("1986-2-23"),
|
2557 |
+
|
2558 |
+
Genre="Comedy",
|
2559 |
+
|
2560 |
+
Rating="R",
|
2561 |
+
|
2562 |
+
Price=9.99M},
|
2563 |
+
|
2564 |
+
newMovie{Title="Rio Bravo",
|
2565 |
+
|
2566 |
+
ReleaseDate=DateTime.Parse("1959-4-15"),
|
2567 |
+
|
2568 |
+
Genre="Western",
|
2569 |
+
|
2570 |
+
Rating="R",
|
2571 |
+
|
2572 |
+
Price=3.99M},
|
2573 |
+
|
2574 |
+
};
|
2575 |
+
|
2576 |
+
movies.ForEach(d => context.Movies.Add(d));
|
2577 |
+
|
2578 |
+
}
|
2579 |
+
|
2580 |
+
}
|
2581 |
+
|
2582 |
+
}
|
2583 |
+
|
2584 |
+
The MovieInitializer class specifies that the database used by the model should be dropped and
|
2585 |
+
|
2586 |
+
automatically re-created if the model classes ever change.DropCreateDatabaseIfModelChanges initializer
|
2587 |
+
|
2588 |
+
specifies the DB should be re-created only if the schema changes. Alternatively, you could use
|
2589 |
+
|
2590 |
+
theDropCreateDatabaseAlways initializer to always recreate and re-seed the database with data the first time
|
2591 |
+
|
2592 |
+
that a context is used in the application domain. TheDropCreateDatabaseAlways approach is useful in some
|
2593 |
+
|
2594 |
+
integration testing scenarios. The code that you inserted into the MovieInitializer class includes a includes a
|
2595 |
+
|
2596 |
+
Seed method that specifies some default data to automatically add to the database any time it's created (or re-
|
2597 |
+
|
2598 |
+
created). This provides a useful way to populate the database with some test data, without requiring you to
|
2599 |
+
|
2600 |
+
manually populate it each time you make a model change.
|
2601 |
+
|
2602 |
+
|
2603 |
+
|
2604 |
+
|
2605 |
+
|
2606 |
+
Now that you've defined the MovieInitializer class, you'll want to wire it up so that each time the
|
2607 |
+
|
2608 |
+
application runs, it checks whether the model classes are different from the schema in the database. If they are,
|
2609 |
+
|
2610 |
+
you can run the initializer to re-create the database to match the model and then populate the database with
|
2611 |
+
|
2612 |
+
the sample data.
|
2613 |
+
|
2614 |
+
Open the Global.asax filet:
|
2615 |
+
|
2616 |
+
|
2617 |
+
The Global.asax file contains the class that defines the entire application for the project, and contains an
|
2618 |
+
|
2619 |
+
Application_Start event handler that runs when the application first starts.
|
2620 |
+
|
2621 |
+
At the beginning of the Application_Start method, add a call to Database.SetInitializer as shown
|
2622 |
+
|
2623 |
+
below:
|
2624 |
+
|
2625 |
+
protectedvoidApplication_Start()
|
2626 |
+
|
2627 |
+
{
|
2628 |
+
|
2629 |
+
Database.SetInitializer<MovieDBContext>(newMovieInitializer());
|
2630 |
+
|
2631 |
+
AreaRegistration.RegisterAllAreas();
|
2632 |
+
|
2633 |
+
// Use LocalDB for Entity Framework by default
|
2634 |
+
|
2635 |
+
Database.DefaultConnectionFactory=newSqlConnectionFactory("Data
|
2636 |
+
|
2637 |
+
Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
|
2638 |
+
|
2639 |
+
RegisterGlobalFilters(GlobalFilters.Filters);
|
2640 |
+
|
2641 |
+
RegisterRoutes(RouteTable.Routes);
|
2642 |
+
|
2643 |
+
BundleTable.Bundles.RegisterTemplateBundles();
|
2644 |
+
|
2645 |
+
}
|
2646 |
+
|
2647 |
+
Put the cursor on the red squiggly line (on MovieDBContext, orMovieInitializer ) right click and select
|
2648 |
+
|
2649 |
+
Resolve, then using MvcMovie.Models;
|
2650 |
+
|
2651 |
+
|
2652 |
+
|
2653 |
+
|
2654 |
+
Alternatively, add the using statement to the top of the file. The using statement references the namespace
|
2655 |
+
|
2656 |
+
where our MovieInitializer class lives:
|
2657 |
+
|
2658 |
+
usingMvcMovie.Models;// MovieInitializer
|
2659 |
+
|
2660 |
+
The Database.SetInitializer statement you just added indicates that the database used by the
|
2661 |
+
|
2662 |
+
MovieDBContext instance should be automatically deleted and re-created if the schema and the database
|
2663 |
+
|
2664 |
+
don't match. And as you saw, it will also populate the database with the sample data that's specified in the
|
2665 |
+
|
2666 |
+
MovieInitializer class.
|
2667 |
+
|
2668 |
+
Close the Global.asax file.
|
2669 |
+
|
2670 |
+
Re-run the application and navigate to the /Movies URL. When the application starts, it detects that the model
|
2671 |
+
|
2672 |
+
structure no longer matches the database schema. It automatically re-creates the database to match the new
|
2673 |
+
|
2674 |
+
model structure and populates the database with the sample movies:
|
2675 |
+
|
2676 |
+
|
2677 |
+
<="">
|
2678 |
+
|
2679 |
+
Click the Create New link to add a new movie. Note that you can add a rating.
|
2680 |
+
|
2681 |
+
Click Create. The new movie, including the rating, now shows up in the movies listing:
|
2682 |
+
|
2683 |
+
|
2684 |
+
You should also add the Rating field to the Edit view template.
|
2685 |
+
|
2686 |
+
In this section you saw how you can modify model objects and keep the database in sync with the changes. You
|
2687 |
+
|
2688 |
+
also learned a way to populate a newly created database with sample data so you can try out scenarios. Next,
|
2689 |
+
|
2690 |
+
let's look at how you can add richer validation logic to the model classes and enable some business rules to be
|
2691 |
+
|
2692 |
+
enforced.
|
2693 |
+
|
2694 |
+
|
2695 |
+
Adding Validation to the Model
|
2696 |
+
|
2697 |
+
In this this section you'll add validation logic to the Movie model, and you'll ensure that the validation rules are
|
2698 |
+
|
2699 |
+
enforced any time a user attempts to create or edit a movie using the application.
|
2700 |
+
|
2701 |
+
Keeping Things DRY
|
2702 |
+
|
2703 |
+
One of the core design tenets of ASP.NET MVC is DRY ("Don't Repeat Yourself"). ASP.NET MVC encourages you
|
2704 |
+
|
2705 |
+
to specify functionality or behavior only once, and then have it be reflected everywhere in an application. This
|
2706 |
+
|
2707 |
+
reduces the amount of code you need to write and makes the code you do write less error prone and easier to
|
2708 |
+
|
2709 |
+
maintain.
|
2710 |
+
|
2711 |
+
The validation support provided by ASP.NET MVC and Entity Framework Code First is a great example of the
|
2712 |
+
|
2713 |
+
DRY principle in action. You can declaratively specify validation rules in one place (in the model class) and the
|
2714 |
+
|
2715 |
+
rules are enforced everywhere in the application.
|
2716 |
+
|
2717 |
+
Let's look at how you can take advantage of this validation support in the movie application.
|
2718 |
+
|
2719 |
+
Adding Validation Rules to the Movie Model
|
2720 |
+
|
2721 |
+
You'll begin by adding some validation logic to the Movie class.
|
2722 |
+
|
2723 |
+
Open the Movie.cs file. Add a using statement at the top of the file that references
|
2724 |
+
|
2725 |
+
theSystem.ComponentModel.DataAnnotations namespace:
|
2726 |
+
|
2727 |
+
usingSystem.ComponentModel.DataAnnotations;
|
2728 |
+
|
2729 |
+
Notice the namespace does not contain System.Web. DataAnnotations provides a built-in set of validation
|
2730 |
+
|
2731 |
+
attributes that you can apply declaratively to any class or property.
|
2732 |
+
|
2733 |
+
Now update the Movie class to take advantage of the built-inRequired,StringLength, andRange validation
|
2734 |
+
|
2735 |
+
attributes. Use the following code as an example of where to apply the attributes.
|
2736 |
+
|
2737 |
+
publicclassMovie{
|
2738 |
+
|
2739 |
+
publicint ID {get;set;}
|
2740 |
+
|
2741 |
+
[Required]
|
2742 |
+
|
2743 |
+
|
2744 |
+
publicstringTitle{get;set;}
|
2745 |
+
|
2746 |
+
[DataType(DataType.Date)]
|
2747 |
+
|
2748 |
+
publicDateTimeReleaseDate{get;set;}
|
2749 |
+
|
2750 |
+
[Required]
|
2751 |
+
|
2752 |
+
publicstringGenre{get;set;}
|
2753 |
+
|
2754 |
+
[Range(1,100)]
|
2755 |
+
|
2756 |
+
[DataType(DataType.Currency)]
|
2757 |
+
|
2758 |
+
publicdecimalPrice{get;set;}
|
2759 |
+
|
2760 |
+
[StringLength(5)]
|
2761 |
+
|
2762 |
+
publicstringRating{get;set;}
|
2763 |
+
|
2764 |
+
}
|
2765 |
+
|
2766 |
+
The validation attributes specify behavior that you want to enforce on the model properties they are applied to.
|
2767 |
+
|
2768 |
+
The Required attribute indicates that a property must have a value; in this sample, a movie has to have values
|
2769 |
+
|
2770 |
+
for the Title, ReleaseDate, Genre, and Price properties in order to be valid. The Range attribute constrains
|
2771 |
+
|
2772 |
+
a value to within a specified range. The StringLength attribute lets you set the maximum length of a string
|
2773 |
+
|
2774 |
+
property, and optionally its minimum length. Intrinsic types (such as decimal, int, float, DateTime) are
|
2775 |
+
|
2776 |
+
required by default and don't need the Requiredattribute.
|
2777 |
+
|
2778 |
+
Code First ensures that the validation rules you specify on a model class are enforced before the application
|
2779 |
+
|
2780 |
+
saves changes in the database. For example, the code below will throw an exception when the SaveChanges
|
2781 |
+
|
2782 |
+
method is called, because several required Movie property values are missing and the price is zero (which is out
|
2783 |
+
|
2784 |
+
of the valid range).
|
2785 |
+
|
2786 |
+
MovieDBContext db =newMovieDBContext();
|
2787 |
+
|
2788 |
+
Movie movie =newMovie();
|
2789 |
+
|
2790 |
+
movie.Title="Gone with the Wind";
|
2791 |
+
|
2792 |
+
movie.Price=0.0M;
|
2793 |
+
|
2794 |
+
db.Movies.Add(movie);
|
2795 |
+
|
2796 |
+
db.SaveChanges();// <= Will throw validation exception
|
2797 |
+
|
2798 |
+
|
2799 |
+
|
2800 |
+
|
2801 |
+
|
2802 |
+
|
2803 |
+
|
2804 |
+
Having validation rules automatically enforced by the .NET Framework helps make your application more
|
2805 |
+
|
2806 |
+
robust. It also ensures that you can't forget to validate something and inadvertently let bad data into the
|
2807 |
+
|
2808 |
+
database.
|
2809 |
+
|
2810 |
+
Here's a complete code listing for the updated Movie.cs file:
|
2811 |
+
|
2812 |
+
usingSystem;
|
2813 |
+
|
2814 |
+
usingSystem.Data.Entity;
|
2815 |
+
|
2816 |
+
usingSystem.ComponentModel.DataAnnotations;
|
2817 |
+
|
2818 |
+
namespaceMvcMovie.Models{
|
2819 |
+
|
2820 |
+
publicclassMovie{
|
2821 |
+
|
2822 |
+
publicint ID {get;set;}
|
2823 |
+
|
2824 |
+
[Required]
|
2825 |
+
|
2826 |
+
publicstringTitle{get;set;}
|
2827 |
+
|
2828 |
+
[DataType(DataType.Date)]
|
2829 |
+
|
2830 |
+
publicDateTimeReleaseDate{get;set;}
|
2831 |
+
|
2832 |
+
[Required]
|
2833 |
+
|
2834 |
+
publicstringGenre{get;set;}
|
2835 |
+
|
2836 |
+
[Range(1,100)]
|
2837 |
+
|
2838 |
+
[DataType(DataType.Currency)]
|
2839 |
+
|
2840 |
+
publicdecimalPrice{get;set;}
|
2841 |
+
|
2842 |
+
[StringLength(5)]
|
2843 |
+
|
2844 |
+
publicstringRating{get;set;}
|
2845 |
+
|
2846 |
+
}
|
2847 |
+
|
2848 |
+
publicclassMovieDBContext:DbContext{
|
2849 |
+
|
2850 |
+
publicDbSet<Movie>Movies{get;set;}
|
2851 |
+
|
2852 |
+
}
|
2853 |
+
|
2854 |
+
}
|
2855 |
+
|
2856 |
+
Validation Error UI in ASP.NET MVC
|
2857 |
+
|
2858 |
+
|
2859 |
+
|
2860 |
+
|
2861 |
+
|
2862 |
+
|
2863 |
+
|
2864 |
+
|
2865 |
+
Re-run the application and navigate to the /Movies URL.
|
2866 |
+
|
2867 |
+
Click the Create New link to add a new movie. Fill out the form with some invalid values and then click the
|
2868 |
+
|
2869 |
+
Create button.
|
2870 |
+
|
2871 |
+
|
2872 |
+
Notice how the form has automatically used a red border color to highlight the text boxes that contain invalid
|
2873 |
+
|
2874 |
+
data and has emitted an appropriate validation error message next to each one. The errors are enforced both
|
2875 |
+
|
2876 |
+
client-side (using JavaScript) and server-side (in case a user has JavaScript disabled).
|
2877 |
+
|
2878 |
+
A real benefit is that you didn't need to change a single line of code in theMoviesController class or in the
|
2879 |
+
|
2880 |
+
Create.cshtml view in order to enable this validation UI. The controller and views you created earlier in this
|
2881 |
+
|
2882 |
+
tutorial automatically picked up the validation rules that you specified by using validation attributes on the
|
2883 |
+
|
2884 |
+
properties of the Movie model class.
|
2885 |
+
|
2886 |
+
You might have noticed for the properties Title and Genre, the required attribute is not enforced until you
|
2887 |
+
|
2888 |
+
submit the form (hit the Create button), or enter text into the input field and removed it. For a field which is
|
2889 |
+
|
2890 |
+
initially empty (such as the fields on the Create view) and which has only the required attribute and no other
|
2891 |
+
|
2892 |
+
validation attributes, you can do the following to trigger validation:
|
2893 |
+
|
2894 |
+
1. Tab into the field.
|
2895 |
+
|
2896 |
+
2. Enter some text.
|
2897 |
+
|
2898 |
+
3. Tab out.
|
2899 |
+
|
2900 |
+
4. Tab back into the field.
|
2901 |
+
|
2902 |
+
5. Remove the text.
|
2903 |
+
|
2904 |
+
6. Tab out.
|
2905 |
+
|
2906 |
+
The above sequence will trigger the required validation without hitting the submit button. Simply hitting the
|
2907 |
+
|
2908 |
+
submit button without entering any of the fields will trigger client side validation. The form data is not sent to
|
2909 |
+
|
2910 |
+
the server until there are no client side validation errors. You can test this by putting a break point in the HTTP
|
2911 |
+
|
2912 |
+
Post method or using thefiddler tool or the IE 9F12 developer tools.
|
2913 |
+
|
2914 |
+
How Validation Occurs in the Create View and Create Action Method
|
2915 |
+
|
2916 |
+
|
2917 |
+
You might wonder how the validation UI was generated without any updates to the code in the controller or
|
2918 |
+
|
2919 |
+
views. The next listing shows what the Create methods in the MovieController class look like. They're
|
2920 |
+
|
2921 |
+
unchanged from how you created them earlier in this tutorial.
|
2922 |
+
|
2923 |
+
//
|
2924 |
+
|
2925 |
+
// GET: /Movies/Create
|
2926 |
+
|
2927 |
+
publicActionResultCreate()
|
2928 |
+
|
2929 |
+
{
|
2930 |
+
|
2931 |
+
returnView();
|
2932 |
+
|
2933 |
+
}
|
2934 |
+
|
2935 |
+
//
|
2936 |
+
|
2937 |
+
// POST: /Movies/Create
|
2938 |
+
|
2939 |
+
[HttpPost]
|
2940 |
+
|
2941 |
+
publicActionResultCreate(Movie movie)
|
2942 |
+
|
2943 |
+
{
|
2944 |
+
|
2945 |
+
if(ModelState.IsValid)
|
2946 |
+
|
2947 |
+
{
|
2948 |
+
|
2949 |
+
db.Movies.Add(movie);
|
2950 |
+
|
2951 |
+
db.SaveChanges();
|
2952 |
+
|
2953 |
+
returnRedirectToAction("Index");
|
2954 |
+
|
2955 |
+
}
|
2956 |
+
|
2957 |
+
returnView(movie);
|
2958 |
+
|
2959 |
+
}
|
2960 |
+
|
2961 |
+
The first (HTTP GET) Create action method displays the initial Create form. The second ([HttpPost]) version
|
2962 |
+
|
2963 |
+
handles the form post. The second Create method (The HttpPost version) calls ModelState.IsValid to
|
2964 |
+
|
2965 |
+
check whether the movie has any validation errors. Calling this method evaluates any validation attributes that
|
2966 |
+
|
2967 |
+
have been applied to the object. If the object has validation errors, the Create method re-displays the form. If
|
2968 |
+
|
2969 |
+
there are no errors, the method saves the new movie in the database. In our movie example we are using, the
|
2970 |
+
|
2971 |
+
form is not posted to the server when their are validation errors detected on the client side; the second Create
|
2972 |
+
|
2973 |
+
method is never called. If you disable JavaScript in your browser, client validation is disabled and the HTTP
|
2974 |
+
|
2975 |
+
POST Create method calls ModelState.IsValid to check whether the movie has any validation errors.
|
2976 |
+
|
2977 |
+
|
2978 |
+
|
2979 |
+
|
2980 |
+
|
2981 |
+
You can set a break point in the HttpPost Create method and verify the method is never called, client side
|
2982 |
+
|
2983 |
+
validation will not submit the form data when validation errors are detected. If you disable JavaScript in your
|
2984 |
+
|
2985 |
+
browser, submit the form with errors, the break point will be hit. You still get full validation without JavaScript.
|
2986 |
+
|
2987 |
+
|
2988 |
+
The following image shows how to disable JavaScript in the FireFox browser.
|
2989 |
+
|
2990 |
+
The following image shows how to disable JavaScript with the Chrome browser.
|
2991 |
+
|
2992 |
+
|
2993 |
+
|
2994 |
+
Below is the Create.cshtml view template that you scaffolded earlier in the tutorial. It's used by the action
|
2995 |
+
|
2996 |
+
methods shown above both to display the initial form and to redisplay it in the event of an error.
|
2997 |
+
|
2998 |
+
|
2999 |
+
@model MvcMovie.Models.Movie
|
3000 |
+
|
3001 |
+
@{
|
3002 |
+
|
3003 |
+
ViewBag.Title = "Create";
|
3004 |
+
|
3005 |
+
}
|
3006 |
+
|
3007 |
+
<h2>Create</h2>
|
3008 |
+
|
3009 |
+
<scriptsrc="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
|
3010 |
+
|
3011 |
+
<scriptsrc="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
|
3012 |
+
|
3013 |
+
@using (Html.BeginForm()) {
|
3014 |
+
|
3015 |
+
@Html.ValidationSummary(true)
|
3016 |
+
|
3017 |
+
<fieldset>
|
3018 |
+
|
3019 |
+
<legend>Movie</legend>
|
3020 |
+
|
3021 |
+
<divclass="editor-label">
|
3022 |
+
|
3023 |
+
@Html.LabelFor(model => model.Title)
|
3024 |
+
|
3025 |
+
</div>
|
3026 |
+
|
3027 |
+
<divclass="editor-field">
|
3028 |
+
|
3029 |
+
@Html.EditorFor(model => model.Title)
|
3030 |
+
|
3031 |
+
@Html.ValidationMessageFor(model => model.Title)
|
3032 |
+
|
3033 |
+
</div>
|
3034 |
+
|
3035 |
+
<divclass="editor-label">
|
3036 |
+
|
3037 |
+
@Html.LabelFor(model => model.ReleaseDate)
|
3038 |
+
|
3039 |
+
</div>
|
3040 |
+
|
3041 |
+
<divclass="editor-field">
|
3042 |
+
|
3043 |
+
@Html.EditorFor(model => model.ReleaseDate)
|
3044 |
+
|
3045 |
+
@Html.ValidationMessageFor(model => model.ReleaseDate)
|
3046 |
+
|
3047 |
+
</div>
|
3048 |
+
|
3049 |
+
<divclass="editor-label">
|
3050 |
+
|
3051 |
+
@Html.LabelFor(model => model.Genre)
|
3052 |
+
|
3053 |
+
</div>
|
3054 |
+
|
3055 |
+
<divclass="editor-field">
|
3056 |
+
|
3057 |
+
@Html.EditorFor(model => model.Genre)
|
3058 |
+
|
3059 |
+
|
3060 |
+
|
3061 |
+
|
3062 |
+
|
3063 |
+
|
3064 |
+
|
3065 |
+
|
3066 |
+
|
3067 |
+
@Html.ValidationMessageFor(model => model.Genre)
|
3068 |
+
|
3069 |
+
</div>
|
3070 |
+
|
3071 |
+
<divclass="editor-label">
|
3072 |
+
|
3073 |
+
@Html.LabelFor(model => model.Price)
|
3074 |
+
|
3075 |
+
</div>
|
3076 |
+
|
3077 |
+
<divclass="editor-field">
|
3078 |
+
|
3079 |
+
@Html.EditorFor(model => model.Price)
|
3080 |
+
|
3081 |
+
@Html.ValidationMessageFor(model => model.Price)
|
3082 |
+
|
3083 |
+
</div>
|
3084 |
+
|
3085 |
+
<divclass="editor-label">
|
3086 |
+
|
3087 |
+
@Html.LabelFor(model => model.Rating)
|
3088 |
+
|
3089 |
+
</div>
|
3090 |
+
|
3091 |
+
<divclass="editor-field">
|
3092 |
+
|
3093 |
+
@Html.EditorFor(model => model.Rating)
|
3094 |
+
|
3095 |
+
@Html.ValidationMessageFor(model => model.Rating)
|
3096 |
+
|
3097 |
+
</div>
|
3098 |
+
|
3099 |
+
<p>
|
3100 |
+
|
3101 |
+
<inputtype="submit"value="Create"/>
|
3102 |
+
|
3103 |
+
</p>
|
3104 |
+
|
3105 |
+
</fieldset>
|
3106 |
+
|
3107 |
+
}
|
3108 |
+
|
3109 |
+
<div>
|
3110 |
+
|
3111 |
+
@Html.ActionLink("Back to List", "Index")
|
3112 |
+
|
3113 |
+
</div>
|
3114 |
+
|
3115 |
+
Notice how the code uses an Html.EditorFor helper to output the<input> element for each Movie
|
3116 |
+
|
3117 |
+
property. Next to this helper is a call to the Html.ValidationMessageFor helper method. These two helper
|
3118 |
+
|
3119 |
+
methods work with the model object that's passed by the controller to the view (in this case, a Movie object).
|
3120 |
+
|
3121 |
+
They automatically look for validation attributes specified on the model and display error messages as
|
3122 |
+
|
3123 |
+
appropriate.
|
3124 |
+
|
3125 |
+
What's really nice about this approach is that neither the controller nor the Create view template knows
|
3126 |
+
|
3127 |
+
anything about the actual validation rules being enforced or about the specific error messages displayed. The
|
3128 |
+
|
3129 |
+
validation rules and the error strings are specified only in the Movie class.
|
3130 |
+
|
3131 |
+
|
3132 |
+
|
3133 |
+
If you want to change the validation logic later, you can do so in exactly one place by adding validation
|
3134 |
+
|
3135 |
+
attributes to the model (in this example, themovie class). You won't have to worry about different parts of the
|
3136 |
+
|
3137 |
+
application being inconsistent with how the rules are enforced — all validation logic will be defined in one
|
3138 |
+
|
3139 |
+
place and used everywhere. This keeps the code very clean, and makes it easy to maintain and evolve. And it
|
3140 |
+
|
3141 |
+
means that that you'll be fully honoring the DRY principle.
|
3142 |
+
|
3143 |
+
Adding Formatting to the Movie Model
|
3144 |
+
|
3145 |
+
Open the Movie.cs file and examine the Movie class. TheSystem.ComponentModel.DataAnnotations
|
3146 |
+
|
3147 |
+
namespace provides formatting attributes in addition to the built-in set of validation attributes. We've already
|
3148 |
+
|
3149 |
+
applied aDataType enumeration value to the release date and to the price fields. The following code shows the
|
3150 |
+
|
3151 |
+
ReleaseDate and Price properties with the appropriateDisplayFormat attribute.
|
3152 |
+
|
3153 |
+
[DataType(DataType.Date)]
|
3154 |
+
|
3155 |
+
publicDateTimeReleaseDate{get;set;}
|
3156 |
+
|
3157 |
+
[DataType(DataType.Currency)]
|
3158 |
+
|
3159 |
+
publicdecimalPrice{get;set;}
|
3160 |
+
|
3161 |
+
Alternatively, you could explicitly set aDataFormatString value. The following code shows the release date
|
3162 |
+
|
3163 |
+
property with a date format string (namely, "d"). You'd use this to specify that you don't want to time as part of
|
3164 |
+
|
3165 |
+
the release date.
|
3166 |
+
|
3167 |
+
[DisplayFormat(DataFormatString="{0:d}")]
|
3168 |
+
|
3169 |
+
publicDateTimeReleaseDate{get;set;}
|
3170 |
+
|
3171 |
+
The following code formats the Price property as currency.
|
3172 |
+
|
3173 |
+
[DisplayFormat(DataFormatString="{0:c}")]
|
3174 |
+
|
3175 |
+
publicdecimalPrice{get;set;}
|
3176 |
+
|
3177 |
+
The complete Movie class is shown below.
|
3178 |
+
|
3179 |
+
publicclassMovie{
|
3180 |
+
|
3181 |
+
publicint ID {get;set;}
|
3182 |
+
|
3183 |
+
|
3184 |
+
|
3185 |
+
[Required]
|
3186 |
+
|
3187 |
+
publicstringTitle{get;set;}
|
3188 |
+
|
3189 |
+
[DataType(DataType.Date)]
|
3190 |
+
|
3191 |
+
publicDateTimeReleaseDate{get;set;}
|
3192 |
+
|
3193 |
+
[Required]
|
3194 |
+
|
3195 |
+
publicstringGenre{get;set;}
|
3196 |
+
|
3197 |
+
[Range(1,100)]
|
3198 |
+
|
3199 |
+
[DataType(DataType.Currency)]
|
3200 |
+
|
3201 |
+
publicdecimalPrice{get;set;}
|
3202 |
+
|
3203 |
+
[StringLength(5)]
|
3204 |
+
|
3205 |
+
publicstringRating{get;set;}
|
3206 |
+
|
3207 |
+
}
|
3208 |
+
|
3209 |
+
Run the application and browse to the Movies controller. The release date and price are nicely formatted.
|
3210 |
+
|
3211 |
+
|
3212 |
+
|
3213 |
+
|
3214 |
+
|
3215 |
+
In the next part of the series, we'll review the application and make some improvements to the automatically
|
3216 |
+
|
3217 |
+
generated Details and Delete methods.
|
3218 |
+
|
3219 |
+
|
3220 |
+
|
3221 |
+
|
3222 |
+
Examining the Details and Delete Methods
|
3223 |
+
|
3224 |
+
In this part of the tutorial, you'll examine the automatically generated Details and Delete methods.
|
3225 |
+
|
3226 |
+
Examining the Details and Delete Methods
|
3227 |
+
|
3228 |
+
Open the Movie controller and examine the Details method.
|
3229 |
+
|
3230 |
+
publicActionResultDetails(int id =0)
|
3231 |
+
|
3232 |
+
{
|
3233 |
+
|
3234 |
+
Movie movie =db.Movies.Find(id);
|
3235 |
+
|
3236 |
+
if(movie ==null)
|
3237 |
+
|
3238 |
+
{
|
3239 |
+
|
3240 |
+
returnHttpNotFound();
|
3241 |
+
|
3242 |
+
}
|
3243 |
+
|
3244 |
+
returnView(movie);
|
3245 |
+
|
3246 |
+
}
|
3247 |
+
|
3248 |
+
Code First makes it easy to search for data using the Find method. An important security feature built into the
|
3249 |
+
|
3250 |
+
method is that the code verifies that the Find method has found a movie before the code tries to do anything
|
3251 |
+
|
3252 |
+
with it. For example, a hacker could introduce errors into the site by changing the URL created by the links from
|
3253 |
+
|
3254 |
+
http://localhost:xxxx/Movies/Details/1 to something like http://localhost:xxxx/Movies/Details/12345 (or some
|
3255 |
+
|
3256 |
+
other value that doesn't represent an actual movie). If you did not check for a null movie, a null movie would
|
3257 |
+
|
3258 |
+
result in a database error.
|
3259 |
+
|
3260 |
+
Examine the Delete and DeleteConfirmed methods.
|
3261 |
+
|
3262 |
+
// GET: /Movies/Delete/5
|
3263 |
+
|
3264 |
+
publicActionResultDelete(int id =0)
|
3265 |
+
|
3266 |
+
{
|
3267 |
+
|
3268 |
+
Movie movie =db.Movies.Find(id);
|
3269 |
+
|
3270 |
+
if(movie ==null)
|
3271 |
+
|
3272 |
+
{
|
3273 |
+
|
3274 |
+
returnHttpNotFound();
|
3275 |
+
|
3276 |
+
}
|
3277 |
+
|
3278 |
+
returnView(movie);
|
3279 |
+
|
3280 |
+
|
3281 |
+
}
|
3282 |
+
|
3283 |
+
//
|
3284 |
+
|
3285 |
+
// POST: /Movies/Delete/5
|
3286 |
+
|
3287 |
+
[HttpPost,ActionName("Delete")]
|
3288 |
+
|
3289 |
+
publicActionResultDeleteConfirmed(int id =0)
|
3290 |
+
|
3291 |
+
{
|
3292 |
+
|
3293 |
+
Movie movie =db.Movies.Find(id);
|
3294 |
+
|
3295 |
+
if(movie ==null)
|
3296 |
+
|
3297 |
+
{
|
3298 |
+
|
3299 |
+
returnHttpNotFound();
|
3300 |
+
|
3301 |
+
}
|
3302 |
+
|
3303 |
+
db.Movies.Remove(movie);
|
3304 |
+
|
3305 |
+
db.SaveChanges();
|
3306 |
+
|
3307 |
+
returnRedirectToAction("Index");
|
3308 |
+
|
3309 |
+
}
|
3310 |
+
|
3311 |
+
Note that the HTTP Get Delete method doesn't delete the specified movie, it returns a view of the movie
|
3312 |
+
|
3313 |
+
where you can submit (HttpPost) the deletion.. Performing a delete operation in response to a GET request (or
|
3314 |
+
|
3315 |
+
for that matter, performing an edit operation, create operation, or any other operation that changes data)
|
3316 |
+
|
3317 |
+
opens up a security hole. For more information about this, see Stephen Walther's blog entryASP.NET MVC Tip
|
3318 |
+
|
3319 |
+
#46 — Don't use Delete Links because they create Security Holes.
|
3320 |
+
|
3321 |
+
The HttpPost method that deletes the data is named DeleteConfirmed to give the HTTP POST method a
|
3322 |
+
|
3323 |
+
unique signature or name. The two method signatures are shown below:
|
3324 |
+
|
3325 |
+
// GET: /Movies/Delete/5
|
3326 |
+
|
3327 |
+
publicActionResultDelete(int id =0)
|
3328 |
+
|
3329 |
+
//
|
3330 |
+
|
3331 |
+
// POST: /Movies/Delete/5
|
3332 |
+
|
3333 |
+
[HttpPost,ActionName("Delete")]
|
3334 |
+
|
3335 |
+
publicActionResultDeleteConfirmed(int id =0)
|
3336 |
+
|
3337 |
+
|
3338 |
+
|
3339 |
+
|
3340 |
+
The common language runtime (CLR) requires overloaded methods to have a unique signature (same method
|
3341 |
+
|
3342 |
+
name but different list of parameters). However, here you need two Delete methods -- one for GET and one for
|
3343 |
+
|
3344 |
+
POST -- that both have the same signature. (They both need to accept a single integer as a parameter.)
|
3345 |
+
|
3346 |
+
To sort this out, you can do a couple of things. One is to give the methods different names. That's what the
|
3347 |
+
|
3348 |
+
scaffolding mechanism did in he preceding example. However, this introduces a small problem: ASP.NET maps
|
3349 |
+
|
3350 |
+
segments of a URL to action methods by name, and if you rename a method, routing normally wouldn't be able
|
3351 |
+
|
3352 |
+
to find that method. The solution is what you see in the example, which is to add the ActionName("Delete")
|
3353 |
+
|
3354 |
+
attribute to theDeleteConfirmed method. This effectively performs mapping for the routing system so that a
|
3355 |
+
|
3356 |
+
URL that includes /Delete/ for a POST request will find the DeleteConfirmed method.
|
3357 |
+
|
3358 |
+
Another common way to avoid a problem with methods that have identical names and signatures is to
|
3359 |
+
|
3360 |
+
artificially change the signature of the POST method to include an unused parameter. For example, some
|
3361 |
+
|
3362 |
+
developers add a parameter typeFormCollectionthat is passed to the POST method, and then simply don't
|
3363 |
+
|
3364 |
+
use the parameter:
|
3365 |
+
|
3366 |
+
publicActionResultDelete(FormCollection fcNotUsed,int id =0)
|
3367 |
+
|
3368 |
+
{
|
3369 |
+
|
3370 |
+
Movie movie =db.Movies.Find(id);
|
3371 |
+
|
3372 |
+
if(movie ==null)
|
3373 |
+
|
3374 |
+
{
|
3375 |
+
|
3376 |
+
returnHttpNotFound();
|
3377 |
+
|
3378 |
+
}
|
3379 |
+
|
3380 |
+
db.Movies.Remove(movie);
|
3381 |
+
|
3382 |
+
db.SaveChanges();
|
3383 |
+
|
3384 |
+
returnRedirectToAction("Index");
|
3385 |
+
|
3386 |
+
}
|
3387 |
+
|
3388 |
+
Wrapping Up
|
3389 |
+
|
3390 |
+
You now have a complete ASP.NET MVC application that stores data in a SQL Server Compact database. You
|
3391 |
+
|
3392 |
+
can create, read, update, delete, and search for movies.
|
3393 |
+
|
3394 |
+
This basic tutorial got you started making controllers, associating them with views, and passing around hard-
|
3395 |
+
|
3396 |
+
coded data. Then you created and designed a data model. Entity Framework code-first created a database from
|
3397 |
+
|
3398 |
+
the data model on the fly, and the ASP.NET MVC scaffolding system automatically generated the action
|
3399 |
+
|
3400 |
+
methods and views for basic CRUD operations. You then added a search form that let users search the
|
3401 |
+
|
3402 |
+
database. You changed the database to include a new column of data, and then updated two pages to create
|
3403 |
+
|
3404 |
+
and display this new data. You added validation by marking the data model with attributes from the
|
3405 |
+
|
3406 |
+
DataAnnotations namespace. The resulting validation runs on the client and on the server.
|
3407 |
+
|
3408 |
+
If you'd like to deploy your application, it's helpful to first test the application on your local IIS 7 server. You can
|
3409 |
+
|
3410 |
+
use thisWeb Platform Installer link to enable IIS setting for ASP.NET applications. See the following deployment
|
3411 |
+
|
3412 |
+
links:
|
3413 |
+
|
3414 |
+
|
3415 |
+
• ASP.NET Deployment Content Map
|
3416 |
+
|
3417 |
+
•
|
3418 |
+
|
3419 |
+
Enabling IIS 7.x
|
3420 |
+
|
3421 |
+
• Web Application Projects Deployment
|
3422 |
+
|
3423 |
+
I now encourage you to move on to our intermediate-levelCreating an Entity Framework Data Model for an
|
3424 |
+
|
3425 |
+
ASP.NET MVC Application andMVC Music Store tutorials, to explore theASP.NET articles on MSDN, and to
|
3426 |
+
|
3427 |
+
check out the many videos and resources athttp://asp.net/mvc to learn even more about ASP.NET MVC! The
|
3428 |
+
|
3429 |
+
ASP.NET MVC forums are a great place to ask questions.
|
3430 |
+
|
3431 |
+
Enjoy!
|
3432 |
+
|
3433 |
+
— Rick Anderson blogs.msdn.com/rickAndy twitter @RickAndMSFT
|
3434 |
+
|
3435 |
+
— Scott Hanselmanhttp://www.hanselman.com/blog/ twitter @shanselman
|
3436 |
+
|
3437 |
+
|
3438 |
+
|
3439 |
+
|
3440 |
+
|
3441 |
+
|
3442 |
+
|
ASP.NET/intro%2520to%2520asp.net%2520mvc%25204%2520with%2520visual%2520studio%2520-%2520beta.pdf.txt
ADDED
@@ -0,0 +1,3442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Intr
|
2 |
+
Visu
|
3 |
+
|
4 |
+
ro to
|
5 |
+
ual S
|
6 |
+
|
7 |
+
o ASP
|
8 |
+
Studio
|
9 |
+
|
10 |
+
P.NET
|
11 |
+
o (Be
|
12 |
+
|
13 |
+
T MV
|
14 |
+
eta)
|
15 |
+
|
16 |
+
VC 4 w
|
17 |
+
|
18 |
+
with
|
19 |
+
|
20 |
+
Rick A
|
21 |
+
|
22 |
+
Anderso
|
23 |
+
|
24 |
+
on and S
|
25 |
+
|
26 |
+
Scott Ha
|
27 |
+
|
28 |
+
anselma
|
29 |
+
|
30 |
+
an
|
31 |
+
|
32 |
+
Summa
|
33 |
+
|
34 |
+
ry: This tuto
|
35 |
+
|
36 |
+
orial will te
|
37 |
+
|
38 |
+
ach you the
|
39 |
+
|
40 |
+
e basics of
|
41 |
+
|
42 |
+
building an
|
43 |
+
|
44 |
+
n ASP.NET M
|
45 |
+
|
46 |
+
MVC Web
|
47 |
+
|
48 |
+
applicat
|
49 |
+
|
50 |
+
ion using M
|
51 |
+
|
52 |
+
Microsoft Vi
|
53 |
+
|
54 |
+
isual Studio
|
55 |
+
|
56 |
+
o 11 Express
|
57 |
+
|
58 |
+
s Beta for W
|
59 |
+
|
60 |
+
Web, which
|
61 |
+
|
62 |
+
is a free
|
63 |
+
|
64 |
+
version o
|
65 |
+
|
66 |
+
of Microsof
|
67 |
+
|
68 |
+
ft Visual Stu
|
69 |
+
|
70 |
+
udio.
|
71 |
+
|
72 |
+
Categor
|
73 |
+
|
74 |
+
ry: Step-By
|
75 |
+
|
76 |
+
-Step
|
77 |
+
|
78 |
+
Applies
|
79 |
+
|
80 |
+
to: ASP.NE
|
81 |
+
|
82 |
+
ET MVC 4 B
|
83 |
+
|
84 |
+
eta, Visual
|
85 |
+
|
86 |
+
Studio 11 B
|
87 |
+
|
88 |
+
Beta
|
89 |
+
|
90 |
+
Source:
|
91 |
+
|
92 |
+
ASP.NET si
|
93 |
+
|
94 |
+
te (link to s
|
95 |
+
|
96 |
+
source cont
|
97 |
+
|
98 |
+
tent)
|
99 |
+
|
100 |
+
E-book
|
101 |
+
|
102 |
+
publicatio
|
103 |
+
|
104 |
+
on date: Ma
|
105 |
+
|
106 |
+
ay 2012
|
107 |
+
|
108 |
+
115 pag
|
109 |
+
|
110 |
+
es
|
111 |
+
|
112 |
+
|
113 |
+
|
114 |
+
|
115 |
+
|
116 |
+
|
117 |
+
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
|
122 |
+
|
123 |
+
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
Copyright © 2012 by Microsoft Corporation
|
129 |
+
|
130 |
+
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means
|
131 |
+
without the written permission of the publisher.
|
132 |
+
|
133 |
+
Microsoft and the trademarks listed at
|
134 |
+
http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the
|
135 |
+
Microsoft group of companies. All other marks are property of their respective owners.
|
136 |
+
|
137 |
+
The example companies, organizations, products, domain names, email addresses, logos, people, places, and events
|
138 |
+
depicted herein are fictitious. No association with any real company, organization, product, domain name, email address,
|
139 |
+
logo, person, place, or event is intended or should be inferred.
|
140 |
+
|
141 |
+
This book expresses the author’s views and opinions. The information contained in this book is provided without any
|
142 |
+
express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will
|
143 |
+
be held liable for any damages caused or alleged to be caused either directly or indirectly by this book.
|
144 |
+
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
|
150 |
+
|
151 |
+
|
152 |
+
|
153 |
+
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
Contents
|
159 |
+
Getting Started ........................................................................................................................................ 3
|
160 |
+
|
161 |
+
What You'll Build ........................................................................................................................... 3
|
162 |
+
|
163 |
+
Skills You'll Learn ........................................................................................................................... 5
|
164 |
+
|
165 |
+
Getting Started .............................................................................................................................. 6
|
166 |
+
|
167 |
+
Creating Your First Application .................................................................................................... 7
|
168 |
+
|
169 |
+
Adding a Controller ............................................................................................................................ 13
|
170 |
+
|
171 |
+
Adding a View ..................................................................................................................................... 20
|
172 |
+
|
173 |
+
Changing Views and Layout Pages ............................................................................................ 25
|
174 |
+
|
175 |
+
Passing Data from the Controller to the View ........................................................................... 31
|
176 |
+
|
177 |
+
Adding a Model .................................................................................................................................. 37
|
178 |
+
|
179 |
+
Adding Model Classes................................................................................................................. 37
|
180 |
+
|
181 |
+
Creating a Connection String and Working with SQL Server LocalDB .................................... 41
|
182 |
+
|
183 |
+
Accessing Your Model's Data from a Controller ............................................................................... 43
|
184 |
+
|
185 |
+
Creating a Movie ......................................................................................................................... 46
|
186 |
+
|
187 |
+
Examining the Generated Code.................................................................................................. 48
|
188 |
+
|
189 |
+
Strongly Typed Models and the @model Keyword .................................................................. 49
|
190 |
+
|
191 |
+
Working with SQL Server LocalDB ............................................................................................. 53
|
192 |
+
|
193 |
+
Examining the Edit Methods and Edit View ...................................................................................... 58
|
194 |
+
|
195 |
+
Processing the POST Request ..................................................................................................... 65
|
196 |
+
|
197 |
+
Adding a Search Method and Search View ............................................................................... 67
|
198 |
+
|
199 |
+
Displaying the SearchIndex Form ............................................................................................... 67
|
200 |
+
|
201 |
+
Adding Search by Genre ............................................................................................................. 77
|
202 |
+
|
203 |
+
Adding Markup to the SearchIndex View to Support Search by Genre .................................. 79
|
204 |
+
|
205 |
+
Adding a New Field to the Movie Model and Table ......................................................................... 80
|
206 |
+
|
207 |
+
Adding a Rating Property to the Movie Model ......................................................................... 80
|
208 |
+
|
209 |
+
Managing Model and Database Schema Differences ............................................................... 82
|
210 |
+
|
211 |
+
Automatically Re-Creating the Database on Model Changes .................................................. 85
|
212 |
+
|
213 |
+
Adding Validation to the Model ........................................................................................................ 95
|
214 |
+
|
215 |
+
Keeping Things DRY .................................................................................................................... 95
|
216 |
+
|
217 |
+
Adding Validation Rules to the Movie Model ........................................................................... 95
|
218 |
+
|
219 |
+
Validation Error UI in ASP.NET MVC .......................................................................................... 97
|
220 |
+
|
221 |
+
How Validation Occurs in the Create View and Create Action Method ................................ 100
|
222 |
+
|
223 |
+
Adding Formatting to the Movie Model.................................................................................. 108
|
224 |
+
|
225 |
+
Examining the Details and Delete Methods .................................................................................... 111
|
226 |
+
|
227 |
+
Examining the Details and Delete Methods ............................................................................ 111
|
228 |
+
|
229 |
+
Wrapping Up ............................................................................................................................. 113
|
230 |
+
|
231 |
+
|
232 |
+
|
233 |
+
|
234 |
+
Getting Started
|
235 |
+
By Rick Anderson and Scott Hanselman
|
236 |
+
|
237 |
+
This tutorial will teach you the basics of building an ASP.NET MVC Web application using Microsoft Visual
|
238 |
+
|
239 |
+
Studio 11 Express Beta for Web, which is a free version of Microsoft Visual Studio. Before you start, make sure
|
240 |
+
|
241 |
+
you've installed the prerequisites listed below. You can install all of them by clicking the following link: Web
|
242 |
+
|
243 |
+
Platform Installer.
|
244 |
+
|
245 |
+
If you're using Visual Studio 11 Beta instead of Visual Studio 11 Express Beta for Web , install the prerequisites
|
246 |
+
|
247 |
+
by clicking the following link: Web Platform Installer
|
248 |
+
|
249 |
+
A Visual Web Developer project with C# source code is available to accompany this topic. Download the C#
|
250 |
+
|
251 |
+
version.
|
252 |
+
|
253 |
+
What You'll Build
|
254 |
+
|
255 |
+
You'll implement a simple movie-listing application that supports creating, editing, searching and listing movies
|
256 |
+
|
257 |
+
from a database. Below are two screenshots of the application you’ll build. It includes a page that displays a list
|
258 |
+
|
259 |
+
of movies from a database:
|
260 |
+
|
261 |
+
|
262 |
+
|
263 |
+
|
264 |
+
The application also lets you add, edit, and delete movies, as well as see details about individual ones. All data-
|
265 |
+
|
266 |
+
entry scenarios include validation to ensure that the data stored in the database is correct.
|
267 |
+
|
268 |
+
|
269 |
+
Skills You'll Learn
|
270 |
+
|
271 |
+
Here's what you'll learn:
|
272 |
+
|
273 |
+
• How to create a new ASP.NET MVC project.
|
274 |
+
|
275 |
+
|
276 |
+
• How to create ASP.NET MVC controllers and views.
|
277 |
+
|
278 |
+
• How to create a new database using the Entity Framework Code First paradigm.
|
279 |
+
|
280 |
+
• How to retrieve and display data.
|
281 |
+
|
282 |
+
• How to edit data and enable data validation.
|
283 |
+
|
284 |
+
Getting Started
|
285 |
+
|
286 |
+
Start by running Visual Web Developer 11 Express Beta("Visual Web Developer" or VWD for short) and select
|
287 |
+
|
288 |
+
New Project from the Start page.
|
289 |
+
|
290 |
+
Visual Web Developer is an IDE, or integrated development environment. Just like you use Microsoft Word to
|
291 |
+
|
292 |
+
write documents, you'll use an IDE to create applications. In Visual Web Developer there's a toolbar along the
|
293 |
+
|
294 |
+
top showing various options available to you. There's also a menu that provides another way to perform tasks
|
295 |
+
|
296 |
+
in the IDE. (For example, instead of selecting New Project from the Start page, you can use the menu and
|
297 |
+
|
298 |
+
select File>New Project.)
|
299 |
+
|
300 |
+
Creating Your First Application
|
301 |
+
|
302 |
+
You can create applications using either Visual Basic or Visual C# as the programming language. Select Visual
|
303 |
+
|
304 |
+
C# on the left and then select ASP.NET MVC 4 Web Application. Name your project "MvcMovie" and then
|
305 |
+
|
306 |
+
click OK.
|
307 |
+
|
308 |
+
|
309 |
+
In the New ASP.NET MVC 4 Project dialog box, select Internet Application. LeaveRazor as the default view
|
310 |
+
|
311 |
+
engine.
|
312 |
+
|
313 |
+
|
314 |
+
Click OK. Visual Web Developer used a default template for the ASP.NET MVC project you just created, so you
|
315 |
+
|
316 |
+
have a working application right now without doing anything! This is a simple "Hello World!" project, and it's a
|
317 |
+
|
318 |
+
good place to start your application.
|
319 |
+
|
320 |
+
|
321 |
+
From the Debug menu, select Start Debugging.
|
322 |
+
|
323 |
+
|
324 |
+
Notice that the keyboard shortcut to start debugging is F5.
|
325 |
+
|
326 |
+
|
327 |
+
F5 causes Visual Web Developer to start IIS Express and run your web application. Visual Web Developer then
|
328 |
+
|
329 |
+
launches a browser and opens the application's home page. Notice that the address bar of the browser says
|
330 |
+
|
331 |
+
localhost and not something like example.com. That's becauselocalhost always points to your own local
|
332 |
+
|
333 |
+
computer, which in this case is running the application you just built. When Visual Web Developer runs a web
|
334 |
+
|
335 |
+
project, a random port is used for the web server. In the image below, the port number is 41788. When you run
|
336 |
+
|
337 |
+
the application, you'll probably see a different port number.
|
338 |
+
|
339 |
+
Right out of the box this default template gives you Home, Contact and About pages. It also provides support
|
340 |
+
|
341 |
+
to register and log in, and links to Facebook and Twitter. The next step is to change how this application works
|
342 |
+
|
343 |
+
and learn a little bit about ASP.NET MVC. Close your browser and let's change some code.
|
344 |
+
|
345 |
+
|
346 |
+
|
347 |
+
|
348 |
+
Adding a Controller
|
349 |
+
|
350 |
+
MVC stands formodel-view-controller. MVC is a pattern for developing applications that are well
|
351 |
+
architected, testable and easy to maintain. MVC-based applications contain:
|
352 |
+
• Models: Classes that represent the data of the application and that use validation logic to enforce
|
353 |
+
|
354 |
+
business rules for that data.
|
355 |
+
|
356 |
+
• Views: Template files that your application uses to dynamically generate HTML responses.
|
357 |
+
|
358 |
+
• Controllers: Classes that handle incoming browser requests, retrieve model data, and then specify
|
359 |
+
|
360 |
+
view templates that return a response to the browser.
|
361 |
+
|
362 |
+
We'll be covering all these concepts in this tutorial series and show you how to use them to build an
|
363 |
+
application.
|
364 |
+
|
365 |
+
Let's begin by creating a controller class. InSolution Explorer, right-click theControllersfolder and then
|
366 |
+
selectAdd Controller.
|
367 |
+
|
368 |
+
Name your new controller "HelloWorldController". Leave the default template asEmpty controllerand
|
369 |
+
clickAdd.
|
370 |
+
|
371 |
+
|
372 |
+
Notice inSolution Explorerthat a new file has been created namedHelloWorldController.cs. The file is
|
373 |
+
open in the IDE.
|
374 |
+
|
375 |
+
|
376 |
+
Replace the contents of the file with the following code.
|
377 |
+
|
378 |
+
usingSystem.Web;
|
379 |
+
usingSystem.Web.Mvc;
|
380 |
+
|
381 |
+
namespaceMvcMovie.Controllers
|
382 |
+
{
|
383 |
+
publicclassHelloWorldController:Controller
|
384 |
+
{
|
385 |
+
//
|
386 |
+
// GET: /HelloWorld/
|
387 |
+
|
388 |
+
|
389 |
+
|
390 |
+
publicstringIndex()
|
391 |
+
{
|
392 |
+
return"This is my <b>default</b> action...";
|
393 |
+
}
|
394 |
+
|
395 |
+
//
|
396 |
+
// GET: /HelloWorld/Welcome/
|
397 |
+
|
398 |
+
publicstringWelcome()
|
399 |
+
{
|
400 |
+
return"This is the Welcome action method...";
|
401 |
+
}
|
402 |
+
}
|
403 |
+
}
|
404 |
+
|
405 |
+
The controller methods will return a string of HTML as an example. The controller is
|
406 |
+
namedHelloWorldControllerand the first method above is namedIndex. Let’s invoke it from a browser.
|
407 |
+
Run the application (press F5 or Ctrl+F5). In the browser, append "HelloWorld" to the path in the address
|
408 |
+
bar. (For example, in the illustration below, it'shttp://localhost:1234/HelloWorld.) The page in the browser
|
409 |
+
will look like the following screenshot. In the method above, the code returned a string directly. You told
|
410 |
+
the system to just return some HTML, and it did!
|
411 |
+
|
412 |
+
ASP.NET MVC invokes different controller classes (and different action methods within them) depending
|
413 |
+
on the incoming URL. The default URL routing logic used by ASP.NET MVC uses a format like this to
|
414 |
+
determine what code to invoke:
|
415 |
+
|
416 |
+
/[Controller]/[ActionName]/[Parameters]
|
417 |
+
The first part of the URL determines the controller class to execute. So/HelloWorldmaps to the
|
418 |
+
HelloWorldControllerclass. The second part of the URL determines the action method on the class to
|
419 |
+
|
420 |
+
|
421 |
+
|
422 |
+
|
423 |
+
|
424 |
+
execute. So/HelloWorld/Indexwould cause theIndexmethod of theHelloWorldControllerclass to
|
425 |
+
execute. Notice that we only had to browse to/HelloWorldand theIndexmethod was used by default. This
|
426 |
+
is because a method named Indexis the default method that will be called on a controller if one is not
|
427 |
+
explicitly specified.
|
428 |
+
Browse tohttp://localhost:xxxx/HelloWorld/Welcome. TheWelcomemethod runs and returns the string "This
|
429 |
+
is the Welcome action method...". The default MVC mapping
|
430 |
+
is/[Controller]/[ActionName]/[Parameters]. For this URL, the controller
|
431 |
+
isHelloWorldandWelcomeis the action method. You haven't used the[Parameters]part of the URL yet.
|
432 |
+
|
433 |
+
Let's modify the example slightly so that you can pass some parameter information from the URL to the
|
434 |
+
controller (for example,/HelloWorld/Welcome?name=Scott&numtimes=4). Change yourWelcomemethod
|
435 |
+
to include two parameters as shown below. Note that the code uses the C# optional-parameter feature to
|
436 |
+
indicate that the numTimesparameter should default to 1 if no value is passed for that parameter.
|
437 |
+
|
438 |
+
publicstringWelcome(string name,int numTimes =1){
|
439 |
+
returnHttpUtility.HtmlEncode("Hello "+ name +", NumTimes is: "+ numTimes);
|
440 |
+
}
|
441 |
+
|
442 |
+
Run your application and browse to the example URL
|
443 |
+
(http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4). You can try different values
|
444 |
+
fornameandnumtimesin the URL. The ASP.NET MVC model binding system automatically maps the named
|
445 |
+
parameters from the query string in the address bar to parameters in your method.
|
446 |
+
|
447 |
+
|
448 |
+
In both these examples the controller has been doing the "VC" portion of MVC — that is, the view and
|
449 |
+
controller work. The controller is returning HTML directly. Ordinarily you don't want controllers returning
|
450 |
+
HTML directly, since that becomes very cumbersome to code. Instead we'll typically use a separate view
|
451 |
+
template file to help generate the HTML response. Let's look next at how we can do this.
|
452 |
+
|
453 |
+
|
454 |
+
|
455 |
+
|
456 |
+
Adding a View
|
457 |
+
|
458 |
+
In this section you're going to modify the HelloWorldController class to use view template files to cleanly
|
459 |
+
|
460 |
+
encapsulate the process of generating HTML responses to a client.
|
461 |
+
|
462 |
+
You'll create a view template file using theRazor view engine introduced with ASP.NET MVC 3. Razor-based
|
463 |
+
|
464 |
+
view templates have a .cshtml file extension, and provide an elegant way to create HTML output using C#. Razor
|
465 |
+
|
466 |
+
minimizes the number of characters and keystrokes required when writing a view template, and enables a fast,
|
467 |
+
|
468 |
+
fluid coding workflow.
|
469 |
+
|
470 |
+
Start by creating a view template with the Index method in theHelloWorldController class. Currently the
|
471 |
+
|
472 |
+
Index method returns a string with a message that is hard-coded in the controller class. Change the Index
|
473 |
+
|
474 |
+
method to return a View object, as shown in the following code:
|
475 |
+
|
476 |
+
publicActionResultIndex()
|
477 |
+
|
478 |
+
{
|
479 |
+
|
480 |
+
returnView();
|
481 |
+
|
482 |
+
}
|
483 |
+
|
484 |
+
The Index method above uses a view template to generate an HTML response to the browser. Controller
|
485 |
+
|
486 |
+
methods (also known asaction methods), such as the Index method above, generally return anActionResult (or a
|
487 |
+
|
488 |
+
class derrived fromActionResult), not primitive types like string.
|
489 |
+
|
490 |
+
In the project, add a view template that you can use with the Index method. To do this, right-click inside the
|
491 |
+
|
492 |
+
Index method and clickAdd View.
|
493 |
+
|
494 |
+
|
495 |
+
The Add View dialog box appears. Leave the defaults the way they are and click the Add button:
|
496 |
+
|
497 |
+
The MvcMovie\Views\HelloWorld folder and the MvcMovie\Views\HelloWorld\Index.cshtml file are created. You
|
498 |
+
|
499 |
+
can see them in Solution Explorer:
|
500 |
+
|
501 |
+
|
502 |
+
The following shows the Index.cshtml file that was created:
|
503 |
+
|
504 |
+
|
505 |
+
Add the following HTML under the <h2> tag.
|
506 |
+
|
507 |
+
<p>Hello from our View Template!</p>
|
508 |
+
|
509 |
+
The complete MvcMovie\Views\HelloWorld\Index.cshtml file is shown below.
|
510 |
+
|
511 |
+
@{
|
512 |
+
|
513 |
+
ViewBag.Title = "Index";
|
514 |
+
|
515 |
+
}
|
516 |
+
|
517 |
+
|
518 |
+
<h2>Index</h2>
|
519 |
+
|
520 |
+
<p>Hello from our View Template!</p>
|
521 |
+
|
522 |
+
In solution explorer, right click the Index.cshtml file and selectView in Page Inspector.
|
523 |
+
|
524 |
+
ThePage Inspector tutorial has more information about this new tool.
|
525 |
+
|
526 |
+
|
527 |
+
|
528 |
+
|
529 |
+
Alternatively, run the application and browse to the HelloWorld controller (http://localhost:xxxx/HelloWorld).
|
530 |
+
|
531 |
+
The Index method in your controller didn't do much work; it simply ran the statement return View(), which
|
532 |
+
|
533 |
+
specified that the method should use a view template file to render a response to the browser. Because you
|
534 |
+
|
535 |
+
didn't explicitly specify the name of the view template file to use, ASP.NET MVC defaulted to using the
|
536 |
+
|
537 |
+
Index.cshtml view file in the \Views\HelloWorld folder. The image below shows the string hard-coded in the
|
538 |
+
|
539 |
+
view.
|
540 |
+
|
541 |
+
Looks pretty good. However, notice that the browser's title bar shows "Index My ASP.NET A" and the big link on
|
542 |
+
|
543 |
+
the top of the page says "your logo here." Below the "your logo here." link are registration and log in links, and
|
544 |
+
|
545 |
+
below that links to Home, About and Contact pages. Let's change some of these.
|
546 |
+
|
547 |
+
Changing Views and Layout Pages
|
548 |
+
|
549 |
+
First, you want to change the "your logo here." title at the top of the page. That text is common to every page.
|
550 |
+
|
551 |
+
It's actually implemented in only one place in the project, even though it appears on every page in the
|
552 |
+
|
553 |
+
application. Go to the /Views/Shared folder in Solution Explorer and open the _Layout.cshtml file. This file is
|
554 |
+
|
555 |
+
called a layout page and it's the shared "shell" that all other pages use.
|
556 |
+
|
557 |
+
|
558 |
+
|
559 |
+
Layout templates allow you to specify the HTML container layout of your site in one place and then apply it
|
560 |
+
|
561 |
+
across multiple pages in your site. Find the@RenderBody() line. RenderBody is a placeholder where all the
|
562 |
+
|
563 |
+
view-specific pages you create show up, "wrapped" in the layout page. For example, if you select the About link,
|
564 |
+
|
565 |
+
the Views\Home\About.cshtml view is rendered inside the RenderBody method.
|
566 |
+
|
567 |
+
Change the site-title heading in the layout template from "your logo here" to "MVC Movie".
|
568 |
+
|
569 |
+
<divclass="float-left">
|
570 |
+
|
571 |
+
<pclass="site-title">@Html.ActionLink("MVC Movie", "Index", "Home")</p>
|
572 |
+
|
573 |
+
</div>
|
574 |
+
|
575 |
+
Replace the contents of the title element with the following markup:
|
576 |
+
|
577 |
+
<title>@ViewBag.Title - Movie App</title>
|
578 |
+
|
579 |
+
The ViewBag is a zzz (dict object) Run the application and notice that it now says "MVC Movie ". Click theAbout
|
580 |
+
|
581 |
+
link, and you see how that page shows "MVC Movie", too. We were able to make the change once in the layout
|
582 |
+
|
583 |
+
template and have all pages on the site reflect the new title.
|
584 |
+
|
585 |
+
The complete _Layout.cshtml file is shown below:
|
586 |
+
|
587 |
+
<!DOCTYPE html>
|
588 |
+
|
589 |
+
<htmllang="en">
|
590 |
+
|
591 |
+
<head>
|
592 |
+
|
593 |
+
<metacharset="utf-8"/>
|
594 |
+
|
595 |
+
<title>@ViewBag.Title - Movie App</title>
|
596 |
+
|
597 |
+
<linkhref="~/favicon.ico"rel="shortcut icon"type="image/x-icon"/>
|
598 |
+
|
599 |
+
<linkhref="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/c
|
600 |
+
|
601 |
+
ss")"rel="stylesheet"type="text/css"/>
|
602 |
+
|
603 |
+
<linkhref="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/t
|
604 |
+
|
605 |
+
hemes/base/css")"rel="stylesheet"type="text/css"/>
|
606 |
+
|
607 |
+
<scriptsrc="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/
|
608 |
+
|
609 |
+
js")"></script>
|
610 |
+
|
611 |
+
<metaname="viewport"content="width=device-width"/>
|
612 |
+
|
613 |
+
</head>
|
614 |
+
|
615 |
+
|
616 |
+
<body>
|
617 |
+
|
618 |
+
<header>
|
619 |
+
|
620 |
+
<divclass="content-wrapper">
|
621 |
+
|
622 |
+
<divclass="float-left">
|
623 |
+
|
624 |
+
<pclass="site-title">@Html.ActionLink("MVC Movie", "Index", "Home")</p>
|
625 |
+
|
626 |
+
</div>
|
627 |
+
|
628 |
+
<divclass="float-right">
|
629 |
+
|
630 |
+
<sectionid="login">
|
631 |
+
|
632 |
+
@Html.Partial("_LoginPartial")
|
633 |
+
|
634 |
+
</section>
|
635 |
+
|
636 |
+
<nav>
|
637 |
+
|
638 |
+
<ulid="menu">
|
639 |
+
|
640 |
+
<li>@Html.ActionLink("Home", "Index", "Home")</li>
|
641 |
+
|
642 |
+
<li>@Html.ActionLink("About", "About", "Home")</li>
|
643 |
+
|
644 |
+
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
|
645 |
+
|
646 |
+
</ul>
|
647 |
+
|
648 |
+
</nav>
|
649 |
+
|
650 |
+
</div>
|
651 |
+
|
652 |
+
</div>
|
653 |
+
|
654 |
+
</header>
|
655 |
+
|
656 |
+
<divid="body">
|
657 |
+
|
658 |
+
@RenderSection("featured", required: false)
|
659 |
+
|
660 |
+
<sectionclass="content-wrapper main-content clear-fix">
|
661 |
+
|
662 |
+
@RenderBody()
|
663 |
+
|
664 |
+
</section>
|
665 |
+
|
666 |
+
</div>
|
667 |
+
|
668 |
+
<footer>
|
669 |
+
|
670 |
+
<divclass="content-wrapper">
|
671 |
+
|
672 |
+
<divclass="float-left">
|
673 |
+
|
674 |
+
<p>© @DateTime.Now.Year - My ASP.NET MVC Application</p>
|
675 |
+
|
676 |
+
</div>
|
677 |
+
|
678 |
+
<divclass="float-right">
|
679 |
+
|
680 |
+
<ulid="social">
|
681 |
+
|
682 |
+
<li><ahref="http://facebook.com"class="facebook">Facebook</a></li>
|
683 |
+
|
684 |
+
<li><ahref="http://twitter.com"class="twitter">Twitter</a></li>
|
685 |
+
|
686 |
+
</ul>
|
687 |
+
|
688 |
+
</div>
|
689 |
+
|
690 |
+
</div>
|
691 |
+
|
692 |
+
</footer>
|
693 |
+
|
694 |
+
</body>
|
695 |
+
|
696 |
+
</html>
|
697 |
+
|
698 |
+
Now, let's change the title of the Index view.
|
699 |
+
|
700 |
+
Open MvcMovie\Views\HelloWorld\Index.cshtml. There are two places to make a change: first, the text that
|
701 |
+
|
702 |
+
appears in the title of the browser, and then in the secondary header (the <h2> element). You'll make them
|
703 |
+
|
704 |
+
slightly different so you can see which bit of code changes which part of the app.
|
705 |
+
|
706 |
+
@{
|
707 |
+
|
708 |
+
ViewBag.Title = "Movie List";
|
709 |
+
|
710 |
+
}
|
711 |
+
|
712 |
+
<h2>My Movie List</h2>
|
713 |
+
|
714 |
+
<p>Hello from our View Template!</p>
|
715 |
+
|
716 |
+
To indicate the HTML title to display, the code above sets a Title property of the ViewBag object (which is in
|
717 |
+
|
718 |
+
the Index.cshtml view template). If you look back at the source code of the layout template, you’ll notice that
|
719 |
+
|
720 |
+
the template uses this value in the <title> element as part of the <head> section of the HTML that we
|
721 |
+
|
722 |
+
modified previously. Using this ViewBag approach, you can easily pass other parameters between your view
|
723 |
+
|
724 |
+
template and your layout file.
|
725 |
+
|
726 |
+
Run the application and browse to http://localhost:xx/HelloWorld. Notice that the browser title, the primary
|
727 |
+
|
728 |
+
heading, and the secondary headings have changed. (If you don't see changes in the browser, you might be
|
729 |
+
|
730 |
+
viewing cached content. Press Ctrl+F5 in your browser to force the response from the server to be loaded.) The
|
731 |
+
|
732 |
+
browser title is created with the ViewBag.Title we set in the Index.cshtml view template and the additional "-
|
733 |
+
|
734 |
+
Movie App" added in the layout file.
|
735 |
+
|
736 |
+
Also notice how the content in the Index.cshtml view template was merged with the _Layout.cshtml view
|
737 |
+
|
738 |
+
template and a single HTML response was sent to the browser. Layout templates make it really easy to make
|
739 |
+
|
740 |
+
changes that apply across all of the pages in your application.
|
741 |
+
|
742 |
+
|
743 |
+
|
744 |
+
Our little bit of "data" (in this case the "Hello from our View Template!" message) is hard-coded, though. The
|
745 |
+
|
746 |
+
MVC application has a "V" (view) and you've got a "C" (controller), but no "M" (model) yet. Shortly, we'll walk
|
747 |
+
|
748 |
+
through how create a database and retrieve model data from it.
|
749 |
+
|
750 |
+
Passing Data from the Controller to the View
|
751 |
+
|
752 |
+
Before we go to a database and talk about models, though, let's first talk about passing information from the
|
753 |
+
|
754 |
+
controller to a view. Controller classes are invoked in response to an incoming URL request. A controller class is
|
755 |
+
|
756 |
+
where you write the code that handles the incoming browser requests, retrieves data from a database, and
|
757 |
+
|
758 |
+
ultimately decides what type of response to send back to the browser. View templates can then be used from a
|
759 |
+
|
760 |
+
controller to generate and format an HTML response to the browser.
|
761 |
+
|
762 |
+
Controllers are responsible for providing whatever data or objects are required in order for a view template to
|
763 |
+
|
764 |
+
render a response to the browser. A best practice: A view template should never perform business logic or
|
765 |
+
|
766 |
+
interact with a database directly. Instead, a view template should work only with the data that's provided to it
|
767 |
+
|
768 |
+
by the controller. Maintaining this "separation of concerns" helps keep your code clean, testable and more
|
769 |
+
|
770 |
+
maintainable.
|
771 |
+
|
772 |
+
|
773 |
+
Currently, the Welcome action method in the HelloWorldController class takes a name and a numTimes
|
774 |
+
|
775 |
+
parameter and then outputs the values directly to the browser. Rather than have the controller render this
|
776 |
+
|
777 |
+
response as a string, let’s change the controller to use a view template instead. The view template will generate
|
778 |
+
|
779 |
+
a dynamic response, which means that you need to pass appropriate bits of data from the controller to the view
|
780 |
+
|
781 |
+
in order to generate the response. You can do this by having the controller put the dynamic data (parameters)
|
782 |
+
|
783 |
+
that the view template needs in a ViewBag object that the view template can then access.
|
784 |
+
|
785 |
+
Return to the HelloWorldController.cs file and change the Welcome method to add a Message and NumTimes
|
786 |
+
|
787 |
+
value to the ViewBag object. ViewBag is a dynamic object, which means you can put whatever you want in to
|
788 |
+
|
789 |
+
it; the ViewBag object has no defined properties until you put something inside it. TheASP.NET MVC model
|
790 |
+
|
791 |
+
binding system automatically maps the named parameters (nameand numTimes) from the query string in the
|
792 |
+
|
793 |
+
address bar to parameters in your method. The completeHelloWorldController.cs file looks like this:
|
794 |
+
|
795 |
+
usingSystem.Web;
|
796 |
+
|
797 |
+
usingSystem.Web.Mvc;
|
798 |
+
|
799 |
+
namespaceMvcMovie.Controllers
|
800 |
+
|
801 |
+
{
|
802 |
+
|
803 |
+
publicclassHelloWorldController:Controller
|
804 |
+
|
805 |
+
{
|
806 |
+
|
807 |
+
publicActionResultIndex()
|
808 |
+
|
809 |
+
{
|
810 |
+
|
811 |
+
returnView();
|
812 |
+
|
813 |
+
}
|
814 |
+
|
815 |
+
publicActionResultWelcome(string name,int numTimes =1)
|
816 |
+
|
817 |
+
{
|
818 |
+
|
819 |
+
ViewBag.Message="Hello "+ name;
|
820 |
+
|
821 |
+
ViewBag.NumTimes= numTimes;
|
822 |
+
|
823 |
+
returnView();
|
824 |
+
|
825 |
+
}
|
826 |
+
|
827 |
+
}
|
828 |
+
|
829 |
+
}
|
830 |
+
|
831 |
+
Now the ViewBag object contains data that will be passed to the view automatically.
|
832 |
+
|
833 |
+
|
834 |
+
|
835 |
+
|
836 |
+
Next, you need a Welcome view template! In the Build menu, select Build MvcMovie to make sure the project
|
837 |
+
|
838 |
+
is compiled.
|
839 |
+
|
840 |
+
Then right-click inside the Welcome method and click Add View.
|
841 |
+
|
842 |
+
|
843 |
+
|
844 |
+
Here's what the Add View dialog box looks like:
|
845 |
+
|
846 |
+
Click Add, and then add the following code under the < h2> element in the new Welcome.cshtml file. You'll
|
847 |
+
|
848 |
+
create a loop that says "Hello" as many times as the user says it should. The completeWelcome.cshtml file is
|
849 |
+
|
850 |
+
shown below.
|
851 |
+
|
852 |
+
@{
|
853 |
+
|
854 |
+
ViewBag.Title = "Welcome";
|
855 |
+
|
856 |
+
}
|
857 |
+
|
858 |
+
<h2>Welcome</h2>
|
859 |
+
|
860 |
+
<ul>
|
861 |
+
|
862 |
+
|
863 |
+
|
864 |
+
|
865 |
+
@for (int i=0; i < ViewBag.NumTimes; i++) {
|
866 |
+
|
867 |
+
<li>@ViewBag.Message</li>
|
868 |
+
|
869 |
+
}
|
870 |
+
|
871 |
+
</ul>
|
872 |
+
|
873 |
+
Run the application and browse to the following URL:
|
874 |
+
|
875 |
+
http://localhost:xx/HelloWorld/Welcome?name=Scott&numtimes=4
|
876 |
+
|
877 |
+
Now data is taken from the URL and passed to the controller using themodel binder. The controller packages
|
878 |
+
|
879 |
+
the data into a ViewBag object and passes that object to the view. The view then displays the data as HTML to
|
880 |
+
|
881 |
+
the user.
|
882 |
+
|
883 |
+
Well, that was a kind of an "M" for model, but not the database kind. Let's take what we've learned and create a
|
884 |
+
|
885 |
+
database of movies.
|
886 |
+
|
887 |
+
|
888 |
+
|
889 |
+
|
890 |
+
Adding a Model
|
891 |
+
|
892 |
+
In this section you'll add some classes for managing movies in a database. These classes will be the "model"
|
893 |
+
|
894 |
+
part of the ASP.NET MVC application.
|
895 |
+
|
896 |
+
You’ll use a .NET Framework data-access technology known as the Entity Framework to define and work with
|
897 |
+
|
898 |
+
these model classes. The Entity Framework (often referred to as EF) supports a development paradigm called
|
899 |
+
|
900 |
+
Code First. Code First allows you to create model objects by writing simple classes. (These are also known as
|
901 |
+
|
902 |
+
POCO classes, from "plain-old CLR objects.") You can then have the database created on the fly from your
|
903 |
+
|
904 |
+
classes, which enables a very clean and rapid development workflow.
|
905 |
+
|
906 |
+
Adding Model Classes
|
907 |
+
|
908 |
+
In Solution Explorer, right click the Models folder, select Add, and then select New Item.
|
909 |
+
|
910 |
+
|
911 |
+
In the Add New Item dialog, select Class then name the class "Movie".
|
912 |
+
|
913 |
+
|
914 |
+
Add the following five properties to the Movie class:
|
915 |
+
|
916 |
+
publicclassMovie
|
917 |
+
|
918 |
+
{
|
919 |
+
|
920 |
+
publicint ID {get;set;}
|
921 |
+
|
922 |
+
publicstringTitle{get;set;}
|
923 |
+
|
924 |
+
publicDateTimeReleaseDate{get;set;}
|
925 |
+
|
926 |
+
publicstringGenre{get;set;}
|
927 |
+
|
928 |
+
publicdecimalPrice{get;set;}
|
929 |
+
|
930 |
+
|
931 |
+
}
|
932 |
+
|
933 |
+
We'll use the Movie class to represent movies in a database. Each instance of a Movie object will correspond to
|
934 |
+
|
935 |
+
a row within a database table, and each property of the Movie class will map to a column in the table.
|
936 |
+
|
937 |
+
In the same file, add the following MovieDBContext class:
|
938 |
+
|
939 |
+
publicclassMovieDBContext:DbContext
|
940 |
+
|
941 |
+
{
|
942 |
+
|
943 |
+
publicDbSet<Movie>Movies{get;set;}
|
944 |
+
|
945 |
+
}
|
946 |
+
|
947 |
+
The MovieDBContext class represents the Entity Framework movie database context, which handles fetching,
|
948 |
+
|
949 |
+
storing, and updating Movie class instances in a database. The MovieDBContext derives from theDbContext
|
950 |
+
|
951 |
+
base class provided by the Entity Framework. For more information about DbContext and DbSet,
|
952 |
+
|
953 |
+
seeProductivity Improvements for the Entity Framework.
|
954 |
+
|
955 |
+
In order to be able to reference DbContext and DbSet, you need to add the following using statement at the
|
956 |
+
|
957 |
+
top of the file:
|
958 |
+
|
959 |
+
usingSystem.Data.Entity;
|
960 |
+
|
961 |
+
The complete Movie.cs file is shown below. (Several using statements that are not needed have been removed.)
|
962 |
+
|
963 |
+
usingSystem;
|
964 |
+
|
965 |
+
usingSystem.Data.Entity;
|
966 |
+
|
967 |
+
namespaceMvcMovie.Models
|
968 |
+
|
969 |
+
{
|
970 |
+
|
971 |
+
publicclassMovie
|
972 |
+
|
973 |
+
{
|
974 |
+
|
975 |
+
publicint ID {get;set;}
|
976 |
+
|
977 |
+
publicstringTitle{get;set;}
|
978 |
+
|
979 |
+
publicDateTimeReleaseDate{get;set;}
|
980 |
+
|
981 |
+
publicstringGenre{get;set;}
|
982 |
+
|
983 |
+
publicdecimalPrice{get;set;}
|
984 |
+
|
985 |
+
|
986 |
+
}
|
987 |
+
|
988 |
+
publicclassMovieDBContext:DbContext
|
989 |
+
|
990 |
+
{
|
991 |
+
|
992 |
+
publicDbSet<Movie>Movies{get;set;}
|
993 |
+
|
994 |
+
}
|
995 |
+
|
996 |
+
}
|
997 |
+
|
998 |
+
Creating a Connection String and Working with SQL Server LocalDB
|
999 |
+
|
1000 |
+
The MovieDBContext class you created handles the task of connecting to the database and mapping Movie
|
1001 |
+
|
1002 |
+
objects to database records. One question you might ask, though, is how to specify which database it will
|
1003 |
+
|
1004 |
+
connect to. You'll do that by adding connection information in the Web.config file of the application.
|
1005 |
+
|
1006 |
+
Open the application root Web.config file. (Not the Web.configfile in the Views folder.) Open the Web.config file
|
1007 |
+
|
1008 |
+
outlined in red.
|
1009 |
+
|
1010 |
+
Add the following connection string to the <connectionStrings> element in the Web.config file.
|
1011 |
+
|
1012 |
+
<addname="MovieDBContext"
|
1013 |
+
|
1014 |
+
|
1015 |
+
|
1016 |
+
connectionString="Data
|
1017 |
+
|
1018 |
+
Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated
|
1019 |
+
|
1020 |
+
Security=True"
|
1021 |
+
|
1022 |
+
providerName="System.Data.SqlClient"
|
1023 |
+
|
1024 |
+
/>
|
1025 |
+
|
1026 |
+
The following example shows a portion of the Web.config file with the new connection string added:
|
1027 |
+
|
1028 |
+
<connectionStrings>
|
1029 |
+
|
1030 |
+
<addname="DefaultConnection"
|
1031 |
+
|
1032 |
+
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcMovie-
|
1033 |
+
|
1034 |
+
2012213181139;Integrated Security=true"
|
1035 |
+
|
1036 |
+
providerName="System.Data.SqlClient"
|
1037 |
+
|
1038 |
+
/>
|
1039 |
+
|
1040 |
+
<addname="MovieDBContext"
|
1041 |
+
|
1042 |
+
connectionString="Data
|
1043 |
+
|
1044 |
+
Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated
|
1045 |
+
|
1046 |
+
Security=True"
|
1047 |
+
|
1048 |
+
providerName="System.Data.SqlClient"
|
1049 |
+
|
1050 |
+
/>
|
1051 |
+
|
1052 |
+
</connectionStrings>
|
1053 |
+
|
1054 |
+
This small amount of code and XML is everything you need to write in order to represent and store the movie
|
1055 |
+
|
1056 |
+
data in a database.
|
1057 |
+
|
1058 |
+
Next, you'll build a new MoviesController class that you can use to display the movie data and allow users
|
1059 |
+
|
1060 |
+
to create new movie listings.
|
1061 |
+
|
1062 |
+
|
1063 |
+
|
1064 |
+
Accessing Your Model's Data from a Controller
|
1065 |
+
|
1066 |
+
In this section, you'll create a new MoviesController class and write code that retrieves the movie data and
|
1067 |
+
|
1068 |
+
displays it in the browser using a view template.
|
1069 |
+
|
1070 |
+
Build the application before going on to the next step.
|
1071 |
+
|
1072 |
+
Right-click the Controllers folder and create a new MoviesController controller. The options below will not
|
1073 |
+
|
1074 |
+
appear until you build your application. Select the following options:
|
1075 |
+
|
1076 |
+
• Controller name: MoviesController. (This is the default. )
|
1077 |
+
|
1078 |
+
•
|
1079 |
+
|
1080 |
+
Template: Controller with read/write actions and views, using Entity Framework.
|
1081 |
+
|
1082 |
+
• Model class: Movie (MvcMovie.Models).
|
1083 |
+
|
1084 |
+
• Data context class: MovieDBContext (MvcMovie.Models).
|
1085 |
+
|
1086 |
+
• Views: Razor (CSHTML). (The default.)
|
1087 |
+
|
1088 |
+
Click Add. Visual Studio Express creates the following files and folders:
|
1089 |
+
|
1090 |
+
• A MoviesController.csfile in the project's Controllers folder.
|
1091 |
+
|
1092 |
+
|
1093 |
+
• A Movies folder in the project's Views folder.
|
1094 |
+
|
1095 |
+
• Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Movies folder.
|
1096 |
+
|
1097 |
+
|
1098 |
+
ASP.NET MVC 4 automatically created the CRUD (create, read, update, and delete) action methods and views
|
1099 |
+
|
1100 |
+
for you (the automatic creation of CRUD action methods and views is known as scaffolding). You now have a
|
1101 |
+
|
1102 |
+
fully functional web application that lets you create, list, edit, and delete movie entries.
|
1103 |
+
|
1104 |
+
Run the application and browse to the Movies controller by appending /Movies to the URL in the address bar
|
1105 |
+
|
1106 |
+
of your browser. Because the application is relying on the default routing (defined in the Global.asax file), the
|
1107 |
+
|
1108 |
+
browser request http://localhost:xxxxx/Movies is routed to the default Index action method of the Movies
|
1109 |
+
|
1110 |
+
controller. In other words, the browser request http://localhost:xxxxx/Movies is effectively the same as the
|
1111 |
+
|
1112 |
+
browser request http://localhost:xxxxx/Movies/Index. The result is an empty list of movies, because you haven't
|
1113 |
+
|
1114 |
+
added any yet.
|
1115 |
+
|
1116 |
+
Creating a Movie
|
1117 |
+
|
1118 |
+
Select the Create New link. Enter some details about a movie and then click the Create button.
|
1119 |
+
|
1120 |
+
|
1121 |
+
Clicking the Create button causes the form to be posted to the server, where the movie information is saved in
|
1122 |
+
|
1123 |
+
the database. You're then redirected to the /Movies URL, where you can see the newly created movie in the
|
1124 |
+
|
1125 |
+
listing.
|
1126 |
+
|
1127 |
+
|
1128 |
+
Create a couple more movie entries. Try the Edit, Details, and Delete links, which are all functional.
|
1129 |
+
|
1130 |
+
Examining the Generated Code
|
1131 |
+
|
1132 |
+
Open the Controllers\MoviesController.cs file and examine the generated Index method. A portion of the movie
|
1133 |
+
|
1134 |
+
controller with theIndex method is shown below.
|
1135 |
+
|
1136 |
+
publicclassMoviesController:Controller
|
1137 |
+
|
1138 |
+
{
|
1139 |
+
|
1140 |
+
privateMovieDBContext db =newMovieDBContext();
|
1141 |
+
|
1142 |
+
//
|
1143 |
+
|
1144 |
+
// GET: /Movies/
|
1145 |
+
|
1146 |
+
publicActionResultIndex()
|
1147 |
+
|
1148 |
+
{
|
1149 |
+
|
1150 |
+
returnView(db.Movies.ToList());
|
1151 |
+
|
1152 |
+
|
1153 |
+
|
1154 |
+
|
1155 |
+
}
|
1156 |
+
|
1157 |
+
The following line from the MoviesController class instantiates a movie database context, as described
|
1158 |
+
|
1159 |
+
previously. You can use the movie database context to query, edit, and delete movies.
|
1160 |
+
|
1161 |
+
privateMovieDBContext db =newMovieDBContext();
|
1162 |
+
|
1163 |
+
A request to the Movies controller returns all the entries in the Movies table of the movie database and then
|
1164 |
+
|
1165 |
+
passes the results to the Index view.
|
1166 |
+
|
1167 |
+
Strongly Typed Models and the @model Keyword
|
1168 |
+
|
1169 |
+
Earlier in this tutorial, you saw how a controller can pass data or objects to a view template using the ViewBag
|
1170 |
+
|
1171 |
+
object. The ViewBag is a dynamic object that provides a convenient late-bound way to pass information to a
|
1172 |
+
|
1173 |
+
view.
|
1174 |
+
|
1175 |
+
ASP.NET MVC also provides the ability to pass strongly typed data or objects to a view template. This strongly
|
1176 |
+
|
1177 |
+
typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Studio
|
1178 |
+
|
1179 |
+
Express editor. The scaffolding mechanism in Visual Studio Express used this approach with the
|
1180 |
+
|
1181 |
+
MoviesController class and view templates when it created the methods and views.
|
1182 |
+
|
1183 |
+
In the Controllers\MoviesController.cs file examine the generated Details method. A portion of the movie
|
1184 |
+
|
1185 |
+
controller with theDetails method is shown below.
|
1186 |
+
|
1187 |
+
publicActionResultDetails(int id =0)
|
1188 |
+
|
1189 |
+
{
|
1190 |
+
|
1191 |
+
Movie movie =db.Movies.Find(id);
|
1192 |
+
|
1193 |
+
if(movie ==null)
|
1194 |
+
|
1195 |
+
{
|
1196 |
+
|
1197 |
+
returnHttpNotFound();
|
1198 |
+
|
1199 |
+
}
|
1200 |
+
|
1201 |
+
returnView(movie);
|
1202 |
+
|
1203 |
+
}
|
1204 |
+
|
1205 |
+
An instance of the Movie model is passed to the Details view.
|
1206 |
+
|
1207 |
+
By including a @model statement at the top of the view template file, you can specify the type of object that the
|
1208 |
+
|
1209 |
+
view expects. When you created the movie controller, Visual Studio Express automatically included the
|
1210 |
+
|
1211 |
+
following@model statement at the top of the Details.cshtml file:
|
1212 |
+
|
1213 |
+
@model MvcMovie.Models.Movie
|
1214 |
+
|
1215 |
+
This @model directive allows you to access the movie that the controller passed to the view by using a Model
|
1216 |
+
|
1217 |
+
object that's strongly typed. For example, in the Details.cshtml template, the code passes each movie field to
|
1218 |
+
|
1219 |
+
the DisplayNameFor and DisplayFor HTML Helpers with the strongly typed Model object. The Create and Edit
|
1220 |
+
|
1221 |
+
methods and view templates also pass a movie model object.
|
1222 |
+
|
1223 |
+
Examine the Index.cshtml view template and the Index method in the MoviesController.cs file. Notice how the
|
1224 |
+
|
1225 |
+
code creates aList object when it calls the View helper method in the Index action method. The code then
|
1226 |
+
|
1227 |
+
passes this Movies list from the controller to the view:
|
1228 |
+
|
1229 |
+
publicActionResultIndex()
|
1230 |
+
|
1231 |
+
{
|
1232 |
+
|
1233 |
+
returnView(db.Movies.ToList());
|
1234 |
+
|
1235 |
+
}
|
1236 |
+
|
1237 |
+
When you created the movie controller, Visual Studio Express automatically included the following@model
|
1238 |
+
|
1239 |
+
statement at the top of the Index.cshtml file:
|
1240 |
+
|
1241 |
+
@model IEnumerable<MvcMovie.Models.Movie>
|
1242 |
+
|
1243 |
+
This @model directive allows you to access the list of movies that the controller passed to the view by using a
|
1244 |
+
|
1245 |
+
Model object that's strongly typed. For example, in the Index.cshtml template, the code loops through the
|
1246 |
+
|
1247 |
+
movies by doing a foreach statement over the strongly typed Model object:
|
1248 |
+
|
1249 |
+
@foreach (var item in Model) {
|
1250 |
+
|
1251 |
+
<tr>
|
1252 |
+
|
1253 |
+
<td>
|
1254 |
+
|
1255 |
+
@Html.DisplayFor(modelItem => item.Title)
|
1256 |
+
|
1257 |
+
</td>
|
1258 |
+
|
1259 |
+
<td>
|
1260 |
+
|
1261 |
+
@Html.DisplayFor(modelItem => item.ReleaseDate)
|
1262 |
+
|
1263 |
+
</td>
|
1264 |
+
|
1265 |
+
<td>
|
1266 |
+
|
1267 |
+
@Html.DisplayFor(modelItem => item.Genre)
|
1268 |
+
|
1269 |
+
</td>
|
1270 |
+
|
1271 |
+
<td>
|
1272 |
+
|
1273 |
+
@Html.DisplayFor(modelItem => item.Price)
|
1274 |
+
|
1275 |
+
</td>
|
1276 |
+
|
1277 |
+
<th>
|
1278 |
+
|
1279 |
+
@Html.DisplayFor(modelItem => item.Rating)
|
1280 |
+
|
1281 |
+
</th>
|
1282 |
+
|
1283 |
+
<td>
|
1284 |
+
|
1285 |
+
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
|
1286 |
+
|
1287 |
+
@Html.ActionLink("Details", "Details", { id=item.ID }) |
|
1288 |
+
|
1289 |
+
@Html.ActionLink("Delete", "Delete", { id=item.ID })
|
1290 |
+
|
1291 |
+
</td>
|
1292 |
+
|
1293 |
+
</tr>
|
1294 |
+
|
1295 |
+
}
|
1296 |
+
|
1297 |
+
Because the Model object is strongly typed (as an IEnumerable<Movie> object), each item object in the loop
|
1298 |
+
|
1299 |
+
is typed as Movie. Among other benefits, this means that you get compile-time checking of the code and full
|
1300 |
+
|
1301 |
+
IntelliSense support in the code editor:
|
1302 |
+
|
1303 |
+
|
1304 |
+
Working with SQL Server LocalDB
|
1305 |
+
|
1306 |
+
Entity Framework Code First detected that the database connection string that was provided pointed to a
|
1307 |
+
|
1308 |
+
Movies database that didn’t exist yet, so Code First created the database automatically. You can verify that it's
|
1309 |
+
|
1310 |
+
been created by looking in the App_Data folder. If you don't see the Movies.sdf file, click the Show All Files
|
1311 |
+
|
1312 |
+
button in theSolution Explorer toolbar, click the Refresh button, and then expand the App_Data folder.
|
1313 |
+
|
1314 |
+
|
1315 |
+
Double-click Movies.mdf to open DATABASE EXPLORER. Then expand the Tables folder to see the tables that
|
1316 |
+
|
1317 |
+
have been created in the database.
|
1318 |
+
|
1319 |
+
|
1320 |
+
|
1321 |
+
There are two tables, one for the Movie entity set and theEdmMetadata table. The EdmMetadata table is used
|
1322 |
+
|
1323 |
+
by the Entity Framework to determine when the model and the database are out of sync.
|
1324 |
+
|
1325 |
+
Right-click the Movies table and select Show Table Data to see the data you created.
|
1326 |
+
|
1327 |
+
Right-click the Movies table and select Open Table Definition to see the table structure that Entity Framework
|
1328 |
+
|
1329 |
+
Code First created for you.
|
1330 |
+
|
1331 |
+
|
1332 |
+
|
1333 |
+
Notice how the schema of the Movies table maps to the Movie class you created earlier. Entity Framework
|
1334 |
+
|
1335 |
+
Code First automatically created this schema for you based on your Movie class.
|
1336 |
+
|
1337 |
+
When you're finished, close the connection by right clicking Movies.mdf and selecting Close Connection. (If you
|
1338 |
+
|
1339 |
+
don't close the connection, you might get an error the next time you run the project).
|
1340 |
+
|
1341 |
+
|
1342 |
+
You now have the database and a simple listing page to display content from it. In the next tutorial, we'll
|
1343 |
+
|
1344 |
+
examine the rest of the scaffolded code and add a SearchIndex method and a SearchIndex view that lets
|
1345 |
+
|
1346 |
+
you search for movies in this database.
|
1347 |
+
|
1348 |
+
|
1349 |
+
|
1350 |
+
|
1351 |
+
Examining the Edit Methods and Edit View
|
1352 |
+
|
1353 |
+
In this section, you'll examine the generated action methods and views for the movie controller. Then you'll add
|
1354 |
+
|
1355 |
+
a custom search page.
|
1356 |
+
|
1357 |
+
Run the application and browse to the Movies controller by appending /Movies to the URL in the address bar
|
1358 |
+
|
1359 |
+
of your browser. Hold the mouse pointer over an Edit link to see the URL that it links to.
|
1360 |
+
|
1361 |
+
The Edit link was generated by the Html.ActionLink method in the Views\Movies\Index.cshtml view:
|
1362 |
+
|
1363 |
+
@Html.ActionLink("Edit", "Edit", new { id=item.ID })
|
1364 |
+
|
1365 |
+
|
1366 |
+
The Html object is a helper that's exposed using a property on the System.Web.Mvc.WebViewPage base class.
|
1367 |
+
|
1368 |
+
The ActionLinkmethod of the helper makes it easy to dynamically generate HTML hyperlinks that link to
|
1369 |
+
|
1370 |
+
action methods on controllers. The first argument to the ActionLink method is the link text to render (for
|
1371 |
+
|
1372 |
+
example,<a>Edit Me</a>). The second argument is the name of the action method to invoke. The final
|
1373 |
+
|
1374 |
+
argument is ananonymous object that generates the route data (in this case, the ID of 4).
|
1375 |
+
|
1376 |
+
The generated link shown in the previous image is http://localhost:xxxxx/Movies/Edit/4. The default route
|
1377 |
+
|
1378 |
+
(established in Global.asax.cs) takes the URL pattern {controller}/{action}/{id}. Therefore, ASP.NET
|
1379 |
+
|
1380 |
+
translateshttp://localhost:xxxxx/Movies/Edit/4 into a request to the Edit action method of the Movies
|
1381 |
+
|
1382 |
+
controller with the parameter ID equal to 4.
|
1383 |
+
|
1384 |
+
You can also pass action method parameters using a query string. For example, the URL
|
1385 |
+
|
1386 |
+
http://localhost:xxxxx/Movies/Edit?ID=4 also passes the parameter ID of 4 to the Edit action method of
|
1387 |
+
|
1388 |
+
theMovies controller.
|
1389 |
+
|
1390 |
+
|
1391 |
+
Open the Movies controller. The two Edit action methods are shown below.
|
1392 |
+
|
1393 |
+
//
|
1394 |
+
|
1395 |
+
// GET: /Movies/Edit/5
|
1396 |
+
|
1397 |
+
publicActionResultEdit(int id =0)
|
1398 |
+
|
1399 |
+
{
|
1400 |
+
|
1401 |
+
Movie movie =db.Movies.Find(id);
|
1402 |
+
|
1403 |
+
if(movie ==null)
|
1404 |
+
|
1405 |
+
{
|
1406 |
+
|
1407 |
+
returnHttpNotFound();
|
1408 |
+
|
1409 |
+
}
|
1410 |
+
|
1411 |
+
|
1412 |
+
|
1413 |
+
returnView(movie);
|
1414 |
+
|
1415 |
+
}
|
1416 |
+
|
1417 |
+
//
|
1418 |
+
|
1419 |
+
// POST: /Movies/Edit/5
|
1420 |
+
|
1421 |
+
[HttpPost]
|
1422 |
+
|
1423 |
+
publicActionResultEdit(Movie movie)
|
1424 |
+
|
1425 |
+
{
|
1426 |
+
|
1427 |
+
if(ModelState.IsValid)
|
1428 |
+
|
1429 |
+
{
|
1430 |
+
|
1431 |
+
db.Entry(movie).State=EntityState.Modified;
|
1432 |
+
|
1433 |
+
db.SaveChanges();
|
1434 |
+
|
1435 |
+
returnRedirectToAction("Index");
|
1436 |
+
|
1437 |
+
}
|
1438 |
+
|
1439 |
+
returnView(movie);
|
1440 |
+
|
1441 |
+
}
|
1442 |
+
|
1443 |
+
Notice the second Edit action method is preceded by the HttpPost attribute. This attribute specifies that that
|
1444 |
+
|
1445 |
+
overload of the Edit method can be invoked only for POST requests. You could apply the HttpGet attribute to
|
1446 |
+
|
1447 |
+
the first edit method, but that's not necessary because it's the default. (We'll refer to action methods that are
|
1448 |
+
|
1449 |
+
implicitly assigned the HttpGet attribute as HttpGet methods.)
|
1450 |
+
|
1451 |
+
The HttpGetEdit method takes the movie ID parameter, looks up the movie using the Entity Framework Find
|
1452 |
+
|
1453 |
+
method, and returns the selected movie to the Edit view. The ID parameter specifies a default value of zero if
|
1454 |
+
|
1455 |
+
the Edit method is called without a parameter. If a movie cannot be found, HttpNotFound is returned. When
|
1456 |
+
|
1457 |
+
the scaffolding system created the Edit view, it examined the Movie class and created code to render <label>
|
1458 |
+
|
1459 |
+
and <input> elements for each property of the class. The following example shows the Edit view that was
|
1460 |
+
|
1461 |
+
generated:
|
1462 |
+
|
1463 |
+
@model MvcMovie.Models.Movie
|
1464 |
+
|
1465 |
+
@{
|
1466 |
+
|
1467 |
+
ViewBag.Title = "Edit";
|
1468 |
+
|
1469 |
+
}
|
1470 |
+
|
1471 |
+
<h2>Edit</h2>
|
1472 |
+
|
1473 |
+
|
1474 |
+
|
1475 |
+
|
1476 |
+
|
1477 |
+
<scriptsrc="@Url.Content("~/Scripts/jquery.validate.min.js")"type="text/javascript"><
|
1478 |
+
|
1479 |
+
/script>
|
1480 |
+
|
1481 |
+
<scriptsrc="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/j
|
1482 |
+
|
1483 |
+
avascript"></script>
|
1484 |
+
|
1485 |
+
@using (Html.BeginForm()) {
|
1486 |
+
|
1487 |
+
@Html.ValidationSummary(true)
|
1488 |
+
|
1489 |
+
<fieldset>
|
1490 |
+
|
1491 |
+
<legend>Movie</legend>
|
1492 |
+
|
1493 |
+
@Html.HiddenFor(model => model.ID)
|
1494 |
+
|
1495 |
+
<divclass="editor-label">
|
1496 |
+
|
1497 |
+
@Html.LabelFor(model => model.Title)
|
1498 |
+
|
1499 |
+
</div>
|
1500 |
+
|
1501 |
+
<divclass="editor-field">
|
1502 |
+
|
1503 |
+
@Html.EditorFor(model => model.Title)
|
1504 |
+
|
1505 |
+
@Html.ValidationMessageFor(model => model.Title)
|
1506 |
+
|
1507 |
+
</div>
|
1508 |
+
|
1509 |
+
<divclass="editor-label">
|
1510 |
+
|
1511 |
+
@Html.LabelFor(model => model.ReleaseDate)
|
1512 |
+
|
1513 |
+
</div>
|
1514 |
+
|
1515 |
+
<divclass="editor-field">
|
1516 |
+
|
1517 |
+
@Html.EditorFor(model => model.ReleaseDate)
|
1518 |
+
|
1519 |
+
@Html.ValidationMessageFor(model => model.ReleaseDate)
|
1520 |
+
|
1521 |
+
</div>
|
1522 |
+
|
1523 |
+
<divclass="editor-label">
|
1524 |
+
|
1525 |
+
@Html.LabelFor(model => model.Genre)
|
1526 |
+
|
1527 |
+
</div>
|
1528 |
+
|
1529 |
+
<divclass="editor-field">
|
1530 |
+
|
1531 |
+
@Html.EditorFor(model => model.Genre)
|
1532 |
+
|
1533 |
+
@Html.ValidationMessageFor(model => model.Genre)
|
1534 |
+
|
1535 |
+
</div>
|
1536 |
+
|
1537 |
+
<divclass="editor-label">
|
1538 |
+
|
1539 |
+
|
1540 |
+
|
1541 |
+
|
1542 |
+
|
1543 |
+
|
1544 |
+
|
1545 |
+
|
1546 |
+
@Html.LabelFor(model => model.Price)
|
1547 |
+
|
1548 |
+
</div>
|
1549 |
+
|
1550 |
+
<divclass="editor-field">
|
1551 |
+
|
1552 |
+
@Html.EditorFor(model => model.Price)
|
1553 |
+
|
1554 |
+
@Html.ValidationMessageFor(model => model.Price)
|
1555 |
+
|
1556 |
+
</div>
|
1557 |
+
|
1558 |
+
<p>
|
1559 |
+
|
1560 |
+
<inputtype="submit"value="Save"/>
|
1561 |
+
|
1562 |
+
</p>
|
1563 |
+
|
1564 |
+
</fieldset>
|
1565 |
+
|
1566 |
+
}
|
1567 |
+
|
1568 |
+
<div>
|
1569 |
+
|
1570 |
+
@Html.ActionLink("Back to List", "Index")
|
1571 |
+
|
1572 |
+
</div>
|
1573 |
+
|
1574 |
+
Notice how the view template has a @model MvcMovie.Models.Movie statement at the top of the file — this
|
1575 |
+
|
1576 |
+
specifies that the view expects the model for the view template to be of type Movie.
|
1577 |
+
|
1578 |
+
The scaffolded code uses several helper methods to streamline the HTML markup. TheHtml.LabelFor helper
|
1579 |
+
|
1580 |
+
displays the name of the field ("Title", "ReleaseDate", "Genre", or "Price"). TheHtml.EditorFor helper renders
|
1581 |
+
|
1582 |
+
an HTML <input> element. TheHtml.ValidationMessageFor helper displays any validation messages
|
1583 |
+
|
1584 |
+
associated with that property.
|
1585 |
+
|
1586 |
+
Run the application and navigate to the /Movies URL. Click anEdit link. In the browser, view the source for the
|
1587 |
+
|
1588 |
+
page. The HTML for the form element is shown below.
|
1589 |
+
|
1590 |
+
<formaction="/Movies/Edit/4"method="post"><fieldset>
|
1591 |
+
|
1592 |
+
<legend>Movie</legend>
|
1593 |
+
|
1594 |
+
<inputdata-val="true"data-val-number="The field ID must be a number."data-val-
|
1595 |
+
|
1596 |
+
required="The ID field is required."id="ID"name="ID"type="hidden"value="4"/>
|
1597 |
+
|
1598 |
+
<divclass="editor-label">
|
1599 |
+
|
1600 |
+
<labelfor="Title">Title</label>
|
1601 |
+
|
1602 |
+
</div>
|
1603 |
+
|
1604 |
+
|
1605 |
+
|
1606 |
+
|
1607 |
+
|
1608 |
+
<divclass="editor-field">
|
1609 |
+
|
1610 |
+
<inputclass="text-box single-line"id="Title"name="Title"type="text"value="Rio
|
1611 |
+
|
1612 |
+
Bravo"/>
|
1613 |
+
|
1614 |
+
<spanclass="field-validation-valid"data-valmsg-for="Title"data-valmsg-
|
1615 |
+
|
1616 |
+
replace="true"></span>
|
1617 |
+
|
1618 |
+
</div>
|
1619 |
+
|
1620 |
+
<divclass="editor-label">
|
1621 |
+
|
1622 |
+
<labelfor="ReleaseDate">ReleaseDate</label>
|
1623 |
+
|
1624 |
+
</div>
|
1625 |
+
|
1626 |
+
<divclass="editor-field">
|
1627 |
+
|
1628 |
+
<inputclass="text-box single-line"data-val="true"data-val-date="The field ReleaseDate
|
1629 |
+
|
1630 |
+
must be a date."data-val-required="The ReleaseDate field is
|
1631 |
+
|
1632 |
+
required."id="ReleaseDate"name="ReleaseDate"type="text"value="4/15/1959 12:00:00
|
1633 |
+
|
1634 |
+
AM"/>
|
1635 |
+
|
1636 |
+
<spanclass="field-validation-valid"data-valmsg-for="ReleaseDate"data-valmsg-
|
1637 |
+
|
1638 |
+
replace="true"></span>
|
1639 |
+
|
1640 |
+
</div>
|
1641 |
+
|
1642 |
+
<divclass="editor-label">
|
1643 |
+
|
1644 |
+
<labelfor="Genre">Genre</label>
|
1645 |
+
|
1646 |
+
</div>
|
1647 |
+
|
1648 |
+
<divclass="editor-field">
|
1649 |
+
|
1650 |
+
<inputclass="text-box single-line"id="Genre"name="Genre"type="text"value="Western"/>
|
1651 |
+
|
1652 |
+
<spanclass="field-validation-valid"data-valmsg-for="Genre"data-valmsg-
|
1653 |
+
|
1654 |
+
replace="true"></span>
|
1655 |
+
|
1656 |
+
</div>
|
1657 |
+
|
1658 |
+
<divclass="editor-label">
|
1659 |
+
|
1660 |
+
<labelfor="Price">Price</label>
|
1661 |
+
|
1662 |
+
</div>
|
1663 |
+
|
1664 |
+
<divclass="editor-field">
|
1665 |
+
|
1666 |
+
<inputclass="text-box single-line"data-val="true"data-val-number="The field Price
|
1667 |
+
|
1668 |
+
must be a number."data-val-required="The Price field is
|
1669 |
+
|
1670 |
+
required."id="Price"name="Price"type="text"value="2.99"/>
|
1671 |
+
|
1672 |
+
<spanclass="field-validation-valid"data-valmsg-for="Price"data-valmsg-
|
1673 |
+
|
1674 |
+
replace="true"></span>
|
1675 |
+
|
1676 |
+
</div>
|
1677 |
+
|
1678 |
+
|
1679 |
+
|
1680 |
+
|
1681 |
+
<p>
|
1682 |
+
|
1683 |
+
<inputtype="submit"value="Save"/>
|
1684 |
+
|
1685 |
+
</p>
|
1686 |
+
|
1687 |
+
</fieldset>
|
1688 |
+
|
1689 |
+
</form>
|
1690 |
+
|
1691 |
+
The <input> elements are in an HTML <form> element whose action attribute is set to post to the
|
1692 |
+
|
1693 |
+
/Movies/Edit URL. The form data will be posted to the server when the Edit button is clicked.
|
1694 |
+
|
1695 |
+
Processing the POST Request
|
1696 |
+
|
1697 |
+
The following listing shows the HttpPost version of the Edit action method.
|
1698 |
+
|
1699 |
+
[HttpPost]
|
1700 |
+
|
1701 |
+
publicActionResultEdit(Movie movie)
|
1702 |
+
|
1703 |
+
{
|
1704 |
+
|
1705 |
+
if(ModelState.IsValid)
|
1706 |
+
|
1707 |
+
{
|
1708 |
+
|
1709 |
+
db.Entry(movie).State=EntityState.Modified;
|
1710 |
+
|
1711 |
+
db.SaveChanges();
|
1712 |
+
|
1713 |
+
returnRedirectToAction("Index");
|
1714 |
+
|
1715 |
+
}
|
1716 |
+
|
1717 |
+
returnView(movie);
|
1718 |
+
|
1719 |
+
}
|
1720 |
+
|
1721 |
+
The ASP.NET MVC model binder takes the posted form values and creates aMovie object that's passed as the
|
1722 |
+
|
1723 |
+
movie parameter. TheModelState.IsValid method verifies that the data submitted in the form can be used
|
1724 |
+
|
1725 |
+
to modify (edit or update) a Movie object. If the data is valid, the movie data is saved to the Movies collection
|
1726 |
+
|
1727 |
+
of the db (MovieDBContext instance). The new movie data is saved to the database by calling the
|
1728 |
+
|
1729 |
+
SaveChanges method ofMovieDBContext. After saving the data, the code redirects the user to the Index
|
1730 |
+
|
1731 |
+
action method of the MoviesController class, which displays the of movie collection, including the changes
|
1732 |
+
|
1733 |
+
just made..
|
1734 |
+
|
1735 |
+
If the posted values aren't valid, they are redisplayed in the form. TheHtml.ValidationMessageFor helpers
|
1736 |
+
|
1737 |
+
in the Edit.cshtml view template take care of displaying appropriate error messages.
|
1738 |
+
|
1739 |
+
|
1740 |
+
Note about locales If you normally work with a locale other than English, see Supporting ASP.NET MVC
|
1741 |
+
|
1742 |
+
Validation with Non-English Locales. The decimal field may require a common, not a decimal point. As a
|
1743 |
+
|
1744 |
+
temporary fix, you can add the globalization element to the projects root web.config file. The following code
|
1745 |
+
|
1746 |
+
shows the globalization element with the culture set to United States English.
|
1747 |
+
|
1748 |
+
|
1749 |
+
<system.web>
|
1750 |
+
|
1751 |
+
<globalizationculture="en-US"/>
|
1752 |
+
|
1753 |
+
<!--elements removed for clarity-->
|
1754 |
+
|
1755 |
+
</system.web>
|
1756 |
+
|
1757 |
+
All the HttpGet methods follow a similar pattern. They get a movie object (or list of objects, in the case of
|
1758 |
+
|
1759 |
+
Index), and pass the model to the view. The Create method passes an empty movie object to the Create view.
|
1760 |
+
|
1761 |
+
All the methods that create, edit, delete, or otherwise modify data do so in the HttpPost overload of the
|
1762 |
+
|
1763 |
+
method. Modifying data in an HTTP GET method is a security risk, as described in the blog post entryASP.NET
|
1764 |
+
|
1765 |
+
MVC Tip #46 – Don’t use Delete Links because they create Security Holes. Modifying data in a GET method also
|
1766 |
+
|
1767 |
+
violates HTTP best practices and the architectural REST pattern, which specifies that GET requests should not
|
1768 |
+
|
1769 |
+
change the state of your application. In other words, performing a GET operation should be a safe operation
|
1770 |
+
|
1771 |
+
that has no side effects and doesn't modify your persisted data.
|
1772 |
+
|
1773 |
+
Adding a Search Method and Search View
|
1774 |
+
|
1775 |
+
In this section you'll add a SearchIndex action method that lets you search movies by genre or name. This will
|
1776 |
+
|
1777 |
+
be available using the /Movies/SearchIndex URL. The request will display an HTML form that contains input
|
1778 |
+
|
1779 |
+
elements that a user can enter in order to search for a movie. When a user submits the form, the action method
|
1780 |
+
|
1781 |
+
will get the search values posted by the user and use the values to search the database.
|
1782 |
+
|
1783 |
+
Displaying the SearchIndex Form
|
1784 |
+
|
1785 |
+
Start by adding a SearchIndex action method to the existingMoviesController class. The method will
|
1786 |
+
|
1787 |
+
return a view that contains an HTML form. Here's the code:
|
1788 |
+
|
1789 |
+
publicActionResultSearchIndex(string searchString)
|
1790 |
+
|
1791 |
+
{
|
1792 |
+
|
1793 |
+
var movies =from m in db.Movies
|
1794 |
+
|
1795 |
+
select m;
|
1796 |
+
|
1797 |
+
if(!String.IsNullOrEmpty(searchString))
|
1798 |
+
|
1799 |
+
{
|
1800 |
+
|
1801 |
+
|
1802 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
1803 |
+
|
1804 |
+
}
|
1805 |
+
|
1806 |
+
returnView(movies);
|
1807 |
+
|
1808 |
+
}
|
1809 |
+
|
1810 |
+
The first line of the SearchIndex method creates the followingLINQ query to select the movies:
|
1811 |
+
|
1812 |
+
var movies =from m in db.Movies
|
1813 |
+
|
1814 |
+
select m;
|
1815 |
+
|
1816 |
+
The query is defined at this point, but hasn't yet been run against the data store.
|
1817 |
+
|
1818 |
+
If the searchString parameter contains a string, the movies query is modified to filter on the value of the
|
1819 |
+
|
1820 |
+
search string, using the following code:
|
1821 |
+
|
1822 |
+
if(!String.IsNullOrEmpty(searchString))
|
1823 |
+
|
1824 |
+
{
|
1825 |
+
|
1826 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
1827 |
+
|
1828 |
+
}
|
1829 |
+
|
1830 |
+
The s => s.Title code above is aLambda Expression. Lambdas are used in method-basedLINQ queries as
|
1831 |
+
|
1832 |
+
arguments to standard query operator methods such asWhere method used in the above code. LINQ queries
|
1833 |
+
|
1834 |
+
are not executed when they are defined or when they are modified by calling a method such as Where or
|
1835 |
+
|
1836 |
+
OrderBy. Instead, query execution is deferred, which means that the evaluation of an expression is delayed
|
1837 |
+
|
1838 |
+
until its realized value is actually iterated over or theToList method is called. In the SearchIndex sample, the
|
1839 |
+
|
1840 |
+
query is executed in the SearchIndex view. For more information about deferred query execution, see Query
|
1841 |
+
|
1842 |
+
Execution.
|
1843 |
+
|
1844 |
+
Now you can implement the SearchIndex view that will display the form to the user. Right-click inside the
|
1845 |
+
|
1846 |
+
SearchIndex method and then click Add View. In the Add View dialog box, specify that you're going to pass
|
1847 |
+
|
1848 |
+
a Movie object to the view template as its model class. In the Scaffold template list, choose List, then click
|
1849 |
+
|
1850 |
+
Add.
|
1851 |
+
|
1852 |
+
|
1853 |
+
When you click the Add button, the Views\Movies\SearchIndex.cshtml view template is created. Because you
|
1854 |
+
|
1855 |
+
selected List in the Scaffold template list, Visual Studio Express automatically generated (scaffolded) some
|
1856 |
+
|
1857 |
+
default markup in the view. The scaffolding created an HTML form. It examined the Movie class and created
|
1858 |
+
|
1859 |
+
code to render <label> elements for each property of the class. The listing below shows the Create view that
|
1860 |
+
|
1861 |
+
was generated:
|
1862 |
+
|
1863 |
+
@model IEnumerable<MvcMovie.Models.Movie>
|
1864 |
+
|
1865 |
+
@{
|
1866 |
+
|
1867 |
+
ViewBag.Title = "SearchIndex";
|
1868 |
+
|
1869 |
+
}
|
1870 |
+
|
1871 |
+
<h2>SearchIndex</h2>
|
1872 |
+
|
1873 |
+
|
1874 |
+
|
1875 |
+
|
1876 |
+
|
1877 |
+
<p>
|
1878 |
+
|
1879 |
+
@Html.ActionLink("Create New", "Create")
|
1880 |
+
|
1881 |
+
</p>
|
1882 |
+
|
1883 |
+
<table>
|
1884 |
+
|
1885 |
+
<tr>
|
1886 |
+
|
1887 |
+
<th>
|
1888 |
+
|
1889 |
+
Title
|
1890 |
+
|
1891 |
+
</th>
|
1892 |
+
|
1893 |
+
<th>
|
1894 |
+
|
1895 |
+
ReleaseDate
|
1896 |
+
|
1897 |
+
</th>
|
1898 |
+
|
1899 |
+
<th>
|
1900 |
+
|
1901 |
+
Genre
|
1902 |
+
|
1903 |
+
</th>
|
1904 |
+
|
1905 |
+
<th>
|
1906 |
+
|
1907 |
+
Price
|
1908 |
+
|
1909 |
+
</th>
|
1910 |
+
|
1911 |
+
<th></th>
|
1912 |
+
|
1913 |
+
</tr>
|
1914 |
+
|
1915 |
+
@foreach (var item in Model) {
|
1916 |
+
|
1917 |
+
<tr>
|
1918 |
+
|
1919 |
+
<td>
|
1920 |
+
|
1921 |
+
@Html.DisplayFor(modelItem => item.Title)
|
1922 |
+
|
1923 |
+
</td>
|
1924 |
+
|
1925 |
+
<td>
|
1926 |
+
|
1927 |
+
@Html.DisplayFor(modelItem => item.ReleaseDate)
|
1928 |
+
|
1929 |
+
</td>
|
1930 |
+
|
1931 |
+
<td>
|
1932 |
+
|
1933 |
+
@Html.DisplayFor(modelItem => item.Genre)
|
1934 |
+
|
1935 |
+
</td>
|
1936 |
+
|
1937 |
+
<td>
|
1938 |
+
|
1939 |
+
@Html.DisplayFor(modelItem => item.Price)
|
1940 |
+
|
1941 |
+
</td>
|
1942 |
+
|
1943 |
+
<td>
|
1944 |
+
|
1945 |
+
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
|
1946 |
+
|
1947 |
+
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
|
1948 |
+
|
1949 |
+
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
|
1950 |
+
|
1951 |
+
|
1952 |
+
</td>
|
1953 |
+
|
1954 |
+
</tr>
|
1955 |
+
|
1956 |
+
}
|
1957 |
+
|
1958 |
+
</table>
|
1959 |
+
|
1960 |
+
Run the application and navigate to /Movies/SearchIndex. Append a query string such as
|
1961 |
+
|
1962 |
+
?searchString=ghost to the URL. The filtered movies are displayed.
|
1963 |
+
|
1964 |
+
If you change the signature of the SearchIndex method to have a parameter named id, the id parameter will
|
1965 |
+
|
1966 |
+
match the{id} placeholder for the default routes set in the Global.asax file.
|
1967 |
+
|
1968 |
+
{controller}/{action}/{id}
|
1969 |
+
|
1970 |
+
|
1971 |
+
|
1972 |
+
The original SearchIndex method looks like this::
|
1973 |
+
|
1974 |
+
publicActionResultSearchIndex(string searchString)
|
1975 |
+
|
1976 |
+
{
|
1977 |
+
|
1978 |
+
var movies =from m in db.Movies
|
1979 |
+
|
1980 |
+
select m;
|
1981 |
+
|
1982 |
+
if(!String.IsNullOrEmpty(searchString))
|
1983 |
+
|
1984 |
+
{
|
1985 |
+
|
1986 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
1987 |
+
|
1988 |
+
}
|
1989 |
+
|
1990 |
+
returnView(movies);
|
1991 |
+
|
1992 |
+
}
|
1993 |
+
|
1994 |
+
The modified SearchIndex method would look as follows:
|
1995 |
+
|
1996 |
+
publicActionResultSearchIndex(string id)
|
1997 |
+
|
1998 |
+
{
|
1999 |
+
|
2000 |
+
string searchString = id;
|
2001 |
+
|
2002 |
+
var movies =from m in db.Movies
|
2003 |
+
|
2004 |
+
select m;
|
2005 |
+
|
2006 |
+
if(!String.IsNullOrEmpty(searchString))
|
2007 |
+
|
2008 |
+
{
|
2009 |
+
|
2010 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
2011 |
+
|
2012 |
+
}
|
2013 |
+
|
2014 |
+
returnView(movies);
|
2015 |
+
|
2016 |
+
}
|
2017 |
+
|
2018 |
+
You can now pass the search title as route data (a URL segment) instead of as a query string value.
|
2019 |
+
|
2020 |
+
|
2021 |
+
|
2022 |
+
|
2023 |
+
|
2024 |
+
However, you can't expect users to modify the URL every time they want to search for a movie. So now you
|
2025 |
+
|
2026 |
+
you'll add UI to help them filter movies. If you changed the signature of the SearchIndex method to test how
|
2027 |
+
|
2028 |
+
to pass the route-bound ID parameter, change it back so that your SearchIndex method takes a string
|
2029 |
+
|
2030 |
+
parameter named searchString:
|
2031 |
+
|
2032 |
+
publicActionResultSearchIndex(string searchString)
|
2033 |
+
|
2034 |
+
{
|
2035 |
+
|
2036 |
+
var movies =from m in db.Movies
|
2037 |
+
|
2038 |
+
select m;
|
2039 |
+
|
2040 |
+
if(!String.IsNullOrEmpty(searchString))
|
2041 |
+
|
2042 |
+
{
|
2043 |
+
|
2044 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
2045 |
+
|
2046 |
+
}
|
2047 |
+
|
2048 |
+
|
2049 |
+
|
2050 |
+
|
2051 |
+
returnView(movies);
|
2052 |
+
|
2053 |
+
}
|
2054 |
+
|
2055 |
+
Open the Views\Movies\SearchIndex.cshtml file, and just after @Html.ActionLink("Create New",
|
2056 |
+
|
2057 |
+
"Create"), add the following:
|
2058 |
+
|
2059 |
+
@using (Html.BeginForm()){
|
2060 |
+
|
2061 |
+
<p> Title: @Html.TextBox("SearchString")<br/>
|
2062 |
+
|
2063 |
+
<inputtype="submit"value="Filter"/></p>
|
2064 |
+
|
2065 |
+
}
|
2066 |
+
|
2067 |
+
The following example shows a portion of the Views\Movies\SearchIndex.cshtml file with the added filtering
|
2068 |
+
|
2069 |
+
markup.
|
2070 |
+
|
2071 |
+
@model IEnumerable<MvcMovie.Models.Movie>
|
2072 |
+
|
2073 |
+
@{
|
2074 |
+
|
2075 |
+
ViewBag.Title = "SearchIndex";
|
2076 |
+
|
2077 |
+
}
|
2078 |
+
|
2079 |
+
<h2>SearchIndex</h2>
|
2080 |
+
|
2081 |
+
<p>
|
2082 |
+
|
2083 |
+
@Html.ActionLink("Create New", "Create")
|
2084 |
+
|
2085 |
+
@using (Html.BeginForm()){
|
2086 |
+
|
2087 |
+
<p> Title: @Html.TextBox("SearchString") <br/>
|
2088 |
+
|
2089 |
+
<inputtype="submit"value="Filter"/></p>
|
2090 |
+
|
2091 |
+
}
|
2092 |
+
|
2093 |
+
</p>
|
2094 |
+
|
2095 |
+
The Html.BeginForm helper creates an opening <form> tag. The Html.BeginForm helper causes the form to
|
2096 |
+
|
2097 |
+
post to itself when the user submits the form by clicking the Filter button.
|
2098 |
+
|
2099 |
+
Run the application and try searching for a movie.
|
2100 |
+
|
2101 |
+
|
2102 |
+
|
2103 |
+
|
2104 |
+
|
2105 |
+
There's no HttpPost overload of the SearchIndex method. You don't need it, because the method isn't
|
2106 |
+
|
2107 |
+
changing the state of the application, just filtering data.
|
2108 |
+
|
2109 |
+
You could add the following HttpPost SearchIndex method. In that case, the action invoker would match
|
2110 |
+
|
2111 |
+
the HttpPost SearchIndex method, and the HttpPost SearchIndex method would run as shown in the
|
2112 |
+
|
2113 |
+
image below.
|
2114 |
+
|
2115 |
+
[HttpPost]
|
2116 |
+
|
2117 |
+
publicstringSearchIndex(FormCollection fc,string searchString)
|
2118 |
+
|
2119 |
+
{
|
2120 |
+
|
2121 |
+
return"<h3> From [HttpPost]SearchIndex: "+ searchString +"</h3>";
|
2122 |
+
|
2123 |
+
}
|
2124 |
+
|
2125 |
+
|
2126 |
+
However, even if you add this HttpPost version of the SearchIndex method, there's a limitation in how this
|
2127 |
+
|
2128 |
+
has all been implemented. Imagine that you want to bookmark a particular search or you want to send a link to
|
2129 |
+
|
2130 |
+
friends that they can click in order to see the same filtered list of movies. Notice that the URL for the HTTP
|
2131 |
+
|
2132 |
+
POST request is the same as the URL for the GET request (localhost:xxxxx/Movies/SearchIndex) -- there's no
|
2133 |
+
|
2134 |
+
search information in the URL itself. Right now, the search string information is sent to the server as a form field
|
2135 |
+
|
2136 |
+
value. This means you can't capture that search information to bookmark or send to friends in a URL.
|
2137 |
+
|
2138 |
+
The solution is to use an overload of BeginForm that specifies that the POST request should add the search
|
2139 |
+
|
2140 |
+
information to the URL and that is should be routed to the HttpGet version of the SearchIndex method.
|
2141 |
+
|
2142 |
+
Replace the existing parameterless BeginForm method with the following:
|
2143 |
+
|
2144 |
+
@using (Html.BeginForm("SearchIndex","Movies",FormMethod.Get))
|
2145 |
+
|
2146 |
+
Now when you submit a search, the URL contains a search query string. Searching will also go to the HttpGet
|
2147 |
+
|
2148 |
+
SearchIndex action method, even if you have a HttpPost SearchIndex method.
|
2149 |
+
|
2150 |
+
|
2151 |
+
|
2152 |
+
Adding Search by Genre
|
2153 |
+
|
2154 |
+
If you added the HttpPost version of the SearchIndex method, delete it now.
|
2155 |
+
|
2156 |
+
Next, you'll add a feature to let users search for movies by genre. Replace the SearchIndex method with the
|
2157 |
+
|
2158 |
+
following code:
|
2159 |
+
|
2160 |
+
publicActionResultSearchIndex(string movieGenre,string searchString)
|
2161 |
+
|
2162 |
+
{
|
2163 |
+
|
2164 |
+
varGenreLst=newList<string>();
|
2165 |
+
|
2166 |
+
varGenreQry=from d in db.Movies
|
2167 |
+
|
2168 |
+
orderby d.Genre
|
2169 |
+
|
2170 |
+
|
2171 |
+
|
2172 |
+
select d.Genre;
|
2173 |
+
|
2174 |
+
GenreLst.AddRange(GenreQry.Distinct());
|
2175 |
+
|
2176 |
+
ViewBag.movieGenre =newSelectList(GenreLst);
|
2177 |
+
|
2178 |
+
var movies =from m in db.Movies
|
2179 |
+
|
2180 |
+
select m;
|
2181 |
+
|
2182 |
+
if(!String.IsNullOrEmpty(searchString))
|
2183 |
+
|
2184 |
+
{
|
2185 |
+
|
2186 |
+
movies= movies.Where(s => s.Title.Contains(searchString));
|
2187 |
+
|
2188 |
+
}
|
2189 |
+
|
2190 |
+
if(string.IsNullOrEmpty(movieGenre))
|
2191 |
+
|
2192 |
+
returnView(movies);
|
2193 |
+
|
2194 |
+
else
|
2195 |
+
|
2196 |
+
{
|
2197 |
+
|
2198 |
+
returnView(movies.Where(x => x.Genre== movieGenre));
|
2199 |
+
|
2200 |
+
}
|
2201 |
+
|
2202 |
+
}
|
2203 |
+
|
2204 |
+
This version of the SearchIndex method takes an additional parameter, namely movieGenre. The first few
|
2205 |
+
|
2206 |
+
lines of code create aList object to hold movie genres from the database.
|
2207 |
+
|
2208 |
+
The following code is a LINQ query that retrieves all the genres from the database.
|
2209 |
+
|
2210 |
+
varGenreQry=from d in db.Movies
|
2211 |
+
|
2212 |
+
orderby d.Genre
|
2213 |
+
|
2214 |
+
select d.Genre;
|
2215 |
+
|
2216 |
+
The code uses the AddRange method of the generic List collection to add all the distinct genres to the list.
|
2217 |
+
|
2218 |
+
(Without the Distinct modifier, duplicate genres would be added — for example, comedy would be added
|
2219 |
+
|
2220 |
+
twice in our sample). The code then stores the list of genres in the ViewBag object.
|
2221 |
+
|
2222 |
+
The following code shows how to check the movieGenre parameter. If it's not empty, the code further
|
2223 |
+
|
2224 |
+
constrains the movies query to limit the selected movies to the specified genre.
|
2225 |
+
|
2226 |
+
|
2227 |
+
|
2228 |
+
|
2229 |
+
|
2230 |
+
if(string.IsNullOrEmpty(movieGenre))
|
2231 |
+
|
2232 |
+
returnView(movies);
|
2233 |
+
|
2234 |
+
else
|
2235 |
+
|
2236 |
+
{
|
2237 |
+
|
2238 |
+
returnView(movies.Where(x => x.Genre== movieGenre));
|
2239 |
+
|
2240 |
+
}
|
2241 |
+
|
2242 |
+
Adding Markup to the SearchIndex View to Support Search by Genre
|
2243 |
+
|
2244 |
+
Add an Html.DropDownList helper to the Views\Movies\SearchIndex.cshtml file, just before the TextBox
|
2245 |
+
|
2246 |
+
helper. The completed markup is shown below:
|
2247 |
+
|
2248 |
+
<p>
|
2249 |
+
|
2250 |
+
@Html.ActionLink("Create New", "Create")
|
2251 |
+
|
2252 |
+
@using (Html.BeginForm("SearchIndex","Movies",FormMethod.Get)){
|
2253 |
+
|
2254 |
+
<p>Genre: @Html.DropDownList("movieGenre", "All")
|
2255 |
+
|
2256 |
+
Title: @Html.TextBox("SearchString")
|
2257 |
+
|
2258 |
+
<inputtype="submit"value="Filter"/></p>
|
2259 |
+
|
2260 |
+
}
|
2261 |
+
|
2262 |
+
</p>
|
2263 |
+
|
2264 |
+
Run the application and browse to /Movies/SearchIndex. Try a search by genre, by movie name, and by both
|
2265 |
+
|
2266 |
+
criteria.
|
2267 |
+
|
2268 |
+
In this section you examined the CRUD action methods and views generated by the framework. You created a
|
2269 |
+
|
2270 |
+
search action method and view that let users search by movie title and genre. In the next section, you'll look at
|
2271 |
+
|
2272 |
+
how to add a property to the Movie model and how to add an initializer that will automatically create a test
|
2273 |
+
|
2274 |
+
database.
|
2275 |
+
|
2276 |
+
|
2277 |
+
|
2278 |
+
Adding a New Field to the Movie Model and
|
2279 |
+
|
2280 |
+
Table
|
2281 |
+
|
2282 |
+
In this section you'll make some changes to the model classes and learn how you can update the database
|
2283 |
+
|
2284 |
+
schema to match the model changes.
|
2285 |
+
|
2286 |
+
Adding a Rating Property to the Movie Model
|
2287 |
+
|
2288 |
+
Start by adding a new Rating property to the existing Movie class. Open the Models\Movie.cs file and add the
|
2289 |
+
|
2290 |
+
Rating property like this one:
|
2291 |
+
|
2292 |
+
publicstringRating{get;set;}
|
2293 |
+
|
2294 |
+
The complete Movie class now looks like the following code:
|
2295 |
+
|
2296 |
+
publicclassMovie
|
2297 |
+
|
2298 |
+
{
|
2299 |
+
|
2300 |
+
publicint ID {get;set;}
|
2301 |
+
|
2302 |
+
publicstringTitle{get;set;}
|
2303 |
+
|
2304 |
+
publicDateTimeReleaseDate{get;set;}
|
2305 |
+
|
2306 |
+
publicstringGenre{get;set;}
|
2307 |
+
|
2308 |
+
publicdecimalPrice{get;set;}
|
2309 |
+
|
2310 |
+
publicstringRating{get;set;}
|
2311 |
+
|
2312 |
+
}
|
2313 |
+
|
2314 |
+
Recompile the application using the Build > Build Movie menu command.
|
2315 |
+
|
2316 |
+
Now that you've updated the Model class, you also need to update the \Views\Movies\Index.cshtml and
|
2317 |
+
|
2318 |
+
\Views\Movies\Create.cshtml view templates in order to display the new Rating property in the browser view.
|
2319 |
+
|
2320 |
+
Open the \Views\Movies\Index.cshtml file and add a <th>Rating</th> column heading just after the Price
|
2321 |
+
|
2322 |
+
column. Then add a <td> column near the end of the template to render the @item.Rating value. Below is
|
2323 |
+
|
2324 |
+
what the updated Index.cshtml view template looks like:
|
2325 |
+
|
2326 |
+
@model IEnumerable<MvcMovie.Models.Movie>
|
2327 |
+
|
2328 |
+
@{
|
2329 |
+
|
2330 |
+
ViewBag.Title = "Index";
|
2331 |
+
|
2332 |
+
}
|
2333 |
+
|
2334 |
+
<h2>Index</h2>
|
2335 |
+
|
2336 |
+
<p>
|
2337 |
+
|
2338 |
+
@Html.ActionLink("Create New", "Create")
|
2339 |
+
|
2340 |
+
</p>
|
2341 |
+
|
2342 |
+
<table>
|
2343 |
+
|
2344 |
+
<tr>
|
2345 |
+
|
2346 |
+
<th>
|
2347 |
+
|
2348 |
+
@Html.DisplayNameFor(model => model.Title)
|
2349 |
+
|
2350 |
+
</th>
|
2351 |
+
|
2352 |
+
<th>
|
2353 |
+
|
2354 |
+
@Html.DisplayNameFor(model => model.ReleaseDate)
|
2355 |
+
|
2356 |
+
</th>
|
2357 |
+
|
2358 |
+
<th>
|
2359 |
+
|
2360 |
+
@Html.DisplayNameFor(model => model.Genre)
|
2361 |
+
|
2362 |
+
</th>
|
2363 |
+
|
2364 |
+
<th>
|
2365 |
+
|
2366 |
+
@Html.DisplayNameFor(model => model.Price)
|
2367 |
+
|
2368 |
+
</th>
|
2369 |
+
|
2370 |
+
<th>
|
2371 |
+
|
2372 |
+
@Html.DisplayNameFor(model => model.Rating)
|
2373 |
+
|
2374 |
+
</th>
|
2375 |
+
|
2376 |
+
<th></th>
|
2377 |
+
|
2378 |
+
</tr>
|
2379 |
+
|
2380 |
+
@foreach (var item in Model) {
|
2381 |
+
|
2382 |
+
<tr>
|
2383 |
+
|
2384 |
+
<td>
|
2385 |
+
|
2386 |
+
@Html.DisplayFor(modelItem => item.Title)
|
2387 |
+
|
2388 |
+
</td>
|
2389 |
+
|
2390 |
+
<td>
|
2391 |
+
|
2392 |
+
@Html.DisplayFor(modelItem => item.ReleaseDate)
|
2393 |
+
|
2394 |
+
</td>
|
2395 |
+
|
2396 |
+
|
2397 |
+
|
2398 |
+
|
2399 |
+
|
2400 |
+
<td>
|
2401 |
+
|
2402 |
+
@Html.DisplayFor(modelItem => item.Genre)
|
2403 |
+
|
2404 |
+
</td>
|
2405 |
+
|
2406 |
+
<td>
|
2407 |
+
|
2408 |
+
@Html.DisplayFor(modelItem => item.Price)
|
2409 |
+
|
2410 |
+
</td>
|
2411 |
+
|
2412 |
+
<td>
|
2413 |
+
|
2414 |
+
@Html.DisplayFor(modelItem => item.Rating)
|
2415 |
+
|
2416 |
+
</td>
|
2417 |
+
|
2418 |
+
<td>
|
2419 |
+
|
2420 |
+
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
|
2421 |
+
|
2422 |
+
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
|
2423 |
+
|
2424 |
+
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
|
2425 |
+
|
2426 |
+
</td>
|
2427 |
+
|
2428 |
+
</tr>
|
2429 |
+
|
2430 |
+
}
|
2431 |
+
|
2432 |
+
</table>
|
2433 |
+
|
2434 |
+
Next, open the \Views\Movies\Create.cshtml file and add the following markup near the end of the form. This
|
2435 |
+
|
2436 |
+
renders a text box so that you can specify a rating when a new movie is created.
|
2437 |
+
|
2438 |
+
<divclass="editor-label">
|
2439 |
+
|
2440 |
+
@Html.LabelFor(model => model.Rating)
|
2441 |
+
|
2442 |
+
</div>
|
2443 |
+
|
2444 |
+
<divclass="editor-field">
|
2445 |
+
|
2446 |
+
@Html.EditorFor(model => model.Rating)
|
2447 |
+
|
2448 |
+
@Html.ValidationMessageFor(model => model.Rating)
|
2449 |
+
|
2450 |
+
</div>
|
2451 |
+
|
2452 |
+
Managing Model and Database Schema Differences
|
2453 |
+
|
2454 |
+
You've now updated the application code to support the new Rating property.
|
2455 |
+
|
2456 |
+
Now run the application and navigate to the /Movies URL. When you do this, though, you'll see one of the
|
2457 |
+
|
2458 |
+
following errors:
|
2459 |
+
|
2460 |
+
|
2461 |
+
|
2462 |
+
You're seeing this error because the updated Movie model class in the application is now different than the
|
2463 |
+
|
2464 |
+
schema of the Movie table of the existing database. (There's no Rating column in the database table.)
|
2465 |
+
|
2466 |
+
By default, when you use Entity Framework Code First to automatically create a database, as you did earlier in
|
2467 |
+
|
2468 |
+
this tutorial, Code First adds a table to the database to help track whether the schema of the database is in sync
|
2469 |
+
|
2470 |
+
with the model classes it was generated from. If they aren't in sync, the Entity Framework throws an error. This
|
2471 |
+
|
2472 |
+
makes it easier to track down issues at development time that you might otherwise only find (by obscure
|
2473 |
+
|
2474 |
+
|
2475 |
+
errors) at run time. The sync-checking feature is what causes the error message to be displayed that you just
|
2476 |
+
|
2477 |
+
saw.
|
2478 |
+
|
2479 |
+
There are two approaches to resolving the error:
|
2480 |
+
|
2481 |
+
1. Have the Entity Framework automatically drop and re-create the database based on the new model class
|
2482 |
+
|
2483 |
+
schema. This approach is very convenient when doing active development on a test database; it allows
|
2484 |
+
|
2485 |
+
you to quickly evolve the model and database schema together. The downside, though, is that you lose
|
2486 |
+
|
2487 |
+
existing data in the database — so you don't want to use this approach on a production database!
|
2488 |
+
|
2489 |
+
2. Explicitly modify the schema of the existing database so that it matches the model classes. The advantage
|
2490 |
+
|
2491 |
+
of this approach is that you keep your data. You can make this change either manually or by creating a
|
2492 |
+
|
2493 |
+
database change script.
|
2494 |
+
|
2495 |
+
For this tutorial, we'll use the first approach — you'll have the Entity Framework Code First automatically re-
|
2496 |
+
|
2497 |
+
create the database anytime the model changes.
|
2498 |
+
|
2499 |
+
Automatically Re-Creating the Database on Model Changes
|
2500 |
+
|
2501 |
+
Let's update the application so that Code First automatically drops and re-creates the database anytime you
|
2502 |
+
|
2503 |
+
change the model for the application.
|
2504 |
+
|
2505 |
+
Warning You should enable this approach of automatically dropping and re-creating the database only when
|
2506 |
+
|
2507 |
+
you're using a development or test database, and never on a production database that contains real data. Using
|
2508 |
+
|
2509 |
+
it on a production server can lead to data loss.
|
2510 |
+
|
2511 |
+
Stop the debugger. In Solution Explorer, right click the Models folder, select Add, and then select New Item.
|
2512 |
+
|
2513 |
+
In the Add New Item dialog, select Class then name the class "MovieInitializer". Update the
|
2514 |
+
|
2515 |
+
MovieInitializer class to contain the following code:
|
2516 |
+
|
2517 |
+
usingSystem;
|
2518 |
+
|
2519 |
+
usingSystem.Collections.Generic;
|
2520 |
+
|
2521 |
+
usingSystem.Data.Entity;
|
2522 |
+
|
2523 |
+
namespaceMvcMovie.Models{
|
2524 |
+
|
2525 |
+
publicclassMovieInitializer:DropCreateDatabaseIfModelChanges<MovieDBContext>{
|
2526 |
+
|
2527 |
+
protectedoverridevoidSeed(MovieDBContext context){
|
2528 |
+
|
2529 |
+
var movies =newList<Movie>{
|
2530 |
+
|
2531 |
+
newMovie{Title="When Harry Met Sally",
|
2532 |
+
|
2533 |
+
ReleaseDate=DateTime.Parse("1989-1-11"),
|
2534 |
+
|
2535 |
+
Genre="Romantic Comedy",
|
2536 |
+
|
2537 |
+
|
2538 |
+
|
2539 |
+
|
2540 |
+
Rating="R",
|
2541 |
+
|
2542 |
+
Price=7.99M},
|
2543 |
+
|
2544 |
+
newMovie{Title="Ghostbusters ",
|
2545 |
+
|
2546 |
+
ReleaseDate=DateTime.Parse("1984-3-13"),
|
2547 |
+
|
2548 |
+
Genre="Comedy",
|
2549 |
+
|
2550 |
+
Rating="R",
|
2551 |
+
|
2552 |
+
Price=8.99M},
|
2553 |
+
|
2554 |
+
newMovie{Title="Ghostbusters 2",
|
2555 |
+
|
2556 |
+
ReleaseDate=DateTime.Parse("1986-2-23"),
|
2557 |
+
|
2558 |
+
Genre="Comedy",
|
2559 |
+
|
2560 |
+
Rating="R",
|
2561 |
+
|
2562 |
+
Price=9.99M},
|
2563 |
+
|
2564 |
+
newMovie{Title="Rio Bravo",
|
2565 |
+
|
2566 |
+
ReleaseDate=DateTime.Parse("1959-4-15"),
|
2567 |
+
|
2568 |
+
Genre="Western",
|
2569 |
+
|
2570 |
+
Rating="R",
|
2571 |
+
|
2572 |
+
Price=3.99M},
|
2573 |
+
|
2574 |
+
};
|
2575 |
+
|
2576 |
+
movies.ForEach(d => context.Movies.Add(d));
|
2577 |
+
|
2578 |
+
}
|
2579 |
+
|
2580 |
+
}
|
2581 |
+
|
2582 |
+
}
|
2583 |
+
|
2584 |
+
The MovieInitializer class specifies that the database used by the model should be dropped and
|
2585 |
+
|
2586 |
+
automatically re-created if the model classes ever change.DropCreateDatabaseIfModelChanges initializer
|
2587 |
+
|
2588 |
+
specifies the DB should be re-created only if the schema changes. Alternatively, you could use
|
2589 |
+
|
2590 |
+
theDropCreateDatabaseAlways initializer to always recreate and re-seed the database with data the first time
|
2591 |
+
|
2592 |
+
that a context is used in the application domain. TheDropCreateDatabaseAlways approach is useful in some
|
2593 |
+
|
2594 |
+
integration testing scenarios. The code that you inserted into the MovieInitializer class includes a includes a
|
2595 |
+
|
2596 |
+
Seed method that specifies some default data to automatically add to the database any time it's created (or re-
|
2597 |
+
|
2598 |
+
created). This provides a useful way to populate the database with some test data, without requiring you to
|
2599 |
+
|
2600 |
+
manually populate it each time you make a model change.
|
2601 |
+
|
2602 |
+
|
2603 |
+
|
2604 |
+
|
2605 |
+
|
2606 |
+
Now that you've defined the MovieInitializer class, you'll want to wire it up so that each time the
|
2607 |
+
|
2608 |
+
application runs, it checks whether the model classes are different from the schema in the database. If they are,
|
2609 |
+
|
2610 |
+
you can run the initializer to re-create the database to match the model and then populate the database with
|
2611 |
+
|
2612 |
+
the sample data.
|
2613 |
+
|
2614 |
+
Open the Global.asax filet:
|
2615 |
+
|
2616 |
+
|
2617 |
+
The Global.asax file contains the class that defines the entire application for the project, and contains an
|
2618 |
+
|
2619 |
+
Application_Start event handler that runs when the application first starts.
|
2620 |
+
|
2621 |
+
At the beginning of the Application_Start method, add a call to Database.SetInitializer as shown
|
2622 |
+
|
2623 |
+
below:
|
2624 |
+
|
2625 |
+
protectedvoidApplication_Start()
|
2626 |
+
|
2627 |
+
{
|
2628 |
+
|
2629 |
+
Database.SetInitializer<MovieDBContext>(newMovieInitializer());
|
2630 |
+
|
2631 |
+
AreaRegistration.RegisterAllAreas();
|
2632 |
+
|
2633 |
+
// Use LocalDB for Entity Framework by default
|
2634 |
+
|
2635 |
+
Database.DefaultConnectionFactory=newSqlConnectionFactory("Data
|
2636 |
+
|
2637 |
+
Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
|
2638 |
+
|
2639 |
+
RegisterGlobalFilters(GlobalFilters.Filters);
|
2640 |
+
|
2641 |
+
RegisterRoutes(RouteTable.Routes);
|
2642 |
+
|
2643 |
+
BundleTable.Bundles.RegisterTemplateBundles();
|
2644 |
+
|
2645 |
+
}
|
2646 |
+
|
2647 |
+
Put the cursor on the red squiggly line (on MovieDBContext, orMovieInitializer ) right click and select
|
2648 |
+
|
2649 |
+
Resolve, then using MvcMovie.Models;
|
2650 |
+
|
2651 |
+
|
2652 |
+
|
2653 |
+
|
2654 |
+
Alternatively, add the using statement to the top of the file. The using statement references the namespace
|
2655 |
+
|
2656 |
+
where our MovieInitializer class lives:
|
2657 |
+
|
2658 |
+
usingMvcMovie.Models;// MovieInitializer
|
2659 |
+
|
2660 |
+
The Database.SetInitializer statement you just added indicates that the database used by the
|
2661 |
+
|
2662 |
+
MovieDBContext instance should be automatically deleted and re-created if the schema and the database
|
2663 |
+
|
2664 |
+
don't match. And as you saw, it will also populate the database with the sample data that's specified in the
|
2665 |
+
|
2666 |
+
MovieInitializer class.
|
2667 |
+
|
2668 |
+
Close the Global.asax file.
|
2669 |
+
|
2670 |
+
Re-run the application and navigate to the /Movies URL. When the application starts, it detects that the model
|
2671 |
+
|
2672 |
+
structure no longer matches the database schema. It automatically re-creates the database to match the new
|
2673 |
+
|
2674 |
+
model structure and populates the database with the sample movies:
|
2675 |
+
|
2676 |
+
|
2677 |
+
<="">
|
2678 |
+
|
2679 |
+
Click the Create New link to add a new movie. Note that you can add a rating.
|
2680 |
+
|
2681 |
+
Click Create. The new movie, including the rating, now shows up in the movies listing:
|
2682 |
+
|
2683 |
+
|
2684 |
+
You should also add the Rating field to the Edit view template.
|
2685 |
+
|
2686 |
+
In this section you saw how you can modify model objects and keep the database in sync with the changes. You
|
2687 |
+
|
2688 |
+
also learned a way to populate a newly created database with sample data so you can try out scenarios. Next,
|
2689 |
+
|
2690 |
+
let's look at how you can add richer validation logic to the model classes and enable some business rules to be
|
2691 |
+
|
2692 |
+
enforced.
|
2693 |
+
|
2694 |
+
|
2695 |
+
Adding Validation to the Model
|
2696 |
+
|
2697 |
+
In this this section you'll add validation logic to the Movie model, and you'll ensure that the validation rules are
|
2698 |
+
|
2699 |
+
enforced any time a user attempts to create or edit a movie using the application.
|
2700 |
+
|
2701 |
+
Keeping Things DRY
|
2702 |
+
|
2703 |
+
One of the core design tenets of ASP.NET MVC is DRY ("Don't Repeat Yourself"). ASP.NET MVC encourages you
|
2704 |
+
|
2705 |
+
to specify functionality or behavior only once, and then have it be reflected everywhere in an application. This
|
2706 |
+
|
2707 |
+
reduces the amount of code you need to write and makes the code you do write less error prone and easier to
|
2708 |
+
|
2709 |
+
maintain.
|
2710 |
+
|
2711 |
+
The validation support provided by ASP.NET MVC and Entity Framework Code First is a great example of the
|
2712 |
+
|
2713 |
+
DRY principle in action. You can declaratively specify validation rules in one place (in the model class) and the
|
2714 |
+
|
2715 |
+
rules are enforced everywhere in the application.
|
2716 |
+
|
2717 |
+
Let's look at how you can take advantage of this validation support in the movie application.
|
2718 |
+
|
2719 |
+
Adding Validation Rules to the Movie Model
|
2720 |
+
|
2721 |
+
You'll begin by adding some validation logic to the Movie class.
|
2722 |
+
|
2723 |
+
Open the Movie.cs file. Add a using statement at the top of the file that references
|
2724 |
+
|
2725 |
+
theSystem.ComponentModel.DataAnnotations namespace:
|
2726 |
+
|
2727 |
+
usingSystem.ComponentModel.DataAnnotations;
|
2728 |
+
|
2729 |
+
Notice the namespace does not contain System.Web. DataAnnotations provides a built-in set of validation
|
2730 |
+
|
2731 |
+
attributes that you can apply declaratively to any class or property.
|
2732 |
+
|
2733 |
+
Now update the Movie class to take advantage of the built-inRequired,StringLength, andRange validation
|
2734 |
+
|
2735 |
+
attributes. Use the following code as an example of where to apply the attributes.
|
2736 |
+
|
2737 |
+
publicclassMovie{
|
2738 |
+
|
2739 |
+
publicint ID {get;set;}
|
2740 |
+
|
2741 |
+
[Required]
|
2742 |
+
|
2743 |
+
|
2744 |
+
publicstringTitle{get;set;}
|
2745 |
+
|
2746 |
+
[DataType(DataType.Date)]
|
2747 |
+
|
2748 |
+
publicDateTimeReleaseDate{get;set;}
|
2749 |
+
|
2750 |
+
[Required]
|
2751 |
+
|
2752 |
+
publicstringGenre{get;set;}
|
2753 |
+
|
2754 |
+
[Range(1,100)]
|
2755 |
+
|
2756 |
+
[DataType(DataType.Currency)]
|
2757 |
+
|
2758 |
+
publicdecimalPrice{get;set;}
|
2759 |
+
|
2760 |
+
[StringLength(5)]
|
2761 |
+
|
2762 |
+
publicstringRating{get;set;}
|
2763 |
+
|
2764 |
+
}
|
2765 |
+
|
2766 |
+
The validation attributes specify behavior that you want to enforce on the model properties they are applied to.
|
2767 |
+
|
2768 |
+
The Required attribute indicates that a property must have a value; in this sample, a movie has to have values
|
2769 |
+
|
2770 |
+
for the Title, ReleaseDate, Genre, and Price properties in order to be valid. The Range attribute constrains
|
2771 |
+
|
2772 |
+
a value to within a specified range. The StringLength attribute lets you set the maximum length of a string
|
2773 |
+
|
2774 |
+
property, and optionally its minimum length. Intrinsic types (such as decimal, int, float, DateTime) are
|
2775 |
+
|
2776 |
+
required by default and don't need the Requiredattribute.
|
2777 |
+
|
2778 |
+
Code First ensures that the validation rules you specify on a model class are enforced before the application
|
2779 |
+
|
2780 |
+
saves changes in the database. For example, the code below will throw an exception when the SaveChanges
|
2781 |
+
|
2782 |
+
method is called, because several required Movie property values are missing and the price is zero (which is out
|
2783 |
+
|
2784 |
+
of the valid range).
|
2785 |
+
|
2786 |
+
MovieDBContext db =newMovieDBContext();
|
2787 |
+
|
2788 |
+
Movie movie =newMovie();
|
2789 |
+
|
2790 |
+
movie.Title="Gone with the Wind";
|
2791 |
+
|
2792 |
+
movie.Price=0.0M;
|
2793 |
+
|
2794 |
+
db.Movies.Add(movie);
|
2795 |
+
|
2796 |
+
db.SaveChanges();// <= Will throw validation exception
|
2797 |
+
|
2798 |
+
|
2799 |
+
|
2800 |
+
|
2801 |
+
|
2802 |
+
|
2803 |
+
|
2804 |
+
Having validation rules automatically enforced by the .NET Framework helps make your application more
|
2805 |
+
|
2806 |
+
robust. It also ensures that you can't forget to validate something and inadvertently let bad data into the
|
2807 |
+
|
2808 |
+
database.
|
2809 |
+
|
2810 |
+
Here's a complete code listing for the updated Movie.cs file:
|
2811 |
+
|
2812 |
+
usingSystem;
|
2813 |
+
|
2814 |
+
usingSystem.Data.Entity;
|
2815 |
+
|
2816 |
+
usingSystem.ComponentModel.DataAnnotations;
|
2817 |
+
|
2818 |
+
namespaceMvcMovie.Models{
|
2819 |
+
|
2820 |
+
publicclassMovie{
|
2821 |
+
|
2822 |
+
publicint ID {get;set;}
|
2823 |
+
|
2824 |
+
[Required]
|
2825 |
+
|
2826 |
+
publicstringTitle{get;set;}
|
2827 |
+
|
2828 |
+
[DataType(DataType.Date)]
|
2829 |
+
|
2830 |
+
publicDateTimeReleaseDate{get;set;}
|
2831 |
+
|
2832 |
+
[Required]
|
2833 |
+
|
2834 |
+
publicstringGenre{get;set;}
|
2835 |
+
|
2836 |
+
[Range(1,100)]
|
2837 |
+
|
2838 |
+
[DataType(DataType.Currency)]
|
2839 |
+
|
2840 |
+
publicdecimalPrice{get;set;}
|
2841 |
+
|
2842 |
+
[StringLength(5)]
|
2843 |
+
|
2844 |
+
publicstringRating{get;set;}
|
2845 |
+
|
2846 |
+
}
|
2847 |
+
|
2848 |
+
publicclassMovieDBContext:DbContext{
|
2849 |
+
|
2850 |
+
publicDbSet<Movie>Movies{get;set;}
|
2851 |
+
|
2852 |
+
}
|
2853 |
+
|
2854 |
+
}
|
2855 |
+
|
2856 |
+
Validation Error UI in ASP.NET MVC
|
2857 |
+
|
2858 |
+
|
2859 |
+
|
2860 |
+
|
2861 |
+
|
2862 |
+
|
2863 |
+
|
2864 |
+
|
2865 |
+
Re-run the application and navigate to the /Movies URL.
|
2866 |
+
|
2867 |
+
Click the Create New link to add a new movie. Fill out the form with some invalid values and then click the
|
2868 |
+
|
2869 |
+
Create button.
|
2870 |
+
|
2871 |
+
|
2872 |
+
Notice how the form has automatically used a red border color to highlight the text boxes that contain invalid
|
2873 |
+
|
2874 |
+
data and has emitted an appropriate validation error message next to each one. The errors are enforced both
|
2875 |
+
|
2876 |
+
client-side (using JavaScript) and server-side (in case a user has JavaScript disabled).
|
2877 |
+
|
2878 |
+
A real benefit is that you didn't need to change a single line of code in theMoviesController class or in the
|
2879 |
+
|
2880 |
+
Create.cshtml view in order to enable this validation UI. The controller and views you created earlier in this
|
2881 |
+
|
2882 |
+
tutorial automatically picked up the validation rules that you specified by using validation attributes on the
|
2883 |
+
|
2884 |
+
properties of the Movie model class.
|
2885 |
+
|
2886 |
+
You might have noticed for the properties Title and Genre, the required attribute is not enforced until you
|
2887 |
+
|
2888 |
+
submit the form (hit the Create button), or enter text into the input field and removed it. For a field which is
|
2889 |
+
|
2890 |
+
initially empty (such as the fields on the Create view) and which has only the required attribute and no other
|
2891 |
+
|
2892 |
+
validation attributes, you can do the following to trigger validation:
|
2893 |
+
|
2894 |
+
1. Tab into the field.
|
2895 |
+
|
2896 |
+
2. Enter some text.
|
2897 |
+
|
2898 |
+
3. Tab out.
|
2899 |
+
|
2900 |
+
4. Tab back into the field.
|
2901 |
+
|
2902 |
+
5. Remove the text.
|
2903 |
+
|
2904 |
+
6. Tab out.
|
2905 |
+
|
2906 |
+
The above sequence will trigger the required validation without hitting the submit button. Simply hitting the
|
2907 |
+
|
2908 |
+
submit button without entering any of the fields will trigger client side validation. The form data is not sent to
|
2909 |
+
|
2910 |
+
the server until there are no client side validation errors. You can test this by putting a break point in the HTTP
|
2911 |
+
|
2912 |
+
Post method or using thefiddler tool or the IE 9F12 developer tools.
|
2913 |
+
|
2914 |
+
How Validation Occurs in the Create View and Create Action Method
|
2915 |
+
|
2916 |
+
|
2917 |
+
You might wonder how the validation UI was generated without any updates to the code in the controller or
|
2918 |
+
|
2919 |
+
views. The next listing shows what the Create methods in the MovieController class look like. They're
|
2920 |
+
|
2921 |
+
unchanged from how you created them earlier in this tutorial.
|
2922 |
+
|
2923 |
+
//
|
2924 |
+
|
2925 |
+
// GET: /Movies/Create
|
2926 |
+
|
2927 |
+
publicActionResultCreate()
|
2928 |
+
|
2929 |
+
{
|
2930 |
+
|
2931 |
+
returnView();
|
2932 |
+
|
2933 |
+
}
|
2934 |
+
|
2935 |
+
//
|
2936 |
+
|
2937 |
+
// POST: /Movies/Create
|
2938 |
+
|
2939 |
+
[HttpPost]
|
2940 |
+
|
2941 |
+
publicActionResultCreate(Movie movie)
|
2942 |
+
|
2943 |
+
{
|
2944 |
+
|
2945 |
+
if(ModelState.IsValid)
|
2946 |
+
|
2947 |
+
{
|
2948 |
+
|
2949 |
+
db.Movies.Add(movie);
|
2950 |
+
|
2951 |
+
db.SaveChanges();
|
2952 |
+
|
2953 |
+
returnRedirectToAction("Index");
|
2954 |
+
|
2955 |
+
}
|
2956 |
+
|
2957 |
+
returnView(movie);
|
2958 |
+
|
2959 |
+
}
|
2960 |
+
|
2961 |
+
The first (HTTP GET) Create action method displays the initial Create form. The second ([HttpPost]) version
|
2962 |
+
|
2963 |
+
handles the form post. The second Create method (The HttpPost version) calls ModelState.IsValid to
|
2964 |
+
|
2965 |
+
check whether the movie has any validation errors. Calling this method evaluates any validation attributes that
|
2966 |
+
|
2967 |
+
have been applied to the object. If the object has validation errors, the Create method re-displays the form. If
|
2968 |
+
|
2969 |
+
there are no errors, the method saves the new movie in the database. In our movie example we are using, the
|
2970 |
+
|
2971 |
+
form is not posted to the server when their are validation errors detected on the client side; the second Create
|
2972 |
+
|
2973 |
+
method is never called. If you disable JavaScript in your browser, client validation is disabled and the HTTP
|
2974 |
+
|
2975 |
+
POST Create method calls ModelState.IsValid to check whether the movie has any validation errors.
|
2976 |
+
|
2977 |
+
|
2978 |
+
|
2979 |
+
|
2980 |
+
|
2981 |
+
You can set a break point in the HttpPost Create method and verify the method is never called, client side
|
2982 |
+
|
2983 |
+
validation will not submit the form data when validation errors are detected. If you disable JavaScript in your
|
2984 |
+
|
2985 |
+
browser, submit the form with errors, the break point will be hit. You still get full validation without JavaScript.
|
2986 |
+
|
2987 |
+
|
2988 |
+
The following image shows how to disable JavaScript in the FireFox browser.
|
2989 |
+
|
2990 |
+
The following image shows how to disable JavaScript with the Chrome browser.
|
2991 |
+
|
2992 |
+
|
2993 |
+
|
2994 |
+
Below is the Create.cshtml view template that you scaffolded earlier in the tutorial. It's used by the action
|
2995 |
+
|
2996 |
+
methods shown above both to display the initial form and to redisplay it in the event of an error.
|
2997 |
+
|
2998 |
+
|
2999 |
+
@model MvcMovie.Models.Movie
|
3000 |
+
|
3001 |
+
@{
|
3002 |
+
|
3003 |
+
ViewBag.Title = "Create";
|
3004 |
+
|
3005 |
+
}
|
3006 |
+
|
3007 |
+
<h2>Create</h2>
|
3008 |
+
|
3009 |
+
<scriptsrc="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
|
3010 |
+
|
3011 |
+
<scriptsrc="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
|
3012 |
+
|
3013 |
+
@using (Html.BeginForm()) {
|
3014 |
+
|
3015 |
+
@Html.ValidationSummary(true)
|
3016 |
+
|
3017 |
+
<fieldset>
|
3018 |
+
|
3019 |
+
<legend>Movie</legend>
|
3020 |
+
|
3021 |
+
<divclass="editor-label">
|
3022 |
+
|
3023 |
+
@Html.LabelFor(model => model.Title)
|
3024 |
+
|
3025 |
+
</div>
|
3026 |
+
|
3027 |
+
<divclass="editor-field">
|
3028 |
+
|
3029 |
+
@Html.EditorFor(model => model.Title)
|
3030 |
+
|
3031 |
+
@Html.ValidationMessageFor(model => model.Title)
|
3032 |
+
|
3033 |
+
</div>
|
3034 |
+
|
3035 |
+
<divclass="editor-label">
|
3036 |
+
|
3037 |
+
@Html.LabelFor(model => model.ReleaseDate)
|
3038 |
+
|
3039 |
+
</div>
|
3040 |
+
|
3041 |
+
<divclass="editor-field">
|
3042 |
+
|
3043 |
+
@Html.EditorFor(model => model.ReleaseDate)
|
3044 |
+
|
3045 |
+
@Html.ValidationMessageFor(model => model.ReleaseDate)
|
3046 |
+
|
3047 |
+
</div>
|
3048 |
+
|
3049 |
+
<divclass="editor-label">
|
3050 |
+
|
3051 |
+
@Html.LabelFor(model => model.Genre)
|
3052 |
+
|
3053 |
+
</div>
|
3054 |
+
|
3055 |
+
<divclass="editor-field">
|
3056 |
+
|
3057 |
+
@Html.EditorFor(model => model.Genre)
|
3058 |
+
|
3059 |
+
|
3060 |
+
|
3061 |
+
|
3062 |
+
|
3063 |
+
|
3064 |
+
|
3065 |
+
|
3066 |
+
|
3067 |
+
@Html.ValidationMessageFor(model => model.Genre)
|
3068 |
+
|
3069 |
+
</div>
|
3070 |
+
|
3071 |
+
<divclass="editor-label">
|
3072 |
+
|
3073 |
+
@Html.LabelFor(model => model.Price)
|
3074 |
+
|
3075 |
+
</div>
|
3076 |
+
|
3077 |
+
<divclass="editor-field">
|
3078 |
+
|
3079 |
+
@Html.EditorFor(model => model.Price)
|
3080 |
+
|
3081 |
+
@Html.ValidationMessageFor(model => model.Price)
|
3082 |
+
|
3083 |
+
</div>
|
3084 |
+
|
3085 |
+
<divclass="editor-label">
|
3086 |
+
|
3087 |
+
@Html.LabelFor(model => model.Rating)
|
3088 |
+
|
3089 |
+
</div>
|
3090 |
+
|
3091 |
+
<divclass="editor-field">
|
3092 |
+
|
3093 |
+
@Html.EditorFor(model => model.Rating)
|
3094 |
+
|
3095 |
+
@Html.ValidationMessageFor(model => model.Rating)
|
3096 |
+
|
3097 |
+
</div>
|
3098 |
+
|
3099 |
+
<p>
|
3100 |
+
|
3101 |
+
<inputtype="submit"value="Create"/>
|
3102 |
+
|
3103 |
+
</p>
|
3104 |
+
|
3105 |
+
</fieldset>
|
3106 |
+
|
3107 |
+
}
|
3108 |
+
|
3109 |
+
<div>
|
3110 |
+
|
3111 |
+
@Html.ActionLink("Back to List", "Index")
|
3112 |
+
|
3113 |
+
</div>
|
3114 |
+
|
3115 |
+
Notice how the code uses an Html.EditorFor helper to output the<input> element for each Movie
|
3116 |
+
|
3117 |
+
property. Next to this helper is a call to the Html.ValidationMessageFor helper method. These two helper
|
3118 |
+
|
3119 |
+
methods work with the model object that's passed by the controller to the view (in this case, a Movie object).
|
3120 |
+
|
3121 |
+
They automatically look for validation attributes specified on the model and display error messages as
|
3122 |
+
|
3123 |
+
appropriate.
|
3124 |
+
|
3125 |
+
What's really nice about this approach is that neither the controller nor the Create view template knows
|
3126 |
+
|
3127 |
+
anything about the actual validation rules being enforced or about the specific error messages displayed. The
|
3128 |
+
|
3129 |
+
validation rules and the error strings are specified only in the Movie class.
|
3130 |
+
|
3131 |
+
|
3132 |
+
|
3133 |
+
If you want to change the validation logic later, you can do so in exactly one place by adding validation
|
3134 |
+
|
3135 |
+
attributes to the model (in this example, themovie class). You won't have to worry about different parts of the
|
3136 |
+
|
3137 |
+
application being inconsistent with how the rules are enforced — all validation logic will be defined in one
|
3138 |
+
|
3139 |
+
place and used everywhere. This keeps the code very clean, and makes it easy to maintain and evolve. And it
|
3140 |
+
|
3141 |
+
means that that you'll be fully honoring the DRY principle.
|
3142 |
+
|
3143 |
+
Adding Formatting to the Movie Model
|
3144 |
+
|
3145 |
+
Open the Movie.cs file and examine the Movie class. TheSystem.ComponentModel.DataAnnotations
|
3146 |
+
|
3147 |
+
namespace provides formatting attributes in addition to the built-in set of validation attributes. We've already
|
3148 |
+
|
3149 |
+
applied aDataType enumeration value to the release date and to the price fields. The following code shows the
|
3150 |
+
|
3151 |
+
ReleaseDate and Price properties with the appropriateDisplayFormat attribute.
|
3152 |
+
|
3153 |
+
[DataType(DataType.Date)]
|
3154 |
+
|
3155 |
+
publicDateTimeReleaseDate{get;set;}
|
3156 |
+
|
3157 |
+
[DataType(DataType.Currency)]
|
3158 |
+
|
3159 |
+
publicdecimalPrice{get;set;}
|
3160 |
+
|
3161 |
+
Alternatively, you could explicitly set aDataFormatString value. The following code shows the release date
|
3162 |
+
|
3163 |
+
property with a date format string (namely, "d"). You'd use this to specify that you don't want to time as part of
|
3164 |
+
|
3165 |
+
the release date.
|
3166 |
+
|
3167 |
+
[DisplayFormat(DataFormatString="{0:d}")]
|
3168 |
+
|
3169 |
+
publicDateTimeReleaseDate{get;set;}
|
3170 |
+
|
3171 |
+
The following code formats the Price property as currency.
|
3172 |
+
|
3173 |
+
[DisplayFormat(DataFormatString="{0:c}")]
|
3174 |
+
|
3175 |
+
publicdecimalPrice{get;set;}
|
3176 |
+
|
3177 |
+
The complete Movie class is shown below.
|
3178 |
+
|
3179 |
+
publicclassMovie{
|
3180 |
+
|
3181 |
+
publicint ID {get;set;}
|
3182 |
+
|
3183 |
+
|
3184 |
+
|
3185 |
+
[Required]
|
3186 |
+
|
3187 |
+
publicstringTitle{get;set;}
|
3188 |
+
|
3189 |
+
[DataType(DataType.Date)]
|
3190 |
+
|
3191 |
+
publicDateTimeReleaseDate{get;set;}
|
3192 |
+
|
3193 |
+
[Required]
|
3194 |
+
|
3195 |
+
publicstringGenre{get;set;}
|
3196 |
+
|
3197 |
+
[Range(1,100)]
|
3198 |
+
|
3199 |
+
[DataType(DataType.Currency)]
|
3200 |
+
|
3201 |
+
publicdecimalPrice{get;set;}
|
3202 |
+
|
3203 |
+
[StringLength(5)]
|
3204 |
+
|
3205 |
+
publicstringRating{get;set;}
|
3206 |
+
|
3207 |
+
}
|
3208 |
+
|
3209 |
+
Run the application and browse to the Movies controller. The release date and price are nicely formatted.
|
3210 |
+
|
3211 |
+
|
3212 |
+
|
3213 |
+
|
3214 |
+
|
3215 |
+
In the next part of the series, we'll review the application and make some improvements to the automatically
|
3216 |
+
|
3217 |
+
generated Details and Delete methods.
|
3218 |
+
|
3219 |
+
|
3220 |
+
|
3221 |
+
|
3222 |
+
Examining the Details and Delete Methods
|
3223 |
+
|
3224 |
+
In this part of the tutorial, you'll examine the automatically generated Details and Delete methods.
|
3225 |
+
|
3226 |
+
Examining the Details and Delete Methods
|
3227 |
+
|
3228 |
+
Open the Movie controller and examine the Details method.
|
3229 |
+
|
3230 |
+
publicActionResultDetails(int id =0)
|
3231 |
+
|
3232 |
+
{
|
3233 |
+
|
3234 |
+
Movie movie =db.Movies.Find(id);
|
3235 |
+
|
3236 |
+
if(movie ==null)
|
3237 |
+
|
3238 |
+
{
|
3239 |
+
|
3240 |
+
returnHttpNotFound();
|
3241 |
+
|
3242 |
+
}
|
3243 |
+
|
3244 |
+
returnView(movie);
|
3245 |
+
|
3246 |
+
}
|
3247 |
+
|
3248 |
+
Code First makes it easy to search for data using the Find method. An important security feature built into the
|
3249 |
+
|
3250 |
+
method is that the code verifies that the Find method has found a movie before the code tries to do anything
|
3251 |
+
|
3252 |
+
with it. For example, a hacker could introduce errors into the site by changing the URL created by the links from
|
3253 |
+
|
3254 |
+
http://localhost:xxxx/Movies/Details/1 to something like http://localhost:xxxx/Movies/Details/12345 (or some
|
3255 |
+
|
3256 |
+
other value that doesn't represent an actual movie). If you did not check for a null movie, a null movie would
|
3257 |
+
|
3258 |
+
result in a database error.
|
3259 |
+
|
3260 |
+
Examine the Delete and DeleteConfirmed methods.
|
3261 |
+
|
3262 |
+
// GET: /Movies/Delete/5
|
3263 |
+
|
3264 |
+
publicActionResultDelete(int id =0)
|
3265 |
+
|
3266 |
+
{
|
3267 |
+
|
3268 |
+
Movie movie =db.Movies.Find(id);
|
3269 |
+
|
3270 |
+
if(movie ==null)
|
3271 |
+
|
3272 |
+
{
|
3273 |
+
|
3274 |
+
returnHttpNotFound();
|
3275 |
+
|
3276 |
+
}
|
3277 |
+
|
3278 |
+
returnView(movie);
|
3279 |
+
|
3280 |
+
|
3281 |
+
}
|
3282 |
+
|
3283 |
+
//
|
3284 |
+
|
3285 |
+
// POST: /Movies/Delete/5
|
3286 |
+
|
3287 |
+
[HttpPost,ActionName("Delete")]
|
3288 |
+
|
3289 |
+
publicActionResultDeleteConfirmed(int id =0)
|
3290 |
+
|
3291 |
+
{
|
3292 |
+
|
3293 |
+
Movie movie =db.Movies.Find(id);
|
3294 |
+
|
3295 |
+
if(movie ==null)
|
3296 |
+
|
3297 |
+
{
|
3298 |
+
|
3299 |
+
returnHttpNotFound();
|
3300 |
+
|
3301 |
+
}
|
3302 |
+
|
3303 |
+
db.Movies.Remove(movie);
|
3304 |
+
|
3305 |
+
db.SaveChanges();
|
3306 |
+
|
3307 |
+
returnRedirectToAction("Index");
|
3308 |
+
|
3309 |
+
}
|
3310 |
+
|
3311 |
+
Note that the HTTP Get Delete method doesn't delete the specified movie, it returns a view of the movie
|
3312 |
+
|
3313 |
+
where you can submit (HttpPost) the deletion.. Performing a delete operation in response to a GET request (or
|
3314 |
+
|
3315 |
+
for that matter, performing an edit operation, create operation, or any other operation that changes data)
|
3316 |
+
|
3317 |
+
opens up a security hole. For more information about this, see Stephen Walther's blog entryASP.NET MVC Tip
|
3318 |
+
|
3319 |
+
#46 — Don't use Delete Links because they create Security Holes.
|
3320 |
+
|
3321 |
+
The HttpPost method that deletes the data is named DeleteConfirmed to give the HTTP POST method a
|
3322 |
+
|
3323 |
+
unique signature or name. The two method signatures are shown below:
|
3324 |
+
|
3325 |
+
// GET: /Movies/Delete/5
|
3326 |
+
|
3327 |
+
publicActionResultDelete(int id =0)
|
3328 |
+
|
3329 |
+
//
|
3330 |
+
|
3331 |
+
// POST: /Movies/Delete/5
|
3332 |
+
|
3333 |
+
[HttpPost,ActionName("Delete")]
|
3334 |
+
|
3335 |
+
publicActionResultDeleteConfirmed(int id =0)
|
3336 |
+
|
3337 |
+
|
3338 |
+
|
3339 |
+
|
3340 |
+
The common language runtime (CLR) requires overloaded methods to have a unique signature (same method
|
3341 |
+
|
3342 |
+
name but different list of parameters). However, here you need two Delete methods -- one for GET and one for
|
3343 |
+
|
3344 |
+
POST -- that both have the same signature. (They both need to accept a single integer as a parameter.)
|
3345 |
+
|
3346 |
+
To sort this out, you can do a couple of things. One is to give the methods different names. That's what the
|
3347 |
+
|
3348 |
+
scaffolding mechanism did in he preceding example. However, this introduces a small problem: ASP.NET maps
|
3349 |
+
|
3350 |
+
segments of a URL to action methods by name, and if you rename a method, routing normally wouldn't be able
|
3351 |
+
|
3352 |
+
to find that method. The solution is what you see in the example, which is to add the ActionName("Delete")
|
3353 |
+
|
3354 |
+
attribute to theDeleteConfirmed method. This effectively performs mapping for the routing system so that a
|
3355 |
+
|
3356 |
+
URL that includes /Delete/ for a POST request will find the DeleteConfirmed method.
|
3357 |
+
|
3358 |
+
Another common way to avoid a problem with methods that have identical names and signatures is to
|
3359 |
+
|
3360 |
+
artificially change the signature of the POST method to include an unused parameter. For example, some
|
3361 |
+
|
3362 |
+
developers add a parameter typeFormCollectionthat is passed to the POST method, and then simply don't
|
3363 |
+
|
3364 |
+
use the parameter:
|
3365 |
+
|
3366 |
+
publicActionResultDelete(FormCollection fcNotUsed,int id =0)
|
3367 |
+
|
3368 |
+
{
|
3369 |
+
|
3370 |
+
Movie movie =db.Movies.Find(id);
|
3371 |
+
|
3372 |
+
if(movie ==null)
|
3373 |
+
|
3374 |
+
{
|
3375 |
+
|
3376 |
+
returnHttpNotFound();
|
3377 |
+
|
3378 |
+
}
|
3379 |
+
|
3380 |
+
db.Movies.Remove(movie);
|
3381 |
+
|
3382 |
+
db.SaveChanges();
|
3383 |
+
|
3384 |
+
returnRedirectToAction("Index");
|
3385 |
+
|
3386 |
+
}
|
3387 |
+
|
3388 |
+
Wrapping Up
|
3389 |
+
|
3390 |
+
You now have a complete ASP.NET MVC application that stores data in a SQL Server Compact database. You
|
3391 |
+
|
3392 |
+
can create, read, update, delete, and search for movies.
|
3393 |
+
|
3394 |
+
This basic tutorial got you started making controllers, associating them with views, and passing around hard-
|
3395 |
+
|
3396 |
+
coded data. Then you created and designed a data model. Entity Framework code-first created a database from
|
3397 |
+
|
3398 |
+
the data model on the fly, and the ASP.NET MVC scaffolding system automatically generated the action
|
3399 |
+
|
3400 |
+
methods and views for basic CRUD operations. You then added a search form that let users search the
|
3401 |
+
|
3402 |
+
database. You changed the database to include a new column of data, and then updated two pages to create
|
3403 |
+
|
3404 |
+
and display this new data. You added validation by marking the data model with attributes from the
|
3405 |
+
|
3406 |
+
DataAnnotations namespace. The resulting validation runs on the client and on the server.
|
3407 |
+
|
3408 |
+
If you'd like to deploy your application, it's helpful to first test the application on your local IIS 7 server. You can
|
3409 |
+
|
3410 |
+
use thisWeb Platform Installer link to enable IIS setting for ASP.NET applications. See the following deployment
|
3411 |
+
|
3412 |
+
links:
|
3413 |
+
|
3414 |
+
|
3415 |
+
• ASP.NET Deployment Content Map
|
3416 |
+
|
3417 |
+
•
|
3418 |
+
|
3419 |
+
Enabling IIS 7.x
|
3420 |
+
|
3421 |
+
• Web Application Projects Deployment
|
3422 |
+
|
3423 |
+
I now encourage you to move on to our intermediate-levelCreating an Entity Framework Data Model for an
|
3424 |
+
|
3425 |
+
ASP.NET MVC Application andMVC Music Store tutorials, to explore theASP.NET articles on MSDN, and to
|
3426 |
+
|
3427 |
+
check out the many videos and resources athttp://asp.net/mvc to learn even more about ASP.NET MVC! The
|
3428 |
+
|
3429 |
+
ASP.NET MVC forums are a great place to ask questions.
|
3430 |
+
|
3431 |
+
Enjoy!
|
3432 |
+
|
3433 |
+
— Rick Anderson blogs.msdn.com/rickAndy twitter @RickAndMSFT
|
3434 |
+
|
3435 |
+
— Scott Hanselmanhttp://www.hanselman.com/blog/ twitter @shanselman
|
3436 |
+
|
3437 |
+
|
3438 |
+
|
3439 |
+
|
3440 |
+
|
3441 |
+
|
3442 |
+
|
Ada/.ipynb_checkpoints/Ada_for_the_C_or_Java_Developer-cc.pdf-checkpoint.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Ada/AdaDistilled07-27-2003.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Ada/Ada_for_the_C_or_Java_Developer-cc.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Ada/RM-Final.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Ada/guide-c2ada.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Angular/Angular2NotesForProfessionals.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
AngularJS/AngularJSNotesForProfessionals.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Arduino/Arduino_-_MakeUseOf.com.pdf.txt
ADDED
@@ -0,0 +1,1283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
By Brad Kendall
|
2 |
+
http://www.bradkendall.ca/
|
3 |
+
|
4 |
+
Published August 2013
|
5 |
+
|
6 |
+
share:
|
7 |
+
|
8 |
+
This manual is the intellectual property of MakeUseOf. It must only be published in its original form. Using
|
9 |
+
parts or republishing altered parts of this guide is prohibited without permission from MakeUseOf.com
|
10 |
+
|
11 |
+
Think you’ve got what it takes to write a manual for MakeUseOf.com? We’re always willing to hear a pitch!
|
12 |
+
Send your ideas to justinpot@makeuseof.com.
|
13 |
+
|
14 |
+
Table Of Contents
|
15 |
+
|
16 |
+
1. Intro to the Arduino
|
17 |
+
|
18 |
+
2. What Can You Do With an Arduino?
|
19 |
+
|
20 |
+
3. What Is Inside an Arduino?
|
21 |
+
|
22 |
+
4. What You Will Need For This Guide
|
23 |
+
|
24 |
+
5. Electrical Component Overview
|
25 |
+
|
26 |
+
5.1 What is a Breadboard?
|
27 |
+
|
28 |
+
5.2 What is an LED?
|
29 |
+
|
30 |
+
5.3 What is a Photo Resistor?
|
31 |
+
|
32 |
+
5.4 What is a Tactile Switch?
|
33 |
+
|
34 |
+
5.5 What is a Piezo Speaker?
|
35 |
+
|
36 |
+
5.6 What is a Resistor?
|
37 |
+
|
38 |
+
5.7 What are Jumper Wires?
|
39 |
+
|
40 |
+
6. Programming Overview
|
41 |
+
|
42 |
+
6.1 Variables
|
43 |
+
|
44 |
+
6.2 Functions
|
45 |
+
|
46 |
+
6.3 Logic Overview
|
47 |
+
|
48 |
+
== - The Equals operator
|
49 |
+
|
50 |
+
&& - The AND operator
|
51 |
+
|
52 |
+
|| - The OR operator
|
53 |
+
|
54 |
+
! - The NOT operator
|
55 |
+
|
56 |
+
Using Multiple Expressions
|
57 |
+
|
58 |
+
7. Setting Up Your Arduino
|
59 |
+
|
60 |
+
7.1 Installing the Arduino IDE on Windows
|
61 |
+
|
62 |
+
Step 1: Download the Arduino software
|
63 |
+
|
64 |
+
Step 2: Install the software
|
65 |
+
|
66 |
+
7.2 Installing the Arduino IDE on Mac OS X
|
67 |
+
|
68 |
+
Step 1: Download the Arduino software
|
69 |
+
|
70 |
+
Step 2: Install the software
|
71 |
+
|
72 |
+
7.3 Installing the Arduino IDE on Ubuntu/ Linux
|
73 |
+
|
74 |
+
7.4 Running the Arduino Software
|
75 |
+
|
76 |
+
5
|
77 |
+
|
78 |
+
6
|
79 |
+
|
80 |
+
7
|
81 |
+
|
82 |
+
8
|
83 |
+
|
84 |
+
9
|
85 |
+
|
86 |
+
9
|
87 |
+
|
88 |
+
9
|
89 |
+
|
90 |
+
10
|
91 |
+
|
92 |
+
10
|
93 |
+
|
94 |
+
10
|
95 |
+
|
96 |
+
11
|
97 |
+
|
98 |
+
11
|
99 |
+
|
100 |
+
12
|
101 |
+
|
102 |
+
12
|
103 |
+
|
104 |
+
12
|
105 |
+
|
106 |
+
12
|
107 |
+
|
108 |
+
13
|
109 |
+
|
110 |
+
13
|
111 |
+
|
112 |
+
13
|
113 |
+
|
114 |
+
13
|
115 |
+
|
116 |
+
13
|
117 |
+
|
118 |
+
14
|
119 |
+
|
120 |
+
14
|
121 |
+
|
122 |
+
14
|
123 |
+
|
124 |
+
14
|
125 |
+
|
126 |
+
15
|
127 |
+
|
128 |
+
15
|
129 |
+
|
130 |
+
15
|
131 |
+
|
132 |
+
15
|
133 |
+
|
134 |
+
15
|
135 |
+
|
136 |
+
HTTP://MAKEUSEOF.COM
|
137 |
+
BRAD KENDALL, HTTP://WWW.BRADKENDALL.CA
|
138 |
+
|
139 |
+
3
|
140 |
+
|
141 |
+
share:
|
142 |
+
|
143 |
+
GETTING STARTED WITH ARDUINO
|
144 |
+
8. Starter Projects
|
145 |
+
|
146 |
+
8.1 Communicating Between Your Arduino and Your PC
|
147 |
+
|
148 |
+
Reading from the Serial Port
|
149 |
+
|
150 |
+
8.2 Building a Calculator
|
151 |
+
|
152 |
+
8.3 Turning on an LED
|
153 |
+
|
154 |
+
8.4 Making Your LED Blink
|
155 |
+
|
156 |
+
8.5 Making Multiple LEDs Blink
|
157 |
+
|
158 |
+
8.6 Pushbuttons with a Pull-up Resistor
|
159 |
+
|
160 |
+
8.7 Turning on an LED with a Pushbutton
|
161 |
+
|
162 |
+
8.8 Control an LED’s Brightness
|
163 |
+
|
164 |
+
8.9 Observing Light with your Arduino
|
165 |
+
|
166 |
+
8.10 Making Music with your Arduino
|
167 |
+
|
168 |
+
9. Where to go From Here
|
169 |
+
|
170 |
+
17
|
171 |
+
|
172 |
+
17
|
173 |
+
|
174 |
+
17
|
175 |
+
|
176 |
+
17
|
177 |
+
|
178 |
+
20
|
179 |
+
|
180 |
+
21
|
181 |
+
|
182 |
+
23
|
183 |
+
|
184 |
+
25
|
185 |
+
|
186 |
+
26
|
187 |
+
|
188 |
+
27
|
189 |
+
|
190 |
+
28
|
191 |
+
|
192 |
+
30
|
193 |
+
|
194 |
+
32
|
195 |
+
|
196 |
+
HTTP://MAKEUSEOF.COM
|
197 |
+
BRAD KENDALL, HTTP://WWW.BRADKENDALL.CA
|
198 |
+
|
199 |
+
4
|
200 |
+
|
201 |
+
share:
|
202 |
+
|
203 |
+
GETTING STARTED WITH ARDUINO1. Intro to the Arduino
|
204 |
+
|
205 |
+
Arduino is an open-source electronics prototyping platform based on flexible, easy-to use hardware and software. It’s
|
206 |
+
intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environments.
|
207 |
+
|
208 |
+
Arduino can sense the environment by receiving input from a variety of sensors and can affect its surroundings by
|
209 |
+
controlling lights, motors, and other actuators. The microcontroller on the board is programmed using the Arduino
|
210 |
+
programming language and the Arduino Development Environment. Arduino projects can be stand-alone, or they can
|
211 |
+
communicate with software running on a computer.
|
212 |
+
|
213 |
+
There are plenty of other microcontrollers available. So you may be asking, why choose the Arduino? Arduino really
|
214 |
+
simplifies the process of building projects on a microcontroller making it a great platform for amateurs. You can easily
|
215 |
+
start working on one with no previous electronics experience.
|
216 |
+
|
217 |
+
That is what this guide is about.
|
218 |
+
|
219 |
+
In addition to Arduino’s simplicity, it is also inexpensive, cross-platform and open source. The Arduino is based on
|
220 |
+
Atmel’s ATMEGA8 and ATMEGA168 microcontrollers. The plans for the modules are published under a Creative Com-
|
221 |
+
mons license, so experienced hobbyists and professionals can make their own version of the Arduino, extending it and
|
222 |
+
improving it.
|
223 |
+
|
224 |
+
Believe it or not, even relatively inexperienced users can build a version of the Arduino module on a breadboard in
|
225 |
+
order to understand how it works and save a little bit of money.
|
226 |
+
|
227 |
+
2. What Can You Do With an Arduino?
|
228 |
+
|
229 |
+
There is a lot you can do with an Arduino. An Arduino can basically do anything by interfacing sensors with a com-
|
230 |
+
puter. This would allow you to take any sensor and have any action applied with the readings. For example (in one of
|
231 |
+
our projects) we will read the level of light in a room and adjust an LED’s brightness to react based on that input. This
|
232 |
+
of course is a simple example of what you can do with an Arduino. A more complicated example would be to read from
|
233 |
+
multiple sensors and use that data to affect other outputs. Think of the possibility of wiring your house with all sorts
|
234 |
+
of different sensors (photocells, oxygen sensors, thermometers) and having it adjust your blinds, air conditioner and
|
235 |
+
furnace and make your house a more comfortable place.
|
236 |
+
|
237 |
+
Hackers have used Arduinos to create some amazing electronics projects. Things like:
|
238 |
+
|
239 |
+
• Robots
|
240 |
+
|
241 |
+
• Breathalyzers
|
242 |
+
|
243 |
+
• Remote controlled cars
|
244 |
+
|
245 |
+
•
|
246 |
+
|
247 |
+
3d printers
|
248 |
+
|
249 |
+
• Video games
|
250 |
+
|
251 |
+
• Home automation systems
|
252 |
+
|
253 |
+
And much more. Read about more great examples of Arduino projects.
|
254 |
+
|
255 |
+
3. What Is Inside an Arduino?
|
256 |
+
|
257 |
+
Although there are many different types of Arduino boards available, this manual focuses on the Arduino Uno. This is
|
258 |
+
the most popular Arduino board around. So what makes this thing tick? Here are the specifications:
|
259 |
+
|
260 |
+
• Processor: 16 Mhz ATmega328
|
261 |
+
|
262 |
+
• Flash memory: 32 KB
|
263 |
+
|
264 |
+
• Ram: 2kb
|
265 |
+
|
266 |
+
• Operating Voltage: 5V
|
267 |
+
|
268 |
+
•
|
269 |
+
|
270 |
+
Input Voltage: 7-12 V
|
271 |
+
|
272 |
+
• Number of analog inputs: 6
|
273 |
+
|
274 |
+
• Number of digital I/O: 14 (6 of them pwm)
|
275 |
+
|
276 |
+
The specs may seem meager compared to your desktop computer, but remember that the Arduino is an embedded
|
277 |
+
device. We have a lot less to process than your desktop.
|
278 |
+
|
279 |
+
Another wonderful feature of the Arduino is the ability to use what are called “Shields”. Although we will not be cov-
|
280 |
+
ering shields in this manual, an Arduino shield will give you crazy functionality like you wouldn’t believe. Check out
|
281 |
+
this list of some really cool Arduino shields to take your projects to the next level.
|
282 |
+
|
283 |
+
4. What You Will Need For This Guide
|
284 |
+
|
285 |
+
Below you will find a shopping list of the components we will use for this manual. All these components should come
|
286 |
+
in under $50.00 USD. This should be enough to give you a good understanding of basic electronics and have enough
|
287 |
+
components to build some pretty cool projects.
|
288 |
+
|
289 |
+
•
|
290 |
+
|
291 |
+
•
|
292 |
+
|
293 |
+
•
|
294 |
+
|
295 |
+
•
|
296 |
+
|
297 |
+
•
|
298 |
+
|
299 |
+
•
|
300 |
+
|
301 |
+
•
|
302 |
+
|
303 |
+
•
|
304 |
+
|
305 |
+
•
|
306 |
+
|
307 |
+
•
|
308 |
+
|
309 |
+
•
|
310 |
+
|
311 |
+
1x Arduino Uno Microcontroller
|
312 |
+
|
313 |
+
1 x USB A-B Cable (same as your printer takes)
|
314 |
+
|
315 |
+
1x Breadboard
|
316 |
+
|
317 |
+
2 x LEDs
|
318 |
+
|
319 |
+
1 x Photo Resistor
|
320 |
+
|
321 |
+
1 x Tactile Switch
|
322 |
+
|
323 |
+
1 x Piezo Speaker
|
324 |
+
|
325 |
+
1 x 10 k-Ohm Resistors
|
326 |
+
|
327 |
+
1 x 2 k-Ohm Resistors
|
328 |
+
|
329 |
+
2 x 1 K-Ohm Resistors
|
330 |
+
|
331 |
+
1 x Jumper Wire Kit
|
332 |
+
|
333 |
+
5. Electrical Component Overview
|
334 |
+
|
335 |
+
5.1 What is a Breadboard?
|
336 |
+
Breadboards are blocks of plastic with holes into which wires can be inserted. The holes are connected electrically, so
|
337 |
+
that wires stuck in the connected holes are also connected electrically.
|
338 |
+
|
339 |
+
The connected holes are arranged in rows, in groups of five, so that up to five parts can be quickly connected just by
|
340 |
+
plugging their leads into connected holes in the breadboard. When you want to rearrange a circuit, just pull the wire or
|
341 |
+
part out of the hole, and move it or replace it. The breadboard I recommended also includes power and ground lanes
|
342 |
+
on each side for easy power management.
|
343 |
+
|
344 |
+
5.2 What is an LED?
|
345 |
+
An LED, short for Light Emitting Diode, is a semiconductor light source. LEDs are typically used as visual indicators.
|
346 |
+
For instance, your new Arduino microcontroller has an LED on pin 13 that we frequently use to indicate an action or
|
347 |
+
event.
|
348 |
+
|
349 |
+
5.3 What is a Photo Resistor?
|
350 |
+
A photo resistor allows us to measure light by decreasing its resistance when it detects an increase of light intensity.
|
351 |
+
|
352 |
+
5.4 What is a Tactile Switch?
|
353 |
+
A tactile switch is an electric switch that controls the flow of electricity. When pressed, the switch completes the circuit.
|
354 |
+
Basically, it is a button.
|
355 |
+
|
356 |
+
5.5 What is a Piezo Speaker?
|
357 |
+
A piezo speaker is a single frequency beeper that converts an electrical signal into a tone. This will allow your Arduino
|
358 |
+
to sing to you.
|
359 |
+
|
360 |
+
5.6 What is a Resistor?
|
361 |
+
A resistor is an electrical component that limits or regulates the flow of electricity.
|
362 |
+
|
363 |
+
5.7 What are Jumper Wires?
|
364 |
+
Jumper wires are short wires that are used for prototyping circuits. These are what you will use to connect the various
|
365 |
+
components electrically to your Arduino.
|
366 |
+
|
367 |
+
6. Programming Overview
|
368 |
+
|
369 |
+
If you’re not too familiar with programming, this guide should get you used to some of the fundamentals. If you’d like to
|
370 |
+
learn more about Arduino-specific functions, http://www.arduino.cc/en/Reference/HomePage is an excellent resource.
|
371 |
+
|
372 |
+
6.1 Variables
|
373 |
+
A variable is defined as a quantity that can assume any of a set of values. In the Arduino programming language, vari-
|
374 |
+
ables have types associated with them, which provide the set of valid values the variable can hold. Some languages
|
375 |
+
are not strict and allow a variable to hold nearly anything, but that is out of the scope of this manual.
|
376 |
+
|
377 |
+
For example, a variable with type ‘int’ can only hold integer values like 1 or 12, and not 12.5 or “cats”. Unfortunately,
|
378 |
+
no variable is capable of holding a cat, something the programming world is quite upset about.
|
379 |
+
|
380 |
+
Variables are an excellent resource, as they improve code readability and reuse, and are extremely convenient for use
|
381 |
+
as temporary storage.
|
382 |
+
|
383 |
+
Before using a variable, you must declare it. This merely lets the Arduino compiler know what data type your variable
|
384 |
+
will hold.
|
385 |
+
|
386 |
+
An example of a variable declaration is as follows:
|
387 |
+
|
388 |
+
int itemCount;
|
389 |
+
In this case, the variable will be of type int, and therefore will only accept integers.
|
390 |
+
|
391 |
+
Here are a few example assignments and operations.
|
392 |
+
|
393 |
+
itemCount = 4; itemCount = itemCount + 8; // itemCount now holds the value 12. itemCount =
|
394 |
+
“10”; // This will not compile.
|
395 |
+
6.2 Functions
|
396 |
+
A function is essentially a group of instructions that perform a specific task. There are many built-in functions, such as
|
397 |
+
digitalWrite() or tone(). In those cases, you don’t necessarily have to see the code, but can still reap the benefits. You
|
398 |
+
can also specify your own functions.
|
399 |
+
|
400 |
+
The general form of a function is:
|
401 |
+
|
402 |
+
[return type] [function name] ({arguments}) { [ Code to execute ] }
|
403 |
+
Note that functions can return data, as illustrated by the function having a return type.
|
404 |
+
|
405 |
+
In many cases, there is no data to return, and in that case, the keyword ‘void’ would be used.
|
406 |
+
|
407 |
+
The function name is a user-friendly ‘handle’ to reference later (digitalWrite would be the function name for the digi-
|
408 |
+
talWrite function).
|
409 |
+
|
410 |
+
A function can accept zero or more arguments. Each argument must be of the form [datatype] [identifier]. For exam-
|
411 |
+
ple, if we called a function foo as such:
|
412 |
+
|
413 |
+
foo(10);
|
414 |
+
The function header for foo would have to look like:
|
415 |
+
|
416 |
+
void foo(int number) { }
|
417 |
+
In the function, code can reference ‘number’ to retrieve the passed value. Outside of the function, ‘number’ would be
|
418 |
+
undefined.
|
419 |
+
|
420 |
+
Say we want to write a function to multiply two numbers, for whatever reason. This function would look like:
|
421 |
+
|
422 |
+
int multiply(int num1, int num2) { int result; result = num1 * num2; return result; }
|
423 |
+
Note that this could simply look like:
|
424 |
+
|
425 |
+
int multiply(int num1, int num2) { return num1 * num2; }
|
426 |
+
It’s usually a good idea to be liberal with the use of spaces, as it makes for much easier debugging. To each their own,
|
427 |
+
however.
|
428 |
+
|
429 |
+
6.3 Logic Overview
|
430 |
+
|
431 |
+
You’ll often find yourself wanting to execute certain code under certain conditions. This will give you a quick overview
|
432 |
+
of the logical operators you have to work with.
|
433 |
+
|
434 |
+
First up, with the exception of the NOT operator, each logical operation takes two operands.
|
435 |
+
|
436 |
+
== - The Equals operator
|
437 |
+
This operator ensures that both operands are equal to one another. To test whether or not the operands are not equal
|
438 |
+
to one another, use the != (not-equals) operator.
|
439 |
+
|
440 |
+
Example:
|
441 |
+
|
442 |
+
4 == 4 (true) 4 == 5 (false) 4 != 5 (true)
|
443 |
+
&& - The AND operator
|
444 |
+
The AND operator is quite similar to the equals operator, except it does not evaluate to true when both operands are
|
445 |
+
false.
|
446 |
+
|
447 |
+
For example: (true && true) evaluates to true, while (true && false) and (false && false) both evaluate to false.
|
448 |
+
|
449 |
+
|| - The OR operator
|
450 |
+
The OR operator will evaluate to true so long as at least one of the two operands is true.
|
451 |
+
|
452 |
+
The only time OR will evaluate to false is if both the operands are false.
|
453 |
+
|
454 |
+
! - The NOT operator
|
455 |
+
This simply flips the truthiness of the operand specified. !false == true.
|
456 |
+
|
457 |
+
Using Multiple Expressions
|
458 |
+
Sometimes you’d like to have more than one test. Fortunately, since (as above), something like (false == true) will
|
459 |
+
evaluate to false, nesting statements in brackets works, and the statements in brackets will be evaluated first.
|
460 |
+
|
461 |
+
For example:
|
462 |
+
|
463 |
+
if (( a != b) && (b > 12))
|
464 |
+
a != b and b > 12 will have to be evaluated first, as their outcome determines whether the entire logical expression is
|
465 |
+
true.
|
466 |
+
|
467 |
+
The past two sections should have given you enough basic knowledge to get started with our projects below. If it all
|
468 |
+
seems a little complicated, don’t worry. It will make a lot more sense when we apply it in a practical sense.
|
469 |
+
|
470 |
+
7. Setting Up Your Arduino
|
471 |
+
|
472 |
+
Before we can start on our projects, we first need to get your Arduino talking to your computer. We need to do this so
|
473 |
+
you can compile and send code for your Arduino to execute.
|
474 |
+
|
475 |
+
7.1 Installing the Arduino IDE on Windows
|
476 |
+
Step 1: Download the Arduino software
|
477 |
+
Go to http://arduino.cc/en/Main/Software and download the Arduino Software for your Windows.
|
478 |
+
|
479 |
+
Step 2: Install the software
|
480 |
+
Install the Drivers:
|
481 |
+
|
482 |
+
• Plug in your board and wait for Windows to begin its driver installation process. After a few mo-
|
483 |
+
|
484 |
+
ments, the process will fail, despite its best efforts.
|
485 |
+
|
486 |
+
• Click on the Start Menu, and open up the Control Panel.
|
487 |
+
|
488 |
+
• While in the Control Panel, navigate to System and Security. Next, click on System. Once the
|
489 |
+
|
490 |
+
System window is up, open the Device Manager.
|
491 |
+
|
492 |
+
•
|
493 |
+
|
494 |
+
Look under Ports (COM & LPT). You should see an open port named “Arduino UNO (COMxx)”.
|
495 |
+
|
496 |
+
• Right click on the “Arduino UNO (COMxx)” port and choose the “Update Driver Software” option.
|
497 |
+
|
498 |
+
• Next, choose the “Browse my computer for Driver software” option.
|
499 |
+
|
500 |
+
• Finally, navigate to and select the Uno’s driver file, named “ArduinoUNO.inf”, located in the “Driv-
|
501 |
+
|
502 |
+
ers” folder of the Arduino Software download.
|
503 |
+
|
504 |
+
• Windows will finish up the driver installation from there.
|
505 |
+
|
506 |
+
7.2 Installing the Arduino IDE on Mac OS X
|
507 |
+
Step 1: Download the Arduino software
|
508 |
+
Go to http://arduino.cc/en/Main/Software and download the Arduino Software for your Mac OS X.
|
509 |
+
|
510 |
+
Step 2: Install the software
|
511 |
+
The disk image (.dmg) should mount automatically. If it doesn’t, double-click it. It should look like the following image.
|
512 |
+
|
513 |
+
Copy the Arduino application into the Applications folder (or elsewhere on your computer). Since you’re using an Ar-
|
514 |
+
duino Uno, you don’t have any drivers to install.
|
515 |
+
|
516 |
+
7.3 Installing the Arduino IDE on Ubuntu/ Linux
|
517 |
+
Install gcc-avr and avr-libc from the Terminal.
|
518 |
+
|
519 |
+
sudo apt-get install gcc-avr avr-libc
|
520 |
+
|
521 |
+
If you don’t have openjdk-6-jre already, install and configure that too:
|
522 |
+
|
523 |
+
sudo apt-get install openjdk-6-jre sudo update-alternatives --config java
|
524 |
+
|
525 |
+
Select the correct JRE if you have more than one installed.
|
526 |
+
|
527 |
+
Go to http://arduino.cc/en/Main/Software/ and download the Arduino Software for Linux. You can untar and run it with
|
528 |
+
the following command:
|
529 |
+
|
530 |
+
tar xzvf arduino-x.x.x-linux64.tgz cd arduino-1.0.1 ./arduino
|
531 |
+
|
532 |
+
7.4 Running the Arduino Software
|
533 |
+
Now that our software is installed and our Arduino is setup, let’s verify everything is working. The easiest way to do
|
534 |
+
this is by using the “Blink” sample application.
|
535 |
+
|
536 |
+
1. Open the Arduino Software by Double-clicking the Arduino Application (./arduino on Linux).
|
537 |
+
|
538 |
+
2. Make sure the board is still connected to your computer.
|
539 |
+
|
540 |
+
3. Open the LED blink example sketch: File > Examples > 1.Basics > Blink. You should see the
|
541 |
+
|
542 |
+
code for the application open and it should look like this:
|
543 |
+
|
544 |
+
|
545 |
+
|
546 |
+
|
547 |
+
4. You’ll need to select the entry in the Tools > Board menu that corresponds to your Arduino. Se-
|
548 |
+
|
549 |
+
lect the Arduino Uno Option.
|
550 |
+
|
551 |
+
5. Select the serial device of the Arduino board from the Tools > Serial Port menu. On Windows,
|
552 |
+
|
553 |
+
This is likely to be COM3 or higher. On the Mac or on Linux, this should be something with ‘/dev/
|
554 |
+
tty.usbmodem ‘ in it.
|
555 |
+
|
556 |
+
6. Now, simply click the “Upload” button in the environment. Wait a few seconds - you should see
|
557 |
+
|
558 |
+
the RX and TX LEDs on the Arduino flashing. If the upload is successful, the message “Done up-
|
559 |
+
loading.” will appear in the status bar.
|
560 |
+
|
561 |
+
A few seconds after the upload finishes, you should see the pin 13 (L) LED on the board start to blink. If it does, con-
|
562 |
+
gratulations! You’ve got your Arduino up and running.
|
563 |
+
|
564 |
+
8. Starter Projects
|
565 |
+
|
566 |
+
Okay, now is when the real fun begins. Let’s get started.
|
567 |
+
|
568 |
+
8.1 Communicating Between Your Arduino and Your PC
|
569 |
+
Most of the communication you’ll be doing with the Arduino (for now) will be done via the Serial port (The USB cord).
|
570 |
+
This is quite trivial to set up on the Arduino. Merely add the following line to your setup() method:
|
571 |
+
|
572 |
+
Serial.begin(9600);
|
573 |
+
9600 is the baud rate, something we will not get into here (it essentially means the number of signal changes made
|
574 |
+
per second, and merely ensures that the PC and the Arduino are on the same page in regards to this). Whenever you
|
575 |
+
would like to write something to the serial port, simply use the Serial.print or Serial.println function, as so:
|
576 |
+
|
577 |
+
Serial.print(“Hello world!”);
|
578 |
+
|
579 |
+
Reading from the Serial Port
|
580 |
+
Note that you will have to read in a single character at a time via the serial port, which is rather unfortunate. If you take
|
581 |
+
a peek at the sample code for our calculator application, specifically the waitForNum() method, you will see an exam-
|
582 |
+
ple of how to read in all characters entered, albeit in this case for a number.
|
583 |
+
|
584 |
+
8.2 Building a Calculator
|
585 |
+
To tie all of your new found programming knowledge together, we submit to you the following program that performs
|
586 |
+
basic mathematical operations. We have clearly commented the code, so you should be able to understand each step.
|
587 |
+
There is a download available for people who don’t like typing at: http://www.bradkendall.ca/arduino
|
588 |
+
|
589 |
+
Here we go!
|
590 |
+
|
591 |
+
/*
|
592 |
+
Example Arduino Calculator
|
593 |
+
Communication protocol: Send an ‘A’, ‘S’, ‘M’, or ‘D’ via serial, than two numbers. The arduino
|
594 |
+
will reply with the result of the operation on the two numbers, (first number first). Note that
|
595 |
+
the division will no doubt look strange - it is an integer division and therefore there will
|
596 |
+
not be anything after the decimal point.
|
597 |
+
*/
|
598 |
+
void setup() {
|
599 |
+
Serial.begin(9600);
|
600 |
+
Serial.println(“Calculator initiated.”);
|
601 |
+
}
|
602 |
+
/* loop()
|
603 |
+
This code gets executed over, and over, and over, and over, and over, and over, and over, and
|
604 |
+
over, and over, and over, and over, and over, and over, and over, and over, and over again.
|
605 |
+
Our loop pretty much starts the ‘waiting for input’ stage, where we wait for the user to input
|
606 |
+
a character (the mathematical operation), then two operands.
|
607 |
+
After we output the result, we let the loop get hit again, and joy is had by all!
|
608 |
+
*/
|
609 |
+
void loop() {
|
610 |
+
char operation;
|
611 |
+
int number1;
|
612 |
+
int number2; // hehe, Number 2.
|
613 |
+
int result; // Hold the result of the operation.
|
614 |
+
boolean success;
|
615 |
+
// Indicates whether the operation
|
616 |
+
// was successful (we knew what to
|
617 |
+
// do - nothing bad was inputted)
|
618 |
+
success = true;
|
619 |
+
// Go ahead and set success to true ;
|
620 |
+
// The only time we will be updating
|
621 |
+
// this variable now is to set it to
|
622 |
+
// false if we’ve encountered a
|
623 |
+
// problem.
|
624 |
+
|
625 |
+
Serial.println(“Pick an operation: ‘A’dd, ‘S’ubtract, ‘M’ultiply, or ‘D’ivide (Simply input the
|
626 |
+
first letter in quotes.)”);
|
627 |
+
// We have to wait for the user to send something
|
628 |
+
// here; the easiest way to do so is to simply loop
|
629 |
+
// and waitfor Serial.available() to be true.
|
630 |
+
while(Serial.available() == 0) {
|
631 |
+
; // ; indicates an empty statement. Or a sea
|
632 |
+
// monster in Nethack. God those suck.
|
633 |
+
}
|
634 |
+
// This loop will continue executing while Serial.
|
635 |
+
// available() == 0. Thus, it will be stuck here until
|
636 |
+
// the serial has a character waiting.
|
637 |
+
operation = Serial.read();
|
638 |
+
// We have to do the same thing to get the two
|
639 |
+
// operands (numbers).
|
640 |
+
// I have factored this code into a function so that
|
641 |
+
// I do not have to rewrite it twice. See if you can
|
642 |
+
// determine why I would not be able to use it (at
|
643 |
+
// least intuitively) to get the operation.
|
644 |
+
Serial.println(“Okay, now please enter the two numbers, one at a time!”);
|
645 |
+
number1 = waitForNum();
|
646 |
+
Serial.print(“Read: “);
|
647 |
+
Serial.println(number1);
|
648 |
+
number2 = waitForNum();
|
649 |
+
Serial.print(“Read: “);
|
650 |
+
Serial.println(number2);
|
651 |
+
// Now we have read in all the data we need. It is
|
652 |
+
// time to calculate the result. We will have to
|
653 |
+
// determine what operation the user specified, and
|
654 |
+
// perform the calculation from there.
|
655 |
+
Serial.print(“Operation: “);
|
656 |
+
if(operation == ‘A’)
|
657 |
+
{
|
658 |
+
// This checks to see if the user sent along the
|
659 |
+
// character ‘A’, specifying an add.
|
660 |
+
Serial.println(“ADD (Look, a kitty!)”);
|
661 |
+
result = number1 + number2;
|
662 |
+
} else if(operation == ‘S’)
|
663 |
+
{
|
664 |
+
// Note that the above condition will only be
|
665 |
+
// tested for if operation is not equal to ‘A’ -
|
666 |
+
// hence the else.
|
667 |
+
// This code executes if the operation is ‘S’ for
|
668 |
+
// subtract.
|
669 |
+
Serial.println(“Subtract”);
|
670 |
+
result = number1 - number2;
|
671 |
+
} else if(operation == ‘M’)
|
672 |
+
{
|
673 |
+
// In this case, we will be multiplying.
|
674 |
+
Serial.println(“Multiply”);
|
675 |
+
result = number1 * number2;
|
676 |
+
} else if(operation == ‘D’)
|
677 |
+
{
|
678 |
+
// Here we will be dividing.
|
679 |
+
Serial.println(“Divide”);
|
680 |
+
result = number1 / number2;
|
681 |
+
} else{
|
682 |
+
// This code will be used if the character
|
683 |
+
// specified doesn’t match anything - in other
|
684 |
+
// words, the user did not send A, S, D, or M,
|
685 |
+
// and we don’t know what to do.
|
686 |
+
// Hence, set ‘success’ to false
|
687 |
+
success = false;
|
688 |
+
|
689 |
+
}
|
690 |
+
// Now we should have our result. Time to send the
|
691 |
+
// user back something! (Then start over again! Joy!)
|
692 |
+
if(success)
|
693 |
+
{
|
694 |
+
// Note that print will not start a new
|
695 |
+
// line, and the next print statement will
|
696 |
+
// continue writing right
|
697 |
+
// where the previous one left off.
|
698 |
+
// Output the result.
|
699 |
+
Serial.print(“Result: “);
|
700 |
+
Serial.println(result);
|
701 |
+
} else
|
702 |
+
{
|
703 |
+
Serial.print(“Sorry, I don’t understand what you want me to do! (You inputted ‘”);
|
704 |
+
Serial.print(operation);
|
705 |
+
Serial.println(“’)”);
|
706 |
+
}
|
707 |
+
}
|
708 |
+
int waitForNum()
|
709 |
+
{
|
710 |
+
int ret;
|
711 |
+
while(Serial.available() == 0) { ;
|
712 |
+
}
|
713 |
+
// Why minus ‘0’? The value we’ll get from Serial.
|
714 |
+
// read() will be a character. What this means is
|
715 |
+
// that its numeric value will not necessarily
|
716 |
+
// reflect the number it represents. (Look at an
|
717 |
+
// ASCII table, the character ‘0’ actually has a
|
718 |
+
// decimal value of 48!)
|
719 |
+
// The take-away from this is that, since fortunately
|
720 |
+
// all the numbers are in sequence, you can simply
|
721 |
+
// subtract the decimal value of ‘0’ from
|
722 |
+
// whatever you read in, and you’ll be left with the
|
723 |
+
// number itself. ‘5’ - ‘0’ = 5 .
|
724 |
+
ret = Serial.read() - ‘0’;
|
725 |
+
// To handle numbers that span more than one
|
726 |
+
// character (like 124, which spans three), we must
|
727 |
+
// loop until there is no more input, and multiply
|
728 |
+
// each number we read by one (as 124 would come in
|
729 |
+
// like: 4 2 1
|
730 |
+
// And the number we build would be:
|
731 |
+
// (((1 * 10) + 2) * 10) + 4,
|
732 |
+
// or 124! The joys of the decimal numbering system!
|
733 |
+
// Note that the delays are merely to slow things
|
734 |
+
// down a bit - removing them would have the
|
735 |
+
// code execute too quickly to ‘notice’ more
|
736 |
+
// characters waiting to come in from Serial.
|
737 |
+
// A little strange, neh? Welcome to the joys of this
|
738 |
+
// type of thing. =]
|
739 |
+
delay(10);
|
740 |
+
while(Serial.available() != 0)
|
741 |
+
{
|
742 |
+
ret = ret * 10;
|
743 |
+
ret += Serial.read() - ‘0’;
|
744 |
+
delay(10);
|
745 |
+
}
|
746 |
+
return ret;
|
747 |
+
}
|
748 |
+
|
749 |
+
|
750 |
+
8.3 Turning on an LED
|
751 |
+
|
752 |
+
What You Need:
|
753 |
+
|
754 |
+
•
|
755 |
+
|
756 |
+
•
|
757 |
+
|
758 |
+
•
|
759 |
+
|
760 |
+
1 – LED
|
761 |
+
|
762 |
+
1 – Resistor – 1 KOhm (brown, black, red)
|
763 |
+
|
764 |
+
4 – Jumper Wires
|
765 |
+
|
766 |
+
You will build a circuit by plugging the LED and resistor leads into small holes called sockets on the breadboard.
|
767 |
+
|
768 |
+
Let’s get started!
|
769 |
+
|
770 |
+
Hardware Setup:
|
771 |
+
|
772 |
+
• Step 1 - Unplug the USB cord from your Arduino.
|
773 |
+
|
774 |
+
• Step 2 - Plug a jumper wire from the 5V port on your Arduino into the positive section of your
|
775 |
+
|
776 |
+
breadboard’s power lane.
|
777 |
+
|
778 |
+
• Step 3 - Plug a jumper wire from the GND port on your Arduino into the negative section of your
|
779 |
+
|
780 |
+
breadboard’s ground lane.
|
781 |
+
|
782 |
+
• Step 4 - Plug the LED’s cathode (the short lead) into the I-2 socket on your breadboard.
|
783 |
+
|
784 |
+
• Step 5 - Plug the LED��s anode (the long lead) into the I-4 socket on your breadboard.
|
785 |
+
|
786 |
+
• Step 6 - Plug one of the resistor’s leads into the H-4 socket on your breadboard.
|
787 |
+
|
788 |
+
• Step 7 - Plug the resistors other lead into the H-9 socket on your breadboard.
|
789 |
+
|
790 |
+
• Step 8 - Connect a jumper wire from your breadboard’s power lane to the J-9 socket on your
|
791 |
+
|
792 |
+
breadboard.
|
793 |
+
|
794 |
+
• Step 9 - Connect a jumper wire from your breadboard’s ground lane to the J-2 socket on your
|
795 |
+
|
796 |
+
breadboard.
|
797 |
+
|
798 |
+
• Step 10 - Reconnect the USB cable to your Arduino.
|
799 |
+
|
800 |
+
Summary: Once power is applied to the circuit, the LED will turn on. This is about as simple as a circuit gets.
|
801 |
+
|
802 |
+
8.4 Making Your LED Blink
|
803 |
+
What You Need:
|
804 |
+
|
805 |
+
•
|
806 |
+
|
807 |
+
•
|
808 |
+
|
809 |
+
•
|
810 |
+
|
811 |
+
1 – LED
|
812 |
+
|
813 |
+
1 – Resistor – 1 K Ohm (brown, black, red)
|
814 |
+
|
815 |
+
4 – Jumper Wires
|
816 |
+
|
817 |
+
Hardware Setup:
|
818 |
+
|
819 |
+
• Step 1 - Unplug the USB cord from your Arduino.
|
820 |
+
|
821 |
+
• Step 2 - Plug a jumper wire from the Digital IO pin 8 into the I-12 socket on your breadboard.
|
822 |
+
|
823 |
+
• Step 3 - Plug one of the resistor’s leads into the H-12 socket on your breadboard.
|
824 |
+
|
825 |
+
• Step 4 - Plug the resistor’s other lead into the H-4 socket on your breadboard.
|
826 |
+
|
827 |
+
• Step 5 - Plug the LED’s cathode (the short lead) into the I-2 socket on your breadboard.
|
828 |
+
|
829 |
+
• Step 6 - Plug the LED’s anode (the long lead) into the I-4 socket on your breadboard.
|
830 |
+
|
831 |
+
• Step 7 - Connect a jumper wire from your breadboard’s ground lane to the J-2 socket on your
|
832 |
+
|
833 |
+
breadboard. Ensure that the ground lane is still grounded.
|
834 |
+
|
835 |
+
• Step 8 - Reconnect the USB cable to your Arduino.
|
836 |
+
|
837 |
+
Software Setup:
|
838 |
+
|
839 |
+
Open up your Arduino Development Environment and create a new sketch (File > New).
|
840 |
+
|
841 |
+
Enter the following code into your sketch:
|
842 |
+
|
843 |
+
void setup() {
|
844 |
+
// initialize the digital pin as an output.
|
845 |
+
// Pin 8 is our output pin
|
846 |
+
pinMode(8, OUTPUT);
|
847 |
+
}
|
848 |
+
void loop() {
|
849 |
+
digitalWrite(8, HIGH); // set the LED on
|
850 |
+
delay(1000); // wait for a second
|
851 |
+
digitalWrite(8, LOW); // set the LED off
|
852 |
+
delay(1000); // wait for a second
|
853 |
+
}
|
854 |
+
|
855 |
+
After you enter the code, press the upload button and your LED should start blinking.
|
856 |
+
|
857 |
+
Summary: The digitalWrite(8, HIGH); command sets the output pin 8 on the Arduino to 5V. The digitalWrite(8, LOW);
|
858 |
+
command sets the output pin 8 on the Arduino to 0V. The delay(1000); command pauses execution on the Arduino for
|
859 |
+
1000 ms or 1 second. Since this in the loop() function, the code is called over and over again. Pretty cool, huh?
|
860 |
+
|
861 |
+
8.5 Making Multiple LEDs Blink
|
862 |
+
|
863 |
+
What You Need:
|
864 |
+
|
865 |
+
•
|
866 |
+
|
867 |
+
•
|
868 |
+
|
869 |
+
•
|
870 |
+
|
871 |
+
2 – LEDs
|
872 |
+
|
873 |
+
2 – Resistor – 1 K Ohm (brown, black, red)
|
874 |
+
|
875 |
+
4 – Jumper Wires
|
876 |
+
|
877 |
+
Hardware Setup:
|
878 |
+
|
879 |
+
• Step 1 - Unplug the USB cord from your Arduino.
|
880 |
+
|
881 |
+
• Step 2 - Setup the project board the same as in Project 3.
|
882 |
+
|
883 |
+
• Step 3 - Plug a jumper wire from the Digital IO pin 9 into the I-16 socket on your breadboard.
|
884 |
+
|
885 |
+
• Step 4 - Plug one of the resistor’s leads into the H-16 socket on your breadboard.
|
886 |
+
|
887 |
+
• Step 5 - Plug the resistor’s other lead into the H-24 socket on your breadboard.
|
888 |
+
|
889 |
+
• Step 6 - Plug the LED’s anode (the long lead) into the I-24 socket on your breadboard.
|
890 |
+
|
891 |
+
• Step 7 - Plug the LED’s cathode (the short lead) into the I-26 socket on your breadboard.
|
892 |
+
|
893 |
+
• Step 8 - Connect a jumper wire from your breadboard’s ground lane to the J-26 socket on your
|
894 |
+
|
895 |
+
breadboard. Ensure that the ground lane is still grounded.
|
896 |
+
|
897 |
+
• Step 9 - Reconnect the USB cable to your Arduino.
|
898 |
+
|
899 |
+
Software Setup:
|
900 |
+
|
901 |
+
Open up your Arduino Development Environment and create a new sketch (File > New).
|
902 |
+
|
903 |
+
Enter the following code into your sketch:
|
904 |
+
|
905 |
+
void setup() {
|
906 |
+
// initialize the digital pins as an output.
|
907 |
+
pinMode(8, OUTPUT);
|
908 |
+
pinMode(9, OUTPUT);
|
909 |
+
}
|
910 |
+
void loop() {
|
911 |
+
digitalWrite(8, HIGH); // set the LED on
|
912 |
+
digitalWrite(9, LOW); // set the LED on
|
913 |
+
|
914 |
+
delay(1000); // wait for a second
|
915 |
+
digitalWrite(8, LOW); // set the LED off
|
916 |
+
digitalWrite(9, HIGH); // set the LED on
|
917 |
+
delay(1000); // wait for a second
|
918 |
+
}
|
919 |
+
After you enter the code, press the upload button and both your LEDs should start blinking.
|
920 |
+
|
921 |
+
Summary: This project is exactly the same as the last project, except we have added an additional LED on output pin
|
922 |
+
9 that turns off when the other LED is on. Can you think of any other ways to expand on this?
|
923 |
+
|
924 |
+
8.6 Pushbuttons with a Pull-up Resistor
|
925 |
+
What You Need:
|
926 |
+
|
927 |
+
•
|
928 |
+
|
929 |
+
•
|
930 |
+
|
931 |
+
•
|
932 |
+
|
933 |
+
•
|
934 |
+
|
935 |
+
1 – Resistor 2 K Ohm (red-black-red)
|
936 |
+
|
937 |
+
1 – Resistor – 1 K Ohm (brown, black, red)
|
938 |
+
|
939 |
+
1 – Tactile Switch
|
940 |
+
|
941 |
+
5 – Jumper Wires
|
942 |
+
|
943 |
+
Hardware Setup:
|
944 |
+
|
945 |
+
• Step 1 - Unplug the USB cord from your Arduino.
|
946 |
+
|
947 |
+
• Step 2 - Connect a jumper wire from your breadboard’s power lane to the C-3 socket on your
|
948 |
+
|
949 |
+
breadboard. Ensure that the power lane is still connected.
|
950 |
+
|
951 |
+
• Step 3 - Plug one of the 2 K Ω resistor’s leads into the B-3 socket on your breadboard.
|
952 |
+
|
953 |
+
• Step 4 - Plug the 2 K Ω resistor’s other lead into the B-7 socket on your breadboard.
|
954 |
+
|
955 |
+
• Step 5 - Plug a tactile switch so the pins are in the F-9, F-7, E-9 and E-7 on your breadboard.
|
956 |
+
|
957 |
+
• Step 6 - Plug one of the 1K Ω resistor���s leads into the H-7 socket on your breadboard.
|
958 |
+
|
959 |
+
• Step 7 - Plug the 1K Ω resistors’ other lead into the H-14 socket on your breadboard.
|
960 |
+
|
961 |
+
• Step 8 - Plug a jumper wire from the Digital IO pin 9 into the I-14 socket on your breadboard.
|
962 |
+
|
963 |
+
• Step 9 - Connect a jumper wire from your breadboard’s ground lane to the H-9 socket on your
|
964 |
+
|
965 |
+
breadboard. Ensure that the ground lane is still connected.
|
966 |
+
|
967 |
+
• Step 10 - Reconnect the USB cable to your Arduino.
|
968 |
+
|
969 |
+
Software Setup:
|
970 |
+
|
971 |
+
Open up your Arduino Development Environment and create a new sketch (File > New).
|
972 |
+
|
973 |
+
Enter the following code into your sketch:
|
974 |
+
|
975 |
+
void setup() {
|
976 |
+
// initialize the digital pin 9 as an input.
|
977 |
+
pinMode(9, INPUT);
|
978 |
+
// initialize the serial port.
|
979 |
+
Serial.begin(9600);
|
980 |
+
}
|
981 |
+
void loop() {
|
982 |
+
int buttonStatus = digitalRead(9);
|
983 |
+
if (buttonStatus == LOW) //The button is down
|
984 |
+
{
|
985 |
+
Serial.println(“The button is down”);
|
986 |
+
}
|
987 |
+
}
|
988 |
+
|
989 |
+
After you enter the code, press the upload button and open the Serial Monitor (Tools > Serial Monitor). When you
|
990 |
+
press the tactile switch, the serial monitor should print “The button is down”.
|
991 |
+
|
992 |
+
Summary: This project reads the digital input for 5v (HIGH). When the button is pressed, the voltage is set to 0v
|
993 |
+
(LOW) and the Arduino executes the code in our if statement.
|
994 |
+
|
995 |
+
8.7 Turning on an LED with a Pushbutton
|
996 |
+
|
997 |
+
What You Need:
|
998 |
+
|
999 |
+
•
|
1000 |
+
|
1001 |
+
•
|
1002 |
+
|
1003 |
+
•
|
1004 |
+
|
1005 |
+
•
|
1006 |
+
|
1007 |
+
1 - LED
|
1008 |
+
|
1009 |
+
1 – Resistor – 1 K Ohm (brown, black, red)
|
1010 |
+
|
1011 |
+
1 – Tactile Switch
|
1012 |
+
|
1013 |
+
4 – Jumper Wires
|
1014 |
+
|
1015 |
+
Hardware Setup:
|
1016 |
+
|
1017 |
+
• Step 1 - Unplug the USB cord from your Arduino.
|
1018 |
+
|
1019 |
+
• Step 2 - Plug a tactile switch so the pins are in H-9, H-11, J-9 and J-11 on your breadboard.
|
1020 |
+
|
1021 |
+
• Step 3 - Plug a jumper wire from the GND port on your Arduino into the negative section on your
|
1022 |
+
|
1023 |
+
breadboard’s ground lane.
|
1024 |
+
|
1025 |
+
• Step 4 - Plug the LED’s cathode (the short lead) into the I-2 socket on your breadboard.
|
1026 |
+
|
1027 |
+
• Step 5 - Plug the LED’s anode (the long lead) into the I-4 socket on your breadboard.
|
1028 |
+
|
1029 |
+
• Step 6 - Plug one of the resistor’s leads into the H-4 socket on your breadboard.
|
1030 |
+
|
1031 |
+
• Step 7 - Plug the resistor’s other lead into the H-9 socket on your breadboard.
|
1032 |
+
|
1033 |
+
• Step 8 - Connect a jumper wire from your breadboard’s power lane to the G-11 socket on your
|
1034 |
+
|
1035 |
+
breadboard.
|
1036 |
+
|
1037 |
+
• Step 9 - Connect a jumper wire from your breadboard’s ground lane to the J-2 socket on your
|
1038 |
+
|
1039 |
+
breadboard.
|
1040 |
+
|
1041 |
+
• Step 10 - Reconnect the USB cable to your Arduino.
|
1042 |
+
|
1043 |
+
8.8 Control an LED’s Brightness
|
1044 |
+
What You Need:
|
1045 |
+
|
1046 |
+
•
|
1047 |
+
|
1048 |
+
•
|
1049 |
+
|
1050 |
+
•
|
1051 |
+
|
1052 |
+
•
|
1053 |
+
|
1054 |
+
1 – Photo Resistor
|
1055 |
+
|
1056 |
+
1 – Resistor – 2 K Ohm (red-black-red)
|
1057 |
+
|
1058 |
+
1 – LED
|
1059 |
+
|
1060 |
+
5 – Jumper Wires
|
1061 |
+
|
1062 |
+
Hardware Setup:
|
1063 |
+
|
1064 |
+
• Step 1 - Unplug the USB cord from your Arduino.
|
1065 |
+
|
1066 |
+
• Step 2 - Plug one of the photo resistor’s leads into the I-14 socket on your breadboard.
|
1067 |
+
|
1068 |
+
• Step 3 - Plug the photo resistor’s other lead into the I-15 socket on your breadboard.
|
1069 |
+
|
1070 |
+
• Step 4 - Plug the LED’s cathode (the short lead) into the H-17 socket on your breadboard.
|
1071 |
+
|
1072 |
+
• Step 5 - Plug the LED’s anode (the long lead) into the H-15 socket on your breadboard.
|
1073 |
+
|
1074 |
+
• Step 6 - Plug one of the resistor’s lead into the I-17 socket on your breadboard.
|
1075 |
+
|
1076 |
+
• Step 7 - Plug the resistor’s other lead into the I-22 socket on your breadboard.
|
1077 |
+
|
1078 |
+
• Step 8 - Connect a jumper wire from your breadboard’s power lane to the J-14 socket on your
|
1079 |
+
|
1080 |
+
breadboard. Ensure that the power lane is still connected.
|
1081 |
+
|
1082 |
+
• Step 9 - Connect a jumper wire from your breadboard’s ground lane to the J-22 socket on your
|
1083 |
+
|
1084 |
+
breadboard. Ensure that the ground lane is still connected.
|
1085 |
+
|
1086 |
+
• Step 10 - Reconnect the USB cable to your Arduino.
|
1087 |
+
|
1088 |
+
Summary: As you see, the resistance of the photo resistor decreases with more light. The lower the resistance, the
|
1089 |
+
brighter the LED. Combine this with the pull up resistor project (Chapter 8.6) and watch the opposite effect.
|
1090 |
+
|
1091 |
+
8.9 Observing Light with your Arduino
|
1092 |
+
What You Need:
|
1093 |
+
|
1094 |
+
•
|
1095 |
+
|
1096 |
+
1 – Photo Resistor
|
1097 |
+
|
1098 |
+
•
|
1099 |
+
|
1100 |
+
•
|
1101 |
+
|
1102 |
+
1 – Resistor – 10 K Ohm (brown-black-orange)
|
1103 |
+
|
1104 |
+
5 – Jumper Wires
|
1105 |
+
|
1106 |
+
Hardware Setup:
|
1107 |
+
|
1108 |
+
• Step 1 - Unplug the USB cord from your Arduino.
|
1109 |
+
|
1110 |
+
• Step 2 - Plug one of the photo resistor’s leads into the F-16 socket on your breadboard.
|
1111 |
+
|
1112 |
+
• Step 3 - Plug the photo resistor’s other lead into the F-15 socket on your breadboard.
|
1113 |
+
|
1114 |
+
• Step 4 - Plug one of the resistor’s leads into the I-15 socket on your breadboard.
|
1115 |
+
|
1116 |
+
• Step 5 - Plug the resistor’s other lead into the I-10 socket on your breadboard.
|
1117 |
+
|
1118 |
+
• Step 6 - Connect a jumper wire from your breadboard’s power lane to the G-16 socket on your
|
1119 |
+
|
1120 |
+
breadboard. Ensure that the power lane is still connected.
|
1121 |
+
|
1122 |
+
• Step 7 - Connect a jumper wire from your breadboard’s ground lane to the J-10 socket on your
|
1123 |
+
|
1124 |
+
breadboard. Ensure that the ground lane is still connected.
|
1125 |
+
|
1126 |
+
• Step 8 - Plug a jumper wire from the Analog IO pin 0 into the G-15 socket on your breadboard
|
1127 |
+
|
1128 |
+
• Step 9 - Reconnect the USB cable to your Arduino.
|
1129 |
+
|
1130 |
+
Software Setup:
|
1131 |
+
|
1132 |
+
Open up your Arduino Development Environment and create a new sketch (File > New).
|
1133 |
+
|
1134 |
+
Enter the following code into your sketch:
|
1135 |
+
|
1136 |
+
int lightPin = 0; //define a pin for Photo resistor
|
1137 |
+
void setup()
|
1138 |
+
{
|
1139 |
+
Serial.begin(9600); //Begin serial communication
|
1140 |
+
}
|
1141 |
+
void loop()
|
1142 |
+
{
|
1143 |
+
//Write the value of the photo resistor to the serial //monitor.
|
1144 |
+
int lightValue = analogRead(lightPin);
|
1145 |
+
Serial.println(lightValue);
|
1146 |
+
delay(1000); //pause for 1000 ms or 1 second.
|
1147 |
+
}
|
1148 |
+
|
1149 |
+
After you enter the code, press the upload button and open the Serial Monitor (Tools > Serial Monitor). The console
|
1150 |
+
should give a light reading in the form of an integer. When you reduce the amount of light, the number will be lower.
|
1151 |
+
|
1152 |
+
Summary: This project is the same as the previous project, except we are reading the values from your Arduino
|
1153 |
+
instead of outputting to an LED. The resistance of the photo resistor decreases with more light. You could use logic to
|
1154 |
+
reverse this effect!
|
1155 |
+
|
1156 |
+
8.10 Making Music with your Arduino
|
1157 |
+
What You Need:
|
1158 |
+
|
1159 |
+
•
|
1160 |
+
|
1161 |
+
•
|
1162 |
+
|
1163 |
+
1 – Piezo Speaker
|
1164 |
+
|
1165 |
+
3 – Jumper Wires
|
1166 |
+
|
1167 |
+
Hardware Setup:
|
1168 |
+
|
1169 |
+
• Step 1 - Unplug the USB cord from your Arduino.
|
1170 |
+
|
1171 |
+
• Step 2 - Plug the positive lead of your piezo speaker into the E-15 socket on your breadboard.
|
1172 |
+
|
1173 |
+
• Step 3 - Plug the negative lead of your piezo speaker into the F-15 socket on your breadboard.
|
1174 |
+
|
1175 |
+
• Step 4 - Plug a jumper wire from the Digital IO pin 8 into the A-15 socket on your breadboard.
|
1176 |
+
|
1177 |
+
• Step 5 - Connect a jumper wire from your breadboard’s ground lane to the J-15 socket on your
|
1178 |
+
|
1179 |
+
breadboard. Ensure that the ground lane is still connected.
|
1180 |
+
|
1181 |
+
• Step 6 - Reconnect the USB cable to your Arduino.
|
1182 |
+
|
1183 |
+
Easy, right?
|
1184 |
+
|
1185 |
+
Software Setup:
|
1186 |
+
|
1187 |
+
This project is included in the Examples Section. No typing on this one! Open up your Arduino Development Environ-
|
1188 |
+
ment .Open the toneMelody Example Sketch (File > Examples > Digital > toneMelody).
|
1189 |
+
|
1190 |
+
After you enter the code, press the upload button and your piezo speaker will start making noise. You can modify the
|
1191 |
+
sound by modifying the melody[] and noteDurations[] arrays.
|
1192 |
+
|
1193 |
+
Summary: This project produces sound out of the piezo speaker.
|
1194 |
+
|
1195 |
+
9. Where to go From Here
|
1196 |
+
|
1197 |
+
As you can see, the Arduino is an easy way to get into electronics and software. Hopefully you have seen that it is
|
1198 |
+
easy to build simple electronic projects with it. I hope you have realized that your projects don’t have to stay simple.
|
1199 |
+
You can build way more complex projects on top of these simple ones. Here are some of my favorite projects that
|
1200 |
+
would be a great next step:
|
1201 |
+
|
1202 |
+
• Create Christmas light ornaments
|
1203 |
+
|
1204 |
+
• Arduino Traffic light controller
|
1205 |
+
|
1206 |
+
• Arduino Shields to superpower your project
|
1207 |
+
|
1208 |
+
• Make your own Arduino
|
1209 |
+
|
1210 |
+
• Build your own pong game with an Arduino
|
1211 |
+
|
1212 |
+
• Connect your Arduino to the internet
|
1213 |
+
|
1214 |
+
• Create a home automation system with your Arduino
|
1215 |
+
|
1216 |
+
Did you like this PDF Guide? Then why not visit MakeUseOf.com for daily posts on
|
1217 |
+
cool websites, free software and internet tips?
|
1218 |
+
|
1219 |
+
If you want more great guides like this, why not subscribe to MakeUseOf and receive
|
1220 |
+
instant access to 50+ PDF Guides like this one covering wide range of topics. More-
|
1221 |
+
over, you will be able to download free Cheat Sheets, Free Giveaways and other cool
|
1222 |
+
things.
|
1223 |
+
|
1224 |
+
Home:
|
1225 |
+
|
1226 |
+
http://www.makeuseof.com
|
1227 |
+
|
1228 |
+
MakeUseOf Answers:
|
1229 |
+
|
1230 |
+
http://www.makeuseof.com/answers
|
1231 |
+
|
1232 |
+
PDF Guides:
|
1233 |
+
|
1234 |
+
Tech Deals:
|
1235 |
+
|
1236 |
+
http://www.makeuseof.com/pages/
|
1237 |
+
|
1238 |
+
http://www.makeuseof.com/pages/hot-tech-deals
|
1239 |
+
|
1240 |
+
Follow MakeUseOf:
|
1241 |
+
|
1242 |
+
RSS Feed:
|
1243 |
+
|
1244 |
+
Newsletter:
|
1245 |
+
|
1246 |
+
Facebook:
|
1247 |
+
|
1248 |
+
Twitter:
|
1249 |
+
|
1250 |
+
http://feedproxy.google.com/Makeuseof
|
1251 |
+
|
1252 |
+
http://www.makeuseof.com/pages/subscribe-to-makeuseof-newsletter
|
1253 |
+
|
1254 |
+
http://www.facebook.com/makeuseof
|
1255 |
+
|
1256 |
+
http://www.twitter.com/Makeuseof
|
1257 |
+
|
1258 |
+
Think you’ve got what it takes to write a manual for MakeUseOf.com? We’re always willing
|
1259 |
+
to hear a pitch! Send your ideas to justinpot@makeuseof.com.
|
1260 |
+
|
1261 |
+
|
1262 |
+
|
1263 |
+
|
1264 |
+
|
1265 |
+
|
1266 |
+
|
1267 |
+
|
1268 |
+
|
1269 |
+
|
1270 |
+
|
1271 |
+
|
1272 |
+
|
1273 |
+
|
1274 |
+
|
1275 |
+
|
1276 |
+
|
1277 |
+
|
1278 |
+
|
1279 |
+
Download Other MakeUseOf PDF Guides!
|
1280 |
+
|
1281 |
+
http://makeuseof.com/pages
|
1282 |
+
|
1283 |
+
|
Arduino/Arduino_Projects_Book.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Arduino/arduino-tips-tricks-and-techniques.pdf.txt
ADDED
@@ -0,0 +1,996 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Error: Can't find stylesheet to import.
|
2 |
+
╷
|
3 |
+
4 │ @import "gist";
|
4 |
+
│ ^^^^^^
|
5 |
+
╵
|
6 |
+
app/assets/stylesheets/application.pdf.scss 4:9 root stylesheet
|
7 |
+
|
8 |
+
Arduino Tips, Tricks, and
|
9 |
+
Techniques
|
10 |
+
|
11 |
+
Created by lady ada
|
12 |
+
|
13 |
+
https://learn.adafruit.com/arduino-tips-tricks-and-techniques
|
14 |
+
Last updated on 2024-03-31 03:44:05 PM EDT
|
15 |
+
|
16 |
+
Table of Contents
|
17 |
+
|
18 |
+
Arduino UNO FAQ
|
19 |
+
|
20 |
+
•
|
21 |
+
•
|
22 |
+
•
|
23 |
+
•
|
24 |
+
|
25 |
+
Arduino Timeline
|
26 |
+
New USB Chip
|
27 |
+
More 3.3v power!
|
28 |
+
UNO R2 and R3
|
29 |
+
|
30 |
+
Arduino Libraries
|
31 |
+
|
32 |
+
•
|
33 |
+
•
|
34 |
+
•
|
35 |
+
•
|
36 |
+
•
|
37 |
+
•
|
38 |
+
|
39 |
+
Need Help Installing a Library?
|
40 |
+
What is a library?
|
41 |
+
Using Libraries
|
42 |
+
What's in a library?
|
43 |
+
It's important to remember!
|
44 |
+
How to install libraries
|
45 |
+
|
46 |
+
Bootloader
|
47 |
+
|
48 |
+
•
|
49 |
+
•
|
50 |
+
•
|
51 |
+
•
|
52 |
+
|
53 |
+
Bootloader for the Atmega328
|
54 |
+
"No-Wait" Bootloader
|
55 |
+
No-Hang Bootloader
|
56 |
+
Upload Sketches with AVRDUDE
|
57 |
+
|
58 |
+
Upgrade
|
59 |
+
|
60 |
+
•
|
61 |
+
•
|
62 |
+
•
|
63 |
+
|
64 |
+
Introduction
|
65 |
+
Replace the Chip
|
66 |
+
Download an Arduino IDE with ATmega328 compatibility
|
67 |
+
|
68 |
+
3.3V Conversion
|
69 |
+
|
70 |
+
•
|
71 |
+
•
|
72 |
+
•
|
73 |
+
|
74 |
+
Introduction
|
75 |
+
Replace the Regulator
|
76 |
+
Replacing the Fuse
|
77 |
+
|
78 |
+
Arduino Hacks
|
79 |
+
|
80 |
+
•
|
81 |
+
•
|
82 |
+
|
83 |
+
Bumpers
|
84 |
+
Free up some RAM
|
85 |
+
|
86 |
+
ArduinoISP
|
87 |
+
|
88 |
+
•
|
89 |
+
•
|
90 |
+
•
|
91 |
+
•
|
92 |
+
•
|
93 |
+
|
94 |
+
Introduction
|
95 |
+
Parts
|
96 |
+
Assemble
|
97 |
+
Load the Code
|
98 |
+
Bonus! Using with AVRdude
|
99 |
+
|
100 |
+
Support Forums
|
101 |
+
|
102 |
+
Arduino UNO FAQ
|
103 |
+
|
104 |
+
There's so many Arduino's out there, it may get a little confusing. We wanted
|
105 |
+
to clarify for people some of the changes in the latest version.
|
106 |
+
|
107 |
+
NB this is just our opinion and interpretation of some of the decisions made
|
108 |
+
by Arduino. We aren't associated with Arduino, and don't speak for them! If
|
109 |
+
you have to get an Official Response to your Arduino question please contact
|
110 |
+
them directly. Thx!
|
111 |
+
|
112 |
+
NB2 Still in progress, we're collecting common questions to answer. If you
|
113 |
+
have more questions, please post them in our forums (https://adafru.it/
|
114 |
+
forums).
|
115 |
+
|
116 |
+
Arduino Timeline
|
117 |
+
|
118 |
+
But first…some history! First there was the serial Arduino (what's the name
|
119 |
+
of it?) with RS232 which was not used outside of the Arduino team &
|
120 |
+
friends.
|
121 |
+
|
122 |
+
The first popularly manufactured Arduino was called the NG (New
|
123 |
+
Generation, like Star Trek, yknow?) The NG used the Atmega8 chip running
|
124 |
+
at 16 MHz and an FT232 chip for the USB interface. The bootloader takes
|
125 |
+
|
126 |
+
up 2KB of space and runs at 19200 baud.
|
127 |
+
|
128 |
+
The next version was the Diecimila. The Diecimila updated the chip from the
|
129 |
+
Atmega8 to the Atmega168. The great thing here is double the space and
|
130 |
+
memory (16K instead of 8K). It still ran at 16MHz. The Diecimila also added
|
131 |
+
two extra header pins for 3.3V (from the FTDI chip) and the reset pin which
|
132 |
+
can be handy when a shield is covering up the Reset button. The bootloader
|
133 |
+
takes up 2KB of space and runs at 19200 baud. Auto-resetting was also
|
134 |
+
added which makes life awesomer for everyone.
|
135 |
+
|
136 |
+
In 2009, the Duemilanove was released. This one also upgraded the chip
|
137 |
+
again, to the Atmega328. Yet another doubling of space and memory!
|
138 |
+
Another upgrade is now the power is automagically switched between USB
|
139 |
+
and DC-jack which removed the previous jumper. This makes it easier and
|
140 |
+
faster to move from programming to standalone and got rid of some
|
141 |
+
confusion. The bootloader takes up 2KB of space and runs at 57600 baud.
|
142 |
+
|
143 |
+
In 2010, we have the Uno! The Uno still uses the 328P chip and the power
|
144 |
+
switcher. It has a smaller bootloader called OptiBoot (more space for users'
|
145 |
+
projects) that runs at 115K. So even though the chip is the same, you get
|
146 |
+
another 1.5K of extra flash space that was previously used by the bootloader.
|
147 |
+
The FTDI chip has also been replaced with a atmega8u2 which allows for
|
148 |
+
different kinds of USB interfaces. Finally, there's an extra 3.3V regulator
|
149 |
+
(LP2985) for a better 3.3V supply. whew!
|
150 |
+
|
151 |
+
New USB Chip
|
152 |
+
|
153 |
+
So! All of the older Arduinos (NG, Diecimila and Duemilanove) have used an
|
154 |
+
FTDI chip (the FT232RL) to convert the TTL serial from the Arduino chip
|
155 |
+
(Atmel ATmega). This allows for printable debugging, connecting to software
|
156 |
+
like PureData/Max, Processing, Python, etc. etc. It also allows updating the
|
157 |
+
firmware via the serial bootloader.
|
158 |
+
|
159 |
+
The good news about the FT232RL has royalty-free drivers and pretty much
|
160 |
+
just works. The bad news is that it can -only- act as a USB/Serial port. It
|
161 |
+
can't act like a keyboard, mouse, disk drive, MIDI device, etc.
|
162 |
+
|
163 |
+
The Uno has changed that by exchanging the FT232RL chip with an
|
164 |
+
atmega8u2 chip. There are a few things that are possible with this new chip
|
165 |
+
but before we discuss that lets make it clear that by default, this chip acts
|
166 |
+
identically to the FTDI chip that it replaces. It's just a USB-serial port!
|
167 |
+
|
168 |
+
One improvement in updating the chip is that, previously, Mac users needed
|
169 |
+
to install FTDI drivers. The 8u2 imitates a 'generic' CDC serial device. So
|
170 |
+
now, Mac users do not have to install a driver. Windows users still need to
|
171 |
+
install the .INF file but luckily there are no drivers. This means there will be
|
172 |
+
fewer problems with new versions of windows. There is no way to have a
|
173 |
+
serial USB device that doesn't require an INF file in windows, sadly :(
|
174 |
+
|
175 |
+
The big thing that is nice about the 8u2 is that advanced users can turn it
|
176 |
+
into a different kind of USB device. For example it can act like a keyboard or
|
177 |
+
mouse. Or a disk driver. Or a MIDI interface, etc. Right now there are no
|
178 |
+
examples of how to do this, but we hope to post some shortly.
|
179 |
+
|
180 |
+
And, finally, going with the 8u2 reduced the price of the board which made
|
181 |
+
up for some of the other extras.
|
182 |
+
|
183 |
+
Why not just go with a atmega32u4?
|
184 |
+
|
185 |
+
The Arduino team has indicated they thought about this but preferred that
|
186 |
+
hackability of a DIP chip.
|
187 |
+
|
188 |
+
Right now there are a few Arduino's with a 32u4 chip such as the Leonardo,
|
189 |
+
Micro and Esplora
|
190 |
+
|
191 |
+
How can I change the USB firmware?
|
192 |
+
|
193 |
+
The 8u2 can be programmed by soldering a 6-pin ISP header (the R3 has the
|
194 |
+
6-pin header pre-soldered in) and using a standard AVR programmer. You
|
195 |
+
can also use the bootloader (DFU) in the 8u2. On first generation Unos, you
|
196 |
+
enable this by soldering the 10K resistor right underneath the board. (R2
|
197 |
+
and R3 versions of the Uno use the 16U2 and do not require the resistor!)
|
198 |
+
Again, we don't have any examples or tutorials but hope to shortly.
|
199 |
+
|
200 |
+
The code for the 8u2 is based on LUFA, Dean Cameran's totally awesome
|
201 |
+
USB-AVR library that has great examples and documentation. Its also
|
202 |
+
completely open source.
|
203 |
+
|
204 |
+
Does the Uno use a resonator or a crystal for
|
205 |
+
the processor clock?
|
206 |
+
|
207 |
+
The FT232RL had an internal oscillator whereas the 8u2 does not. That
|
208 |
+
means there is a 16mhz crystal next to the 8u2 to allow it to keep up with
|
209 |
+
precise USB timing.
|
210 |
+
|
211 |
+
On the other hand, the Atmega328p chip that is the core processor in the
|
212 |
+
Arduino now has a 16mhz ceramic resonator. Ceramic resonators are
|
213 |
+
slightly less precise than crystals but we have been assured that this one
|
214 |
+
was specified and works quite well.
|
215 |
+
|
216 |
+
So the Arduino is not as precise, timing-wise?
|
217 |
+
|
218 |
+
The short answer is: yes. The long answer is that most things that people are
|
219 |
+
doing with Arduino do not rely on 20ppm precision timing where 100ppm
|
220 |
+
would fail. For people who want long term precise timekeeping we suggest
|
221 |
+
going with a TCXO (temperature compensation crystal oscillator) - but you
|
222 |
+
would know if you needed that.
|
223 |
+
|
224 |
+
Why not have one 16Mhz crystal shared
|
225 |
+
between both?
|
226 |
+
|
227 |
+
Good question, technically you can. However, in practice the board did not
|
228 |
+
make it through FCC certification with one crystal (long traces with fast
|
229 |
+
squarewaves = lots of noise).
|
230 |
+
|
231 |
+
OK well lets say I don't care about that...
|
232 |
+
|
233 |
+
You can absolutely connect the CLKO out the crystal from the '8u2 to the
|
234 |
+
'328p but you're on your own as we don't think there will be any tutorials
|
235 |
+
about that.
|
236 |
+
|
237 |
+
Whats with the FCC logo on the back?
|
238 |
+
|
239 |
+
Arduino is now FCC certified! That means that the board by itself passes
|
240 |
+
FCC certification for electromagnetic emissions. It does not mean that your
|
241 |
+
project is FCC certified. The moment you change the Arduino, it's no longer
|
242 |
+
FCC certified (although we'd like some back-up documentation on this).
|
243 |
+
|
244 |
+
It is also, still, CE certified for Europeans.
|
245 |
+
|
246 |
+
A new Bootloader?
|
247 |
+
|
248 |
+
There's a new bootloader. It works just like the old one - being an STK500-
|
249 |
+
protocol compatible but its a quarter of the size! Down from 2K, the new
|
250 |
+
bootloader is a tiny 512b. This gives you more space for your project code!
|
251 |
+
Yay! It's also faster - 115K instead of 57.6k so you'll be uploading code in 3
|
252 |
+
seconds.
|
253 |
+
|
254 |
+
The Bad News is that you must make sure to select Uno in the Boards
|
255 |
+
menu!!! If you don't things will be confusing because the bootloader speed
|
256 |
+
is wrong, and you won't get that extra 1.5K!
|
257 |
+
|
258 |
+
Overall, its a good direction, and the chips can be used in older Arduinos
|
259 |
+
just fine (so you can upgrade your Diecimila or Duemilanove to the Uno by
|
260 |
+
simply replacing the chip).
|
261 |
+
|
262 |
+
For more detailed information about the bootloader, such as source code,
|
263 |
+
please visit the Optiboot (https://adafru.it/aUM) project page.
|
264 |
+
|
265 |
+
Why not just use the '8u2 as a programmer?
|
266 |
+
|
267 |
+
While it is possible that the 8u2 could act as a full ISP programmer there are
|
268 |
+
a few reasons why its good that it isn't.
|
269 |
+
|
270 |
+
1.
|
271 |
+
|
272 |
+
Giving beginners access to a full ISP programmer will result in bricked
|
273 |
+
chips. There's no risk of messing up the Arduino chip beyond
|
274 |
+
recognition if it's just being bootloaded
|
275 |
+
|
276 |
+
2.
|
277 |
+
|
278 |
+
3.
|
279 |
+
|
280 |
+
Having the chip act only as a USB/serial passthrough simplifies the
|
281 |
+
firmware so that the chip has only one function instead of having to
|
282 |
+
have it do double duty as programmer -and- serial interface (think
|
283 |
+
about it, its not easy)
|
284 |
+
Backwards compatibility - the Arduino chips can still be programmed
|
285 |
+
with FTDI breakout boards or cables, making it easy for people to
|
286 |
+
breadboard or make clones.
|
287 |
+
|
288 |
+
How does the new '8u2 affect Arduino-
|
289 |
+
derivatives?
|
290 |
+
|
291 |
+
Every USB device needs to have a unique product id and vendor id. Vendor
|
292 |
+
IDs (VID) are sold to companies and Product IDs (PID) are chosen by that
|
293 |
+
company. So for example FTDI owns VID #0403 and they give their chips
|
294 |
+
ID's between #0000 and #FFFF (65,536 different PIDs) Older Ardiuno's
|
295 |
+
used FTDI's VID/PID as that is part of the deal when you purchase their
|
296 |
+
chips. Because the Uno does not use an FTDI chip anymore, the Arduino
|
297 |
+
team had to purchase a USB Vendor ID (VID). Every Arduino product will
|
298 |
+
now have their own PID starting with the Uno (#0001).
|
299 |
+
|
300 |
+
If you want to make your own Arduino-compatible board, you have a few
|
301 |
+
choices:
|
302 |
+
|
303 |
+
1.
|
304 |
+
2.
|
305 |
+
|
306 |
+
3.
|
307 |
+
|
308 |
+
4.
|
309 |
+
|
310 |
+
Don't use an 8u2, go with an FTDI chip instead that comes with a VID
|
311 |
+
If you're planning to make more than one board for your personal use,
|
312 |
+
you will have to purchase a VID from USB IF (https://adafru.it/aUN) for
|
313 |
+
a one time $2000 fee
|
314 |
+
If you're making a single board for your own experimentation, you can
|
315 |
+
pick a VID/PID that doesn't interfere with any devices on your
|
316 |
+
computer and substitute those in
|
317 |
+
You can purchase licenses for single VID/PID pairs from companies that
|
318 |
+
develop USB devices (we dont have any specific links at the moment)
|
319 |
+
|
320 |
+
However, you can't use the Arduino VID when distributing your own
|
321 |
+
Arduino-compatibles! If the cost of a VID is too much for you, simply go with
|
322 |
+
an FTDI chip, K?
|
323 |
+
|
324 |
+
I tried to find a place to buy some '8u2s and
|
325 |
+
couldnt locate any!
|
326 |
+
|
327 |
+
Yep, there is a worldwide shortage of Atmel parts right now. Even the chip
|
328 |
+
used in the Arduino core (Atmega328P) is really hard to get. This happens
|
329 |
+
after recesssions. We hope that these and other Atmel chips will show up
|
330 |
+
again in places like digikey soon. Till then, keep searching on findchips.com!
|
331 |
+
|
332 |
+
So does this mean there may be an Arduino
|
333 |
+
shortage?
|
334 |
+
|
335 |
+
Probably not. The Arduino team buys chips in the 10's of thousands, directly
|
336 |
+
from Atmel. They probably get priority over distributors because of this.
|
337 |
+
We're assuming the team bought enough to last for a while.
|
338 |
+
|
339 |
+
Did the Arduino team move from the FTDI
|
340 |
+
chip to the '8u2 to screw over derivative-
|
341 |
+
makers?
|
342 |
+
|
343 |
+
While the appearance of a hard-to-get chip coupled with the VID/PID
|
344 |
+
mishegas may seem to be a little annoying, we don't think that means that
|
345 |
+
the Arduino team is being malicious or attempting to make life difficult for
|
346 |
+
people who make derivatives. The move to an '8u2 makes the Arduino more
|
347 |
+
powerful, and easy to use as there are fewer drivers to install. While there is
|
348 |
+
a shortage now, there will eventually be plenty of chips on the market.
|
349 |
+
|
350 |
+
Some people in the Arduino forum have thought of forming a group that
|
351 |
+
would purchase a VID for Arduinites to use in personal projects. This is a
|
352 |
+
pretty good idea and its probably the best way to avoid VID/PID conflicts.
|
353 |
+
Between 65,536 projects, that comes to under a nickel per PID.
|
354 |
+
|
355 |
+
And of course, because they didn't get rid of the bootloader system, you can
|
356 |
+
always just use an FTDI chip.
|
357 |
+
|
358 |
+
Are Shields still going to work?
|
359 |
+
|
360 |
+
All previous shields should still work perfectly fine as the header spacing is
|
361 |
+
the same, the core chip is the same and the location of parts is the same. In
|
362 |
+
fact, some should work better because the 3V supply has been upgraded
|
363 |
+
(see next point).
|
364 |
+
|
365 |
+
Will enclosures, plates, etc still work?
|
366 |
+
|
367 |
+
Yup! The Uno is physicially the same size and layout as previous Arduinos.
|
368 |
+
The mounting holes are in the same location. There is an additional
|
369 |
+
mounting hole as well, now.
|
370 |
+
|
371 |
+
More 3.3v power!
|
372 |
+
|
373 |
+
One sad thing about older boards is that they had a 3.3v power supply but it
|
374 |
+
was really just whatever the FTDI chip's internal 3.3v regulator could give.
|
375 |
+
You -could- get 50mA out of it, maybe. But high power stuff like XBees, SD
|
376 |
+
cards, some fast ADC or DACs could easily drag down the FTDI chip and
|
377 |
+
reset the USB connection. The Uno solves this problem by adding a new
|
378 |
+
3.3V regulator the LP2985 which can easily provide 150mA.
|
379 |
+
|
380 |
+
The LP2985 is a very high quality regulator, and will work great for
|
381 |
+
powering stuff and as a nice solid 1% analog reference.
|
382 |
+
|
383 |
+
Why is the Arduino chip running at 16MHz
|
384 |
+
when it can run at 20MHz?
|
385 |
+
|
386 |
+
This is a common question. The reason is that the first Arduino used the
|
387 |
+
Atmega8 which could not run faster than 16Mhz. As the chip has been
|
388 |
+
upgraded they wanted to make the boards speed compatible. Arduino is also
|
389 |
+
not really intended for fast-processing (its only 8-bit anyways) so the chips
|
390 |
+
are running at 16MHz.
|
391 |
+
|
392 |
+
Is it still Open source hardware and software?
|
393 |
+
|
394 |
+
Yes! The Uno is still available under a Creative commons license. You can
|
395 |
+
get the latest schematics and layouts over at the Arduino website. (https://
|
396 |
+
adafru.it/aP4)
|
397 |
+
|
398 |
+
UNO R2 and R3
|
399 |
+
|
400 |
+
During fall of 2011, the Arduino team revealed that there will be a new
|
401 |
+
minor revision of the classic Arduino, the "UNO R3" (revision 3). A lot of
|
402 |
+
people have asked us about the R3 so here is everything we know so far.
|
403 |
+
|
404 |
+
1.
|
405 |
+
|
406 |
+
2.
|
407 |
+
|
408 |
+
The UNO R3 is not available to resellers until December 1st or so.
|
409 |
+
Really! Nobody has them until then!
|
410 |
+
The UNO R3 is backwards compatible with the UNO - same driver,
|
411 |
+
same uploading, same look
|
412 |
+
|
413 |
+
There are a few changes in the UNO, here is what they are:
|
414 |
+
|
415 |
+
1.
|
416 |
+
|
417 |
+
2.
|
418 |
+
|
419 |
+
3.
|
420 |
+
|
421 |
+
The USB controller chip has moved from an atmega8u2 (8K flash) to an
|
422 |
+
atmega16u2 (16K flash). This does not mean that you have more
|
423 |
+
flash or RAM for your sketches this upgrade is for the USB interface
|
424 |
+
chip only. In theory this will mean that it will be easier to have low
|
425 |
+
level USB interfaces such as MIDI/Joystick/Keyboard available.
|
426 |
+
However these are only theoretical at this time, there is no example
|
427 |
+
code or firmware which will actually do this.
|
428 |
+
There are three more breakout pins on the PCB, next to the AREF pin
|
429 |
+
there is are two I2C pins (SDA/SCL) - this is a duplication of the
|
430 |
+
Analog 4 and 5 pins. There is not an extra I2C interface or anything, its
|
431 |
+
just that they made a copy of those pins there for future shields since
|
432 |
+
the I2C pins are in a different place on Mega. There is also an IOREF
|
433 |
+
pin which is next to the Reset pin - this is to let shields know what the
|
434 |
+
running I/O pin voltage is on the board (for the UNO, its 5V). Again, this
|
435 |
+
is a duplication of the power pin, it does not add voltage level shifting
|
436 |
+
to the UNO.
|
437 |
+
The RESET button has moved to be next to the USB connector, this
|
438 |
+
makes it easier to press when a shield is on top.
|
439 |
+
|
440 |
+
Here is what didn't change in the UNO:
|
441 |
+
|
442 |
+
1.
|
443 |
+
|
444 |
+
2.
|
445 |
+
|
446 |
+
3.
|
447 |
+
4.
|
448 |
+
|
449 |
+
5.
|
450 |
+
6.
|
451 |
+
|
452 |
+
Processor size and speed - its the same ATMega328P running at 16MHz
|
453 |
+
that we've had since the Duemilanove. Your code will not run faster or
|
454 |
+
better on the R3
|
455 |
+
Same number of pins - no extra pins are added EVEN THOUGH
|
456 |
+
THERE ARE MORE BREAKOUTS (see above!)
|
457 |
+
Board size and shape - same size as before
|
458 |
+
Shield compatibility - Every shield that works and plugs into the UNO
|
459 |
+
R1/R2 should be able to work fine with the R3
|
460 |
+
Driver - the driver is the same
|
461 |
+
Upload speed - same upload speed and technique
|
462 |
+
|
463 |
+
If you want to get up an Arduino R3 now, visit the adafruit store (http://
|
464 |
+
adafru.it/50) and pick up a board or pack!
|
465 |
+
|
466 |
+
Arduino Libraries
|
467 |
+
|
468 |
+
Need Help Installing a Library?
|
469 |
+
|
470 |
+
Check out our super-detailed tutorial for all operating systems here:
|
471 |
+
http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-
|
472 |
+
use (https://adafru.it/aYM)
|
473 |
+
|
474 |
+
What is a library?
|
475 |
+
|
476 |
+
Libraries are great places, and not yet illegal in the United States! If you
|
477 |
+
ever need to learn how to do something, like say fix a motorcycle, you can go
|
478 |
+
to your local library and take out a book. Sure you could buy the book but
|
479 |
+
the library is nice because as a resource you can get the book whenever you
|
480 |
+
need it, keeping your house uncluttered.
|
481 |
+
|
482 |
+
Software Libraries are very similar. We already studied what a procedure is,
|
483 |
+
in lesson 3 (https://adafru.it/aV0): a procedure is a list of things to do. A
|
484 |
+
library is a big collection of procedures, where all the procedures are
|
485 |
+
related! If you, say, want to control a motor, you may want to find a Motor
|
486 |
+
Control Library: a collection of procedures that have already been written
|
487 |
+
for you that you can use without having to do the dirty work of learning the
|
488 |
+
nuances of motors.
|
489 |
+
|
490 |
+
For example, this is the Serial Library, which allows the Arduino to send
|
491 |
+
data back to the computer:
|
492 |
+
|
493 |
+
Using Libraries
|
494 |
+
|
495 |
+
One of the best features of the Arduino project is the ability to add on pre-
|
496 |
+
crafted libraries that add hardware support. There's tons of them, and you
|
497 |
+
can pick and choose which to install. They're only loaded in when the sketch
|
498 |
+
you're working on needs them, so for the most part you can download and
|
499 |
+
|
500 |
+
stash them for future use.
|
501 |
+
|
502 |
+
Sketches will often depend on libraries, you can see what they are by
|
503 |
+
looking at the top of the sketch. If you see something like:
|
504 |
+
|
505 |
+
#include <FatReader.h>
|
506 |
+
|
507 |
+
That means that you'll need a library called FatReader or a library that
|
508 |
+
contains the file FatReader. If you dont have it installed you'll get an error:
|
509 |
+
|
510 |
+
What's in a library?
|
511 |
+
|
512 |
+
A library is a folder with some files in it, the files will end in .cpp (C++ code
|
513 |
+
file) and .h (C++ header file).
|
514 |
+
|
515 |
+
There may also be some .o files. The .o files are C++ compiled Objects. If
|
516 |
+
you end up working on the library and modifying it, be sure to delete the .o
|
517 |
+
files as that will force the Arduino IDE to recompile the modified .cpp's into
|
518 |
+
fresh .o's.
|
519 |
+
|
520 |
+
Two optional files you may see are keywords.txt (this is a hints file to tell
|
521 |
+
the Arduino IDE how to colorize your sketch and examples folder, which
|
522 |
+
may have some handy test-sketches. These will show up under the
|
523 |
+
File→Examples→Library dropdown.
|
524 |
+
|
525 |
+
It's important to remember!
|
526 |
+
|
527 |
+
The structure of the library folder is very important! The .c and .h files must
|
528 |
+
be in the 'lowest level' of folders. For example, you cant have Arduino/
|
529 |
+
libraries/WaveHC/WaveHC/file.c or Arduino/libraries/MyLibraries/
|
530 |
+
WaveHC/file.c - it must be Arduino/libraries/WaveHC/file.c
|
531 |
+
|
532 |
+
How to install libraries
|
533 |
+
|
534 |
+
In Arduino v16 and earlier, libraries were stored in the
|
535 |
+
ArduinoInstallDirectory/hardware/libraries folder, which also contained
|
536 |
+
all the built-in libraries (like Wire and Serial).
|
537 |
+
|
538 |
+
In v17 and up, the user libraries are now stored in the
|
539 |
+
ArduinoSketchDirectory/libraries folder. You may need to make the
|
540 |
+
libraries sub-folder the first time. However, the good thing about this is you
|
541 |
+
wont have to move & reinstall your libraries every time you upgrade the
|
542 |
+
software.
|
543 |
+
|
544 |
+
For example, here is how it looks when NewSoftSerial is installed in
|
545 |
+
Windows (of course your username will be different).
|
546 |
+
|
547 |
+
On a Mac, your arduino sketch folder is likely going to be called
|
548 |
+
Documents/arduino so create a NEW FOLDER inside that called libraries
|
549 |
+
and place the uncompressed library folder inside of that.
|
550 |
+
|
551 |
+
Check that the Documents/arduino/libraries/MyNewLibary folder contains
|
552 |
+
the .cpp and .h files.
|
553 |
+
|
554 |
+
After you're done, restart the Arduino IDE.
|
555 |
+
|
556 |
+
Bootloader
|
557 |
+
|
558 |
+
This is some advanced bootloader tweaks - 99% of Arduino users should not
|
559 |
+
mess with their bootloader! Only for the wild at heart!
|
560 |
+
|
561 |
+
Bootloader for the Atmega328
|
562 |
+
|
563 |
+
Here is the package for a 'fixed up' ATmega328 bootloader (https://adafru.it/
|
564 |
+
cnD). To program it you may need to change the Makefile's ISPTOOL, etc
|
565 |
+
definitions. The commands are make adaboot328; make
|
566 |
+
TARGET=adaboot328 isp328 (I couldn't get the default 'isp' target to
|
567 |
+
work so I made a new one).
|
568 |
+
|
569 |
+
This version has a few fixes: first it integrates the 'no-wait' and 'no-hang'
|
570 |
+
fixes below. It also fixes the annoying "missing signature bytes" bug that
|
571 |
+
freaks out avrdude when programming without the IDE. I also repaired the
|
572 |
+
EEPROM code so that now you can upload and download the EEPROM
|
573 |
+
memory as well as flash. Finally, theres a 'upload feedback' using the LED,
|
574 |
+
for arduino clones that don't have TX/RX leds.
|
575 |
+
|
576 |
+
Please note that the fuses are different for this chip because of the extended
|
577 |
+
memory!
|
578 |
+
|
579 |
+
"No-Wait" Bootloader
|
580 |
+
|
581 |
+
Here's a bootloader hack that will automatically start the sketch after it has
|
582 |
+
been uploaded and will also only start the bootloader when the reset button
|
583 |
+
is pressed (so when you plug in power it will go straight to the sketch).
|
584 |
+
|
585 |
+
Copy the following lines:
|
586 |
+
|
587 |
+
ch = MCUSR;
|
588 |
+
MCUSR = 0;
|
589 |
+
|
590 |
+
WDTCSR |= _BV(WDCE) | _BV(WDE);
|
591 |
+
WDTCSR = 0;
|
592 |
+
|
593 |
+
// Check if the WDT was used to reset, in which case we dont bootload and skip straight to the code. woot.
|
594 |
+
if (! (ch & _BV(EXTRF))) // if its a not an external reset...
|
595 |
+
app_start(); // skip bootloader
|
596 |
+
|
597 |
+
And paste them as shown:
|
598 |
+
|
599 |
+
/* main program starts here */
|
600 |
+
int main(void)
|
601 |
+
{
|
602 |
+
uint8_t ch,ch2;
|
603 |
+
uint16_t w;
|
604 |
+
|
605 |
+
ch = MCUSR;
|
606 |
+
MCUSR = 0;
|
607 |
+
|
608 |
+
WDTCSR |= _BV(WDCE) | _BV(WDE);
|
609 |
+
WDTCSR = 0;
|
610 |
+
|
611 |
+
// Check if the WDT was used to reset, in which case we dont bootload and skip straight to the code. woot.
|
612 |
+
if (! (ch & _BV(EXTRF))) // if its a not an external reset...
|
613 |
+
app_start(); // skip bootloader
|
614 |
+
|
615 |
+
/* set pin direction for bootloader pin and enable pullup */
|
616 |
+
/* for ATmega128, two pins need to be initialized */
|
617 |
+
|
618 |
+
Now, in the same way, copy the following code:
|
619 |
+
|
620 |
+
// autoreset via watchdog (sneaky!)
|
621 |
+
WDTCSR = _BV(WDE);
|
622 |
+
while (1); // 16 ms
|
623 |
+
|
624 |
+
And paste it here:
|
625 |
+
|
626 |
+
/* Leave programming mode */
|
627 |
+
|
628 |
+
else if(ch=='Q') {
|
629 |
+
nothing_response();
|
630 |
+
|
631 |
+
// autoreset via watchdog (sneaky!)
|
632 |
+
|
633 |
+
WDTCSR = _BV(WDE);
|
634 |
+
while (1); // 16 ms
|
635 |
+
}
|
636 |
+
/* Erase device, don't care as we will erase one page at a time anyway. */
|
637 |
+
else if(ch=='R') {
|
638 |
+
nothing_response();
|
639 |
+
}
|
640 |
+
|
641 |
+
You can also just grab the source code (https://adafru.it/cnE) and compiled
|
642 |
+
hex file here (https://adafru.it/cnF).
|
643 |
+
|
644 |
+
It will work in NG or Diecimila Arduinos.
|
645 |
+
|
646 |
+
No-Hang Bootloader
|
647 |
+
|
648 |
+
If you are using a Diecimila with auto-reset you may be frustrated when your
|
649 |
+
communications program accidentally triggers the bootloader. Here is a
|
650 |
+
quick hack to make the bootloader quit if it doesn't receive a '0' character
|
651 |
+
first (which would indicate the Arduino software is trying to talk to it.
|
652 |
+
|
653 |
+
Copy the following line:
|
654 |
+
|
655 |
+
uint8_t firstchar = 0;
|
656 |
+
|
657 |
+
And paste:
|
658 |
+
|
659 |
+
/* main program starts here */
|
660 |
+
int main(void)
|
661 |
+
{
|
662 |
+
uint8_t ch,ch2;
|
663 |
+
uint16_t w;
|
664 |
+
uint8_t firstchar = 0;
|
665 |
+
|
666 |
+
Copy:
|
667 |
+
|
668 |
+
firstchar = 1; // we got an appropriate bootloader instruction
|
669 |
+
|
670 |
+
Paste:
|
671 |
+
|
672 |
+
/* Hello is anyone home ? */
|
673 |
+
if(ch=='0') {
|
674 |
+
firstchar = 1; // we got an appropriate bootloader instruction
|
675 |
+
nothing_response();
|
676 |
+
|
677 |
+
Then paste this below the above code:
|
678 |
+
|
679 |
+
} else if (firstchar == 0) {
|
680 |
+
|
681 |
+
// the first character we got is not '0', lets bail!
|
682 |
+
// autoreset via watchdog (sneaky!)
|
683 |
+
WDTCSR = _BV(WDE);
|
684 |
+
while (1); // 16 ms
|
685 |
+
}
|
686 |
+
|
687 |
+
You can also just replace the last two lines with app_start()
|
688 |
+
|
689 |
+
Upload Sketches with AVRDUDE
|
690 |
+
|
691 |
+
The bootloader is an 'stk500'-compatible, which means you can use good ol'
|
692 |
+
AVRDUDE to program the arduino.
|
693 |
+
|
694 |
+
Just plug in the USB cable, then press the reset just before you start
|
695 |
+
avrdude. If you need an avrdude tutorial, check out this page (https://
|
696 |
+
adafru.it/aVy).
|
697 |
+
|
698 |
+
•
|
699 |
+
•
|
700 |
+
•
|
701 |
+
•
|
702 |
+
•
|
703 |
+
|
704 |
+
Use -b 19200 to set the baud rate to 19200
|
705 |
+
The device signature reads dont seem to work so you'll want to use -F
|
706 |
+
The programmer type is avrisp
|
707 |
+
The device type is -p m168
|
708 |
+
The port is whatever the FTDI chip shows up as
|
709 |
+
|
710 |
+
Upgrade
|
711 |
+
|
712 |
+
Introduction
|
713 |
+
|
714 |
+
The 'brains' of the Arduino is a microcontroller called an ATmega. It is a
|
715 |
+
product line from ATMEL (https://adafru.it/aVz) (a Norweigen chip
|
716 |
+
company). Just like Intel & AMD release new & better chips each year, so
|
717 |
+
does Atmel. The first versions of the Arduino (up to the NG) used an
|
718 |
+
ATmega8 - a chip with 8K of flash memory and 1K of RAM. Then Atmel
|
719 |
+
released the ATmega168 (https://adafru.it/aIH), a drop-in replacement with
|
720 |
+
16K of flash and 1K of RAM - a really big improvement! Now there is the
|
721 |
+
ATmega328 (https://adafru.it/aIH) with 32K of flash and 2K of RAM.
|
722 |
+
|
723 |
+
Updating and replacing your Arduino is easy and painless and costs only a
|
724 |
+
few dollars. Your sketches will work just as before but with a little more
|
725 |
+
breathing room.
|
726 |
+
|
727 |
+
In order to perform this upgrade you will have to either purchase a
|
728 |
+
preprogrammed chip (https://adafru.it/aIH) or program it yourself with a
|
729 |
+
AVR programmer (https://adafru.it/aIH) or by 'bitbanging' it.
|
730 |
+
|
731 |
+
Replace the Chip
|
732 |
+
|
733 |
+
First, gently pry the Arduino microcontroller from its socket using a small
|
734 |
+
flat screwdriver or similar. Try to make sure the pins dont get bent. Put it in
|
735 |
+
a safe place. Preferably in an anti-static bag.
|
736 |
+
|
737 |
+
Next, prepare the new chip. The pins of ICs are a little skewed when they
|
738 |
+
come from the factory, so they need to be bent in just a tiny bit, to be
|
739 |
+
parallel. Grip the chip from the ends and use a table.
|
740 |
+
|
741 |
+
Finally, replace the old chip, lining up all the pins and making sure that the
|
742 |
+
notch in the chip matches the notch in the socket!
|
743 |
+
|
744 |
+
Download an Arduino IDE with ATmega328
|
745 |
+
compatibility
|
746 |
+
|
747 |
+
Version 13 and up of the Arduino software supports the 328! (https://
|
748 |
+
adafru.it/aVB)
|
749 |
+
|
750 |
+
If you purchased a chip from Adafruit that shipped before Feb 5, 2009 the
|
751 |
+
chip will have the baudrate set at 19200 (same as the older Arduinos). After
|
752 |
+
Feb 5 the upgrade chips were changed to 57600 baud rate (3 times faster!)
|
753 |
+
in order to be compatible with new Arduinos. If you have a 19200 baud rate
|
754 |
+
chip you will have difficulty uploading. Simply quit the Arduino application
|
755 |
+
and edit the file in the hardware folder named boards.txt and change the
|
756 |
+
line from:
|
757 |
+
|
758 |
+
atmega328.upload.speed=57600
|
759 |
+
|
760 |
+
to:
|
761 |
+
|
762 |
+
atmega328.upload.speed=19200
|
763 |
+
|
764 |
+
If you're having problems please try BOTH just in case!
|
765 |
+
|
766 |
+
3.3V Conversion
|
767 |
+
|
768 |
+
Introduction
|
769 |
+
|
770 |
+
Arduino UNO's and many other Arduino boards run on 5 volts, which for a
|
771 |
+
long time was the 'standard' voltage for hobbyist electronics and
|
772 |
+
microcontrollers. But now the coolest new sensors, displays and chips are
|
773 |
+
3.3V and are not 5V compatible. For example, XBee radios, and SD cards
|
774 |
+
and acellerometers all run on 3.3V logic and power. If you tried to connect to
|
775 |
+
them with 5V you could damage the internals of the accessory.
|
776 |
+
|
777 |
+
We use chips like the CD4050 to do level conversion (https://adafru.it/Cc7)
|
778 |
+
but if you are using a lot of 3.3V devices, maybe you're just better off
|
779 |
+
upgrading the entire Arduino to run from 3.3V!
|
780 |
+
|
781 |
+
To do that, we will replace the regulator so that the DC barrel jack goes to a
|
782 |
+
3.3v type regulator, not a 5V. And then reconfigure the 5V usb power line so
|
783 |
+
it goes through the regulator as well.
|
784 |
+
|
785 |
+
Replace the Regulator
|
786 |
+
|
787 |
+
The default regulator is a 5.0V type, but we want 3.3V out, so we'll need to
|
788 |
+
replace it. We'll use a 1117-3.3V (there are a few manufacturers of 1117
|
789 |
+
regulators, just like the 7805 is made by many factories) regulator in a
|
790 |
+
TO-252-3 package. It looks like this:
|
791 |
+
|
792 |
+
You can get these from any electronics component shop, for example here is
|
793 |
+
the digikey link (https://adafru.it/aLu).
|
794 |
+
|
795 |
+
To start, we'll need to remove the old regulator. The easiest way to do that is
|
796 |
+
to first clip the two legs.
|
797 |
+
|
798 |
+
Then you'll need to heat the tab up to get it liquid so you can lift off the old
|
799 |
+
part. Although it may seem counter intuitive, its best to add some solder to
|
800 |
+
the tab, melt it on with your iron, this will improve the heat conduction since
|
801 |
+
the tab is so large.
|
802 |
+
|
803 |
+
Clean up the tabs and remove any clipped parts still stuck on.
|
804 |
+
|
805 |
+
Now line up the new 3.3V regulator, and solder the tab first, use plenty of
|
806 |
+
solder and be patient, the tab acts like a heat sink.
|
807 |
+
|
808 |
+
Then do the two legs.
|
809 |
+
|
810 |
+
Replacing the Fuse
|
811 |
+
|
812 |
+
The next part is a little tricky, the USB jack gives us exactly 5V already, and
|
813 |
+
normally that is tied to the output of the voltage regulator (essentially, its
|
814 |
+
got a little circuitry that connects it when the DC jack is not powered).
|
815 |
+
|
816 |
+
The easiest way to make the USB 5V also go through the regulator is to
|
817 |
+
remove the fuse and solder a diode from the USB output to the regulator
|
818 |
+
input.
|
819 |
+
|
820 |
+
You can use any power diode, a 1N4001 is perfect (https://adafru.it/cuU) and
|
821 |
+
only a few pennies.
|
822 |
+
|
823 |
+
The trade off is now there is no 500 mA fuse for the USB jack. The good
|
824 |
+
news is that computers will have their own fuses on the USB connector
|
825 |
+
(inside the computer) so its not likely you will destroy your PC. But be aware
|
826 |
+
|
827 |
+
that you're losing a little safety.
|
828 |
+
|
829 |
+
Heat the fuse with your soldering iron, again adding solder may help
|
830 |
+
thermal conductivity. Since the fuse is very conductive you can probably just
|
831 |
+
heat one side for a while and both ends will melt.
|
832 |
+
|
833 |
+
Clip the diode short and bend the leads over. Solder the side without a stripe
|
834 |
+
(anode) to the old fuse pad, nearest the board edge. Solder the striped end
|
835 |
+
(cathode) to the right hand leg of the regulator.
|
836 |
+
|
837 |
+
The Arduino will still automatically select whichever power plug is giving
|
838 |
+
you more power.
|
839 |
+
|
840 |
+
That's it! You are now 3.3V powered. This is a little lower than the power/
|
841 |
+
frequency specification for the AVR chips since they ought to have about
|
842 |
+
3.6V to run 16Mhz but its probably not going to be an issue since AVRs can
|
843 |
+
be overclocked a little.
|
844 |
+
|
845 |
+
Arduino Hacks
|
846 |
+
|
847 |
+
Bumpers
|
848 |
+
|
849 |
+
Having the conductive traces touch your table is not so great, you can
|
850 |
+
protect your Arduino by adding bumpers to the bottom.
|
851 |
+
|
852 |
+
You can buy these from McMaster Carr part no. 95495K66 (https://adafru.it/
|
853 |
+
aVH) (in large quantities) or Adafruit (http://adafru.it/550)
|
854 |
+
|
855 |
+
Free up some RAM
|
856 |
+
|
857 |
+
If you're working on a project that needs a lot of memory, you can free up
|
858 |
+
100 more bytes (10% of the RAM on an ATmega168!) by lessening the serial
|
859 |
+
receive buffer. By default its 128 bytes, which is quite a bit!
|
860 |
+
|
861 |
+
Open up hardware/cores/arduino (or cores/arduino) directory, and edit
|
862 |
+
the file named wiring_serial.c or HardwareSerial.cpp
|
863 |
+
|
864 |
+
Near the top is a #define RX_BUFFER_SIZE 128, which means 128 bytes
|
865 |
+
are used for the buffer. You can change this to 32 (or even 16!). If you have
|
866 |
+
almost no serial input, make it as low as you'd like as long as its > 0.
|
867 |
+
|
868 |
+
You can also save another 2 bytes by changing rx_buffer_head and
|
869 |
+
rx_buffer_tail from int to uint8_t
|
870 |
+
|
871 |
+
ArduinoISP
|
872 |
+
|
873 |
+
Introduction
|
874 |
+
|
875 |
+
A lot of people start learning about microcontrollers with an Arduino but
|
876 |
+
then want to build their own projects without having to sacrifice their dev
|
877 |
+
board. Or maybe they want to make their own Arduino variant, that is
|
878 |
+
compatible with the IDE. Either way, a common problem is how to burn the
|
879 |
+
bootloader onto the fresh AVR chip. Since AVRs come blank, they need to be
|
880 |
+
set up to be Arduino IDE compatible but to do that you need an AVR
|
881 |
+
programmer (like the USBtinyISP).
|
882 |
+
|
883 |
+
The good news is that you can burn bootloader using your existing Arduino
|
884 |
+
with only a little bit of work. There's even a minitutorial on the arduino.cc
|
885 |
+
site (https://adafru.it/aVI).
|
886 |
+
|
887 |
+
This tutorial is an extention of that tutorial. First we'll show how you can
|
888 |
+
make a permanent bootloader-burner by soldering a 28-pin ZIF
|
889 |
+
socket (http://adafru.it/382) to a proto shield (http://adafru.it/51)and use the
|
890 |
+
PWM output line of the Arduino to generate a clock. This will let you 'rescue'
|
891 |
+
many chips that have been set to the wrong type of oscillator, or change
|
892 |
+
ones that are set from external oscillator (most Arduino bootloaders) to
|
893 |
+
internal (such as the lilypad).
|
894 |
+
|
895 |
+
Parts
|
896 |
+
|
897 |
+
You will need…
|
898 |
+
|
899 |
+
•
|
900 |
+
•
|
901 |
+
•
|
902 |
+
|
903 |
+
•
|
904 |
+
•
|
905 |
+
|
906 |
+
An Arduino (http://adafru.it/50)
|
907 |
+
A proto shield kit (http://adafru.it/51)
|
908 |
+
28-pin ZIF (zero-insertion force) socket (http://adafru.it/382) (you can
|
909 |
+
use a plain socket but ZIF is ideal)
|
910 |
+
Some wire (http://adafru.it/289)
|
911 |
+
Blank ATmega328P (https://adafru.it/Cc8)
|
912 |
+
|
913 |
+
If you bought the kit from Adafruit, you'll have an extra few items such as a
|
914 |
+
Piezo beeper, LEDs, buttons, etc. that you can use for the Standalone
|
915 |
+
version of this project (https://adafru.it/clC), just ignore them for now!
|
916 |
+
|
917 |
+
Assemble
|
918 |
+
|
919 |
+
First up, place the ZIF socket on the proto shield like so:
|
920 |
+
|
921 |
+
Solder all 28 pins for a solid connection!
|
922 |
+
|
923 |
+
Solder the following wires to the ZIF socket
|
924 |
+
|
925 |
+
•
|
926 |
+
|
927 |
+
•
|
928 |
+
•
|
929 |
+
•
|
930 |
+
•
|
931 |
+
•
|
932 |
+
•
|
933 |
+
•
|
934 |
+
•
|
935 |
+
|
936 |
+
Pin 1 to digital 10 - Blue Don't forget to bend the wire over
|
937 |
+
underneath to connect to the ZIF socket pin when soldering!!!
|
938 |
+
Pin 7 to 5V - Red
|
939 |
+
Pin 8 to Ground - Black
|
940 |
+
Pin 9 to digital 9 - Gray
|
941 |
+
Pin 17 to digital 11 - Brown
|
942 |
+
Pin 18 to digital 12 - Orange
|
943 |
+
Pin 19 to digital 13 - Yellow
|
944 |
+
Pin 20 to +5V - Red
|
945 |
+
Pin 22 to Ground - Black
|
946 |
+
|
947 |
+
Follow the protoshield tutorial to solder in the Red LED into LED1 position,
|
948 |
+
Green LED into LED2 position. Also solder in the two 1.0K resistors next to
|
949 |
+
the LEDs. We'll use the LEDs as indicators. Then solder a wire from the
|
950 |
+
LED2 breakout (white) to analog 0 and a wire from LED1 breakout (white)
|
951 |
+
to digital 8.
|
952 |
+
|
953 |
+
Finally, you'll need to solder on the header to allow the shield to be placed
|
954 |
+
on, break the 0.1" male header and place it into the Arduino sockets. Then
|
955 |
+
place the shield above on top to solder it in place.
|
956 |
+
|
957 |
+
Load the Code
|
958 |
+
|
959 |
+
Time to load the sketch! Grab the code from our Github repository and paste
|
960 |
+
it into a new sketch (https://adafru.it/ECM). Then upload it to the Arduino.
|
961 |
+
|
962 |
+
We have a report that this procedure does not work with Arduino 1.5.2. Use
|
963 |
+
the latest mainstream Arduino release instead!
|
964 |
+
Plug the shield on top, lift the latch, pop in the chip and then lower the
|
965 |
+
latch. Make sure the chip orientation is like so (so with the lever on the left
|
966 |
+
side you can read the text):
|
967 |
+
|
968 |
+
With the USB cable still plugged in (and the same Serial port selected as
|
969 |
+
before) Select Tools→Burn Bootloader→w/Arduino as ISP
|
970 |
+
|
971 |
+
On newer versions of the Arduino IDE, select Arduino as ISP from the
|
972 |
+
Tools→Programmer menu, then select Burn Bootloader from the Tools
|
973 |
+
menu.
|
974 |
+
|
975 |
+
The Green LED will be on during the programming, when its done you'll see
|
976 |
+
this message and the LED will turn off.
|
977 |
+
|
978 |
+
Thats it! Don't forget, you can burn a few different kinds of bootloaders,
|
979 |
+
such as Uno, Duemilanove, Lilypad so depending on your situation you may
|
980 |
+
want to use one over the other.
|
981 |
+
|
982 |
+
Bonus! Using with AVRdude
|
983 |
+
|
984 |
+
You can use ArduinoISP from the command line very easily, with AVRdude
|
985 |
+
which is the standard program used to program AVRs by running:
|
986 |
+
|
987 |
+
avrdude -c arduino -p atmega328 -P COMPORT -b 19200 -U flash:w:filetoburn.hex
|
988 |
+
|
989 |
+
Instead of atmega328 you can also program atmega8 atmega88
|
990 |
+
atmega48 atmega168, etc.
|
991 |
+
|
992 |
+
Support Forums
|
993 |
+
|
994 |
+
Support Forums (https://adafru.it/forums)
|
995 |
+
|
996 |
+
|
Arduino/arduino.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Assembly+Language/ARMBook.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Assembly+Language/ProgrammingGroundUp-1-0-booksize.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Assembly+Language/asl.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Assembly+Language/wizardcode4.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Bash/LinuxShellScriptingWithBash-Sams.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Bash/bash.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Bash/bashguide.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Basic/gambas-beginner-guide.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
BeanShell/bshmanual.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
C/EssentialC.pdf.txt
ADDED
@@ -0,0 +1,2747 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
3 |
+
By Nick Parlante
|
4 |
+
|
5 |
+
Copyright 1996-2003, Nick Parlante
|
6 |
+
|
7 |
+
This Stanford CS Education document tries to summarize all the basic features of the C
|
8 |
+
language. The coverage is pretty quick, so it is most appropriate as review or for someone
|
9 |
+
with some programming background in another language. Topics include variables, int
|
10 |
+
types, floating point types, promotion, truncation, operators, control structures (if, while,
|
11 |
+
for), functions, value parameters, reference parameters, structs, pointers, arrays, the pre-
|
12 |
+
processor, and the standard C library functions.
|
13 |
+
|
14 |
+
The most recent version is always maintained at its Stanford CS Education Library URL
|
15 |
+
http://cslibrary.stanford.edu/101/. Please send your comments to
|
16 |
+
nick.parlante@cs.stanford.edu.
|
17 |
+
|
18 |
+
I hope you can share and enjoy this document in the spirit of goodwill in which it is given
|
19 |
+
away -- Nick Parlante, 4/2003, Stanford California.
|
20 |
+
|
21 |
+
Stanford CS Education Library
|
22 |
+
CS Education Library. This and other educational materials are available for free at
|
23 |
+
http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted,
|
24 |
+
retransmitted, or sold so long as this notice is clearly reproduced at its beginning.
|
25 |
+
Table of Contents
|
26 |
+
|
27 |
+
This is document #101, Essential C, in the Stanford
|
28 |
+
|
29 |
+
Introduction .........................................................................................pg. 2
|
30 |
+
|
31 |
+
Where C came from, what is it like, what other resources might you look at.
|
32 |
+
|
33 |
+
Section 1
|
34 |
+
|
35 |
+
Basic Types and Operators ..........................................pg. 3
|
36 |
+
|
37 |
+
Integer types, floating point types, assignment operator, comparison operators,
|
38 |
+
arithmetic operators, truncation, promotion.
|
39 |
+
|
40 |
+
Section 2
|
41 |
+
|
42 |
+
Control Structures ........................................................pg. 11
|
43 |
+
|
44 |
+
If statement, conditional operator, switch, while, for, do-while, break, continue.
|
45 |
+
|
46 |
+
Section 3
|
47 |
+
|
48 |
+
Complex Data Types .....................................................pg. 15
|
49 |
+
|
50 |
+
Structs, arrays, pointers, ampersand operator (&), NULL, C strings, typedef.
|
51 |
+
|
52 |
+
Section 4
|
53 |
+
|
54 |
+
Functions ........................................................................pg. 24
|
55 |
+
|
56 |
+
Functions, void, value and reference parameters, const.
|
57 |
+
|
58 |
+
Section 5
|
59 |
+
|
60 |
+
Odds and Ends ..............................................................pg. 29
|
61 |
+
|
62 |
+
Main(), the .h/.c file convention, pre-processor, assert.
|
63 |
+
|
64 |
+
Section 6
|
65 |
+
|
66 |
+
Advanced Arrays and Pointers ....................................pg. 33
|
67 |
+
|
68 |
+
How arrays and pointers interact. The [ ] and + operators with pointers, base
|
69 |
+
address/offset arithmetic, heap memory management, heap arrays.
|
70 |
+
|
71 |
+
Section 7
|
72 |
+
|
73 |
+
Operators and Standard Library Reference ..............pg. 41
|
74 |
+
A summary reference of the most common operators and library functions.
|
75 |
+
|
76 |
+
The C Language
|
77 |
+
C is a professional programmer's language. It was designed to get in one's way as little as
|
78 |
+
possible. Kernighan and Ritchie wrote the original language definition in their book, The
|
79 |
+
C Programming Language (below), as part of their research at AT&T. Unix and C++
|
80 |
+
emerged from the same labs. For several years I used AT&T as my long distance carrier
|
81 |
+
in appreciation of all that CS research, but hearing "thank you for using AT&T" for the
|
82 |
+
millionth time has used up that good will.
|
83 |
+
|
84 |
+
2
|
85 |
+
|
86 |
+
Some languages are forgiving. The programmer needs only a basic sense of how things
|
87 |
+
work. Errors in the code are flagged by the compile-time or run-time system, and the
|
88 |
+
programmer can muddle through and eventually fix things up to work correctly. The C
|
89 |
+
language is not like that.
|
90 |
+
|
91 |
+
The C programming model is that the programmer knows exactly what they want to do
|
92 |
+
and how to use the language constructs to achieve that goal. The language lets the expert
|
93 |
+
programmer express what they want in the minimum time by staying out of their way.
|
94 |
+
|
95 |
+
C is "simple" in that the number of components in the language is small-- If two language
|
96 |
+
features accomplish more-or-less the same thing, C will include only one. C's syntax is
|
97 |
+
terse and the language does not restrict what is "allowed" -- the programmer can pretty
|
98 |
+
much do whatever they want.
|
99 |
+
|
100 |
+
C's type system and error checks exist only at compile-time. The compiled code runs in a
|
101 |
+
stripped down run-time model with no safety checks for bad type casts, bad array indices,
|
102 |
+
or bad pointers. There is no garbage collector to manage memory. Instead the
|
103 |
+
programmer mangages heap memory manually. All this makes C fast but fragile.
|
104 |
+
|
105 |
+
Analysis -- Where C Fits
|
106 |
+
Because of the above features, C is hard for beginners. A feature can work fine in one
|
107 |
+
context, but crash in another. The programmer needs to understand how the features work
|
108 |
+
and use them correctly. On the other hand, the number of features is pretty small.
|
109 |
+
|
110 |
+
Like most programmers, I have had some moments of real loathing for the C language. It
|
111 |
+
can be irritatingly obedient -- you type something incorrectly, and it has a way of
|
112 |
+
compiling fine and just doing something you don't expect at run-time. However, as I have
|
113 |
+
become a more experienced C programmer, I have grown to appreciate C's straight-to-the
|
114 |
+
point style. I have learned not to fall into its little traps, and I appreciate its simplicity.
|
115 |
+
|
116 |
+
Perhaps the best advice is just to be careful. Don't type things in you don't understand.
|
117 |
+
Debugging takes too much time. Have a mental picture (or a real drawing) of how your C
|
118 |
+
code is using memory. That's good advice in any language, but in C it's critical.
|
119 |
+
|
120 |
+
Perl and Java are more "portable" than C (you can run them on different computers
|
121 |
+
without a recompile). Java and C++ are more structured than C. Structure is useful for
|
122 |
+
large projects. C works best for small projects where performance is important and the
|
123 |
+
progammers have the time and skill to make it work in C. In any case, C is a very popular
|
124 |
+
and influential language. This is mainly because of C's clean (if minimal) style, it's lack
|
125 |
+
of annoying or regrettable constructs, and the relative ease of writing a C compiler.
|
126 |
+
|
127 |
+
Other Resources
|
128 |
+
|
129 |
+
•
|
130 |
+
|
131 |
+
•
|
132 |
+
|
133 |
+
•
|
134 |
+
|
135 |
+
The C Programming Language, 2nd ed., by Kernighan and Ritchie. The thin book
|
136 |
+
which for years was the bible for all C programmers. Written by the original
|
137 |
+
designers of the language. The explanations are pretty short, so this book is better as a
|
138 |
+
reference than for beginners.
|
139 |
+
http://cslibrary.stanford.edu/102/
|
140 |
+
about local memory, pointers, reference parameters, and heap memory than in this
|
141 |
+
article, and memory is really the hardest part of C and C++.
|
142 |
+
http://cslibrary.stanford.edu//103/
|
143 |
+
basics of pointers and C, these problems are a good way to get more practice.
|
144 |
+
|
145 |
+
Linked List Basics -- Once you understand the
|
146 |
+
|
147 |
+
Pointers and Memory -- Much more detail
|
148 |
+
|
149 |
+
3
|
150 |
+
|
151 |
+
Section 1
|
152 |
+
Basic Types and Operators
|
153 |
+
C provides a standard, minimal set of basic data types. Sometimes these are called
|
154 |
+
"primitive" types. More complex data structures can be built up from these basic types.
|
155 |
+
|
156 |
+
Integer Types
|
157 |
+
The "integral" types in C form a family of integer types. They all behave like integers and
|
158 |
+
can be mixed together and used in similar ways. The differences are due to the different
|
159 |
+
number of bits ("widths") used to implement each type -- the wider types can store a
|
160 |
+
greater ranges of values.
|
161 |
+
|
162 |
+
char
|
163 |
+
|
164 |
+
ASCII character -- at least 8 bits. Pronounced "car". As a practical matter
|
165 |
+
char is basically always a byte which is 8 bits which is enough to store a single
|
166 |
+
ASCII character. 8 bits provides a signed range of -128..127 or an unsigned range is
|
167 |
+
0..255. char is also required to be the "smallest addressable unit" for the machine --
|
168 |
+
each byte in memory has its own address.
|
169 |
+
|
170 |
+
short
|
171 |
+
|
172 |
+
Small integer -- at least 16 bits which provides a signed range of
|
173 |
+
|
174 |
+
-32768..32767. Typical size is 16 bits. Not used so much.
|
175 |
+
|
176 |
+
int
|
177 |
+
|
178 |
+
Default integer -- at least 16 bits, with 32 bits being typical. Defined to be
|
179 |
+
|
180 |
+
the "most comfortable" size for the computer. If you do not really care about the
|
181 |
+
range for an integer variable, declare it int since that is likely to be an appropriate
|
182 |
+
size (16 or 32 bit) which works well for that machine.
|
183 |
+
|
184 |
+
long
|
185 |
+
|
186 |
+
Large integer -- at least 32 bits. Typical size is 32 bits which gives a signed
|
187 |
+
range of about -2 billion ..+2 billion. Some compilers support "long long" for 64 bit
|
188 |
+
ints.
|
189 |
+
|
190 |
+
The integer types can be preceded by the qualifier unsigned which disallows
|
191 |
+
representing negative numbers, but doubles the largest positive number representable. For
|
192 |
+
example, a 16 bit implementation of short can store numbers in the range
|
193 |
+
-32768..32767, while unsigned short can store 0..65535. You can think of pointers
|
194 |
+
as being a form of unsigned long on a machine with 4 byte pointers. In my opinion,
|
195 |
+
it's best to avoid using unsigned unless you really need to. It tends to cause more
|
196 |
+
misunderstandings and problems than it is worth.
|
197 |
+
|
198 |
+
Extra: Portability Problems
|
199 |
+
Instead of defining the exact sizes of the integer types, C defines lower bounds. This
|
200 |
+
makes it easier to implement C compilers on a wide range of hardware. Unfortunately it
|
201 |
+
occasionally leads to bugs where a program runs differently on a 16-bit-int machine than
|
202 |
+
it runs on a 32-bit-int machine. In particular, if you are designing a function that will be
|
203 |
+
implemented on several different machines, it is a good idea to use typedefs to set up
|
204 |
+
types like Int32 for 32 bit int and Int16 for 16 bit int. That way you can prototype a
|
205 |
+
function Foo(Int32) and be confident that the typedefs for each machine will be set so
|
206 |
+
that the function really takes exactly a 32 bit int. That way the code will behave the same
|
207 |
+
on all the different machines.
|
208 |
+
|
209 |
+
char Constants
|
210 |
+
A char constant is written with single quotes (') like 'A' or 'z'. The char constant 'A' is
|
211 |
+
really just a synonym for the ordinary integer value 65 which is the ASCII value for
|
212 |
+
|
213 |
+
4
|
214 |
+
|
215 |
+
uppercase 'A'. There are special case char constants, such as '\t' for tab, for characters
|
216 |
+
which are not convenient to type on a keyboard.
|
217 |
+
|
218 |
+
'A'
|
219 |
+
|
220 |
+
uppercase 'A' character
|
221 |
+
|
222 |
+
'\n'
|
223 |
+
|
224 |
+
newline character
|
225 |
+
|
226 |
+
'\t'
|
227 |
+
|
228 |
+
tab character
|
229 |
+
|
230 |
+
'\0'
|
231 |
+
|
232 |
+
the "null" character -- integer value 0 (different from the char digit '0')
|
233 |
+
|
234 |
+
'\012' the character with value 12 in octal, which is decimal 10
|
235 |
+
|
236 |
+
int Constants
|
237 |
+
Numbers in the source code such as 234 default to type int. They may be followed by
|
238 |
+
an 'L' (upper or lower case) to designate that the constant should be a long such as 42L.
|
239 |
+
An integer constant can be written with a leading 0x to indicate that it is expressed in
|
240 |
+
hexadecimal -- 0x10 is way of expressing the number 16. Similarly, a constant may be
|
241 |
+
written in octal by preceding it with "0" -- 012 is a way of expressing the number 10.
|
242 |
+
|
243 |
+
Type Combination and Promotion
|
244 |
+
The integral types may be mixed together in arithmetic expressions since they are all
|
245 |
+
basically just integers with variation in their width. For example, char and int can be
|
246 |
+
combined in arithmetic expressions such as ('b' + 5). How does the compiler deal
|
247 |
+
with the different widths present in such an expression? In such a case, the compiler
|
248 |
+
"promotes" the smaller type (char) to be the same size as the larger type (int) before
|
249 |
+
combining the values. Promotions are determined at compile time based purely on the
|
250 |
+
types of the values in the expressions. Promotions do not lose information -- they always
|
251 |
+
convert from a type to compatible, larger type to avoid losing information.
|
252 |
+
|
253 |
+
Pitfall -- int Overflow
|
254 |
+
I once had a piece of code which tried to compute the number of bytes in a buffer with
|
255 |
+
the expression (k * 1024) where k was an int representing the number of kilobytes
|
256 |
+
I wanted. Unfortunately this was on a machine where int happened to be 16 bits. Since
|
257 |
+
k and 1024 were both int, there was no promotion. For values of k >= 32, the product
|
258 |
+
was too big to fit in the 16 bit int resulting in an overflow. The compiler can do
|
259 |
+
whatever it wants in overflow situations -- typically the high order bits just vanish. One
|
260 |
+
way to fix the code was to rewrite it as (k * 1024L) -- the long constant forced the
|
261 |
+
promotion of the int. This was not a fun bug to track down -- the expression sure looked
|
262 |
+
reasonable in the source code. Only stepping past the key line in the debugger showed the
|
263 |
+
overflow problem. "Professional Programmer's Language." This example also
|
264 |
+
demonstrates the way that C only promotes based on the types in an expression. The
|
265 |
+
compiler does not consider the values 32 or 1024 to realize that the operation will
|
266 |
+
overflow (in general, the values don't exist until run time anyway). The compiler just
|
267 |
+
looks at the compile time types, int and int in this case, and thinks everything is fine.
|
268 |
+
|
269 |
+
Floating point Types
|
270 |
+
|
271 |
+
float
|
272 |
+
Single precision floating point number
|
273 |
+
double Double precision floating point number
|
274 |
+
long double Possibly even bigger floating point number (somewhat obscure)
|
275 |
+
Constants in the source code such as 3.14 default to type double unless the are suffixed
|
276 |
+
with an 'f' (float) or 'l' (long double). Single precision equates to about 6 digits of
|
277 |
+
|
278 |
+
typical size: 32 bits
|
279 |
+
typical size: 64 bits
|
280 |
+
|
281 |
+
5
|
282 |
+
|
283 |
+
precision and double is about 15 digits of precision. Most C programs use double for
|
284 |
+
their computations. The main reason to use float is to save memory if many numbers
|
285 |
+
need to be stored. The main thing to remember about floating point numbers is that they
|
286 |
+
are inexact. For example, what is the value of the following double expression?
|
287 |
+
|
288 |
+
(1.0/3.0 + 1.0/3.0 + 1.0/3.0)
|
289 |
+
|
290 |
+
// is this equal to 1.0 exactly?
|
291 |
+
|
292 |
+
The sum may or may not be 1.0 exactly, and it may vary from one type of machine to
|
293 |
+
another. For this reason, you should never compare floating numbers to eachother for
|
294 |
+
equality (==) -- use inequality (<) comparisons instead. Realize that a correct C program
|
295 |
+
run on different computers may produce slightly different outputs in the rightmost digits
|
296 |
+
of its floating point computations.
|
297 |
+
|
298 |
+
Comments
|
299 |
+
Comments in C are enclosed by slash/star pairs: /* .. comments .. */ which
|
300 |
+
may cross multiple lines. C++ introduced a form of comment started by two slashes and
|
301 |
+
extending to the end of the line: // comment until the line end
|
302 |
+
The // comment form is so handy that many C compilers now also support it, although it
|
303 |
+
is not technically part of the C language.
|
304 |
+
|
305 |
+
Along with well-chosen function names, comments are an important part of well written
|
306 |
+
code. Comments should not just repeat what the code says. Comments should describe
|
307 |
+
what the code accomplishes which is much more interesting than a translation of what
|
308 |
+
each statement does. Comments should also narrate what is tricky or non-obvious about a
|
309 |
+
section of code.
|
310 |
+
|
311 |
+
Variables
|
312 |
+
As in most languages, a variable declaration reserves and names an area in memory at run
|
313 |
+
time to hold a value of particular type. Syntactically, C puts the type first followed by the
|
314 |
+
name of the variable. The following declares an int variable named "num" and the 2nd
|
315 |
+
line stores the value 42 into num.
|
316 |
+
|
317 |
+
int num;
|
318 |
+
num = 42;
|
319 |
+
|
320 |
+
num
|
321 |
+
|
322 |
+
42
|
323 |
+
|
324 |
+
A variable corresponds to an area of memory which can store a value of the given type.
|
325 |
+
Making a drawing is an excellent way to think about the variables in a program. Draw
|
326 |
+
each variable as box with the current value inside the box. This may seem like a
|
327 |
+
"beginner" technique, but when I'm buried in some horribly complex programming
|
328 |
+
problem, I invariably resort to making a drawing to help think the problem through.
|
329 |
+
|
330 |
+
Variables, such as num, do not have their memory cleared or set in any way when they
|
331 |
+
are allocated at run time. Variables start with random values, and it is up to the program
|
332 |
+
to set them to something sensible before depending on their values.
|
333 |
+
|
334 |
+
Names in C are case sensitive so "x" and "X" refer to different variables. Names can
|
335 |
+
contain digits and underscores (_), but may not begin with a digit. Multiple variables can
|
336 |
+
be declared after the type by separating them with commas. C is a classical "compile
|
337 |
+
time" language -- the names of the variables, their types, and their implementations are all
|
338 |
+
flushed out by the compiler at compile time (as opposed to figuring such details out at run
|
339 |
+
time like an interpreter).
|
340 |
+
|
341 |
+
6
|
342 |
+
|
343 |
+
float x, y, z, X;
|
344 |
+
|
345 |
+
Assignment Operator =
|
346 |
+
The assignment operator is the single equals sign (=).
|
347 |
+
|
348 |
+
i = 6;
|
349 |
+
i = i + 1;
|
350 |
+
|
351 |
+
The assignment operator copies the value from its right hand side to the variable on its
|
352 |
+
left hand side. The assignment also acts as an expression which returns the newly
|
353 |
+
assigned value. Some programmers will use that feature to write things like the following.
|
354 |
+
|
355 |
+
y = (x = 2 * x);
|
356 |
+
|
357 |
+
// double x, and also put x's new value in y
|
358 |
+
|
359 |
+
Truncation
|
360 |
+
The opposite of promotion, truncation moves a value from a type to a smaller type. In
|
361 |
+
that case, the compiler just drops the extra bits. It may or may not generate a compile
|
362 |
+
time warning of the loss of information. Assigning from an integer to a smaller integer
|
363 |
+
(e.g.. long to int, or int to char) drops the most significant bits. Assigning from a
|
364 |
+
floating point type to an integer drops the fractional part of the number.
|
365 |
+
|
366 |
+
char ch;
|
367 |
+
int i;
|
368 |
+
|
369 |
+
i = 321;
|
370 |
+
ch = i;
|
371 |
+
// ch is now 65
|
372 |
+
|
373 |
+
// truncation of an int value to fit in a char
|
374 |
+
|
375 |
+
The assignment will drop the upper bits of the int 321. The lower 8 bits of the number
|
376 |
+
321 represents the number 65 (321 - 256). So the value of ch will be (char)65 which
|
377 |
+
happens to be 'A'.
|
378 |
+
|
379 |
+
The assignment of a floating point type to an integer type will drop the fractional part of
|
380 |
+
the number. The following code will set i to the value 3. This happens when assigning a
|
381 |
+
floating point number to an integer or passing a floating point number to a function which
|
382 |
+
takes an integer.
|
383 |
+
|
384 |
+
double pi;
|
385 |
+
int i;
|
386 |
+
|
387 |
+
pi = 3.14159;
|
388 |
+
i = pi;
|
389 |
+
// i is now 3
|
390 |
+
|
391 |
+
// truncation of a double to fit in an int
|
392 |
+
|
393 |
+
Pitfall -- int vs. float Arithmetic
|
394 |
+
Here's an example of the sort of code where int vs. float arithmetic can cause
|
395 |
+
problems. Suppose the following code is supposed to scale a homework score in the
|
396 |
+
range 0..20 to be in the range 0..100.
|
397 |
+
|
398 |
+
{
|
399 |
+
|
400 |
+
int score;
|
401 |
+
|
402 |
+
...// suppose score gets set in the range 0..20 somehow
|
403 |
+
|
404 |
+
7
|
405 |
+
|
406 |
+
score = (score / 20) * 100;
|
407 |
+
|
408 |
+
// NO -- score/20 truncates to 0
|
409 |
+
|
410 |
+
...
|
411 |
+
|
412 |
+
Unfortunately, score will almost always be set to 0 for this code because the integer
|
413 |
+
division in the expression (score/20) will be 0 for every value of score less than 20.
|
414 |
+
The fix is to force the quotient to be computed as a floating point number...
|
415 |
+
|
416 |
+
score = ((double)score / 20) * 100;
|
417 |
+
|
418 |
+
// OK -- floating point division from cast
|
419 |
+
|
420 |
+
score = (score / 20.0) * 100;
|
421 |
+
|
422 |
+
// OK -- floating point division from 20.0
|
423 |
+
|
424 |
+
score = (int)(score / 20.0) * 100;
|
425 |
+
|
426 |
+
// NO -- the (int) truncates the floating
|
427 |
+
// quotient back to 0
|
428 |
+
|
429 |
+
No Boolean -- Use int
|
430 |
+
C does not have a distinct boolean type-- int is used instead. The language treats integer
|
431 |
+
0 as false and all non-zero values as true. So the statement...
|
432 |
+
|
433 |
+
i = 0;
|
434 |
+
while (i - 10) {
|
435 |
+
|
436 |
+
...
|
437 |
+
|
438 |
+
will execute until the variable i takes on the value 10 at which time the expression (i -
|
439 |
+
10) will become false (i.e. 0). (we'll see the while() statement a bit later)
|
440 |
+
|
441 |
+
Mathematical Operators
|
442 |
+
C includes the usual binary and unary arithmetic operators. See the appendix for the table
|
443 |
+
of precedence. Personally, I just use parenthesis liberally to avoid any bugs due to a
|
444 |
+
misunderstanding of precedence. The operators are sensitive to the type of the operands.
|
445 |
+
So division (/) with two integer arguments will do integer division. If either argument is
|
446 |
+
a float, it does floating point division. So (6/4) evaluates to 1 while (6/4.0)
|
447 |
+
evaluates to 1.5 -- the 6 is promoted to 6.0 before the division.
|
448 |
+
|
449 |
+
+ Addition
|
450 |
+
|
451 |
+
- Subtraction
|
452 |
+
|
453 |
+
/ Division
|
454 |
+
|
455 |
+
* Multiplication
|
456 |
+
|
457 |
+
% Remainder (mod)
|
458 |
+
|
459 |
+
Unary Increment Operators: ++ --
|
460 |
+
The unary ++ and -- operators increment or decrement the value in a variable. There are
|
461 |
+
"pre" and "post" variants for both operators which do slightly different things (explained
|
462 |
+
below)
|
463 |
+
|
464 |
+
var++
|
465 |
+
|
466 |
+
increment
|
467 |
+
|
468 |
+
"post" variant
|
469 |
+
|
470 |
+
++var
|
471 |
+
|
472 |
+
increment
|
473 |
+
|
474 |
+
"pre" variant
|
475 |
+
|
476 |
+
var--
|
477 |
+
|
478 |
+
decrement
|
479 |
+
|
480 |
+
"post" variant
|
481 |
+
|
482 |
+
--var
|
483 |
+
|
484 |
+
decrement
|
485 |
+
|
486 |
+
"pre" variant
|
487 |
+
|
488 |
+
8
|
489 |
+
|
490 |
+
int i = 42;
|
491 |
+
i++;
|
492 |
+
// i is now 43
|
493 |
+
i--;
|
494 |
+
// i is now 42
|
495 |
+
|
496 |
+
// increment on i
|
497 |
+
|
498 |
+
// decrement on i
|
499 |
+
|
500 |
+
Pre and Post Variations
|
501 |
+
The Pre/Post variation has to do with nesting a variable with the increment or decrement
|
502 |
+
operator inside an expression -- should the entire expression represent the value of the
|
503 |
+
variable before or after the change? I never use the operators in this way (see below), but
|
504 |
+
an example looks like...
|
505 |
+
|
506 |
+
int i = 42;
|
507 |
+
int j;
|
508 |
+
|
509 |
+
j = (i++ + 10);
|
510 |
+
// i is now 43
|
511 |
+
// j is now 52 (NOT 53)
|
512 |
+
|
513 |
+
j = (++i + 10)
|
514 |
+
// i is now 44
|
515 |
+
// j is now 54
|
516 |
+
|
517 |
+
C Programming Cleverness and Ego Issues
|
518 |
+
Relying on the difference between the pre and post variations of these operators is a
|
519 |
+
classic area of C programmer ego showmanship. The syntax is a little tricky. It makes the
|
520 |
+
code a little shorter. These qualities drive some C programmers to show off how clever
|
521 |
+
they are. C invites this sort of thing since the language has many areas (this is just one
|
522 |
+
example) where the programmer can get a complex effect using a code which is short and
|
523 |
+
dense.
|
524 |
+
|
525 |
+
If I want j to depend on i's value before the increment, I write...
|
526 |
+
|
527 |
+
j = (i + 10);
|
528 |
+
i++;
|
529 |
+
|
530 |
+
Or if I want to j to use the value after the increment, I write...
|
531 |
+
|
532 |
+
i++;
|
533 |
+
j = (i + 10);
|
534 |
+
|
535 |
+
Now then, isn't that nicer? (editorial) Build programs that do something cool rather than
|
536 |
+
programs which flex the language's syntax. Syntax -- who cares?
|
537 |
+
|
538 |
+
Relational Operators
|
539 |
+
These operate on integer or floating point values and return a 0 or 1 boolean value.
|
540 |
+
|
541 |
+
==
|
542 |
+
|
543 |
+
Equal
|
544 |
+
|
545 |
+
9
|
546 |
+
|
547 |
+
!=
|
548 |
+
|
549 |
+
>
|
550 |
+
|
551 |
+
<
|
552 |
+
|
553 |
+
>=
|
554 |
+
|
555 |
+
<=
|
556 |
+
|
557 |
+
Not Equal
|
558 |
+
|
559 |
+
Greater Than
|
560 |
+
|
561 |
+
Less Than
|
562 |
+
|
563 |
+
Greater or Equal
|
564 |
+
|
565 |
+
Less or Equal
|
566 |
+
|
567 |
+
To see if x equals three, write something like:
|
568 |
+
|
569 |
+
if (x == 3) ...
|
570 |
+
|
571 |
+
Pitfall = ==
|
572 |
+
|
573 |
+
An absolutely classic pitfall is to write assignment (=) when you mean comparison (==).
|
574 |
+
This would not be such a problem, except the incorrect assignment version compiles fine
|
575 |
+
because the compiler assumes you mean to use the value returned by the assignment. This
|
576 |
+
is rarely what you want
|
577 |
+
|
578 |
+
if (x = 3) ...
|
579 |
+
|
580 |
+
This does not test if x is 3. This sets x to the value 3, and then returns the 3 to the if for
|
581 |
+
testing. 3 is not 0, so it counts as "true" every time. This is probably the single most
|
582 |
+
common error made by beginning C programmers. The problem is that the compiler is no
|
583 |
+
help -- it thinks both forms are fine, so the only defense is extreme vigilance when
|
584 |
+
coding. Or write "= „
|
585 |
+
mistake is an absolute classic and it's a bear to debug. Watch Out! And need I say:
|
586 |
+
"Professional Programmer's Language."
|
587 |
+
|
588 |
+
==" in big letters on the back of your hand before coding. This
|
589 |
+
|
590 |
+
Logical Operators
|
591 |
+
The value 0 is false, anything else is true. The operators evaluate left to right and stop as
|
592 |
+
soon as the truth or falsity of the expression can be deduced. (Such operators are called
|
593 |
+
"short circuiting") In ANSI C, these are furthermore guaranteed to use 1 to represent true,
|
594 |
+
and not just some random non-zero bit pattern. However, there are many C programs out
|
595 |
+
there which use values other than 1 for true (non-zero pointers for example), so when
|
596 |
+
programming, do not assume that a true boolean is necessarily 1 exactly.
|
597 |
+
|
598 |
+
!
|
599 |
+
|
600 |
+
&&
|
601 |
+
|
602 |
+
||
|
603 |
+
|
604 |
+
Boolean not (unary)
|
605 |
+
|
606 |
+
Boolean and
|
607 |
+
|
608 |
+
Boolean or
|
609 |
+
|
610 |
+
Bitwise Operators
|
611 |
+
C includes operators to manipulate memory at the bit level. This is useful for writing low-
|
612 |
+
level hardware or operating system code where the ordinary abstractions of numbers,
|
613 |
+
characters, pointers, etc... are insufficient -- an increasingly rare need. Bit manipulation
|
614 |
+
code tends to be less "portable". Code is "portable" if with no programmer intervention it
|
615 |
+
compiles and runs correctly on different types of computers. The bitwise operations are
|
616 |
+
|
617 |
+
10
|
618 |
+
|
619 |
+
typically used with unsigned types. In particular, the shift operations are guaranteed to
|
620 |
+
shift 0 bits into the newly vacated positions when used on unsigned values.
|
621 |
+
|
622 |
+
~
|
623 |
+
|
624 |
+
&
|
625 |
+
|
626 |
+
|
|
627 |
+
|
628 |
+
^
|
629 |
+
|
630 |
+
>>
|
631 |
+
|
632 |
+
<<
|
633 |
+
|
634 |
+
Bitwise Negation (unary) – flip 0 to 1 and 1 to 0 throughout
|
635 |
+
|
636 |
+
Bitwise And
|
637 |
+
|
638 |
+
Bitwise Or
|
639 |
+
|
640 |
+
Bitwise Exclusive Or
|
641 |
+
|
642 |
+
Right Shift by right hand side (RHS) (divide by power of 2)
|
643 |
+
|
644 |
+
Left Shift by RHS (multiply by power of 2)
|
645 |
+
|
646 |
+
Do not confuse the Bitwise operators with the logical operators. The bitwise connectives
|
647 |
+
are one character wide (&, |) while the boolean connectives are two characters wide (&&,
|
648 |
+
||). The bitwise operators have higher precedence than the boolean operators. The
|
649 |
+
compiler will never help you out with a type error if you use & when you meant &&. As
|
650 |
+
far as the type checker is concerned, they are identical-- they both take and produce
|
651 |
+
integers since there is no distinct boolean type.
|
652 |
+
|
653 |
+
Other Assignment Operators
|
654 |
+
In addition to the plain = operator, C includes many shorthand operators which represents
|
655 |
+
variations on the basic =. For example "+=" adds the right hand side to the left hand side.
|
656 |
+
x = x + 10; can be reduced to x += 10;. This is most useful if x is a long
|
657 |
+
expression such as the following, and in some cases it may run a little faster.
|
658 |
+
|
659 |
+
person->relatives.mom.numChildren += 2;
|
660 |
+
|
661 |
+
// increase children by 2
|
662 |
+
|
663 |
+
Here's the list of assignment shorthand operators...
|
664 |
+
|
665 |
+
+=, -= Increment or decrement by RHS
|
666 |
+
|
667 |
+
*=, /= Multiply or divide by RHS
|
668 |
+
|
669 |
+
%=
|
670 |
+
|
671 |
+
>>=
|
672 |
+
|
673 |
+
<<=
|
674 |
+
|
675 |
+
Mod by RHS
|
676 |
+
|
677 |
+
Bitwise right shift by RHS (divide by power of 2)
|
678 |
+
|
679 |
+
Bitwise left shift RHS (multiply by power of 2)
|
680 |
+
|
681 |
+
&=, |=, ^=
|
682 |
+
|
683 |
+
Bitwise and, or, xor by RHS
|
684 |
+
|
685 |
+
11
|
686 |
+
|
687 |
+
Section 2
|
688 |
+
Control Structures
|
689 |
+
Curly Braces {}
|
690 |
+
C uses curly braces ({}) to group multiple statements together. The statements execute in
|
691 |
+
order. Some languages let you declare variables on any line (C++). Other languages insist
|
692 |
+
that variables are declared only at the beginning of functions (Pascal). C takes the middle
|
693 |
+
road -- variables may be declared within the body of a function, but they must follow a
|
694 |
+
'{'. More modern languages like Java and C++ allow you to declare variables on any line,
|
695 |
+
which is handy.
|
696 |
+
|
697 |
+
If Statement
|
698 |
+
Both an if and an if-else are available in C. The <expression> can be any valid
|
699 |
+
expression. The parentheses around the expression are required, even if it is just a single
|
700 |
+
variable.
|
701 |
+
|
702 |
+
if (<expression>) <statement>
|
703 |
+
|
704 |
+
// simple form with no {}'s or else clause
|
705 |
+
|
706 |
+
if (<expression>) {
|
707 |
+
|
708 |
+
// simple form with {}'s to group statements
|
709 |
+
|
710 |
+
<statement>
|
711 |
+
<statement>
|
712 |
+
|
713 |
+
}
|
714 |
+
|
715 |
+
if (<expression>) {
|
716 |
+
|
717 |
+
// full then/else form
|
718 |
+
|
719 |
+
<statement>
|
720 |
+
|
721 |
+
}
|
722 |
+
else {
|
723 |
+
|
724 |
+
<statement>
|
725 |
+
|
726 |
+
}
|
727 |
+
|
728 |
+
Conditional Expression -or- The Ternary Operator
|
729 |
+
The conditional expression can be used as a shorthand for some if-else statements. The
|
730 |
+
general syntax of the conditional operator is:
|
731 |
+
|
732 |
+
<expression1> ? <expression2> : <expression3>
|
733 |
+
|
734 |
+
This is an expression, not a statement, so it represents a value. The operator works by
|
735 |
+
evaluating expression1. If it is true (non-zero), it evaluates and returns expression2 .
|
736 |
+
Otherwise, it evaluates and returns expression3.
|
737 |
+
|
738 |
+
The classic example of the ternary operator is to return the smaller of two variables.
|
739 |
+
Every once in a while, the following form is just what you needed. Instead of...
|
740 |
+
|
741 |
+
if (x < y) {
|
742 |
+
|
743 |
+
min = x;
|
744 |
+
|
745 |
+
}
|
746 |
+
else {
|
747 |
+
|
748 |
+
min = y;
|
749 |
+
|
750 |
+
}
|
751 |
+
|
752 |
+
12
|
753 |
+
|
754 |
+
You just say...
|
755 |
+
|
756 |
+
min = (x < y) ? x : y;
|
757 |
+
|
758 |
+
Switch Statement
|
759 |
+
The switch statement is a sort of specialized form of if used to efficiently separate
|
760 |
+
different blocks of code based on the value of an integer. The switch expression is
|
761 |
+
evaluated, and then the flow of control jumps to the matching const-expression case. The
|
762 |
+
case expressions are typically int or char constants. The switch statement is probably
|
763 |
+
the single most syntactically awkward and error-prone features of the C language.
|
764 |
+
|
765 |
+
switch (<expression>) {
|
766 |
+
|
767 |
+
case <const-expression-1>:
|
768 |
+
|
769 |
+
<statement>
|
770 |
+
break;
|
771 |
+
|
772 |
+
case <const-expression-2>:
|
773 |
+
|
774 |
+
<statement>
|
775 |
+
break;
|
776 |
+
|
777 |
+
case <const-expression-3>:
|
778 |
+
case <const-expression-4>:
|
779 |
+
|
780 |
+
<statement>
|
781 |
+
break;
|
782 |
+
|
783 |
+
default:
|
784 |
+
|
785 |
+
// optional
|
786 |
+
|
787 |
+
<statement>
|
788 |
+
|
789 |
+
}
|
790 |
+
|
791 |
+
// here we combine case 3 and 4
|
792 |
+
|
793 |
+
Each constant needs its own case keyword and a trailing colon (:). Once execution has
|
794 |
+
jumped to a particular case, the program will keep running through all the cases from that
|
795 |
+
point down -- this so called "fall through" operation is used in the above example so that
|
796 |
+
expression-3 and expression-4 run the same statements. The explicit break statements
|
797 |
+
are necessary to exit the switch. Omitting the break statements is a common error -- it
|
798 |
+
compiles, but leads to inadvertent fall-through behavior.
|
799 |
+
|
800 |
+
Why does the switch statement fall-through behavior work the way it does? The best
|
801 |
+
explanation I can think of is that originally C was developed for an audience of assembly
|
802 |
+
language programmers. The assembly language programmers were used to the idea of a
|
803 |
+
jump table with fall-through behavior, so that's the way C does it (it's also relatively easy
|
804 |
+
to implement it this way.) Unfortunately, the audience for C is now quite different, and
|
805 |
+
the fall-through behavior is widely regarded as a terrible part of the language.
|
806 |
+
|
807 |
+
While Loop
|
808 |
+
The while loop evaluates the test expression before every loop, so it can execute zero
|
809 |
+
times if the condition is initially false. It requires the parenthesis like the if.
|
810 |
+
|
811 |
+
while (<expression>) {
|
812 |
+
|
813 |
+
<statement>
|
814 |
+
|
815 |
+
}
|
816 |
+
|
817 |
+
13
|
818 |
+
|
819 |
+
Do-While Loop
|
820 |
+
Like a while, but with the test condition at the bottom of the loop. The loop body will
|
821 |
+
always execute at least once. The do-while is an unpopular area of the language, most
|
822 |
+
everyone tries to use the straight while if at all possible.
|
823 |
+
|
824 |
+
do {
|
825 |
+
|
826 |
+
<statement>
|
827 |
+
|
828 |
+
} while (<expression>)
|
829 |
+
|
830 |
+
For Loop
|
831 |
+
The for loop in C is the most general looping construct. The loop header contains three
|
832 |
+
parts: an initialization, a continuation condition, and an action.
|
833 |
+
|
834 |
+
for (<initialization>; <continuation>; <action>) {
|
835 |
+
|
836 |
+
<statement>
|
837 |
+
|
838 |
+
}
|
839 |
+
|
840 |
+
The initialization is executed once before the body of the loop is entered. The loop
|
841 |
+
continues to run as long as the continuation condition remains true (like a while). After
|
842 |
+
every execution of the loop, the action is executed. The following example executes 10
|
843 |
+
times by counting 0..9. Many loops look very much like the following...
|
844 |
+
|
845 |
+
for (i = 0; i < 10; i++) {
|
846 |
+
|
847 |
+
<statement>
|
848 |
+
|
849 |
+
}
|
850 |
+
|
851 |
+
C programs often have series of the form 0..(some_number-1). It's idiomatic in C for the
|
852 |
+
above type loop to start at 0 and use < in the test so the series runs up to but not equal to
|
853 |
+
the upper bound. In other languages you might start at 1 and use <= in the test.
|
854 |
+
|
855 |
+
Each of the three parts of the for loop can be made up of multiple expressions separated
|
856 |
+
by commas. Expressions separated by commas are executed in order, left to right, and
|
857 |
+
represent the value of the last expression. (See the string-reverse example below for a
|
858 |
+
demonstration of a complex for loop.)
|
859 |
+
|
860 |
+
Break
|
861 |
+
The break statement will move control outside a loop or switch statement. Stylistically
|
862 |
+
speaking, break has the potential to be a bit vulgar. It's preferable to use a straight
|
863 |
+
while with a single test at the top if possible. Sometimes you are forced to use a break
|
864 |
+
because the test can occur only somewhere in the midst of the statements in the loop
|
865 |
+
body. To keep the code readable, be sure to make the break obvious -- forgetting to
|
866 |
+
account for the action of a break is a traditional source of bugs in loop behavior.
|
867 |
+
|
868 |
+
while (<expression>) {
|
869 |
+
|
870 |
+
<statement>
|
871 |
+
<statement>
|
872 |
+
|
873 |
+
if (<condition which can only be evaluated here>)
|
874 |
+
|
875 |
+
break;
|
876 |
+
|
877 |
+
<statement>
|
878 |
+
<statement>
|
879 |
+
|
880 |
+
}
|
881 |
+
// control jumps down here on the break
|
882 |
+
|
883 |
+
14
|
884 |
+
|
885 |
+
The break does not work with if. It only works in loops and switches. Thinking that a
|
886 |
+
break refers to an if when it really refers to the enclosing while has created some high
|
887 |
+
quality bugs. When using a break, it's nice to write the enclosing loop to iterate in the
|
888 |
+
most straightforward, obvious, normal way, and then use the break to explicitly catch
|
889 |
+
the exceptional, weird cases.
|
890 |
+
|
891 |
+
Continue
|
892 |
+
The continue statement causes control to jump to the bottom of the loop, effectively
|
893 |
+
skipping over any code below the continue. As with break, this has a reputation as
|
894 |
+
being vulgar, so use it sparingly. You can almost always get the effect more clearly using
|
895 |
+
an if inside your loop.
|
896 |
+
|
897 |
+
while (<expression>) {
|
898 |
+
|
899 |
+
...
|
900 |
+
if (<condition>)
|
901 |
+
continue;
|
902 |
+
|
903 |
+
...
|
904 |
+
...
|
905 |
+
// control jumps here on the continue
|
906 |
+
|
907 |
+
}
|
908 |
+
|
909 |
+
15
|
910 |
+
|
911 |
+
Section 3
|
912 |
+
Complex Data Types
|
913 |
+
C has the usual facilities for grouping things together to form composite types-- arrays
|
914 |
+
and records (which are called "structures"). The following definition declares a type
|
915 |
+
called "struct fraction" that has two integer sub fields named "numerator" and
|
916 |
+
"denominator". If you forget the semicolon it tends to produce a syntax error in whatever
|
917 |
+
thing follows the struct declaration.
|
918 |
+
|
919 |
+
struct fraction {
|
920 |
+
int numerator;
|
921 |
+
int denominator;
|
922 |
+
|
923 |
+
};
|
924 |
+
|
925 |
+
// Don't forget the semicolon!
|
926 |
+
|
927 |
+
This declaration introduces the type struct fraction (both words are required) as a
|
928 |
+
new type. C uses the period (.) to access the fields in a record. You can copy two records
|
929 |
+
of the same type using a single assignment statement, however == does not work on
|
930 |
+
structs.
|
931 |
+
|
932 |
+
struct fraction f1, f2;
|
933 |
+
|
934 |
+
// declare two fractions
|
935 |
+
|
936 |
+
f1.numerator = 22;
|
937 |
+
f1.denominator = 7;
|
938 |
+
|
939 |
+
f2 = f1;
|
940 |
+
|
941 |
+
// this copies over the whole struct
|
942 |
+
|
943 |
+
Arrays
|
944 |
+
The simplest type of array in C is one which is declared and used in one place. There are
|
945 |
+
more complex uses of arrays which I will address later along with pointers. The following
|
946 |
+
declares an array called scores to hold 100 integers and sets the first and last elements.
|
947 |
+
C arrays are always indexed from 0. So the first int in scores array is scores[0]
|
948 |
+
and the last is scores[99].
|
949 |
+
|
950 |
+
int scores[100];
|
951 |
+
|
952 |
+
scores[0] = 13;
|
953 |
+
scores[99] = 42;
|
954 |
+
|
955 |
+
// set first element
|
956 |
+
// set last element
|
957 |
+
|
958 |
+
16
|
959 |
+
|
960 |
+
scores
|
961 |
+
|
962 |
+
The name of the array refers to the
|
963 |
+
whole array. (implementation) it
|
964 |
+
works by representing a pointer to the
|
965 |
+
start of the array.
|
966 |
+
|
967 |
+
13
|
968 |
+
|
969 |
+
-5673
|
970 |
+
|
971 |
+
22541
|
972 |
+
|
973 |
+
Index
|
974 |
+
|
975 |
+
0
|
976 |
+
|
977 |
+
1
|
978 |
+
|
979 |
+
2
|
980 |
+
|
981 |
+
42
|
982 |
+
|
983 |
+
99
|
984 |
+
|
985 |
+
There is space for
|
986 |
+
each int element in
|
987 |
+
the scores array —
|
988 |
+
this element is
|
989 |
+
referred to as
|
990 |
+
scores[0].
|
991 |
+
|
992 |
+
These elements
|
993 |
+
have random
|
994 |
+
values because the
|
995 |
+
code has not yet
|
996 |
+
initialized them to
|
997 |
+
anything.
|
998 |
+
|
999 |
+
Someone else’s memory
|
1000 |
+
off either end of the
|
1001 |
+
array — do not read or
|
1002 |
+
write this memory.
|
1003 |
+
|
1004 |
+
It's a very common error to try to refer to non-existent scores[100] element. C does
|
1005 |
+
not do any run time or compile time bounds checking in arrays. At run time the code will
|
1006 |
+
just access or mangle whatever memory it happens to hit and crash or misbehave in some
|
1007 |
+
unpredictable way thereafter. "Professional programmer's language." The convention of
|
1008 |
+
numbering things 0..(number of things - 1) pervades the language. To best
|
1009 |
+
integrate with C and other C programmers, you should use that sort of numbering in your
|
1010 |
+
own data structures as well.
|
1011 |
+
|
1012 |
+
Multidimensional Arrays
|
1013 |
+
The following declares a two-dimensional 10 by 10 array of integers and sets the first and
|
1014 |
+
last elements to be 13.
|
1015 |
+
|
1016 |
+
int board [10][10];
|
1017 |
+
|
1018 |
+
board[0][0] = 13;
|
1019 |
+
board[9][9] = 13;
|
1020 |
+
|
1021 |
+
The implementation of the array stores all the elements in a single contiguous block of
|
1022 |
+
memory. The other possible implementation would be a combination of several distinct
|
1023 |
+
one dimensional arrays -- that's not how C does it. In memory, the array is arranged with
|
1024 |
+
the elements of the rightmost index next to each other. In other words, board[1][8]
|
1025 |
+
comes right before board[1][9] in memory.
|
1026 |
+
|
1027 |
+
(highly optional efficiency point) It's typically efficient to access memory which is near
|
1028 |
+
other recently accessed memory. This means that the most efficient way to read through a
|
1029 |
+
chunk of the array is to vary the rightmost index the most frequently since that will access
|
1030 |
+
elements that are near each other in memory.
|
1031 |
+
|
1032 |
+
17
|
1033 |
+
|
1034 |
+
Array of Structs
|
1035 |
+
The following declares an array named "numbers" which holds 1000 struct
|
1036 |
+
fraction's.
|
1037 |
+
|
1038 |
+
struct fraction numbers[1000];
|
1039 |
+
|
1040 |
+
numbers[0].numerator = 22;
|
1041 |
+
numbers[0].denominator = 7;
|
1042 |
+
|
1043 |
+
/* set the 0th struct fraction */
|
1044 |
+
|
1045 |
+
Here's a general trick for unraveling C variable declarations: look at the right hand side
|
1046 |
+
and imagine that it is an expression. The type of that expression is the left hand side. For
|
1047 |
+
the above declarations, an expression which looks like the right hand side
|
1048 |
+
(numbers[1000], or really anything of the form numbers[...]) will be the type
|
1049 |
+
on the left hand side (struct fraction).
|
1050 |
+
|
1051 |
+
Pointers
|
1052 |
+
A pointer is a value which represents a reference to another value sometimes known as
|
1053 |
+
the pointer's "pointee". Hopefully you have learned about pointers somewhere else, since
|
1054 |
+
the preceding sentence is probably inadequate explanation. This discussion will
|
1055 |
+
concentrate on the syntax of pointers in C -- for a much more complete discussion of
|
1056 |
+
pointers and their use see http://cslibrary.stanford.edu/102/, Pointers and Memory.
|
1057 |
+
|
1058 |
+
Syntax
|
1059 |
+
Syntactically C uses the asterisk or "star" (*) to indicate a pointer. C defines pointer types
|
1060 |
+
based on the type pointee. A char* is type of pointer which refers to a single char. a
|
1061 |
+
struct fraction* is type of pointer which refers to a struct fraction.
|
1062 |
+
|
1063 |
+
int* intPtr;
|
1064 |
+
|
1065 |
+
// declare an integer pointer variable intPtr
|
1066 |
+
|
1067 |
+
char* charPtr; // declares a character pointer --
|
1068 |
+
|
1069 |
+
// a very common type of pointer
|
1070 |
+
|
1071 |
+
// Declare two struct fraction pointers
|
1072 |
+
// (when declaring multiple variables on one line, the *
|
1073 |
+
// should go on the right with the variable)
|
1074 |
+
struct fraction *f1, *f2;
|
1075 |
+
|
1076 |
+
The Floating "*"
|
1077 |
+
In the syntax, the star is allowed to be anywhere between the base type and the variable
|
1078 |
+
name. Programmer's have their own conventions-- I generally stick the * on the left with
|
1079 |
+
the type. So the above declaration of intPtr could be written equivalently...
|
1080 |
+
|
1081 |
+
int *intPtr;
|
1082 |
+
int * intPtr;
|
1083 |
+
int* intPtr;
|
1084 |
+
|
1085 |
+
// these are all the same
|
1086 |
+
|
1087 |
+
Pointer Dereferencing
|
1088 |
+
We'll see shortly how a pointer is set to point to something -- for now just assume the
|
1089 |
+
pointer points to memory of the appropriate type. In an expression, the unary * to the left
|
1090 |
+
of a pointer dereferences it to retrieve the value it points to. The following drawing shows
|
1091 |
+
the types involved with a single pointer pointing to a struct fraction.
|
1092 |
+
|
1093 |
+
18
|
1094 |
+
|
1095 |
+
struct fraction* f1;
|
1096 |
+
|
1097 |
+
f1
|
1098 |
+
|
1099 |
+
struct fraction*
|
1100 |
+
|
1101 |
+
7
|
1102 |
+
|
1103 |
+
22
|
1104 |
+
|
1105 |
+
denominator
|
1106 |
+
|
1107 |
+
numerator
|
1108 |
+
|
1109 |
+
struct fraction
|
1110 |
+
(the whole
|
1111 |
+
block of
|
1112 |
+
memory)
|
1113 |
+
|
1114 |
+
int
|
1115 |
+
(within
|
1116 |
+
block of
|
1117 |
+
memory)
|
1118 |
+
|
1119 |
+
Expression
|
1120 |
+
f1
|
1121 |
+
*f1
|
1122 |
+
(*f1).numerator
|
1123 |
+
|
1124 |
+
Type
|
1125 |
+
struct fraction*
|
1126 |
+
struct fraction
|
1127 |
+
int
|
1128 |
+
|
1129 |
+
There's an alternate, more readable syntax available for dereferencing a pointer to a
|
1130 |
+
struct. A "->" at the right of the pointer can access any of the fields in the struct. So the
|
1131 |
+
reference to the numerator field could be written f1->numerator.
|
1132 |
+
|
1133 |
+
Here are some more complex declarations...
|
1134 |
+
|
1135 |
+
struct fraction** fp;
|
1136 |
+
|
1137 |
+
// a pointer to a pointer to a struct fraction
|
1138 |
+
|
1139 |
+
struct fraction fract_array[20];
|
1140 |
+
|
1141 |
+
// an array of 20 struct fractions
|
1142 |
+
|
1143 |
+
struct fraction* fract_ptr_array[20];
|
1144 |
+
|
1145 |
+
// an array of 20 pointers to
|
1146 |
+
// struct fractions
|
1147 |
+
|
1148 |
+
One nice thing about the C type syntax is that it avoids the circular definition problems
|
1149 |
+
which come up when a pointer structure needs to refer to itself. The following definition
|
1150 |
+
defines a node in a linked list. Note that no preparatory declaration of the node pointer
|
1151 |
+
type is necessary.
|
1152 |
+
|
1153 |
+
struct node {
|
1154 |
+
|
1155 |
+
int data;
|
1156 |
+
struct node* next;
|
1157 |
+
|
1158 |
+
};
|
1159 |
+
|
1160 |
+
The & Operator
|
1161 |
+
The & operator is one of the ways that pointers are set to point to things. The & operator
|
1162 |
+
computes a pointer to the argument to its right. The argument can be any variable which
|
1163 |
+
takes up space in the stack or heap (known as an "LValue" technically). So &i and
|
1164 |
+
&(f1->numerator) are ok, but &6 is not. Use & when you have some memory, and
|
1165 |
+
you want a pointer to that memory.
|
1166 |
+
|
1167 |
+
19
|
1168 |
+
|
1169 |
+
void foo() {
|
1170 |
+
|
1171 |
+
int* p; // p is a pointer to an integer
|
1172 |
+
int i; // i is an integer
|
1173 |
+
|
1174 |
+
p = &i; // Set p to point to i
|
1175 |
+
*p = 13; // Change what p points to -- in this case i -- to 13
|
1176 |
+
|
1177 |
+
// At this point i is 13. So is *p. In fact *p is i.
|
1178 |
+
|
1179 |
+
}
|
1180 |
+
|
1181 |
+
p
|
1182 |
+
|
1183 |
+
i
|
1184 |
+
|
1185 |
+
13
|
1186 |
+
|
1187 |
+
When using a pointer to an object created with &, it is important to only use the pointer so
|
1188 |
+
long as the object exists. A local variable exists only as long as the function where it is
|
1189 |
+
declared is still executing (we'll see functions shortly). In the above example, i exists
|
1190 |
+
only as long as foo() is executing. Therefore any pointers which were initialized with
|
1191 |
+
&i are valid only as long as foo() is executing. This "lifetime" constraint of local
|
1192 |
+
memory is standard in many languages, and is something you need to take into account
|
1193 |
+
when using the & operator.
|
1194 |
+
|
1195 |
+
NULL
|
1196 |
+
A pointer can be assigned the value 0 to explicitly represent that it does not currently
|
1197 |
+
have a pointee. Having a standard representation for "no current pointee" turns out to be
|
1198 |
+
very handy when using pointers. The constant NULL is defined to be 0 and is typically
|
1199 |
+
used when setting a pointer to NULL. Since it is just 0, a NULL pointer will behave like
|
1200 |
+
a boolean false when used in a boolean context. Dereferencing a NULL pointer is an error
|
1201 |
+
which, if you are lucky, the computer will detect at runtime -- whether the computer
|
1202 |
+
detects this depends on the operating system.
|
1203 |
+
|
1204 |
+
Pitfall -- Uninitialized Pointers
|
1205 |
+
When using pointers, there are two entities to keep track of. The pointer and the memory
|
1206 |
+
it is pointing to, sometimes called the "pointee". There are three things which must be
|
1207 |
+
done for a pointer/pointee relationship to work...
|
1208 |
+
|
1209 |
+
(1) The pointer must be declared and allocated
|
1210 |
+
|
1211 |
+
(2) The pointee must be declared and allocated
|
1212 |
+
|
1213 |
+
(3) The pointer (1) must be initialized so that it points to the pointee (2)
|
1214 |
+
|
1215 |
+
The most common pointer related error of all time is the following: Declare and allocate
|
1216 |
+
the pointer (step 1). Forget step 2 and/or 3. Start using the pointer as if it has been setup
|
1217 |
+
to point to something. Code with this error frequently compiles fine, but the runtime
|
1218 |
+
results are disastrous. Unfortunately the pointer does not point anywhere good unless (2)
|
1219 |
+
and (3) are done, so the run time dereference operations on the pointer with * will misuse
|
1220 |
+
and trample memory leading to a random crash at some point.
|
1221 |
+
|
1222 |
+
int* p;
|
1223 |
+
|
1224 |
+
*p = 13;
|
1225 |
+
|
1226 |
+
{
|
1227 |
+
|
1228 |
+
}
|
1229 |
+
|
1230 |
+
// NO NO NO p does not point to an int yet
|
1231 |
+
// this just overwrites a random area in memory
|
1232 |
+
|
1233 |
+
20
|
1234 |
+
|
1235 |
+
p
|
1236 |
+
|
1237 |
+
i
|
1238 |
+
|
1239 |
+
-14346
|
1240 |
+
|
1241 |
+
Of course your code won't be so trivial, but the bug has the same basic form: declare a
|
1242 |
+
pointer, but forget to set it up to point to a particular pointee.
|
1243 |
+
|
1244 |
+
Using Pointers
|
1245 |
+
Declaring a pointer allocates space for the pointer itself, but it does not allocate space
|
1246 |
+
for the pointee. The pointer must be set to point to something before you can dereference
|
1247 |
+
it.
|
1248 |
+
|
1249 |
+
Here's some code which doesn't do anything useful, but which does demonstrate (1) (2)
|
1250 |
+
(3) for pointer use correctly...
|
1251 |
+
|
1252 |
+
int* p;
|
1253 |
+
int i;
|
1254 |
+
struct fraction f1;
|
1255 |
+
|
1256 |
+
// (1) allocate the pointer
|
1257 |
+
// (2) allocate pointee
|
1258 |
+
|
1259 |
+
// (2) allocate pointee
|
1260 |
+
|
1261 |
+
p = &i;
|
1262 |
+
*p = 42;
|
1263 |
+
|
1264 |
+
// (3) setup p to point to i
|
1265 |
+
// ok to use p since it's setup
|
1266 |
+
|
1267 |
+
p = &(f1.numerator);
|
1268 |
+
*p = 22;
|
1269 |
+
|
1270 |
+
// (3) setup p to point to a different int
|
1271 |
+
|
1272 |
+
p = &(f1.denominator);
|
1273 |
+
*p = 7;
|
1274 |
+
|
1275 |
+
// (3)
|
1276 |
+
|
1277 |
+
So far we have just used the & operator to create pointers to simple variables such as i.
|
1278 |
+
Later, we'll see other ways of getting pointers with arrays and other techniques.
|
1279 |
+
|
1280 |
+
C Strings
|
1281 |
+
C has minimal support of character strings. For the most part, strings operate as ordinary
|
1282 |
+
arrays of characters. Their maintenance is up to the programmer using the standard
|
1283 |
+
facilities available for arrays and pointers. C does include a standard library of functions
|
1284 |
+
which perform common string operations, but the programmer is responsible for the
|
1285 |
+
managing the string memory and calling the right functions. Unfortunately computations
|
1286 |
+
involving strings are very common, so becoming a good C programmer often requires
|
1287 |
+
becoming adept at writing code which manages strings which means managing pointers
|
1288 |
+
and arrays.
|
1289 |
+
|
1290 |
+
21
|
1291 |
+
|
1292 |
+
A C string is just an array of char with the one additional convention that a "null"
|
1293 |
+
character ('\0') is stored after the last real character in the array to mark the end of the
|
1294 |
+
string. The compiler represents string constants in the source code such as "binky" as
|
1295 |
+
arrays which follow this convention. The string library functions (see the appendix for a
|
1296 |
+
partial list) operate on strings stored in this way. The most useful library function is
|
1297 |
+
strcpy(char dest[], const char source[]); which copies the bytes of
|
1298 |
+
one string over to another. The order of the arguments to strcpy() mimics the arguments
|
1299 |
+
in of '=' -- the right is assigned to the left. Another useful string function is
|
1300 |
+
strlen(const char string[]); which returns the number of characters in C
|
1301 |
+
string not counting the trailing '\0'.
|
1302 |
+
|
1303 |
+
Note that the regular assignment operator (=) does not do string copying which is why
|
1304 |
+
strcpy() is necessary. See Section 6, Advanced Pointers and Arrays, for more detail on
|
1305 |
+
how arrays and pointers work.
|
1306 |
+
|
1307 |
+
The following code allocates a 10 char array and uses strcpy() to copy the bytes of the
|
1308 |
+
string constant "binky" into that local array.
|
1309 |
+
|
1310 |
+
{
|
1311 |
+
|
1312 |
+
}
|
1313 |
+
|
1314 |
+
char localString[10];
|
1315 |
+
|
1316 |
+
strcpy(localString, "binky");
|
1317 |
+
|
1318 |
+
localString
|
1319 |
+
|
1320 |
+
b
|
1321 |
+
|
1322 |
+
0
|
1323 |
+
|
1324 |
+
i
|
1325 |
+
|
1326 |
+
1
|
1327 |
+
|
1328 |
+
n
|
1329 |
+
|
1330 |
+
k
|
1331 |
+
|
1332 |
+
y
|
1333 |
+
|
1334 |
+
0
|
1335 |
+
|
1336 |
+
x
|
1337 |
+
|
1338 |
+
x
|
1339 |
+
|
1340 |
+
x
|
1341 |
+
|
1342 |
+
x
|
1343 |
+
|
1344 |
+
2 ...
|
1345 |
+
|
1346 |
+
The memory drawing shows the local variable localString with the string "binky"
|
1347 |
+
copied into it. The letters take up the first 5 characters and the '\0' char marks the end of
|
1348 |
+
the string after the 'y'. The x's represent characters which have not been set to any
|
1349 |
+
particular value.
|
1350 |
+
|
1351 |
+
If the code instead tried to store the string "I enjoy languages which have good string
|
1352 |
+
support" into localString, the code would just crash at run time since the 10 character
|
1353 |
+
array can contain at most a 9 character string. The large string will be written passed the
|
1354 |
+
right hand side of localString, overwriting whatever was stored there.
|
1355 |
+
|
1356 |
+
String Code Example
|
1357 |
+
Here's a moderately complex for loop which reverses a string stored in a local array. It
|
1358 |
+
demonstrates calling the standard library functions strcpy() and strlen() and demonstrates
|
1359 |
+
that a string really is just an array of characters with a '\0' to mark the effective end of the
|
1360 |
+
string. Test your C knowledge of arrays and for loops by making a drawing of the
|
1361 |
+
memory for this code and tracing through its execution to see how it works.
|
1362 |
+
|
1363 |
+
22
|
1364 |
+
|
1365 |
+
{
|
1366 |
+
|
1367 |
+
char string[1000];
|
1368 |
+
int len;
|
1369 |
+
|
1370 |
+
// string is a local 1000 char array
|
1371 |
+
|
1372 |
+
strcpy(string, "binky");
|
1373 |
+
len = strlen(string);
|
1374 |
+
|
1375 |
+
/*
|
1376 |
+
Reverse the chars in the string:
|
1377 |
+
i starts at the beginning and goes up
|
1378 |
+
j starts at the end and goes down
|
1379 |
+
i/j exchange their chars as they go until they meet
|
1380 |
+
*/
|
1381 |
+
int i, j;
|
1382 |
+
char temp;
|
1383 |
+
for (i = 0, j = len - 1; i < j; i++, j--) {
|
1384 |
+
|
1385 |
+
temp = string[i];
|
1386 |
+
string[i] = string[j];
|
1387 |
+
string[j] = temp;
|
1388 |
+
|
1389 |
+
}
|
1390 |
+
|
1391 |
+
// at this point the local string should be "yknib"
|
1392 |
+
|
1393 |
+
}
|
1394 |
+
|
1395 |
+
"Large Enough" Strings
|
1396 |
+
The convention with C strings is that the owner of the string is responsible for allocating
|
1397 |
+
array space which is "large enough" to store whatever the string will need to store. Most
|
1398 |
+
routines do not check that size of the string memory they operate on, they just assume its
|
1399 |
+
big enough and blast away. Many, many programs contain declarations like the
|
1400 |
+
following...
|
1401 |
+
|
1402 |
+
{
|
1403 |
+
|
1404 |
+
}
|
1405 |
+
|
1406 |
+
char localString[1000];
|
1407 |
+
...
|
1408 |
+
|
1409 |
+
The program works fine so long as the strings stored are 999 characters or shorter.
|
1410 |
+
Someday when the program needs to store a string which is 1000 characters or longer,
|
1411 |
+
then it crashes. Such array-not-quite-big-enough problems are a common source of bugs,
|
1412 |
+
and are also the source of so called "buffer overflow" security problems. This scheme has
|
1413 |
+
the additional disadvantage that most of the time when the array is storing short strings,
|
1414 |
+
95% of the memory reserved is actually being wasted. A better solution allocates the
|
1415 |
+
string dynamically in the heap, so it has just the right size.
|
1416 |
+
|
1417 |
+
To avoid buffer overflow attacks, production code should check the size of the data first,
|
1418 |
+
to make sure it fits in the destination string. See the strlcpy() function in Appendix A.
|
1419 |
+
|
1420 |
+
char*
|
1421 |
+
Because of the way C handles the types of arrays, the type of the variable
|
1422 |
+
localString above is essentially char*. C programs very often manipulate strings
|
1423 |
+
using variables of type char* which point to arrays of characters. Manipulating the
|
1424 |
+
actual chars in a string requires code which manipulates the underlying array, or the use
|
1425 |
+
|
1426 |
+
23
|
1427 |
+
|
1428 |
+
of library functions such as strcpy() which manipulate the array for you. See Section 6 for
|
1429 |
+
more detail on pointers and arrays.
|
1430 |
+
|
1431 |
+
TypeDef
|
1432 |
+
A typedef statement introduces a shorthand name for a type. The syntax is...
|
1433 |
+
|
1434 |
+
typedef <type> <name>;
|
1435 |
+
|
1436 |
+
The following defines Fraction type to be the type (struct fraction). C is case
|
1437 |
+
sensitive, so fraction is different from Fraction. It's convenient to use typedef to
|
1438 |
+
create types with upper case names and use the lower-case version of the same word as a
|
1439 |
+
variable.
|
1440 |
+
|
1441 |
+
typedef struct fraction Fraction;
|
1442 |
+
|
1443 |
+
Fraction fraction;
|
1444 |
+
|
1445 |
+
// Declare the variable "fraction" of type "Fraction"
|
1446 |
+
// which is really just a synonym for "struct fraction".
|
1447 |
+
|
1448 |
+
The following typedef defines the name Tree as a standard pointer to a binary tree node
|
1449 |
+
where each node contains some data and "smaller" and "larger" subtree pointers.
|
1450 |
+
|
1451 |
+
typedef struct treenode* Tree;
|
1452 |
+
struct treenode {
|
1453 |
+
|
1454 |
+
int data;
|
1455 |
+
Tree smaller, larger;
|
1456 |
+
|
1457 |
+
};
|
1458 |
+
|
1459 |
+
// equivalently, this line could say
|
1460 |
+
// "struct treenode *smaller, *larger"
|
1461 |
+
|
1462 |
+
24
|
1463 |
+
|
1464 |
+
Section 4
|
1465 |
+
Functions
|
1466 |
+
All languages have a construct to separate and package blocks of code. C uses the
|
1467 |
+
"function" to package blocks of code. This article concentrates on the syntax and
|
1468 |
+
peculiarities of C functions. The motivation and design for dividing a computation into
|
1469 |
+
separate blocks is an entire discipline in its own.
|
1470 |
+
|
1471 |
+
A function has a name, a list of arguments which it takes when called, and the block of
|
1472 |
+
code it executes when called. C functions are defined in a text file and the names of all
|
1473 |
+
the functions in a C program are lumped together in a single, flat namespace. The special
|
1474 |
+
function called "main" is where program execution begins. Some programmers like to
|
1475 |
+
begin their function names with Upper case, using lower case for variables and
|
1476 |
+
parameters, Here is a simple C function declaration. This declares a function named
|
1477 |
+
Twice which takes a single int argument named num. The body of the function
|
1478 |
+
computes the value which is twice the num argument and returns that value to the caller.
|
1479 |
+
|
1480 |
+
/*
|
1481 |
+
Computes double of a number.
|
1482 |
+
Works by tripling the number, and then subtracting to get back to double.
|
1483 |
+
*/
|
1484 |
+
static int Twice(int num) {
|
1485 |
+
int result = num * 3;
|
1486 |
+
result = result - num;
|
1487 |
+
return(result);
|
1488 |
+
|
1489 |
+
}
|
1490 |
+
|
1491 |
+
Syntax
|
1492 |
+
The keyword "static" defines that the function will only be available to callers in the
|
1493 |
+
file where it is declared. If a function needs to be called from another file, the function
|
1494 |
+
cannot be static and will require a prototype -- see prototypes below. The static form
|
1495 |
+
is convenient for utility functions which will only be used in the file where they are
|
1496 |
+
declared. Next , the "int" in the function above is the type of its return value. Next
|
1497 |
+
comes name of the function and its list of parameters. When referring to a function by
|
1498 |
+
name in documentation or other prose, it's a convention to keep the parenthesis () suffix,
|
1499 |
+
so in this case I refer to the function as "Twice()". The parameters are listed with their
|
1500 |
+
types and names, just like variables.
|
1501 |
+
|
1502 |
+
Inside the function, the parameter num and the local variable result are "local" to the
|
1503 |
+
function -- they get their own memory and exist only so long as the function is executing.
|
1504 |
+
This independence of "local" memory is a standard feature of most languages (See
|
1505 |
+
CSLibrary/102 for the detailed discussion of local memory).
|
1506 |
+
|
1507 |
+
The "caller" code which calls Twice() looks like...
|
1508 |
+
|
1509 |
+
int num = 13;
|
1510 |
+
int a = 1;
|
1511 |
+
int b = 2;
|
1512 |
+
a = Twice(a);
|
1513 |
+
b = Twice(b + num);
|
1514 |
+
// a == 2
|
1515 |
+
// b == 30
|
1516 |
+
// num == 13 (this num is totally independent of the "num" local to Twice()
|
1517 |
+
|
1518 |
+
// call Twice() passing the value of a
|
1519 |
+
// call Twice() passing the value b+num
|
1520 |
+
|
1521 |
+
25
|
1522 |
+
|
1523 |
+
Things to notice...
|
1524 |
+
|
1525 |
+
(vocabulary) The expression passed to a function by its caller is called the "actual
|
1526 |
+
|
1527 |
+
parameter" -- such as "a" and "b + num" above. The parameter storage local to the
|
1528 |
+
function is called the "formal parameter" such as the "num" in "static int Twice(int
|
1529 |
+
num)".
|
1530 |
+
|
1531 |
+
Parameters are passed "by value" that means there is a single copying assignment
|
1532 |
+
|
1533 |
+
operation (=) from each actual parameter to set each formal parameter. The actual
|
1534 |
+
parameter is evaluated in the caller's context, and then the value is copied into the
|
1535 |
+
function's formal parameter just before the function begins executing. The alternative
|
1536 |
+
parameter mechanism is "by reference" which C does not implement directly, but
|
1537 |
+
which the programmer can implement manually when needed (see below). When a
|
1538 |
+
parameter is a struct, it is copied.
|
1539 |
+
|
1540 |
+
The variables local to Twice(), num and result, only exist temporarily while
|
1541 |
+
Twice() is executing. This is the standard definition for "local" storage for
|
1542 |
+
functions.
|
1543 |
+
|
1544 |
+
The return at the end of Twice() computes the return value and exits the function.
|
1545 |
+
Execution resumes with the caller. There can be multiple return statements within a
|
1546 |
+
function, but it's good style to at least have one at the end if a return value needs to be
|
1547 |
+
specified. Forgetting to account of a return somewhere in the middle of a function
|
1548 |
+
is a traditional source of bugs.
|
1549 |
+
|
1550 |
+
C-ing and Nothingness -- void
|
1551 |
+
void is a type formalized in ANSI C which means "nothing". To indicate that a function
|
1552 |
+
does not return anything, use void as the return type. Also, by convention, a pointer
|
1553 |
+
which does not point to any particular type is declared as void*. Sometimes void* is
|
1554 |
+
used to force two bodies of code to not depend on each other where void* translates
|
1555 |
+
roughly to "this points to something, but I'm not telling you (the client) the type of the
|
1556 |
+
pointee exactly because you do not really need to know." If a function does not take any
|
1557 |
+
parameters, its parameter list is empty, or it can contain the keyword void but that style
|
1558 |
+
is now out of favor.
|
1559 |
+
|
1560 |
+
void TakesAnIntAndReturnsNothing(int anInt);
|
1561 |
+
|
1562 |
+
int TakesNothingAndReturnsAnInt();
|
1563 |
+
int TakesNothingAndReturnsAnInt(void); // equivalent syntax for above
|
1564 |
+
|
1565 |
+
Call by Value vs. Call by Reference
|
1566 |
+
C passes parameters "by value" which means that the actual parameter values are copied
|
1567 |
+
into local storage. The caller and callee functions do not share any memory -- they each
|
1568 |
+
have their own copy. This scheme is fine for many purposes, but it has two
|
1569 |
+
disadvantages.
|
1570 |
+
|
1571 |
+
1) Because the callee has its own copy, modifications to that memory are not
|
1572 |
+
|
1573 |
+
communicated back to the caller. Therefore, value parameters do not allow the callee
|
1574 |
+
to communicate back to the caller. The function's return value can communicate some
|
1575 |
+
information back to the caller, but not all problems can be solved with the single
|
1576 |
+
return value.
|
1577 |
+
|
1578 |
+
26
|
1579 |
+
|
1580 |
+
2) Sometimes it is undesirable to copy the value from the caller to the callee because the
|
1581 |
+
value is large and so copying it is expensive, or because at a conceptual level copying
|
1582 |
+
the value is undesirable.
|
1583 |
+
|
1584 |
+
The alternative is to pass the arguments "by reference". Instead of passing a copy of a
|
1585 |
+
value from the caller to the callee, pass a pointer to the value. In this way there is only
|
1586 |
+
one copy of the value at any time, and the caller and callee both access that one value
|
1587 |
+
through pointers.
|
1588 |
+
|
1589 |
+
Some languages support reference parameters automatically. C does not do this -- the
|
1590 |
+
programmer must implement reference parameters manually using the existing pointer
|
1591 |
+
constructs in the language.
|
1592 |
+
|
1593 |
+
Swap Example
|
1594 |
+
The classic example of wanting to modify the caller's memory is a swap() function
|
1595 |
+
which exchanges two values. Because C uses call by value, the following version of
|
1596 |
+
Swap will not work...
|
1597 |
+
|
1598 |
+
void Swap(int x, int y) {
|
1599 |
+
|
1600 |
+
// NO does not work
|
1601 |
+
|
1602 |
+
int temp;
|
1603 |
+
|
1604 |
+
temp = x;
|
1605 |
+
x = y;
|
1606 |
+
y = temp;
|
1607 |
+
|
1608 |
+
}
|
1609 |
+
|
1610 |
+
// these operations just change the local x,y,temp
|
1611 |
+
// -- nothing connects them back to the caller's a,b
|
1612 |
+
|
1613 |
+
// Some caller code which calls Swap()...
|
1614 |
+
int a = 1;
|
1615 |
+
int b = 2;
|
1616 |
+
Swap(a, b);
|
1617 |
+
|
1618 |
+
Swap() does not affect the arguments a and b in the caller. The function above only
|
1619 |
+
operates on the copies of a and b local to Swap() itself. This is a good example of how
|
1620 |
+
"local" memory such as ( x, y, temp) behaves -- it exists independent of everything else
|
1621 |
+
only while its owning function is running. When the owning function exits, its local
|
1622 |
+
memory disappears.
|
1623 |
+
|
1624 |
+
Reference Parameter Technique
|
1625 |
+
To pass an object X as a reference parameter, the programmer must pass a pointer to X
|
1626 |
+
instead of X itself. The formal parameter will be a pointer to the value of interest. The
|
1627 |
+
caller will need to use & or other operators to compute the correct pointer actual
|
1628 |
+
parameter. The callee will need to dereference the pointer with * where appropriate to
|
1629 |
+
access the value of interest. Here is an example of a correct Swap() function.
|
1630 |
+
|
1631 |
+
static void Swap(int* x, int* y) {
|
1632 |
+
|
1633 |
+
// params are int* instead of int
|
1634 |
+
|
1635 |
+
int temp;
|
1636 |
+
|
1637 |
+
temp = *x;
|
1638 |
+
*x = *y;
|
1639 |
+
*y = temp;
|
1640 |
+
|
1641 |
+
}
|
1642 |
+
|
1643 |
+
// use * to follow the pointer back to the caller's memory
|
1644 |
+
|
1645 |
+
27
|
1646 |
+
|
1647 |
+
// Some caller code which calls Swap()...
|
1648 |
+
int a = 1;
|
1649 |
+
int b = 2;
|
1650 |
+
|
1651 |
+
Swap(&a, &b);
|
1652 |
+
|
1653 |
+
Things to notice...
|
1654 |
+
|
1655 |
+
• The formal parameters are int* instead of int.
|
1656 |
+
|
1657 |
+
• The caller uses & to compute pointers to its local memory (a,b).
|
1658 |
+
|
1659 |
+
• The callee uses * to dereference the formal parameter pointers back to get the caller's
|
1660 |
+
|
1661 |
+
memory.
|
1662 |
+
|
1663 |
+
Since the operator & produces the address of a variable -- &a is a pointer to a. In
|
1664 |
+
Swap() itself, the formal parameters are declared to be pointers, and the values of
|
1665 |
+
interest (a,b) are accessed through them. There is no special relationship between the
|
1666 |
+
names used for the actual and formal parameters. The function call matches up the actual
|
1667 |
+
and formal parameters by their order -- the first actual parameter is assigned to the first
|
1668 |
+
formal parameter, and so on. I deliberately used different names (a,b vs x,y) to emphasize
|
1669 |
+
that the names do not matter.
|
1670 |
+
|
1671 |
+
const
|
1672 |
+
The qualifier const can be added to the left of a variable or parameter type to declare that
|
1673 |
+
the code using the variable will not change the variable. As a practical matter, use of
|
1674 |
+
const is very sporadic in the C programming community. It does have one very handy
|
1675 |
+
use, which is to clarify the role of a parameter in a function prototype...
|
1676 |
+
|
1677 |
+
void foo(const struct fraction* fract);
|
1678 |
+
|
1679 |
+
In the foo() prototype, the const declares that foo() does not intend to change the struct
|
1680 |
+
fraction pointee which is passed to it. Since the fraction is passed by pointer, we could
|
1681 |
+
not know otherwise if foo() intended to change our memory or not. Using the const,
|
1682 |
+
foo() makes its intentions clear. Declaring this extra bit of information helps to clarify the
|
1683 |
+
role of the function to its implementor and caller.
|
1684 |
+
|
1685 |
+
28
|
1686 |
+
|
1687 |
+
Bigger Pointer Example
|
1688 |
+
The following code is a large example of using reference parameters. There are several
|
1689 |
+
common features of C programs in this example...Reference parameters are used to allow
|
1690 |
+
the functions Swap() and IncrementAndSwap() to affect the memory of their callers.
|
1691 |
+
There's a tricky case inside of IncrementAndSwap() where it calls Swap() -- no additional
|
1692 |
+
use of & is necessary in this case since the parameters x, y inside InrementAndSwap() are
|
1693 |
+
already pointers to the values of interest. The names of the variables through the
|
1694 |
+
program(a, b, x, y, alice, bob) do not need to match up in any particular way for the
|
1695 |
+
parameters to work. The parameter mechanism only depends on the types of the
|
1696 |
+
parameters and their order in the parameter list -- not their names. Finally this is an
|
1697 |
+
example of what multiple functions look like in a file and how they are called from the
|
1698 |
+
main() function.
|
1699 |
+
|
1700 |
+
static void Swap(int* a, int* b) {
|
1701 |
+
|
1702 |
+
int temp;
|
1703 |
+
temp = *a;
|
1704 |
+
*a = *b;
|
1705 |
+
*b = temp;
|
1706 |
+
|
1707 |
+
}
|
1708 |
+
|
1709 |
+
static void IncrementAndSwap(int* x, int* y) {
|
1710 |
+
|
1711 |
+
// don't need & here since a and b are already
|
1712 |
+
// int*'s.
|
1713 |
+
|
1714 |
+
(*x)++;
|
1715 |
+
(*y)++;
|
1716 |
+
Swap(x, y);
|
1717 |
+
|
1718 |
+
}
|
1719 |
+
|
1720 |
+
int main()
|
1721 |
+
{
|
1722 |
+
|
1723 |
+
int alice = 10;
|
1724 |
+
int bob = 20;
|
1725 |
+
|
1726 |
+
Swap(&alice, &bob);
|
1727 |
+
// at this point alice==20 and bob==10
|
1728 |
+
|
1729 |
+
IncrementAndSwap(&alice, &bob);
|
1730 |
+
// at this point alice==11 and bob==21
|
1731 |
+
|
1732 |
+
return 0;
|
1733 |
+
|
1734 |
+
}
|
1735 |
+
|
1736 |
+
29
|
1737 |
+
|
1738 |
+
Section 5
|
1739 |
+
Odds and Ends
|
1740 |
+
main()
|
1741 |
+
The execution of a C program begins with function named main(). All of the files and
|
1742 |
+
libraries for the C program are compiled together to build a single program file. That file
|
1743 |
+
must contain exactly one main() function which the operating system uses as the starting
|
1744 |
+
point for the program. Main() returns an int which, by convention, is 0 if the program
|
1745 |
+
completed successfully and non-zero if the program exited due to some error condition.
|
1746 |
+
This is just a convention which makes sense in shell oriented environments such as Unix
|
1747 |
+
or DOS.
|
1748 |
+
|
1749 |
+
Multiple Files
|
1750 |
+
For a program of any size, it's convenient to separate the functions into several separate
|
1751 |
+
files. To allow the functions in separate files to cooperate, and yet allow the compiler to
|
1752 |
+
work on the files independently, C programs typically depend on two features...
|
1753 |
+
|
1754 |
+
Prototypes
|
1755 |
+
A "prototype" for a function gives its name and arguments but not its body. In order for a
|
1756 |
+
caller, in any file, to use a function, the caller must have seen the prototype for that
|
1757 |
+
function. For example, here's what the prototypes would look like for Twice() and
|
1758 |
+
Swap(). The function body is absent and there's a semicolon (;) to terminate the
|
1759 |
+
prototype...
|
1760 |
+
|
1761 |
+
int Twice(int num);
|
1762 |
+
void Swap(int* a, int* b);
|
1763 |
+
|
1764 |
+
In pre-ANSI C, the rules for prototypes where very sloppy -- callers were not required to
|
1765 |
+
see prototypes before calling functions, and as a result it was possible to get in situations
|
1766 |
+
where the compiler generated code which would crash horribly.
|
1767 |
+
|
1768 |
+
In ANSI C, I'll oversimplify a little to say that...
|
1769 |
+
|
1770 |
+
1) a function may be declared static in which case it can only be used in the same file
|
1771 |
+
where it is used below the point of its declaration. Static functions do not require a
|
1772 |
+
separate prototype so long as they are defined before or above where they are called
|
1773 |
+
which saves some work.
|
1774 |
+
|
1775 |
+
2) A non-static function needs a prototype. When the compiler compiles a function
|
1776 |
+
|
1777 |
+
definition, it must have previously seen a prototype so that it can verify that the two
|
1778 |
+
are in agreement ("prototype before definition" rule). The prototype must also be seen
|
1779 |
+
by any client code which wants to call the function ("clients must see prototypes"
|
1780 |
+
rule).(The require-prototypes behavior is actually somewhat of a compiler option, but
|
1781 |
+
it's smart to leave it on.)
|
1782 |
+
|
1783 |
+
Preprocessor
|
1784 |
+
The preprocessing step happens to the C source before it is fed to the compiler. The two
|
1785 |
+
most common preprocessor directives are #define and #include...
|
1786 |
+
|
1787 |
+
30
|
1788 |
+
|
1789 |
+
#define
|
1790 |
+
The #define directive can be used to set up symbolic replacements in the source. As with
|
1791 |
+
all preprocessor operations, #define is extremely unintelligent -- it just does textual
|
1792 |
+
replacement without understanding. #define statements are used as a crude way of
|
1793 |
+
establishing symbolic constants.
|
1794 |
+
|
1795 |
+
#define MAX 100
|
1796 |
+
#define SEVEN_WORDS that_symbol_expands_to_all_these_words
|
1797 |
+
|
1798 |
+
Later code can use the symbols MAX or SEVEN_WORDS which will be replaced by the
|
1799 |
+
text to the right of each symbol in its #define.
|
1800 |
+
|
1801 |
+
#include
|
1802 |
+
The "#include" directive brings in text from different files during compilation. #include is
|
1803 |
+
a very unintelligent and unstructured -- it just pastes in the text from the given file and
|
1804 |
+
continues compiling. The #include directive is used in the .h/.c file convention below
|
1805 |
+
which is used to satisfy the various constraints necessary to get prototypes correct.
|
1806 |
+
|
1807 |
+
#include "foo.h"
|
1808 |
+
|
1809 |
+
// refers to a "user" foo.h file --
|
1810 |
+
//
|
1811 |
+
|
1812 |
+
in the originating directory for the compile
|
1813 |
+
|
1814 |
+
#include <foo.h>
|
1815 |
+
|
1816 |
+
// refers to a "system" foo.h file --
|
1817 |
+
//
|
1818 |
+
|
1819 |
+
in the compiler's directory somewhere
|
1820 |
+
|
1821 |
+
foo.h vs foo.c
|
1822 |
+
The universally followed convention for C is that for a file named "foo.c" containing a
|
1823 |
+
bunch of functions...
|
1824 |
+
|
1825 |
+
• A separate file named foo.h will contain the prototypes for the functions in foo.c
|
1826 |
+
which clients may want to call. Functions in foo.c which are for "internal use
|
1827 |
+
only" and should never be called by clients should be declared static.
|
1828 |
+
|
1829 |
+
• Near the top of foo.c will be the following line which ensures that the function
|
1830 |
+
definitions in foo.c see the prototypes in foo.h which ensures the "prototype
|
1831 |
+
before definition" rule above.
|
1832 |
+
#include "foo.h"
|
1833 |
+
|
1834 |
+
// show the contents of "foo.h"
|
1835 |
+
// to the compiler at this point
|
1836 |
+
|
1837 |
+
• Any xxx.c file which wishes to call a function defined in foo.c must include the
|
1838 |
+
following line to see the prototypes, ensuring the "clients must see prototypes" rule
|
1839 |
+
above.
|
1840 |
+
#include "foo.h"
|
1841 |
+
|
1842 |
+
#if
|
1843 |
+
At compile time, there is some space of names defined by the #defines. The #if test can
|
1844 |
+
be used at compile-time to look at those symbols and turn on and off which lines the
|
1845 |
+
compiler uses. The following example depends on the value of the FOO #define symbol.
|
1846 |
+
If it is true, then the "aaa" lines (whatever they are) are compiled, and the "bbb" lines are
|
1847 |
+
ignored. If FOO were 0, then the reverse would be true.
|
1848 |
+
|
1849 |
+
31
|
1850 |
+
|
1851 |
+
#define FOO 1
|
1852 |
+
|
1853 |
+
...
|
1854 |
+
|
1855 |
+
#if FOO
|
1856 |
+
|
1857 |
+
aaa
|
1858 |
+
aaa
|
1859 |
+
|
1860 |
+
#else
|
1861 |
+
|
1862 |
+
bbb
|
1863 |
+
bbb
|
1864 |
+
#endif
|
1865 |
+
|
1866 |
+
You can use #if 0 ...#endif to effectively comment out areas of code you don't
|
1867 |
+
want to compile, but which you want to keeep in the source file.
|
1868 |
+
|
1869 |
+
Multiple #includes -- #pragma once
|
1870 |
+
There's a problem sometimes where a .h file is #included into a file more than one time
|
1871 |
+
resulting in compile errors. This can be a serious problem. Because of this, you want to
|
1872 |
+
avoid #including .h files in other .h files if at all possible. On the other hand, #including
|
1873 |
+
.h files in .c files is fine. If you are lucky, your compiler will support the #pragma once
|
1874 |
+
feature which automatically prevents a single file from being #included more than once in
|
1875 |
+
any one file. This largely solves multiple #include problems.
|
1876 |
+
|
1877 |
+
// foo.h
|
1878 |
+
// The following line prevents problems in files which #include "foo.h"
|
1879 |
+
#pragma once
|
1880 |
+
|
1881 |
+
<rest of foo.h ...>
|
1882 |
+
|
1883 |
+
Assert
|
1884 |
+
Array out of bounds references are an extremely common form of C run-time error. You
|
1885 |
+
can use the assert() function to sprinkle your code with your own bounds checks. A few
|
1886 |
+
seconds putting in assert statements can save you hours of debugging.
|
1887 |
+
|
1888 |
+
Getting out all the bugs is the hardest and scariest part of writing a large piece of
|
1889 |
+
software. Assert statements are one of the easiest and most effective helpers for that
|
1890 |
+
difficult phase.
|
1891 |
+
|
1892 |
+
#include <assert.h>
|
1893 |
+
#define MAX_INTS 100
|
1894 |
+
{
|
1895 |
+
|
1896 |
+
int ints[MAX_INTS];
|
1897 |
+
i = foo(<something complicated>);
|
1898 |
+
|
1899 |
+
// i should be in bounds,
|
1900 |
+
// but is it really?
|
1901 |
+
|
1902 |
+
assert(i>=0);
|
1903 |
+
assert(i<MAX_INTS);
|
1904 |
+
|
1905 |
+
ints[i] = 0;
|
1906 |
+
|
1907 |
+
// safety assertions
|
1908 |
+
|
1909 |
+
32
|
1910 |
+
|
1911 |
+
Depending on the options specified at compile time, the assert() expressions will be left
|
1912 |
+
in the code for testing, or may be ignored. For that reason, it is important to only put
|
1913 |
+
expressions in assert() tests which do not need to be evaluated for the proper functioning
|
1914 |
+
of the program...
|
1915 |
+
|
1916 |
+
int errCode = foo();
|
1917 |
+
assert(errCode == 0);
|
1918 |
+
|
1919 |
+
// yes
|
1920 |
+
|
1921 |
+
assert(foo() == 0);
|
1922 |
+
|
1923 |
+
// NO, foo() will not be called if
|
1924 |
+
// the compiler removes the assert()
|
1925 |
+
|
1926 |
+
33
|
1927 |
+
|
1928 |
+
Section 6
|
1929 |
+
Advanced Arrays and Pointers
|
1930 |
+
Advanced C Arrays
|
1931 |
+
In C, an array is formed by laying out all the elements contiguously in memory. The
|
1932 |
+
square bracket syntax can be used to refer to the elements in the array. The array as a
|
1933 |
+
whole is referred to by the address of the first element which is also known as the "base
|
1934 |
+
address" of the whole array.
|
1935 |
+
|
1936 |
+
{
|
1937 |
+
|
1938 |
+
}
|
1939 |
+
|
1940 |
+
int array[6];
|
1941 |
+
|
1942 |
+
int sum = 0;
|
1943 |
+
sum += array[0] + array[1];
|
1944 |
+
|
1945 |
+
// refer to elements using []
|
1946 |
+
|
1947 |
+
array
|
1948 |
+
|
1949 |
+
The array name acts like a pointer to the
|
1950 |
+
first element- in this case an (int*).
|
1951 |
+
|
1952 |
+
array[0] array[1] array[2] ...
|
1953 |
+
|
1954 |
+
Index
|
1955 |
+
|
1956 |
+
0
|
1957 |
+
|
1958 |
+
1
|
1959 |
+
|
1960 |
+
2
|
1961 |
+
|
1962 |
+
3
|
1963 |
+
|
1964 |
+
4
|
1965 |
+
|
1966 |
+
5
|
1967 |
+
|
1968 |
+
The programmer can refer to elements in the array with the simple [ ] syntax such as
|
1969 |
+
array[1]. This scheme works by combining the base address of the whole array with
|
1970 |
+
the index to compute the base address of the desired element in the array. It just requires
|
1971 |
+
a little arithmetic. Each element takes up a fixed number of bytes which is known at
|
1972 |
+
compile-time. So the address of element n in the array using 0 based indexing will be at
|
1973 |
+
an offset of (n * element_size) bytes from the base address of the whole array.
|
1974 |
+
|
1975 |
+
address of nth element = address_of_0th_element + (n * element_size_in_bytes)
|
1976 |
+
|
1977 |
+
The square bracket syntax [ ] deals with this address arithmetic for you, but it's useful to
|
1978 |
+
know what it's doing. The [ ] takes the integer index, multiplies by the element size, adds
|
1979 |
+
the resulting offset to the array base address, and finally dereferences the resulting pointer
|
1980 |
+
to get to the desired element.
|
1981 |
+
|
1982 |
+
{
|
1983 |
+
|
1984 |
+
}
|
1985 |
+
|
1986 |
+
int intArray[6];
|
1987 |
+
|
1988 |
+
intArray[3] = 13;
|
1989 |
+
|
1990 |
+
34
|
1991 |
+
|
1992 |
+
intArray
|
1993 |
+
|
1994 |
+
12 bytes of offset
|
1995 |
+
|
1996 |
+
(intArray+3)
|
1997 |
+
|
1998 |
+
1
|
1999 |
+
|
2000 |
+
4
|
2001 |
+
|
2002 |
+
2
|
2003 |
+
|
2004 |
+
8
|
2005 |
+
|
2006 |
+
13
|
2007 |
+
|
2008 |
+
3
|
2009 |
+
|
2010 |
+
12
|
2011 |
+
|
2012 |
+
4
|
2013 |
+
|
2014 |
+
16
|
2015 |
+
|
2016 |
+
5
|
2017 |
+
|
2018 |
+
20
|
2019 |
+
|
2020 |
+
Index
|
2021 |
+
|
2022 |
+
0
|
2023 |
+
|
2024 |
+
0
|
2025 |
+
|
2026 |
+
Offset
|
2027 |
+
in bytes =
|
2028 |
+
n * elem_size
|
2029 |
+
|
2030 |
+
Assume sizeof(int) = 4i.e. Each array
|
2031 |
+
element takes up 4 bytes.
|
2032 |
+
|
2033 |
+
'+' Syntax
|
2034 |
+
In a closely related piece of syntax, a + between a pointer and an integer does the same
|
2035 |
+
offset computation, but leaves the result as a pointer. The square bracket syntax gives the
|
2036 |
+
nth element while the + syntax gives a pointer to the nth element.
|
2037 |
+
|
2038 |
+
So the expression (intArray + 3) is a pointer to the integer intArray[3].
|
2039 |
+
(intArray + 3) is of type (int*) while intArray[3] is of type int. The two
|
2040 |
+
expressions only differ by whether the pointer is dereferenced or not. So the expression
|
2041 |
+
(intArray + 3) is exactly equivalent to the expression (&(intArray[3])). In
|
2042 |
+
fact those two probably compile to exactly the same code. They both represent a pointer
|
2043 |
+
to the element at index 3.
|
2044 |
+
|
2045 |
+
Any [] expression can be written with the + syntax instead. We just need to add in the
|
2046 |
+
pointer dereference. So intArray[3] is exactly equivalent to *(intArray + 3).
|
2047 |
+
For most purposes, it's easiest and most readable to use the [] syntax. Every once in a
|
2048 |
+
while the + is convenient if you needed a pointer to the element instead of the element
|
2049 |
+
itself.
|
2050 |
+
|
2051 |
+
Pointer++ Style -- strcpy()
|
2052 |
+
If p is a pointer to an element in an array, then (p+1) points to the next element in the
|
2053 |
+
array. Code can exploit this using the construct p++ to step a pointer over the elements in
|
2054 |
+
an array. It doesn't help readability any, so I can't recommend the technique, but you may
|
2055 |
+
see it in code written by others.
|
2056 |
+
|
2057 |
+
(This example was originally inspired by Mike Cleron) There's a library function called
|
2058 |
+
strcpy(char* destination, char* source) which copies the bytes of a C
|
2059 |
+
string from one place to another. Below are four different implementations of strcpy()
|
2060 |
+
written in order: from most verbose to most cryptic. In the first one, the normally
|
2061 |
+
straightforward while loop is actually sortof tricky to ensure that the terminating null
|
2062 |
+
character is copied over. The second removes that trickiness by moving assignment into
|
2063 |
+
the test. The last two are cute (and they demonstrate using ++ on pointers), but not really
|
2064 |
+
the sort of code you want to maintain. Among the four, I think strcpy2() is the best
|
2065 |
+
stylistically. With a smart compiler, all four will compile to basically the same code with
|
2066 |
+
the same efficiency.
|
2067 |
+
|
2068 |
+
35
|
2069 |
+
|
2070 |
+
// Unfortunately, a straight while or for loop won't work.
|
2071 |
+
// The best we can do is use a while (1) with the test
|
2072 |
+
// in the middle of the loop.
|
2073 |
+
void strcpy1(char dest[], const char source[]) {
|
2074 |
+
|
2075 |
+
int i = 0;
|
2076 |
+
|
2077 |
+
while (1) {
|
2078 |
+
|
2079 |
+
dest[i] = source[i];
|
2080 |
+
if (dest[i] == '\0') break;
|
2081 |
+
i++;
|
2082 |
+
|
2083 |
+
// we're done
|
2084 |
+
|
2085 |
+
}
|
2086 |
+
|
2087 |
+
}
|
2088 |
+
|
2089 |
+
// Move the assignment into the test
|
2090 |
+
void strcpy2(char dest[], const char source[]) {
|
2091 |
+
|
2092 |
+
int i = 0;
|
2093 |
+
|
2094 |
+
while ((dest[i] = source[i]) != '\0') {
|
2095 |
+
|
2096 |
+
i++;
|
2097 |
+
|
2098 |
+
}
|
2099 |
+
|
2100 |
+
}
|
2101 |
+
|
2102 |
+
// Get rid of i and just move the pointers.
|
2103 |
+
// Relies on the precedence of * and ++.
|
2104 |
+
void strcpy3(char dest[], const char source[])
|
2105 |
+
{
|
2106 |
+
|
2107 |
+
while ((*dest++ = *source++) != '\0') ;
|
2108 |
+
|
2109 |
+
}
|
2110 |
+
|
2111 |
+
// Rely on the fact that '\0' is equivalent to FALSE
|
2112 |
+
void strcpy4(char dest[], const char source[])
|
2113 |
+
{
|
2114 |
+
|
2115 |
+
while (*dest++ = *source++) ;
|
2116 |
+
|
2117 |
+
}
|
2118 |
+
|
2119 |
+
Pointer Type Effects
|
2120 |
+
Both [ ] and + implicitly use the compile time type of the pointer to compute the
|
2121 |
+
element_size which affects the offset arithmetic. When looking at code, it's easy to
|
2122 |
+
assume that everything is in the units of bytes.
|
2123 |
+
|
2124 |
+
int *p;
|
2125 |
+
|
2126 |
+
p = p + 12;
|
2127 |
+
|
2128 |
+
// at run-time, what does this add to p? 12?
|
2129 |
+
|
2130 |
+
The above code does not add the number 12 to the address in p-- that would increment p
|
2131 |
+
by 12 bytes. The code above increments p by 12 ints. Each int probably takes 4 bytes, so
|
2132 |
+
at run time the code will effectively increment the address in p by 48. The compiler
|
2133 |
+
figures all this out based on the type of the pointer.
|
2134 |
+
|
2135 |
+
Using casts, the following code really does just add 12 to the address in the pointer p. It
|
2136 |
+
works by telling the compiler that the pointer points to char instead of int. The size of
|
2137 |
+
char is defined to be exactly 1 byte (or whatever the smallest addressable unit is on the
|
2138 |
+
computer). In other words, sizeof(char) is always 1. We then cast the resulting
|
2139 |
+
|
2140 |
+
36
|
2141 |
+
|
2142 |
+
(char*) back to an (int*). The programmer is allowed to cast any pointer type to
|
2143 |
+
any other pointer type like this to change the code the compiler generates.
|
2144 |
+
|
2145 |
+
p = (int*) ( ((char*)p) + 12);
|
2146 |
+
|
2147 |
+
Arrays and Pointers
|
2148 |
+
One effect of the C array scheme is that the compiler does not distinguish meaningfully
|
2149 |
+
between arrays and pointers-- they both just look like pointers. In the following example,
|
2150 |
+
the value of intArray is a pointer to the first element in the array so it's an (int*).
|
2151 |
+
The value of the variable intPtr is also (int*) and it is set to point to a single integer
|
2152 |
+
i. So what's the difference between intArray and intPtr? Not much as far as the
|
2153 |
+
compiler is concerned. They are both just (int*) pointers, and the compiler is perfectly
|
2154 |
+
happy to apply the [] or + syntax to either. It's the programmer's responsibility to ensure
|
2155 |
+
that the elements referred to by a [] or + operation really are there. Really its' just the
|
2156 |
+
same old rule that C doesn't do any bounds checking. C thinks of the single integer i as
|
2157 |
+
just a sort of degenerate array of size 1.
|
2158 |
+
|
2159 |
+
{
|
2160 |
+
|
2161 |
+
}
|
2162 |
+
|
2163 |
+
int intArray[6];
|
2164 |
+
int *intPtr;
|
2165 |
+
int i;
|
2166 |
+
|
2167 |
+
intPtr = &i;
|
2168 |
+
|
2169 |
+
intArray[3] = 13;
|
2170 |
+
intPtr[0] = 12;
|
2171 |
+
intPtr[3] = 13;
|
2172 |
+
|
2173 |
+
// ok
|
2174 |
+
// odd, but ok. Changes i.
|
2175 |
+
// BAD! There is no integer reserved here!
|
2176 |
+
|
2177 |
+
intArray
|
2178 |
+
|
2179 |
+
(intArray+3)
|
2180 |
+
|
2181 |
+
37
|
2182 |
+
|
2183 |
+
Index
|
2184 |
+
|
2185 |
+
0
|
2186 |
+
|
2187 |
+
1
|
2188 |
+
|
2189 |
+
2
|
2190 |
+
|
2191 |
+
intPtr
|
2192 |
+
|
2193 |
+
12
|
2194 |
+
|
2195 |
+
i
|
2196 |
+
|
2197 |
+
4
|
2198 |
+
|
2199 |
+
5
|
2200 |
+
|
2201 |
+
(intPtr+3)
|
2202 |
+
|
2203 |
+
13
|
2204 |
+
|
2205 |
+
3
|
2206 |
+
|
2207 |
+
13
|
2208 |
+
|
2209 |
+
These bytes exist, but they have not been explicitly reserved.
|
2210 |
+
They are the bytes which happen to be adjacent to the
|
2211 |
+
memory for i. They are probably being used to store
|
2212 |
+
something already, such as a smashed looking smiley face.
|
2213 |
+
The 13 just gets blindly written over the smiley face. This
|
2214 |
+
error will only be apparent later when the program tries to
|
2215 |
+
read the smiley face data.
|
2216 |
+
|
2217 |
+
Array Names Are Const
|
2218 |
+
One subtle distinction between an array and a pointer, is that the pointer which represents
|
2219 |
+
the base address of an array cannot be changed in the code. The array base address
|
2220 |
+
behaves like a const pointer. The constraint applies to the name of the array where it is
|
2221 |
+
declared in the code-- the variable ints in the example below.
|
2222 |
+
|
2223 |
+
{
|
2224 |
+
|
2225 |
+
}
|
2226 |
+
|
2227 |
+
int ints[100]
|
2228 |
+
int *p;
|
2229 |
+
int i;
|
2230 |
+
|
2231 |
+
ints = NULL;
|
2232 |
+
ints = &i;
|
2233 |
+
ints = ints + 1;
|
2234 |
+
ints++;
|
2235 |
+
|
2236 |
+
p = ints;
|
2237 |
+
|
2238 |
+
p++;
|
2239 |
+
p = NULL;
|
2240 |
+
p = &i;
|
2241 |
+
|
2242 |
+
// NO, cannot change the base addr ptr
|
2243 |
+
// NO
|
2244 |
+
// NO
|
2245 |
+
// NO
|
2246 |
+
|
2247 |
+
// OK, p is a regular pointer which can be changed
|
2248 |
+
// here it is getting a copy of the ints pointer
|
2249 |
+
|
2250 |
+
// OK, p can still be changed (and ints cannot)
|
2251 |
+
// OK
|
2252 |
+
// OK
|
2253 |
+
|
2254 |
+
foo(ints);
|
2255 |
+
|
2256 |
+
// OK (possible foo definitions are below)
|
2257 |
+
|
2258 |
+
38
|
2259 |
+
|
2260 |
+
Array parameters are passed as pointers. The following two definitions of foo look
|
2261 |
+
different, but to the compiler they mean exactly the same thing. It's preferable to use
|
2262 |
+
whichever syntax is more accurate for readability. If the pointer coming in really is the
|
2263 |
+
base address of a whole array, then use [ ].
|
2264 |
+
|
2265 |
+
void foo(int arrayParam[]) {
|
2266 |
+
|
2267 |
+
arrayParam = NULL;
|
2268 |
+
|
2269 |
+
// Silly but valid. Just changes the local pointer
|
2270 |
+
|
2271 |
+
}
|
2272 |
+
|
2273 |
+
void foo(int *arrayParam) {
|
2274 |
+
|
2275 |
+
arrayParam = NULL;
|
2276 |
+
|
2277 |
+
// ditto
|
2278 |
+
|
2279 |
+
}
|
2280 |
+
|
2281 |
+
Heap Memory
|
2282 |
+
C gives programmers the standard sort of facilities to allocate and deallocate dynamic
|
2283 |
+
heap memory. A word of warning: writing programs which manage their heap memory is
|
2284 |
+
notoriously difficult. This partly explains the great popularity of languages such as Java
|
2285 |
+
and Perl which handle heap management automatically. These languages take over a task
|
2286 |
+
which has proven to be extremely difficult for the programmer. As a result Perl and Java
|
2287 |
+
programs run a little more slowly, but they contain far fewer bugs. (For a detailed
|
2288 |
+
discussion of heap memory see http://cslibrary.stanford.edu/102/, Pointers and Memory.)
|
2289 |
+
|
2290 |
+
C provides access to the heap features through library functions which any C code can
|
2291 |
+
call. The prototypes for these functions are in the file <stdlib.h>, so any code which
|
2292 |
+
wants to call these must #include that header file. The three functions of interest are...
|
2293 |
+
|
2294 |
+
void* malloc(size_t size)
|
2295 |
+
|
2296 |
+
Request a contiguous block of memory
|
2297 |
+
of the given size in the heap. malloc() returns a pointer to the heap block or NULL if
|
2298 |
+
the request could not be satisfied. The type size_t is essentially an unsigned
|
2299 |
+
long which indicates how large a block the caller would like measured in bytes.
|
2300 |
+
Because the block pointer returned by malloc() is a void* (i.e. it makes no claim
|
2301 |
+
about the type of its pointee), a cast will probably be required when storing the void*
|
2302 |
+
pointer into a regular typed pointer.
|
2303 |
+
|
2304 |
+
void free(void* block)
|
2305 |
+
|
2306 |
+
The mirror image of malloc() -- free takes a
|
2307 |
+
|
2308 |
+
pointer to a heap block earlier allocated by malloc() and returns that block to the heap
|
2309 |
+
for re-use. After the free(), the client should not access any part of the block or
|
2310 |
+
assume that the block is valid memory. The block should not be freed a second time.
|
2311 |
+
|
2312 |
+
void* realloc(void* block, size_t size);
|
2313 |
+
|
2314 |
+
Take an existing heap
|
2315 |
+
block and try to relocate it to a heap block of the given size which may be larger or
|
2316 |
+
smaller than the original size of the block. Returns a pointer to the new block, or
|
2317 |
+
NULL if the relocation was unsuccessful. Remember to catch and examine the return
|
2318 |
+
value of realloc() -- it is a common error to continue to use the old block pointer.
|
2319 |
+
Realloc() takes care of moving the bytes from the old block to the new block.
|
2320 |
+
Realloc() exists because it can be implemented using low-level features which make
|
2321 |
+
it more efficient than C code the client could write.
|
2322 |
+
|
2323 |
+
Memory Management
|
2324 |
+
All of a program's memory is deallocated automatically when the it exits, so a program
|
2325 |
+
only needs to use free() during execution if it is important for the program to recycle its
|
2326 |
+
memory while it runs -- typically because it uses a lot of memory or because it runs for a
|
2327 |
+
|
2328 |
+
39
|
2329 |
+
|
2330 |
+
long time. The pointer passed to free() must be exactly the pointer which was originally
|
2331 |
+
returned by malloc() or realloc(), not just a pointer into somewhere within the heap block.
|
2332 |
+
|
2333 |
+
Dynamic Arrays
|
2334 |
+
Since arrays are just contiguous areas of bytes, you can allocate your own arrays in the
|
2335 |
+
heap using malloc(). The following code allocates two arrays of 1000 ints-- one in the
|
2336 |
+
stack the usual "local" way, and one in the heap using malloc(). Other than the different
|
2337 |
+
allocations, the two are syntactically similar in use.
|
2338 |
+
|
2339 |
+
{
|
2340 |
+
|
2341 |
+
}
|
2342 |
+
|
2343 |
+
int a[1000];
|
2344 |
+
|
2345 |
+
int *b;
|
2346 |
+
b = (int*) malloc( sizeof(int) * 1000);
|
2347 |
+
assert(b != NULL);
|
2348 |
+
|
2349 |
+
// check that the allocation succeeded
|
2350 |
+
|
2351 |
+
a[123] = 13;
|
2352 |
+
b[123] = 13;
|
2353 |
+
|
2354 |
+
// Just use good ol' [] to access elements
|
2355 |
+
// in both arrays.
|
2356 |
+
|
2357 |
+
free(b);
|
2358 |
+
|
2359 |
+
Although both arrays can be accessed with [ ], the rules for their maintenance are very
|
2360 |
+
different....
|
2361 |
+
|
2362 |
+
Advantages of being in the heap
|
2363 |
+
|
2364 |
+
• Size (in this case 1000) can be defined at run time. Not so for an array like "a".
|
2365 |
+
|
2366 |
+
• The array will exist until it is explicitly deallocated with a call to free().
|
2367 |
+
|
2368 |
+
• You can change the size of the array at will at run time using realloc(). The following
|
2369 |
+
changes the size of the array to 2000. Realloc() takes care of copying over the old
|
2370 |
+
elements.
|
2371 |
+
|
2372 |
+
...
|
2373 |
+
b = realloc(b, sizeof(int) * 2000);
|
2374 |
+
assert(b != NULL);
|
2375 |
+
|
2376 |
+
Disadvantages of being in the heap
|
2377 |
+
|
2378 |
+
• You have to remember to allocate the array, and you have to get it right.
|
2379 |
+
|
2380 |
+
• You have to remember to deallocate it exactly once when you are done with it, and you
|
2381 |
+
|
2382 |
+
have to get that right.
|
2383 |
+
|
2384 |
+
• The above two disadvantages have the same basic profile: if you get them wrong, your
|
2385 |
+
code still looks right. It compiles fine. It even runs for small cases, but for some input
|
2386 |
+
cases it just crashes unexpectedly because random memory is getting overwritten
|
2387 |
+
somewhere like the smiley face. This sort of "random memory smasher" bug can be a
|
2388 |
+
real ordeal to track down.
|
2389 |
+
|
2390 |
+
40
|
2391 |
+
|
2392 |
+
Dynamic Strings
|
2393 |
+
The dynamic allocation of arrays works very well for allocating strings in the heap. The
|
2394 |
+
advantage of heap allocating a string is that the heap block can be just big enough to store
|
2395 |
+
the actual number of characters in the string. The common local variable technique such
|
2396 |
+
as char string[1000]; allocates way too much space most of the time, wasting
|
2397 |
+
the unused bytes, and yet fails if the string ever gets bigger than the variable's fixed size.
|
2398 |
+
|
2399 |
+
#include <string.h>
|
2400 |
+
|
2401 |
+
/*
|
2402 |
+
Takes a c string as input, and makes a copy of that string
|
2403 |
+
in the heap. The caller takes over ownership of the new string
|
2404 |
+
and is responsible for freeing it.
|
2405 |
+
*/
|
2406 |
+
char* MakeStringInHeap(const char* source) {
|
2407 |
+
|
2408 |
+
char* newString;
|
2409 |
+
|
2410 |
+
newString = (char*) malloc(strlen(source) + 1); // +1 for the '\0'
|
2411 |
+
assert(newString != NULL);
|
2412 |
+
strcpy(newString, source);
|
2413 |
+
return(newString);
|
2414 |
+
|
2415 |
+
}
|
2416 |
+
|
2417 |
+
41
|
2418 |
+
|
2419 |
+
Section 7
|
2420 |
+
Details and Library Functions
|
2421 |
+
Precedence and Associativity
|
2422 |
+
function-call() [] -> .
|
2423 |
+
|
2424 |
+
L to R
|
2425 |
+
|
2426 |
+
! ~ ++ -- + - *(ptr deref) sizeof &(addr of)
|
2427 |
+
(all unary ops are the same)
|
2428 |
+
|
2429 |
+
* / %
|
2430 |
+
(the top tier arithmetic binary ops)
|
2431 |
+
|
2432 |
+
+ -
|
2433 |
+
(second tier arithmetic binary ops)
|
2434 |
+
|
2435 |
+
< <= > >=
|
2436 |
+
|
2437 |
+
== !=
|
2438 |
+
|
2439 |
+
in order: & ^ | && ||
|
2440 |
+
(note that bitwise comes before boolean)
|
2441 |
+
|
2442 |
+
= and all its variants
|
2443 |
+
|
2444 |
+
, (comma) .
|
2445 |
+
|
2446 |
+
R to L
|
2447 |
+
|
2448 |
+
L to R
|
2449 |
+
|
2450 |
+
L to R
|
2451 |
+
|
2452 |
+
L to R
|
2453 |
+
|
2454 |
+
L to R
|
2455 |
+
|
2456 |
+
L to R
|
2457 |
+
|
2458 |
+
R to L
|
2459 |
+
|
2460 |
+
L to R
|
2461 |
+
|
2462 |
+
A combinations which never works right without parens: *structptr.field
|
2463 |
+
You have to write it as (*structptr).field or structptr->field
|
2464 |
+
|
2465 |
+
Standard Library Functions
|
2466 |
+
Many basic housekeeping funcions are available to a C program in form of standard
|
2467 |
+
library functions. To call these, a program must #include the appropriate .h file. Most
|
2468 |
+
compilers link in the standard library code by default. The functions listed in the next
|
2469 |
+
section are the most commonly used ones, but there are many more which are not listed
|
2470 |
+
here.
|
2471 |
+
|
2472 |
+
stdio.h
|
2473 |
+
|
2474 |
+
file input and output
|
2475 |
+
|
2476 |
+
ctype.h
|
2477 |
+
|
2478 |
+
character tests
|
2479 |
+
|
2480 |
+
string.h
|
2481 |
+
|
2482 |
+
string operations
|
2483 |
+
|
2484 |
+
math.h
|
2485 |
+
|
2486 |
+
mathematical functions such as sin() and cos()
|
2487 |
+
|
2488 |
+
stdlib.h
|
2489 |
+
|
2490 |
+
utility functions such as malloc() and rand()
|
2491 |
+
|
2492 |
+
assert.h
|
2493 |
+
|
2494 |
+
the assert() debugging macro
|
2495 |
+
|
2496 |
+
stdarg.h
|
2497 |
+
|
2498 |
+
support for functions with variable numbers of arguments
|
2499 |
+
|
2500 |
+
setjmp.h
|
2501 |
+
|
2502 |
+
support for non-local flow control jumps
|
2503 |
+
|
2504 |
+
signal.h
|
2505 |
+
|
2506 |
+
support for exceptional condition signals
|
2507 |
+
|
2508 |
+
time.h
|
2509 |
+
|
2510 |
+
date and time
|
2511 |
+
|
2512 |
+
42
|
2513 |
+
|
2514 |
+
limits.h, float.h
|
2515 |
+
|
2516 |
+
constants which define type range values such as INT_MAX
|
2517 |
+
|
2518 |
+
stdio.h
|
2519 |
+
Stdio.h is a very common file to #include -- it includes functions to print and read strings
|
2520 |
+
from files and to open and close files in the file system.
|
2521 |
+
|
2522 |
+
FILE* fopen(const char* fname, const char* mode);
|
2523 |
+
|
2524 |
+
Open a file named in the filesystem and return a FILE* for it. Mode = "r" read,"w"
|
2525 |
+
write,"a"append, returns NULL on error. The standard files stdout, stdin,
|
2526 |
+
stderr are automatically opened and closed for you by the system.
|
2527 |
+
|
2528 |
+
int fclose(FILE* file);
|
2529 |
+
|
2530 |
+
Close a previously opened file. Returns EOF on error. The operating system closes all
|
2531 |
+
of a program's files when it exits, but it's tidy to do it beforehand. Also, there is
|
2532 |
+
typically a limit to the number of files which a program may have open
|
2533 |
+
simultaneously.
|
2534 |
+
|
2535 |
+
int fgetc(FILE* in);
|
2536 |
+
|
2537 |
+
Read and return the next unsigned char out of a file, or EOF if the file has been
|
2538 |
+
exhausted. (detail) This and other file functions return ints instead of a chars because
|
2539 |
+
the EOF constant they potentially is not a char, but is an int. getc() is an alternate,
|
2540 |
+
faster version implemented as a macro which may evaluate the FILE* expression
|
2541 |
+
more than once.
|
2542 |
+
|
2543 |
+
char* fgets(char* dest, int n, FILE* in)
|
2544 |
+
|
2545 |
+
Reads the next line of text into a string supplied by the caller. Reads at most n-1
|
2546 |
+
characters from the file, stopping at the first '\n' character. In any case, the string is '\0'
|
2547 |
+
terminated. The '\n' is included in the string. Returns NULL on EOF or error.
|
2548 |
+
|
2549 |
+
int fputc(int ch, FILE* out);
|
2550 |
+
|
2551 |
+
Write the char to the file as an unsigned char. Returns ch, or EOF on err. putc() is an
|
2552 |
+
alternate, faster version implemented as a macro which may evaluate the FILE*
|
2553 |
+
expression more than once.
|
2554 |
+
|
2555 |
+
int ungetc(int ch, FILE* in);
|
2556 |
+
|
2557 |
+
Push the most recent fgetc() char back onto the file. EOF may not be pushed back.
|
2558 |
+
Returns ch or EOF on error.
|
2559 |
+
|
2560 |
+
int printf(const char* format_string, ...);
|
2561 |
+
|
2562 |
+
Prints a string with values possibly inserted into it to standard output. Takes a variable
|
2563 |
+
number of arguments -- first a format string followed by a number of matching
|
2564 |
+
arguments. The format string contains text mixed with % directives which mark
|
2565 |
+
things to be inserted in the output. %d = int, %Ld=long int, %s=string, %f=double,
|
2566 |
+
%c=char. Every % directive must have a matching argument of the correct type after
|
2567 |
+
the format string. Returns the number of characters written, or negative on error. If
|
2568 |
+
the percent directives do not match the number and type of arguments, printf() tends
|
2569 |
+
to crash or otherwise do the wrong thing at run time. fprintf() is a variant which takes
|
2570 |
+
an additional FILE* argument which specifies the file to print to. Examples...
|
2571 |
+
printf("hello\n");
|
2572 |
+
printf("hello %d there %d\n", 13, 1+1);
|
2573 |
+
printf("hello %c there %d %s\n", 'A', 42, "ok");
|
2574 |
+
|
2575 |
+
prints: hello
|
2576 |
+
prints: hello 13 there 2
|
2577 |
+
prints: hello A there 42 ok
|
2578 |
+
|
2579 |
+
43
|
2580 |
+
|
2581 |
+
int scanf(const char* format, ...)
|
2582 |
+
|
2583 |
+
Opposite of printf() -- reads characters from standard input trying to match elements
|
2584 |
+
in the format string. Each percent directive in the format string must have a matching
|
2585 |
+
pointer in the argument list which scanf() uses to store the values it finds. scanf()
|
2586 |
+
skips whitespace as it tries to read in each percent directive. Returns the number of
|
2587 |
+
percent directives processed successfully, or EOF on error. scanf() is famously
|
2588 |
+
sensitive to programmer errors. If scanf() is called with anything but the correct
|
2589 |
+
pointers after the format string, it tends to crash or otherwise do the wrong thing at
|
2590 |
+
run time. sscanf() is a variant which takes an additional initial string from which it
|
2591 |
+
does its reading. fscanf() is a variant which takes an additional initial FILE* from
|
2592 |
+
which it does its reading. Example...
|
2593 |
+
{
|
2594 |
+
|
2595 |
+
int num;
|
2596 |
+
char s1[1000];
|
2597 |
+
char s2[1000];
|
2598 |
+
|
2599 |
+
scanf("hello %d %s %s", &num, s1, s2);
|
2600 |
+
|
2601 |
+
}
|
2602 |
+
Looks for the word "hello" followed by a number and two words (all separated by
|
2603 |
+
whitespace). scanf() uses the pointers &num, s1, and s2 to store what it finds into the
|
2604 |
+
local variables.
|
2605 |
+
|
2606 |
+
ctype.h
|
2607 |
+
ctype.h includes macros for doing simple tests and operations on characters
|
2608 |
+
|
2609 |
+
isalpha(ch)
|
2610 |
+
|
2611 |
+
// ch is an upper or lower case letter
|
2612 |
+
|
2613 |
+
islower(ch), isupper(ch)
|
2614 |
+
|
2615 |
+
// same as above, but upper/lower specific
|
2616 |
+
|
2617 |
+
isspace(ch)
|
2618 |
+
|
2619 |
+
// ch is a whitepace character such as tab, space, newline, etc.
|
2620 |
+
|
2621 |
+
isdigit(ch)
|
2622 |
+
|
2623 |
+
// digit such as '0'..'9'
|
2624 |
+
|
2625 |
+
toupper(ch), tolower(ch)
|
2626 |
+
|
2627 |
+
// Return the lower or upper case version of a
|
2628 |
+
|
2629 |
+
alphabetic character, otherwise pass it through unchanged.
|
2630 |
+
|
2631 |
+
44
|
2632 |
+
|
2633 |
+
string.h
|
2634 |
+
None of these string routines allocate memory or check that the passed in memory is the
|
2635 |
+
right size. The caller is responsible for making sure there is "enough" memory for the
|
2636 |
+
operation. The type size_t is an unsigned integer wide enough for the computer's
|
2637 |
+
address space -- most likely an unsigned long.
|
2638 |
+
|
2639 |
+
size_t strlen(const char* string);
|
2640 |
+
|
2641 |
+
Return the number of chars in a C string. EG strlen("abc")==3
|
2642 |
+
|
2643 |
+
char* strcpy(char* dest, const char* source);
|
2644 |
+
|
2645 |
+
Copy the characters from the source string to the destination string.
|
2646 |
+
|
2647 |
+
size_t strlcpy(char* dest, const char* source,
|
2648 |
+
|
2649 |
+
size_t dest_size);
|
2650 |
+
|
2651 |
+
Like strcpy(), but knows the size of the dest. Truncates if necessary. Use this to avoid
|
2652 |
+
memory errors and buffer-overflow security problems. This function is not as
|
2653 |
+
standard as strcpy(), but most sytems have it. Do not use the old strncpy() function --
|
2654 |
+
it is difficult to use correctly.
|
2655 |
+
|
2656 |
+
char *strcat(char* dest, const char* source);
|
2657 |
+
|
2658 |
+
Append the characters from the source string to the end of destination string. (There is
|
2659 |
+
a non-standard strlcat() variant that takes the size of the dest as third argument.)
|
2660 |
+
|
2661 |
+
int strcmp(const char* a, const char* b);
|
2662 |
+
|
2663 |
+
Compare two strings and return an int which encodes their ordering. zero:a==b,
|
2664 |
+
negative:a<b, positive:a>b. It is a common error to think of the result of strcmp() as
|
2665 |
+
being boolean true if the strings are equal which is, unfortunately, exactly backwards.
|
2666 |
+
|
2667 |
+
char* strchr(const char* searchIn, char ch);
|
2668 |
+
|
2669 |
+
Search the given string for the first occurence of the given character. Returns a
|
2670 |
+
pointer to the character, or NULL if none is found.
|
2671 |
+
|
2672 |
+
char* strstr(const char* searchIn, const char* searchFor);
|
2673 |
+
Similar to strchr(), but searches for an entire string instead of a single character. The
|
2674 |
+
search is case sensitive.
|
2675 |
+
|
2676 |
+
void* memcpy(void* dest, const void* source, size_t n);
|
2677 |
+
|
2678 |
+
Copy the given number of bytes from the source to the destination. The source and
|
2679 |
+
destination must not overlap. This may be implemented in a specialized but highly
|
2680 |
+
optimized way for a particular computer.
|
2681 |
+
|
2682 |
+
void* memmove(void* dest, const void* source, size_t n);
|
2683 |
+
Similar to memcpy() but allows the areas to overlap. This probably runs slightly
|
2684 |
+
slower than memcpy().
|
2685 |
+
|
2686 |
+
45
|
2687 |
+
|
2688 |
+
stdlib.h
|
2689 |
+
|
2690 |
+
int rand();
|
2691 |
+
|
2692 |
+
Returns a pseudo random integer in the range 0..RAND_MAX (limits.h) which is at
|
2693 |
+
least 32767.
|
2694 |
+
|
2695 |
+
void srand(unsigned int seed);
|
2696 |
+
|
2697 |
+
The sequence of random numbers returned by rand() is initially controlled by a global
|
2698 |
+
"seed" variable. srand() sets this seed which, by default, starts with the value 1. Pass
|
2699 |
+
the expression time(NULL) (time.h) to set the seed to a value based on the current
|
2700 |
+
time to ensure that the random sequence is different from one run to the next.
|
2701 |
+
|
2702 |
+
void* malloc(size_t size);
|
2703 |
+
|
2704 |
+
Allocate a heap block of the given size in bytes. Returns a pointer to the block or
|
2705 |
+
NULL on failure. A cast may be required to store the void* pointer into a regular
|
2706 |
+
typed pointer. [ed: see the Heap Allocation section above for the longer discussion of
|
2707 |
+
malloc(), free(), and realloc()]
|
2708 |
+
void free(void* block);
|
2709 |
+
|
2710 |
+
Opposite of malloc(). Returns a previous malloc block to the system for reuse
|
2711 |
+
|
2712 |
+
void* realloc(void* block, size_t size);
|
2713 |
+
|
2714 |
+
Resize an existing heap block to the new size. Takes care of copying bytes from the
|
2715 |
+
old block to the new. Returns the new base address of the heap block. It is a common
|
2716 |
+
error to forget to catch the return value from realloc(). Returns NULL if the resize
|
2717 |
+
operation was not possible.
|
2718 |
+
|
2719 |
+
void exit(int status);
|
2720 |
+
|
2721 |
+
Halt and exit the program and pass a condition int back to the operating sytem. Pass 0
|
2722 |
+
to signal normal program termination, non-zero otherwise.
|
2723 |
+
|
2724 |
+
void* bsearch(const void* key, const void* base, size_t len,
|
2725 |
+
|
2726 |
+
size_t elem_size, <compare_function>);
|
2727 |
+
Do a binary search in an array of elements. The last argument is a function which
|
2728 |
+
takes pointers to the two elements to compare. Its prototype should be:
|
2729 |
+
int compare(const void* a, const void* b);, and it should return 0, -1, or 1 as strcmp()
|
2730 |
+
does. Returns a pointer to a found element, or NULL otherwise. Note that strcmp()
|
2731 |
+
itself cannot be used directly as a compare function for bsearch() on an array of char*
|
2732 |
+
strings because strcmp() takes char* arguments and bsearch() will need a comparator
|
2733 |
+
that takes pointers to the array elements -- char**.
|
2734 |
+
|
2735 |
+
void qsort(void* base, size_t len, size_t elem_size,
|
2736 |
+
|
2737 |
+
<compare_function>);
|
2738 |
+
Sort an array of elements. Takes a function pointer just like besearch().
|
2739 |
+
|
2740 |
+
Revision History
|
2741 |
+
11/1998 -- original major version. Based on my old C handout for CS107. Thanks to Jon
|
2742 |
+
Becker for proofreading and Mike Cleron for the original inspiration.
|
2743 |
+
|
2744 |
+
Revised 4/2003 with many helpful typo and other suggestions from Negar Shamma and
|
2745 |
+
A. P. Garcia
|
2746 |
+
|
2747 |
+
|
C/arm-baremetal-ebook.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
C/book.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
C/c17_updated_proposed_fdis.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
C/ctut.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
C/gnu-c-manual.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
C/gsl_stats.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
C/learning_gnu_c.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
C/pointers.pdf.txt
ADDED
@@ -0,0 +1,2742 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A TUTORIAL ON POINTERS AND ARRAYS IN C
|
2 |
+
|
3 |
+
by Ted Jensen
|
4 |
+
Version 1.2 (PDF Version)
|
5 |
+
Sept. 2003
|
6 |
+
This material is hereby placed in the public domain
|
7 |
+
Available in various formats via
|
8 |
+
http://pweb.netcom.com/~tjensen/ptr/cpoint.htm
|
9 |
+
|
10 |
+
TABLE OF CONTENTS
|
11 |
+
|
12 |
+
PREFACE
|
13 |
+
|
14 |
+
INTRODUCTION
|
15 |
+
|
16 |
+
CHAPTER 1: What is a pointer?
|
17 |
+
|
18 |
+
CHAPTER 2: Pointer types and Arrays
|
19 |
+
|
20 |
+
CHAPTER 3: Pointers and Strings
|
21 |
+
|
22 |
+
CHAPTER 4: More on Strings
|
23 |
+
|
24 |
+
CHAPTER 5: Pointers and Structures
|
25 |
+
|
26 |
+
CHAPTER 6: Some more on Strings, and Arrays of Strings
|
27 |
+
|
28 |
+
CHAPTER 7: More on Multi-Dimensional Arrays
|
29 |
+
|
30 |
+
CHAPTER 8: Pointers to Arrays
|
31 |
+
|
32 |
+
CHAPTER 9: Pointers and Dynamic Allocation of Memory
|
33 |
+
|
34 |
+
CHAPTER 10: Pointers to Functions
|
35 |
+
|
36 |
+
EPILOG
|
37 |
+
|
38 |
+
2
|
39 |
+
|
40 |
+
4
|
41 |
+
|
42 |
+
5
|
43 |
+
|
44 |
+
9
|
45 |
+
|
46 |
+
14
|
47 |
+
|
48 |
+
19
|
49 |
+
|
50 |
+
22
|
51 |
+
|
52 |
+
26
|
53 |
+
|
54 |
+
30
|
55 |
+
|
56 |
+
32
|
57 |
+
|
58 |
+
34
|
59 |
+
|
60 |
+
42
|
61 |
+
|
62 |
+
53
|
63 |
+
|
64 |
+
1
|
65 |
+
|
66 |
+
|
67 |
+
|
68 |
+
|
69 |
+
PREFACE
|
70 |
+
|
71 |
+
This document is intended to introduce pointers to beginning programmers in the C
|
72 |
+
programming language. Over several years of reading and contributing to various
|
73 |
+
conferences on C including those on the FidoNet and UseNet, I have noted a large
|
74 |
+
number of newcomers to C appear to have a difficult time in grasping the fundamentals
|
75 |
+
of pointers. I therefore undertook the task of trying to explain them in plain language with
|
76 |
+
lots of examples.
|
77 |
+
|
78 |
+
The first version of this document was placed in the public domain, as is this one. It was
|
79 |
+
picked up by Bob Stout who included it as a file called PTR-HELP.TXT in his widely
|
80 |
+
distributed collection of SNIPPETS. Since that original 1995 release, I have added a
|
81 |
+
significant amount of material and made some minor corrections in the original work.
|
82 |
+
|
83 |
+
I subsequently posted an HTML version around 1998 on my website at:
|
84 |
+
|
85 |
+
http://pweb.netcom.com/~tjensen/ptr/cpoint.htm
|
86 |
+
|
87 |
+
After numerous requests, I’ve finally come out with this PDF version which is identical
|
88 |
+
to that HTML version cited above, and which can be obtained from that same web site.
|
89 |
+
|
90 |
+
Acknowledgements:
|
91 |
+
|
92 |
+
There are so many people who have unknowingly contributed to this work because of the
|
93 |
+
questions they have posed in the FidoNet C Echo, or the UseNet Newsgroup
|
94 |
+
comp.lang.c, or several other conferences in other networks, that it would be impossible
|
95 |
+
to list them all. Special thanks go to Bob Stout who was kind enough to include the first
|
96 |
+
version of this material in his SNIPPETS file.
|
97 |
+
|
98 |
+
About the Author:
|
99 |
+
|
100 |
+
Ted Jensen is a retired Electronics Engineer who worked as a hardware designer or
|
101 |
+
manager of hardware designers in the field of magnetic recording. Programming has been
|
102 |
+
a hobby of his off and on since 1968 when he learned how to keypunch cards for
|
103 |
+
submission to be run on a mainframe. (The mainframe had 64K of magnetic core
|
104 |
+
memory!).
|
105 |
+
|
106 |
+
Use of this Material:
|
107 |
+
|
108 |
+
Everything contained herein is hereby released to the Public Domain. Any person may
|
109 |
+
copy or distribute this material in any manner they wish. The only thing I ask is that if
|
110 |
+
this material is used as a teaching aid in a class, I would appreciate it if it were distributed
|
111 |
+
in its entirety, i.e. including all chapters, the preface and the introduction. I would also
|
112 |
+
appreciate it if, under such circumstances, the instructor of such a class would drop me a
|
113 |
+
|
114 |
+
2
|
115 |
+
|
116 |
+
|
117 |
+
note at one of the addresses below informing me of this. I have written this with the hope
|
118 |
+
that it will be useful to others and since I'm not asking any financial remuneration, the
|
119 |
+
only way I know that I have at least partially reached that goal is via feedback from those
|
120 |
+
who find this material useful.
|
121 |
+
|
122 |
+
By the way, you needn't be an instructor or teacher to contact me. I would appreciate a
|
123 |
+
note from anyone who finds the material useful, or who has constructive criticism to
|
124 |
+
offer. I'm also willing to answer questions submitted by email at the addresses shown
|
125 |
+
below.
|
126 |
+
|
127 |
+
Ted Jensen
|
128 |
+
Redwood City, California
|
129 |
+
tjensen@ix.netcom.com
|
130 |
+
July 1998
|
131 |
+
|
132 |
+
3
|
133 |
+
|
134 |
+
|
135 |
+
INTRODUCTION
|
136 |
+
|
137 |
+
If you want to be proficient in the writing of code in the C programming language, you
|
138 |
+
must have a thorough working knowledge of how to use pointers. Unfortunately, C
|
139 |
+
pointers appear to represent a stumbling block to newcomers, particularly those coming
|
140 |
+
from other computer languages such as Fortran, Pascal or Basic.
|
141 |
+
|
142 |
+
To aid those newcomers in the understanding of pointers I have written the following
|
143 |
+
material. To get the maximum benefit from this material, I feel it is important that the
|
144 |
+
user be able to run the code in the various listings contained in the article. I have
|
145 |
+
attempted, therefore, to keep all code ANSI compliant so that it will work with any ANSI
|
146 |
+
compliant compiler. I have also tried to carefully block the code within the text. That
|
147 |
+
way, with the help of an ASCII text editor, you can copy a given block of code to a new
|
148 |
+
file and compile it on your system. I recommend that readers do this as it will help in
|
149 |
+
understanding the material.
|
150 |
+
|
151 |
+
4
|
152 |
+
|
153 |
+
|
154 |
+
CHAPTER 1: What is a pointer?
|
155 |
+
|
156 |
+
One of those things beginners in C find difficult is the concept of pointers. The purpose
|
157 |
+
of this tutorial is to provide an introduction to pointers and their use to these beginners.
|
158 |
+
|
159 |
+
I have found that often the main reason beginners have a problem with pointers is that
|
160 |
+
they have a weak or minimal feeling for variables, (as they are used in C). Thus we start
|
161 |
+
with a discussion of C variables in general.
|
162 |
+
|
163 |
+
A variable in a program is something with a name, the value of which can vary. The way
|
164 |
+
the compiler and linker handles this is that it assigns a specific block of memory within
|
165 |
+
the computer to hold the value of that variable. The size of that block depends on the
|
166 |
+
range over which the variable is allowed to vary. For example, on PC's the size of an
|
167 |
+
integer variable is 2 bytes, and that of a long integer is 4 bytes. In C the size of a variable
|
168 |
+
type such as an integer need not be the same on all types of machines.
|
169 |
+
|
170 |
+
When we declare a variable we inform the compiler of two things, the name of the
|
171 |
+
variable and the type of the variable. For example, we declare a variable of type integer
|
172 |
+
with the name k by writing:
|
173 |
+
|
174 |
+
int k;
|
175 |
+
|
176 |
+
On seeing the "int" part of this statement the compiler sets aside 2 bytes of memory (on a
|
177 |
+
PC) to hold the value of the integer. It also sets up a symbol table. In that table it adds the
|
178 |
+
symbol k and the relative address in memory where those 2 bytes were set aside.
|
179 |
+
|
180 |
+
Thus, later if we write:
|
181 |
+
|
182 |
+
k = 2;
|
183 |
+
|
184 |
+
we expect that, at run time when this statement is executed, the value 2 will be placed in
|
185 |
+
that memory location reserved for the storage of the value of k. In C we refer to a
|
186 |
+
variable such as the integer k as an "object".
|
187 |
+
|
188 |
+
In a sense there are two "values" associated with the object k. One is the value of the
|
189 |
+
integer stored there (2 in the above example) and the other the "value" of the memory
|
190 |
+
location, i.e., the address of k. Some texts refer to these two values with the nomenclature
|
191 |
+
rvalue (right value, pronounced "are value") and lvalue (left value, pronounced "el
|
192 |
+
value") respectively.
|
193 |
+
|
194 |
+
In some languages, the lvalue is the value permitted on the left side of the assignment
|
195 |
+
operator '=' (i.e. the address where the result of evaluation of the right side ends up). The
|
196 |
+
rvalue is that which is on the right side of the assignment statement, the 2 above. Rvalues
|
197 |
+
cannot be used on the left side of the assignment statement. Thus: 2 = k; is illegal.
|
198 |
+
|
199 |
+
5
|
200 |
+
|
201 |
+
|
202 |
+
Actually, the above definition of "lvalue" is somewhat modified for C. According to
|
203 |
+
K&R II (page 197): [1]
|
204 |
+
|
205 |
+
"An object is a named region of storage; an lvalue is an expression
|
206 |
+
referring to an object."
|
207 |
+
|
208 |
+
However, at this point, the definition originally cited above is sufficient. As we become
|
209 |
+
more familiar with pointers we will go into more detail on this.
|
210 |
+
|
211 |
+
Okay, now consider:
|
212 |
+
|
213 |
+
int j, k;
|
214 |
+
|
215 |
+
k = 2;
|
216 |
+
j = 7; <-- line 1
|
217 |
+
k = j; <-- line 2
|
218 |
+
|
219 |
+
In the above, the compiler interprets the j in line 1 as the address of the variable j (its
|
220 |
+
lvalue) and creates code to copy the value 7 to that address. In line 2, however, the j is
|
221 |
+
interpreted as its rvalue (since it is on the right hand side of the assignment operator '=').
|
222 |
+
That is, here the j refers to the value stored at the memory location set aside for j, in this
|
223 |
+
case 7. So, the 7 is copied to the address designated by the lvalue of k.
|
224 |
+
|
225 |
+
In all of these examples, we are using 2 byte integers so all copying of rvalues from one
|
226 |
+
storage location to the other is done by copying 2 bytes. Had we been using long integers,
|
227 |
+
we would be copying 4 bytes.
|
228 |
+
|
229 |
+
Now, let's say that we have a reason for wanting a variable designed to hold an lvalue (an
|
230 |
+
address). The size required to hold such a value depends on the system. On older desk top
|
231 |
+
computers with 64K of memory total, the address of any point in memory can be
|
232 |
+
contained in 2 bytes. Computers with more memory would require more bytes to hold an
|
233 |
+
address. Some computers, such as the IBM PC might require special handling to hold a
|
234 |
+
segment and offset under certain circumstances. The actual size required is not too
|
235 |
+
important so long as we have a way of informing the compiler that what we want to store
|
236 |
+
is an address.
|
237 |
+
|
238 |
+
Such a variable is called a pointer variable (for reasons which hopefully will become
|
239 |
+
clearer a little later). In C when we define a pointer variable we do so by preceding its
|
240 |
+
name with an asterisk. In C we also give our pointer a type which, in this case, refers to
|
241 |
+
the type of data stored at the address we will be storing in our pointer. For example,
|
242 |
+
consider the variable declaration:
|
243 |
+
|
244 |
+
int *ptr;
|
245 |
+
|
246 |
+
ptr is the name of our variable (just as k was the name of our integer variable). The '*'
|
247 |
+
informs the compiler that we want a pointer variable, i.e. to set aside however many bytes
|
248 |
+
is required to store an address in memory. The int says that we intend to use our pointer
|
249 |
+
|
250 |
+
6
|
251 |
+
|
252 |
+
|
253 |
+
|
254 |
+
variable to store the address of an integer. Such a pointer is said to "point to" an integer.
|
255 |
+
However, note that when we wrote int k; we did not give k a value. If this definition is
|
256 |
+
made outside of any function ANSI compliant compilers will initialize it to zero.
|
257 |
+
Similarly, ptr has no value, that is we haven't stored an address in it in the above
|
258 |
+
declaration. In this case, again if the declaration is outside of any function, it is initialized
|
259 |
+
to a value guaranteed in such a way that it is guaranteed to not point to any C object or
|
260 |
+
function. A pointer initialized in this manner is called a "null" pointer.
|
261 |
+
|
262 |
+
The actual bit pattern used for a null pointer may or may not evaluate to zero since it
|
263 |
+
depends on the specific system on which the code is developed. To make the source code
|
264 |
+
compatible between various compilers on various systems, a macro is used to represent a
|
265 |
+
null pointer. That macro goes under the name NULL. Thus, setting the value of a pointer
|
266 |
+
using the NULL macro, as with an assignment statement such as ptr = NULL, guarantees
|
267 |
+
that the pointer has become a null pointer. Similarly, just as one can test for an integer
|
268 |
+
value of zero, as in if(k == 0), we can test for a null pointer using if (ptr == NULL).
|
269 |
+
|
270 |
+
But, back to using our new variable ptr. Suppose now that we want to store in ptr the
|
271 |
+
address of our integer variable k. To do this we use the unary & operator and write:
|
272 |
+
|
273 |
+
ptr = &k;
|
274 |
+
|
275 |
+
What the & operator does is retrieve the lvalue (address) of k, even though k is on the
|
276 |
+
right hand side of the assignment operator '=', and copies that to the contents of our
|
277 |
+
pointer ptr. Now, ptr is said to "point to" k. Bear with us now, there is only one more
|
278 |
+
operator we need to discuss.
|
279 |
+
|
280 |
+
The "dereferencing operator" is the asterisk and it is used as follows:
|
281 |
+
|
282 |
+
*ptr = 7;
|
283 |
+
|
284 |
+
will copy 7 to the address pointed to by ptr. Thus if ptr "points to" (contains the address
|
285 |
+
of) k, the above statement will set the value of k to 7. That is, when we use the '*' this
|
286 |
+
way we are referring to the value of that which ptr is pointing to, not the value of the
|
287 |
+
pointer itself.
|
288 |
+
|
289 |
+
Similarly, we could write:
|
290 |
+
|
291 |
+
printf("%d\n",*ptr);
|
292 |
+
|
293 |
+
to print to the screen the integer value stored at the address pointed to by ptr;.
|
294 |
+
|
295 |
+
One way to see how all this stuff fits together would be to run the following program and
|
296 |
+
then review the code and the output carefully.
|
297 |
+
|
298 |
+
------------ Program 1.1 ---------------------------------
|
299 |
+
|
300 |
+
/* Program 1.1 from PTRTUT10.TXT 6/10/97 */
|
301 |
+
|
302 |
+
7
|
303 |
+
|
304 |
+
|
305 |
+
|
306 |
+
|
307 |
+
#include <stdio.h>
|
308 |
+
|
309 |
+
int j, k;
|
310 |
+
int *ptr;
|
311 |
+
|
312 |
+
int main(void)
|
313 |
+
{
|
314 |
+
j = 1;
|
315 |
+
k = 2;
|
316 |
+
ptr = &k;
|
317 |
+
printf("\n");
|
318 |
+
printf("j has the value %d and is stored at %p\n", j, (void *)&j);
|
319 |
+
printf("k has the value %d and is stored at %p\n", k, (void *)&k);
|
320 |
+
printf("ptr has the value %p and is stored at %p\n", ptr, (void
|
321 |
+
*)&ptr);
|
322 |
+
printf("The value of the integer pointed to by ptr is %d\n", *ptr);
|
323 |
+
|
324 |
+
return 0;
|
325 |
+
}
|
326 |
+
|
327 |
+
Note: We have yet to discuss those aspects of C which require the use of the (void *)
|
328 |
+
expression used here. For now, include it in your test code. We'll explain the reason
|
329 |
+
behind this expression later.
|
330 |
+
|
331 |
+
To review:
|
332 |
+
|
333 |
+
• A variable is declared by giving it a type and a name (e.g. int k;)
|
334 |
+
• A pointer variable is declared by giving it a type and a name (e.g. int *ptr) where
|
335 |
+
the asterisk tells the compiler that the variable named ptr is a pointer variable and
|
336 |
+
the type tells the compiler what type the pointer is to point to (integer in this
|
337 |
+
case).
|
338 |
+
|
339 |
+
• Once a variable is declared, we can get its address by preceding its name with the
|
340 |
+
|
341 |
+
unary & operator, as in &k.
|
342 |
+
|
343 |
+
• We can "dereference" a pointer, i.e. refer to the value of that which it points to, by
|
344 |
+
|
345 |
+
using the unary '*' operator as in *ptr.
|
346 |
+
|
347 |
+
• An "lvalue" of a variable is the value of its address, i.e. where it is stored in
|
348 |
+
|
349 |
+
memory. The "rvalue" of a variable is the value stored in that variable (at that
|
350 |
+
address).
|
351 |
+
|
352 |
+
References for Chapter 1:
|
353 |
+
|
354 |
+
1. "The C Programming Language" 2nd Edition
|
355 |
+
|
356 |
+
B. Kernighan and D. Ritchie
|
357 |
+
Prentice Hall
|
358 |
+
ISBN 0-13-110362-8
|
359 |
+
|
360 |
+
8
|
361 |
+
|
362 |
+
|
363 |
+
|
364 |
+
|
365 |
+
|
366 |
+
CHAPTER 2: Pointer types and Arrays
|
367 |
+
|
368 |
+
Okay, let's move on. Let us consider why we need to identify the type of variable that a
|
369 |
+
pointer points to, as in:
|
370 |
+
|
371 |
+
int *ptr;
|
372 |
+
|
373 |
+
One reason for doing this is so that later, once ptr "points to" something, if we write:
|
374 |
+
|
375 |
+
*ptr = 2;
|
376 |
+
|
377 |
+
the compiler will know how many bytes to copy into that memory location pointed to by
|
378 |
+
ptr. If ptr was declared as pointing to an integer, 2 bytes would be copied, if a long, 4
|
379 |
+
bytes would be copied. Similarly for floats and doubles the appropriate number will be
|
380 |
+
copied. But, defining the type that the pointer points to permits a number of other
|
381 |
+
interesting ways a compiler can interpret code. For example, consider a block in memory
|
382 |
+
consisting if ten integers in a row. That is, 20 bytes of memory are set aside to hold 10
|
383 |
+
integers.
|
384 |
+
|
385 |
+
Now, let's say we point our integer pointer ptr at the first of these integers. Furthermore
|
386 |
+
lets say that integer is located at memory location 100 (decimal). What happens when we
|
387 |
+
write:
|
388 |
+
|
389 |
+
ptr + 1;
|
390 |
+
|
391 |
+
Because the compiler "knows" this is a pointer (i.e. its value is an address) and that it
|
392 |
+
points to an integer (its current address, 100, is the address of an integer), it adds 2 to ptr
|
393 |
+
instead of 1, so the pointer "points to" the next integer, at memory location 102.
|
394 |
+
Similarly, were the ptr declared as a pointer to a long, it would add 4 to it instead of 1.
|
395 |
+
The same goes for other data types such as floats, doubles, or even user defined data
|
396 |
+
types such as structures. This is obviously not the same kind of "addition" that we
|
397 |
+
normally think of. In C it is referred to as addition using "pointer arithmetic", a term
|
398 |
+
which we will come back to later.
|
399 |
+
|
400 |
+
Similarly, since ++ptr and ptr++ are both equivalent to ptr + 1 (though the point in the
|
401 |
+
program when ptr is incremented may be different), incrementing a pointer using the
|
402 |
+
unary ++ operator, either pre- or post-, increments the address it stores by the amount
|
403 |
+
sizeof(type) where "type" is the type of the object pointed to. (i.e. 2 for an integer, 4 for a
|
404 |
+
long, etc.).
|
405 |
+
|
406 |
+
Since a block of 10 integers located contiguously in memory is, by definition, an array of
|
407 |
+
integers, this brings up an interesting relationship between arrays and pointers.
|
408 |
+
|
409 |
+
9
|
410 |
+
|
411 |
+
|
412 |
+
Consider the following:
|
413 |
+
|
414 |
+
int my_array[] = {1,23,17,4,-5,100};
|
415 |
+
|
416 |
+
Here we have an array containing 6 integers. We refer to each of these integers by means
|
417 |
+
of a subscript to my_array, i.e. using my_array[0] through my_array[5]. But, we could
|
418 |
+
alternatively access them via a pointer as follows:
|
419 |
+
|
420 |
+
int *ptr;
|
421 |
+
ptr = &my_array[0]; /* point our pointer at the first
|
422 |
+
integer in our array */
|
423 |
+
|
424 |
+
And then we could print out our array either using the array notation or by dereferencing
|
425 |
+
our pointer. The following code illustrates this:
|
426 |
+
|
427 |
+
----------- Program 2.1 -----------------------------------
|
428 |
+
|
429 |
+
/* Program 2.1 from PTRTUT10.HTM 6/13/97 */
|
430 |
+
|
431 |
+
#include <stdio.h>
|
432 |
+
|
433 |
+
int my_array[] = {1,23,17,4,-5,100};
|
434 |
+
int *ptr;
|
435 |
+
|
436 |
+
int main(void)
|
437 |
+
{
|
438 |
+
int i;
|
439 |
+
ptr = &my_array[0]; /* point our pointer to the first
|
440 |
+
element of the array */
|
441 |
+
printf("\n\n");
|
442 |
+
for (i = 0; i < 6; i++)
|
443 |
+
{
|
444 |
+
printf("my_array[%d] = %d ",i,my_array[i]); /*<-- A */
|
445 |
+
printf("ptr + %d = %d\n",i, *(ptr + i)); /*<-- B */
|
446 |
+
}
|
447 |
+
return 0;
|
448 |
+
}
|
449 |
+
|
450 |
+
Compile and run the above program and carefully note lines A and B and that the
|
451 |
+
program prints out the same values in either case. Also observe how we dereferenced our
|
452 |
+
pointer in line B, i.e. we first added i to it and then dereferenced the new pointer. Change
|
453 |
+
line B to read:
|
454 |
+
|
455 |
+
printf("ptr + %d = %d\n",i, *ptr++);
|
456 |
+
|
457 |
+
and run it again... then change it to:
|
458 |
+
|
459 |
+
printf("ptr + %d = %d\n",i, *(++ptr));
|
460 |
+
|
461 |
+
10
|
462 |
+
|
463 |
+
|
464 |
+
|
465 |
+
|
466 |
+
|
467 |
+
|
468 |
+
|
469 |
+
and try once more. Each time try and predict the outcome and carefully look at the actual
|
470 |
+
outcome.
|
471 |
+
|
472 |
+
In C, the standard states that wherever we might use &var_name[0] we can replace that
|
473 |
+
with var_name, thus in our code where we wrote:
|
474 |
+
|
475 |
+
ptr = &my_array[0];
|
476 |
+
|
477 |
+
we can write:
|
478 |
+
|
479 |
+
ptr = my_array;
|
480 |
+
|
481 |
+
to achieve the same result.
|
482 |
+
|
483 |
+
This leads many texts to state that the name of an array is a pointer. I prefer to mentally
|
484 |
+
think "the name of the array is the address of first element in the array". Many beginners
|
485 |
+
(including myself when I was learning) have a tendency to become confused by thinking
|
486 |
+
of it as a pointer. For example, while we can write
|
487 |
+
|
488 |
+
ptr = my_array;
|
489 |
+
|
490 |
+
we cannot write
|
491 |
+
|
492 |
+
my_array = ptr;
|
493 |
+
|
494 |
+
The reason is that while ptr is a variable, my_array is a constant. That is, the location at
|
495 |
+
which the first element of my_array will be stored cannot be changed once my_array[]
|
496 |
+
has been declared.
|
497 |
+
|
498 |
+
Earlier when discussing the term "lvalue" I cited K&R-2 where it stated:
|
499 |
+
|
500 |
+
"An object is a named region of storage; an lvalue is an expression
|
501 |
+
referring to an object".
|
502 |
+
|
503 |
+
This raises an interesting problem. Since my_array is a named region of storage, why is
|
504 |
+
my_array in the above assignment statement not an lvalue? To resolve this problem,
|
505 |
+
some refer to my_array as an "unmodifiable lvalue".
|
506 |
+
|
507 |
+
Modify the example program above by changing
|
508 |
+
|
509 |
+
ptr = &my_array[0];
|
510 |
+
|
511 |
+
to
|
512 |
+
|
513 |
+
ptr = my_array;
|
514 |
+
|
515 |
+
and run it again to verify the results are identical.
|
516 |
+
|
517 |
+
11
|
518 |
+
|
519 |
+
|
520 |
+
Now, let's delve a little further into the difference between the names ptr and my_array
|
521 |
+
as used above. Some writers will refer to an array's name as a constant pointer. What do
|
522 |
+
we mean by that? Well, to understand the term "constant" in this sense, let's go back to
|
523 |
+
our definition of the term "variable". When we declare a variable we set aside a spot in
|
524 |
+
memory to hold the value of the appropriate type. Once that is done the name of the
|
525 |
+
variable can be interpreted in one of two ways. When used on the left side of the
|
526 |
+
assignment operator, the compiler interprets it as the memory location to which to move
|
527 |
+
that value resulting from evaluation of the right side of the assignment operator. But,
|
528 |
+
when used on the right side of the assignment operator, the name of a variable is
|
529 |
+
interpreted to mean the contents stored at that memory address set aside to hold the value
|
530 |
+
of that variable.
|
531 |
+
|
532 |
+
With that in mind, let's now consider the simplest of constants, as in:
|
533 |
+
|
534 |
+
int i, k;
|
535 |
+
i = 2;
|
536 |
+
|
537 |
+
Here, while i is a variable and then occupies space in the data portion of memory, 2 is a
|
538 |
+
constant and, as such, instead of setting aside memory in the data segment, it is imbedded
|
539 |
+
directly in the code segment of memory. That is, while writing something like k = i; tells
|
540 |
+
the compiler to create code which at run time will look at memory location &i to
|
541 |
+
determine the value to be moved to k, code created by i = 2; simply puts the 2 in the code
|
542 |
+
and there is no referencing of the data segment. That is, both k and i are objects, but 2 is
|
543 |
+
not an object.
|
544 |
+
|
545 |
+
Similarly, in the above, since my_array is a constant, once the compiler establishes
|
546 |
+
where the array itself is to be stored, it "knows" the address of my_array[0] and on
|
547 |
+
seeing:
|
548 |
+
|
549 |
+
ptr = my_array;
|
550 |
+
|
551 |
+
it simply uses this address as a constant in the code segment and there is no referencing
|
552 |
+
of the data segment beyond that.
|
553 |
+
|
554 |
+
This might be a good place explain further the use of the (void *) expression used in
|
555 |
+
Program 1.1 of Chapter 1. As we have seen we can have pointers of various types. So far
|
556 |
+
we have discussed pointers to integers and pointers to characters. In coming chapters we
|
557 |
+
will be learning about pointers to structures and even pointer to pointers.
|
558 |
+
|
559 |
+
Also we have learned that on different systems the size of a pointer can vary. As it turns
|
560 |
+
out it is also possible that the size of a pointer can vary depending on the data type of the
|
561 |
+
object to which it points. Thus, as with integers where you can run into trouble
|
562 |
+
attempting to assign a long integer to a variable of type short integer, you can run into
|
563 |
+
trouble attempting to assign the values of pointers of various types to pointer variables of
|
564 |
+
other types.
|
565 |
+
|
566 |
+
12
|
567 |
+
|
568 |
+
|
569 |
+
To minimize this problem, C provides for a pointer of type void. We can declare such a
|
570 |
+
pointer by writing:
|
571 |
+
|
572 |
+
void *vptr;
|
573 |
+
|
574 |
+
A void pointer is sort of a generic pointer. For example, while C will not permit the
|
575 |
+
comparison of a pointer to type integer with a pointer to type character, for example,
|
576 |
+
either of these can be compared to a void pointer. Of course, as with other variables, casts
|
577 |
+
can be used to convert from one type of pointer to another under the proper
|
578 |
+
circumstances. In Program 1.1. of Chapter 1 I cast the pointers to integers into void
|
579 |
+
pointers to make them compatible with the %p conversion specification. In later chapters
|
580 |
+
other casts will be made for reasons defined therein.
|
581 |
+
|
582 |
+
Well, that's a lot of technical stuff to digest and I don't expect a beginner to understand all
|
583 |
+
of it on first reading. With time and experimentation you will want to come back and re-
|
584 |
+
read the first 2 chapters. But for now, let's move on to the relationship between pointers,
|
585 |
+
character arrays, and strings.
|
586 |
+
|
587 |
+
13
|
588 |
+
|
589 |
+
|
590 |
+
CHAPTER 3: Pointers and Strings
|
591 |
+
|
592 |
+
The study of strings is useful to further tie in the relationship between pointers and arrays.
|
593 |
+
It also makes it easy to illustrate how some of the standard C string functions can be
|
594 |
+
implemented. Finally it illustrates how and when pointers can and should be passed to
|
595 |
+
functions.
|
596 |
+
|
597 |
+
In C, strings are arrays of characters. This is not necessarily true in other languages. In
|
598 |
+
BASIC, Pascal, Fortran and various other languages, a string has its own data type. But in
|
599 |
+
C it does not. In C a string is an array of characters terminated with a binary zero
|
600 |
+
character (written as '\0'). To start off our discussion we will write some code which,
|
601 |
+
while preferred for illustrative purposes, you would probably never write in an actual
|
602 |
+
program. Consider, for example:
|
603 |
+
|
604 |
+
char my_string[40];
|
605 |
+
|
606 |
+
my_string[0] = 'T';
|
607 |
+
my_string[1] = 'e';
|
608 |
+
my_string[2] = 'd':
|
609 |
+
my_string[3] = '\0';
|
610 |
+
|
611 |
+
While one would never build a string like this, the end result is a string in that it is an
|
612 |
+
array of characters terminated with a nul character. By definition, in C, a string is an
|
613 |
+
array of characters terminated with the nul character. Be aware that "nul" is not the same
|
614 |
+
as "NULL". The nul refers to a zero as defined by the escape sequence '\0'. That is it
|
615 |
+
occupies one byte of memory. NULL, on the other hand, is the name of the macro used to
|
616 |
+
initialize null pointers. NULL is #defined in a header file in your C compiler, nul may not
|
617 |
+
be #defined at all.
|
618 |
+
|
619 |
+
Since writing the above code would be very time consuming, C permits two alternate
|
620 |
+
ways of achieving the same thing. First, one might write:
|
621 |
+
|
622 |
+
char my_string[40] = {'T', 'e', 'd', '\0',};
|
623 |
+
|
624 |
+
But this also takes more typing than is convenient. So, C permits:
|
625 |
+
|
626 |
+
char my_string[40] = "Ted";
|
627 |
+
|
628 |
+
When the double quotes are used, instead of the single quotes as was done in the previous
|
629 |
+
examples, the nul character ( '\0' ) is automatically appended to the end of the string.
|
630 |
+
|
631 |
+
In all of the above cases, the same thing happens. The compiler sets aside an contiguous
|
632 |
+
block of memory 40 bytes long to hold characters and initialized it such that the first 4
|
633 |
+
characters are Ted\0.
|
634 |
+
|
635 |
+
Now, consider the following program:
|
636 |
+
|
637 |
+
14
|
638 |
+
|
639 |
+
|
640 |
+
|
641 |
+
------------------program 3.1-------------------------------------
|
642 |
+
|
643 |
+
/* Program 3.1 from PTRTUT10.HTM 6/13/97 */
|
644 |
+
|
645 |
+
#include <stdio.h>
|
646 |
+
|
647 |
+
char strA[80] = "A string to be used for demonstration purposes";
|
648 |
+
char strB[80];
|
649 |
+
|
650 |
+
int main(void)
|
651 |
+
{
|
652 |
+
|
653 |
+
char *pA; /* a pointer to type character */
|
654 |
+
char *pB; /* another pointer to type character */
|
655 |
+
puts(strA); /* show string A */
|
656 |
+
pA = strA; /* point pA at string A */
|
657 |
+
puts(pA); /* show what pA is pointing to */
|
658 |
+
pB = strB; /* point pB at string B */
|
659 |
+
putchar('\n'); /* move down one line on the screen */
|
660 |
+
while(*pA != '\0') /* line A (see text) */
|
661 |
+
{
|
662 |
+
*pB++ = *pA++; /* line B (see text) */
|
663 |
+
}
|
664 |
+
*pB = '\0'; /* line C (see text) */
|
665 |
+
puts(strB); /* show strB on screen */
|
666 |
+
return 0;
|
667 |
+
}
|
668 |
+
|
669 |
+
--------- end program 3.1 -------------------------------------
|
670 |
+
|
671 |
+
In the above we start out by defining two character arrays of 80 characters each. Since
|
672 |
+
these are globally defined, they are initialized to all '\0's first. Then, strA has the first 42
|
673 |
+
characters initialized to the string in quotes.
|
674 |
+
|
675 |
+
Now, moving into the code, we declare two character pointers and show the string on the
|
676 |
+
screen. We then "point" the pointer pA at strA. That is, by means of the assignment
|
677 |
+
statement we copy the address of strA[0] into our variable pA. We now use puts() to
|
678 |
+
show that which is pointed to by pA on the screen. Consider here that the function
|
679 |
+
prototype for puts() is:
|
680 |
+
|
681 |
+
int puts(const char *s);
|
682 |
+
|
683 |
+
For the moment, ignore the const. The parameter passed to puts() is a pointer, that is the
|
684 |
+
value of a pointer (since all parameters in C are passed by value), and the value of a
|
685 |
+
pointer is the address to which it points, or, simply, an address. Thus when we write
|
686 |
+
puts(strA); as we have seen, we are passing the address of strA[0].
|
687 |
+
|
688 |
+
Similarly, when we write puts(pA); we are passing the same address, since we have set
|
689 |
+
pA = strA;
|
690 |
+
|
691 |
+
15
|
692 |
+
|
693 |
+
|
694 |
+
|
695 |
+
|
696 |
+
|
697 |
+
|
698 |
+
|
699 |
+
|
700 |
+
|
701 |
+
|
702 |
+
Given that, follow the code down to the while() statement on line A. Line A states:
|
703 |
+
|
704 |
+
While the character pointed to by pA (i.e. *pA) is not a nul character (i.e. the terminating
|
705 |
+
'\0'), do the following:
|
706 |
+
|
707 |
+
Line B states: copy the character pointed to by pA to the space pointed to by pB, then
|
708 |
+
increment pA so it points to the next character and pB so it points to the next space.
|
709 |
+
|
710 |
+
When we have copied the last character, pA now points to the terminating nul character
|
711 |
+
and the loop ends. However, we have not copied the nul character. And, by definition a
|
712 |
+
string in C must be nul terminated. So, we add the nul character with line C.
|
713 |
+
|
714 |
+
It is very educational to run this program with your debugger while watching strA, strB,
|
715 |
+
pA and pB and single stepping through the program. It is even more educational if
|
716 |
+
instead of simply defining strB[] as has been done above, initialize it also with something
|
717 |
+
like:
|
718 |
+
|
719 |
+
strB[80] = "12345678901234567890123456789012345678901234567890"
|
720 |
+
|
721 |
+
where the number of digits used is greater than the length of strA and then repeat the
|
722 |
+
single stepping procedure while watching the above variables. Give these things a try!
|
723 |
+
|
724 |
+
Getting back to the prototype for puts() for a moment, the "const" used as a parameter
|
725 |
+
modifier informs the user that the function will not modify the string pointed to by s, i.e.
|
726 |
+
it will treat that string as a constant.
|
727 |
+
|
728 |
+
Of course, what the above program illustrates is a simple way of copying a string. After
|
729 |
+
playing with the above until you have a good understanding of what is happening, we can
|
730 |
+
proceed to creating our own replacement for the standard strcpy() that comes with C. It
|
731 |
+
might look like:
|
732 |
+
|
733 |
+
char *my_strcpy(char *destination, char *source)
|
734 |
+
{
|
735 |
+
char *p = destination;
|
736 |
+
while (*source != '\0')
|
737 |
+
{
|
738 |
+
*p++ = *source++;
|
739 |
+
}
|
740 |
+
*p = '\0';
|
741 |
+
return destination;
|
742 |
+
}
|
743 |
+
|
744 |
+
In this case, I have followed the practice used in the standard routine of returning a
|
745 |
+
pointer to the destination.
|
746 |
+
|
747 |
+
Again, the function is designed to accept the values of two character pointers, i.e.
|
748 |
+
addresses, and thus in the previous program we could write:
|
749 |
+
|
750 |
+
16
|
751 |
+
|
752 |
+
|
753 |
+
int main(void)
|
754 |
+
{
|
755 |
+
my_strcpy(strB, strA);
|
756 |
+
puts(strB);
|
757 |
+
}
|
758 |
+
|
759 |
+
I have deviated slightly from the form used in standard C which would have the
|
760 |
+
prototype:
|
761 |
+
|
762 |
+
char *my_strcpy(char *destination, const char *source);
|
763 |
+
|
764 |
+
Here the "const" modifier is used to assure the user that the function will not modify the
|
765 |
+
contents pointed to by the source pointer. You can prove this by modifying the function
|
766 |
+
above, and its prototype, to include the "const" modifier as shown. Then, within the
|
767 |
+
function you can add a statement which attempts to change the contents of that which is
|
768 |
+
pointed to by source, such as:
|
769 |
+
|
770 |
+
*source = 'X';
|
771 |
+
|
772 |
+
which would normally change the first character of the string to an X. The const modifier
|
773 |
+
should cause your compiler to catch this as an error. Try it and see.
|
774 |
+
|
775 |
+
Now, let's consider some of the things the above examples have shown us. First off,
|
776 |
+
consider the fact that *ptr++ is to be interpreted as returning the value pointed to by ptr
|
777 |
+
and then incrementing the pointer value. This has to do with the precedence of the
|
778 |
+
operators. Were we to write (*ptr)++ we would increment, not the pointer, but that which
|
779 |
+
the pointer points to! i.e. if used on the first character of the above example string the 'T'
|
780 |
+
would be incremented to a 'U'. You can write some simple example code to illustrate this.
|
781 |
+
|
782 |
+
Recall again that a string is nothing more than an array of characters, with the last
|
783 |
+
character being a '\0'. What we have done above is deal with copying an array. It happens
|
784 |
+
to be an array of characters but the technique could be applied to an array of integers,
|
785 |
+
doubles, etc. In those cases, however, we would not be dealing with strings and hence the
|
786 |
+
end of the array would not be marked with a special value like the nul character. We
|
787 |
+
could implement a version that relied on a special value to identify the end. For example,
|
788 |
+
we could copy an array of positive integers by marking the end with a negative integer.
|
789 |
+
On the other hand, it is more usual that when we write a function to copy an array of
|
790 |
+
items other than strings we pass the function the number of items to be copied as well as
|
791 |
+
the address of the array, e.g. something like the following prototype might indicate:
|
792 |
+
|
793 |
+
void int_copy(int *ptrA, int *ptrB, int nbr);
|
794 |
+
|
795 |
+
where nbr is the number of integers to be copied. You might want to play with this idea
|
796 |
+
and create an array of integers and see if you can write the function int_copy() and make
|
797 |
+
it work.
|
798 |
+
|
799 |
+
17
|
800 |
+
|
801 |
+
|
802 |
+
|
803 |
+
This permits using functions to manipulate large arrays. For example, if we have an array
|
804 |
+
of 5000 integers that we want to manipulate with a function, we need only pass to that
|
805 |
+
function the address of the array (and any auxiliary information such as nbr above,
|
806 |
+
depending on what we are doing). The array itself does not get passed, i.e. the whole
|
807 |
+
array is not copied and put on the stack before calling the function, only its address is
|
808 |
+
sent.
|
809 |
+
|
810 |
+
This is different from passing, say an integer, to a function. When we pass an integer we
|
811 |
+
make a copy of the integer, i.e. get its value and put it on the stack. Within the function
|
812 |
+
any manipulation of the value passed can in no way effect the original integer. But, with
|
813 |
+
arrays and pointers we can pass the address of the variable and hence manipulate the
|
814 |
+
values of the original variables.
|
815 |
+
|
816 |
+
18
|
817 |
+
|
818 |
+
|
819 |
+
CHAPTER 4: More on Strings
|
820 |
+
|
821 |
+
Well, we have progressed quite a way in a short time! Let's back up a little and look at
|
822 |
+
what was done in Chapter 3 on copying of strings but in a different light. Consider the
|
823 |
+
following function:
|
824 |
+
|
825 |
+
char *my_strcpy(char dest[], char source[])
|
826 |
+
{
|
827 |
+
int i = 0;
|
828 |
+
while (source[i] != '\0')
|
829 |
+
{
|
830 |
+
dest[i] = source[i];
|
831 |
+
i++;
|
832 |
+
}
|
833 |
+
dest[i] = '\0';
|
834 |
+
return dest;
|
835 |
+
}
|
836 |
+
Recall that strings are arrays of characters. Here we have chosen to use array notation
|
837 |
+
instead of pointer notation to do the actual copying. The results are the same, i.e. the
|
838 |
+
string gets copied using this notation just as accurately as it did before. This raises some
|
839 |
+
interesting points which we will discuss.
|
840 |
+
|
841 |
+
Since parameters are passed by value, in both the passing of a character pointer or the
|
842 |
+
name of the array as above, what actually gets passed is the address of the first element of
|
843 |
+
each array. Thus, the numerical value of the parameter passed is the same whether we use
|
844 |
+
a character pointer or an array name as a parameter. This would tend to imply that
|
845 |
+
somehow source[i] is the same as *(p+i).
|
846 |
+
|
847 |
+
In fact, this is true, i.e wherever one writes a[i] it can be replaced with *(a + i) without
|
848 |
+
any problems. In fact, the compiler will create the same code in either case. Thus we see
|
849 |
+
that pointer arithmetic is the same thing as array indexing. Either syntax produces the
|
850 |
+
same result.
|
851 |
+
|
852 |
+
This is NOT saying that pointers and arrays are the same thing, they are not. We are only
|
853 |
+
saying that to identify a given element of an array we have the choice of two syntaxes,
|
854 |
+
one using array indexing and the other using pointer arithmetic, which yield identical
|
855 |
+
results.
|
856 |
+
|
857 |
+
Now, looking at this last expression, part of it.. (a + i), is a simple addition using the +
|
858 |
+
operator and the rules of C state that such an expression is commutative. That is (a + i) is
|
859 |
+
identical to (i + a). Thus we could write *(i + a) just as easily as *(a + i).
|
860 |
+
|
861 |
+
19
|
862 |
+
|
863 |
+
|
864 |
+
|
865 |
+
But *(i + a) could have come from i[a] ! From all of this comes the curious truth that if:
|
866 |
+
|
867 |
+
char a[20];
|
868 |
+
int i;
|
869 |
+
|
870 |
+
writing
|
871 |
+
|
872 |
+
a[3] = 'x';
|
873 |
+
|
874 |
+
is the same as writing
|
875 |
+
|
876 |
+
3[a] = 'x';
|
877 |
+
|
878 |
+
Try it! Set up an array of characters, integers or longs, etc. and assigned the 3rd or 4th
|
879 |
+
element a value using the conventional approach and then print out that value to be sure
|
880 |
+
you have that working. Then reverse the array notation as I have done above. A good
|
881 |
+
compiler will not balk and the results will be identical. A curiosity... nothing more!
|
882 |
+
|
883 |
+
Now, looking at our function above, when we write:
|
884 |
+
|
885 |
+
dest[i] = source[i];
|
886 |
+
|
887 |
+
due to the fact that array indexing and pointer arithmetic yield identical results, we can
|
888 |
+
write this as:
|
889 |
+
|
890 |
+
*(dest + i) = *(source + i);
|
891 |
+
|
892 |
+
But, this takes 2 additions for each value taken on by i. Additions, generally speaking,
|
893 |
+
take more time than incrementations (such as those done using the ++ operator as in i++).
|
894 |
+
This may not be true in modern optimizing compilers, but one can never be sure. Thus,
|
895 |
+
the pointer version may be a bit faster than the array version.
|
896 |
+
|
897 |
+
Another way to speed up the pointer version would be to change:
|
898 |
+
|
899 |
+
while (*source != '\0')
|
900 |
+
|
901 |
+
to simply
|
902 |
+
|
903 |
+
while (*source)
|
904 |
+
|
905 |
+
since the value within the parenthesis will go to zero (FALSE) at the same time in either
|
906 |
+
case.
|
907 |
+
|
908 |
+
20
|
909 |
+
|
910 |
+
|
911 |
+
|
912 |
+
|
913 |
+
|
914 |
+
|
915 |
+
|
916 |
+
|
917 |
+
|
918 |
+
|
919 |
+
|
920 |
+
|
921 |
+
|
922 |
+
At this point you might want to experiment a bit with writing some of your own programs
|
923 |
+
using pointers. Manipulating strings is a good place to experiment. You might want to
|
924 |
+
write your own versions of such standard functions as:
|
925 |
+
|
926 |
+
strlen();
|
927 |
+
strcat();
|
928 |
+
strchr();
|
929 |
+
and any others you might have on your system.
|
930 |
+
|
931 |
+
We will come back to strings and their manipulation through pointers in a future chapter.
|
932 |
+
For now, let's move on and discuss structures for a bit.
|
933 |
+
|
934 |
+
21
|
935 |
+
|
936 |
+
|
937 |
+
|
938 |
+
|
939 |
+
CHAPTER 5: Pointers and Structures
|
940 |
+
|
941 |
+
As you may know, we can declare the form of a block of data containing different data
|
942 |
+
types by means of a structure declaration. For example, a personnel file might contain
|
943 |
+
structures which look something like:
|
944 |
+
|
945 |
+
struct tag {
|
946 |
+
char lname[20]; /* last name */
|
947 |
+
char fname[20]; /* first name */
|
948 |
+
int age; /* age */
|
949 |
+
float rate; /* e.g. 12.75 per hour */
|
950 |
+
};
|
951 |
+
|
952 |
+
Let's say we have a bunch of these structures in a disk file and we want to read each one
|
953 |
+
out and print out the first and last name of each one so that we can have a list of the
|
954 |
+
people in our files. The remaining information will not be printed out. We will want to do
|
955 |
+
this printing with a function call and pass to that function a pointer to the structure at
|
956 |
+
hand. For demonstration purposes I will use only one structure for now. But realize the
|
957 |
+
goal is the writing of the function, not the reading of the file which, presumably, we
|
958 |
+
know how to do.
|
959 |
+
|
960 |
+
For review, recall that we can access structure members with the dot operator as in:
|
961 |
+
|
962 |
+
--------------- program 5.1 ------------------
|
963 |
+
|
964 |
+
/* Program 5.1 from PTRTUT10.HTM 6/13/97 */
|
965 |
+
|
966 |
+
#include <stdio.h>
|
967 |
+
#include <string.h>
|
968 |
+
|
969 |
+
struct tag {
|
970 |
+
char lname[20]; /* last name */
|
971 |
+
char fname[20]; /* first name */
|
972 |
+
int age; /* age */
|
973 |
+
float rate; /* e.g. 12.75 per hour */
|
974 |
+
};
|
975 |
+
|
976 |
+
struct tag my_struct; /* declare the structure my_struct */
|
977 |
+
|
978 |
+
int main(void)
|
979 |
+
{
|
980 |
+
strcpy(my_struct.lname,"Jensen");
|
981 |
+
strcpy(my_struct.fname,"Ted");
|
982 |
+
printf("\n%s ",my_struct.fname);
|
983 |
+
printf("%s\n",my_struct.lname);
|
984 |
+
return 0;
|
985 |
+
}
|
986 |
+
|
987 |
+
-------------- end of program 5.1 --------------
|
988 |
+
|
989 |
+
22
|
990 |
+
|
991 |
+
|
992 |
+
|
993 |
+
|
994 |
+
|
995 |
+
|
996 |
+
|
997 |
+
|
998 |
+
|
999 |
+
|
1000 |
+
Now, this particular structure is rather small compared to many used in C programs. To
|
1001 |
+
the above we might want to add:
|
1002 |
+
|
1003 |
+
date_of_hire; (data types not shown)
|
1004 |
+
date_of_last_raise;
|
1005 |
+
last_percent_increase;
|
1006 |
+
emergency_phone;
|
1007 |
+
medical_plan;
|
1008 |
+
Social_S_Nbr;
|
1009 |
+
etc.....
|
1010 |
+
|
1011 |
+
If we have a large number of employees, what we want to do is manipulate the data in
|
1012 |
+
these structures by means of functions. For example we might want a function print out
|
1013 |
+
the name of the employee listed in any structure passed to it. However, in the original C
|
1014 |
+
(Kernighan & Ritchie, 1st Edition) it was not possible to pass a structure, only a pointer
|
1015 |
+
to a structure could be passed. In ANSI C, it is now permissible to pass the complete
|
1016 |
+
structure. But, since our goal here is to learn more about pointers, we won't pursue that.
|
1017 |
+
|
1018 |
+
Anyway, if we pass the whole structure it means that we must copy the contents of the
|
1019 |
+
structure from the calling function to the called function. In systems using stacks, this is
|
1020 |
+
done by pushing the contents of the structure on the stack. With large structures this
|
1021 |
+
could prove to be a problem. However, passing a pointer uses a minimum amount of
|
1022 |
+
stack space.
|
1023 |
+
|
1024 |
+
In any case, since this is a discussion of pointers, we will discuss how we go about
|
1025 |
+
passing a pointer to a structure and then using it within the function.
|
1026 |
+
|
1027 |
+
Consider the case described, i.e. we want a function that will accept as a parameter a
|
1028 |
+
pointer to a structure and from within that function we want to access members of the
|
1029 |
+
structure. For example we want to print out the name of the employee in our example
|
1030 |
+
structure.
|
1031 |
+
|
1032 |
+
Okay, so we know that our pointer is going to point to a structure declared using struct
|
1033 |
+
tag. We declare such a pointer with the declaration:
|
1034 |
+
|
1035 |
+
struct tag *st_ptr;
|
1036 |
+
|
1037 |
+
and we point it to our example structure with:
|
1038 |
+
|
1039 |
+
st_ptr = &my_struct;
|
1040 |
+
|
1041 |
+
Now, we can access a given member by de-referencing the pointer. But, how do we de-
|
1042 |
+
reference the pointer to a structure? Well, consider the fact that we might want to use the
|
1043 |
+
pointer to set the age of the employee. We would write:
|
1044 |
+
|
1045 |
+
(*st_ptr).age = 63;
|
1046 |
+
|
1047 |
+
23
|
1048 |
+
|
1049 |
+
|
1050 |
+
|
1051 |
+
Look at this carefully. It says, replace that within the parenthesis with that which st_ptr
|
1052 |
+
points to, which is the structure my_struct. Thus, this breaks down to the same as
|
1053 |
+
my_struct.age.
|
1054 |
+
|
1055 |
+
However, this is a fairly often used expression and the designers of C have created an
|
1056 |
+
alternate syntax with the same meaning which is:
|
1057 |
+
|
1058 |
+
st_ptr->age = 63;
|
1059 |
+
|
1060 |
+
With that in mind, look at the following program:
|
1061 |
+
|
1062 |
+
------------ program 5.2 ---------------------
|
1063 |
+
|
1064 |
+
/* Program 5.2 from PTRTUT10.HTM 6/13/97 */
|
1065 |
+
|
1066 |
+
#include <stdio.h>
|
1067 |
+
#include <string.h>
|
1068 |
+
|
1069 |
+
struct tag{ /* the structure type */
|
1070 |
+
char lname[20]; /* last name */
|
1071 |
+
char fname[20]; /* first name */
|
1072 |
+
int age; /* age */
|
1073 |
+
float rate; /* e.g. 12.75 per hour */
|
1074 |
+
};
|
1075 |
+
|
1076 |
+
struct tag my_struct; /* define the structure */
|
1077 |
+
void show_name(struct tag *p); /* function prototype */
|
1078 |
+
|
1079 |
+
int main(void)
|
1080 |
+
{
|
1081 |
+
struct tag *st_ptr; /* a pointer to a structure */
|
1082 |
+
st_ptr = &my_struct; /* point the pointer to my_struct */
|
1083 |
+
strcpy(my_struct.lname,"Jensen");
|
1084 |
+
strcpy(my_struct.fname,"Ted");
|
1085 |
+
printf("\n%s ",my_struct.fname);
|
1086 |
+
printf("%s\n",my_struct.lname);
|
1087 |
+
my_struct.age = 63;
|
1088 |
+
show_name(st_ptr); /* pass the pointer */
|
1089 |
+
return 0;
|
1090 |
+
}
|
1091 |
+
|
1092 |
+
void show_name(struct tag *p)
|
1093 |
+
{
|
1094 |
+
printf("\n%s ", p->fname); /* p points to a structure */
|
1095 |
+
printf("%s ", p->lname);
|
1096 |
+
printf("%d\n", p->age);
|
1097 |
+
}
|
1098 |
+
|
1099 |
+
-------------------- end of program 5.2 ----------------
|
1100 |
+
|
1101 |
+
Again, this is a lot of information to absorb at one time. The reader should compile and
|
1102 |
+
run the various code snippets and using a debugger monitor things like my_struct and p
|
1103 |
+
|
1104 |
+
24
|
1105 |
+
|
1106 |
+
|
1107 |
+
|
1108 |
+
|
1109 |
+
|
1110 |
+
|
1111 |
+
|
1112 |
+
|
1113 |
+
|
1114 |
+
|
1115 |
+
|
1116 |
+
while single stepping through the main and following the code down into the function to
|
1117 |
+
see what is happening.
|
1118 |
+
|
1119 |
+
25
|
1120 |
+
|
1121 |
+
|
1122 |
+
CHAPTER 6: Some more on Strings, and Arrays of
|
1123 |
+
Strings
|
1124 |
+
|
1125 |
+
Well, let's go back to strings for a bit. In the following all assignments are to be
|
1126 |
+
understood as being global, i.e. made outside of any function, including main().
|
1127 |
+
|
1128 |
+
We pointed out in an earlier chapter that we could write:
|
1129 |
+
|
1130 |
+
char my_string[40] = "Ted";
|
1131 |
+
|
1132 |
+
which would allocate space for a 40 byte array and put the string in the first 4 bytes (three
|
1133 |
+
for the characters in the quotes and a 4th to handle the terminating '\0').
|
1134 |
+
|
1135 |
+
Actually, if all we wanted to do was store the name "Ted" we could write:
|
1136 |
+
|
1137 |
+
char my_name[] = "Ted";
|
1138 |
+
|
1139 |
+
and the compiler would count the characters, leave room for the nul character and store
|
1140 |
+
the total of the four characters in memory the location of which would be returned by the
|
1141 |
+
array name, in this case my_name.
|
1142 |
+
|
1143 |
+
In some code, instead of the above, you might see:
|
1144 |
+
|
1145 |
+
char *my_name = "Ted";
|
1146 |
+
|
1147 |
+
which is an alternate approach. Is there a difference between these? The answer is.. yes.
|
1148 |
+
Using the array notation 4 bytes of storage in the static memory block are taken up, one
|
1149 |
+
for each character and one for the terminating nul character. But, in the pointer notation
|
1150 |
+
the same 4 bytes required, plus N bytes to store the pointer variable my_name (where N
|
1151 |
+
depends on the system but is usually a minimum of 2 bytes and can be 4 or more).
|
1152 |
+
|
1153 |
+
In the array notation, my_name is short for &myname[0] which is the address of the
|
1154 |
+
first element of the array. Since the location of the array is fixed during run time, this is a
|
1155 |
+
constant (not a variable). In the pointer notation my_name is a variable. As to which is
|
1156 |
+
the better method, that depends on what you are going to do within the rest of the
|
1157 |
+
program.
|
1158 |
+
|
1159 |
+
Let's now go one step further and consider what happens if each of these declarations are
|
1160 |
+
done within a function as opposed to globally outside the bounds of any function.
|
1161 |
+
|
1162 |
+
void my_function_A(char *ptr)
|
1163 |
+
{
|
1164 |
+
char a[] = "ABCDE"
|
1165 |
+
.
|
1166 |
+
.
|
1167 |
+
}
|
1168 |
+
|
1169 |
+
26
|
1170 |
+
|
1171 |
+
|
1172 |
+
|
1173 |
+
void my_function_B(char *ptr)
|
1174 |
+
{
|
1175 |
+
char *cp = "FGHIJ"
|
1176 |
+
.
|
1177 |
+
.
|
1178 |
+
}
|
1179 |
+
|
1180 |
+
In the case of my_function_A, the content, or value(s), of the array a[] is considered to
|
1181 |
+
be the data. The array is said to be initialized to the values ABCDE. In the case of
|
1182 |
+
my_function_B, the value of the pointer cp is considered to be the data. The pointer has
|
1183 |
+
been initialized to point to the string FGHIJ. In both my_function_A and
|
1184 |
+
my_function_B the definitions are local variables and thus the string ABCDE is stored
|
1185 |
+
on the stack, as is the value of the pointer cp. The string FGHIJ can be stored anywhere.
|
1186 |
+
On my system it gets stored in the data segment.
|
1187 |
+
|
1188 |
+
By the way, array initialization of automatic variables as I have done in my_function_A
|
1189 |
+
was illegal in the older K&R C and only "came of age" in the newer ANSI C. A fact that
|
1190 |
+
may be important when one is considering portability and backwards compatibility.
|
1191 |
+
|
1192 |
+
As long as we are discussing the relationship/differences between pointers and arrays,
|
1193 |
+
let's move on to multi-dimensional arrays. Consider, for example the array:
|
1194 |
+
|
1195 |
+
char multi[5][10];
|
1196 |
+
|
1197 |
+
Just what does this mean? Well, let's consider it in the following light.
|
1198 |
+
|
1199 |
+
char multi[5][10];
|
1200 |
+
|
1201 |
+
Let's take the underlined part to be the "name" of an array. Then prepending the char and
|
1202 |
+
appending the [10] we have an array of 10 characters. But, the name multi[5] is itself an
|
1203 |
+
array indicating that there are 5 elements each being an array of 10 characters. Hence we
|
1204 |
+
have an array of 5 arrays of 10 characters each..
|
1205 |
+
|
1206 |
+
Assume we have filled this two dimensional array with data of some kind. In memory, it
|
1207 |
+
might look as if it had been formed by initializing 5 separate arrays using something like:
|
1208 |
+
|
1209 |
+
multi[0] = {'0','1','2','3','4','5','6','7','8','9'}
|
1210 |
+
multi[1] = {'a','b','c','d','e','f','g','h','i','j'}
|
1211 |
+
multi[2] = {'A','B','C','D','E','F','G','H','I','J'}
|
1212 |
+
multi[3] = {'9','8','7','6','5','4','3','2','1','0'}
|
1213 |
+
multi[4] = {'J','I','H','G','F','E','D','C','B','A'}
|
1214 |
+
|
1215 |
+
At the same time, individual elements might be addressable using syntax such as:
|
1216 |
+
|
1217 |
+
multi[0][3] = '3'
|
1218 |
+
multi[1][7] = 'h'
|
1219 |
+
multi[4][0] = 'J'
|
1220 |
+
|
1221 |
+
27
|
1222 |
+
|
1223 |
+
|
1224 |
+
|
1225 |
+
Since arrays are contiguous in memory, our actual memory block for the above should
|
1226 |
+
look like:
|
1227 |
+
|
1228 |
+
0123456789abcdefghijABCDEFGHIJ9876543210JIHGFEDCBA
|
1229 |
+
^
|
1230 |
+
|_____ starting at the address &multi[0][0]
|
1231 |
+
|
1232 |
+
Note that I did not write multi[0] = "0123456789". Had I done so a terminating '\0'
|
1233 |
+
would have been implied since whenever double quotes are used a '\0' character is
|
1234 |
+
appended to the characters contained within those quotes. Had that been the case I would
|
1235 |
+
have had to set aside room for 11 characters per row instead of 10.
|
1236 |
+
|
1237 |
+
My goal in the above is to illustrate how memory is laid out for 2 dimensional arrays.
|
1238 |
+
That is, this is a 2 dimensional array of characters, NOT an array of "strings".
|
1239 |
+
|
1240 |
+
Now, the compiler knows how many columns are present in the array so it can interpret
|
1241 |
+
multi + 1 as the address of the 'a' in the 2nd row above. That is, it adds 10, the number of
|
1242 |
+
columns, to get this location. If we were dealing with integers and an array with the same
|
1243 |
+
dimension the compiler would add 10*sizeof(int) which, on my machine, would be 20.
|
1244 |
+
Thus, the address of the 9 in the 4th row above would be &multi[3][0] or *(multi + 3) in
|
1245 |
+
pointer notation. To get to the content of the 2nd element in the 4th row we add 1 to this
|
1246 |
+
address and dereference the result as in
|
1247 |
+
|
1248 |
+
*(*(multi + 3) + 1)
|
1249 |
+
|
1250 |
+
With a little thought we can see that:
|
1251 |
+
|
1252 |
+
*(*(multi + row) + col) and
|
1253 |
+
multi[row][col] yield the same results.
|
1254 |
+
|
1255 |
+
The following program illustrates this using integer arrays instead of character arrays.
|
1256 |
+
|
1257 |
+
------------------- program 6.1 ----------------------
|
1258 |
+
|
1259 |
+
/* Program 6.1 from PTRTUT10.HTM 6/13/97*/
|
1260 |
+
|
1261 |
+
#include <stdio.h>
|
1262 |
+
#define ROWS 5
|
1263 |
+
#define COLS 10
|
1264 |
+
|
1265 |
+
int multi[ROWS][COLS];
|
1266 |
+
|
1267 |
+
int main(void)
|
1268 |
+
{
|
1269 |
+
int row, col;
|
1270 |
+
for (row = 0; row < ROWS; row++)
|
1271 |
+
{
|
1272 |
+
for (col = 0; col < COLS; col++)
|
1273 |
+
{
|
1274 |
+
multi[row][col] = row*col;
|
1275 |
+
}
|
1276 |
+
|
1277 |
+
28
|
1278 |
+
|
1279 |
+
|
1280 |
+
|
1281 |
+
|
1282 |
+
|
1283 |
+
|
1284 |
+
}
|
1285 |
+
|
1286 |
+
for (row = 0; row < ROWS; row++)
|
1287 |
+
{
|
1288 |
+
for (col = 0; col < COLS; col++)
|
1289 |
+
{
|
1290 |
+
printf("\n%d ",multi[row][col]);
|
1291 |
+
printf("%d ",*(*(multi + row) + col));
|
1292 |
+
}
|
1293 |
+
}
|
1294 |
+
|
1295 |
+
return 0;
|
1296 |
+
}
|
1297 |
+
----------------- end of program 6.1 ---------------------
|
1298 |
+
|
1299 |
+
Because of the double de-referencing required in the pointer version, the name of a 2
|
1300 |
+
dimensional array is often said to be equivalent to a pointer to a pointer. With a three
|
1301 |
+
dimensional array we would be dealing with an array of arrays of arrays and some might
|
1302 |
+
say its name would be equivalent to a pointer to a pointer to a pointer. However, here we
|
1303 |
+
have initially set aside the block of memory for the array by defining it using array
|
1304 |
+
notation. Hence, we are dealing with a constant, not a variable. That is we are talking
|
1305 |
+
about a fixed address not a variable pointer. The dereferencing function used above
|
1306 |
+
permits us to access any element in the array of arrays without the need of changing the
|
1307 |
+
value of that address (the address of multi[0][0] as given by the symbol multi).
|
1308 |
+
|
1309 |
+
29
|
1310 |
+
|
1311 |
+
|
1312 |
+
|
1313 |
+
|
1314 |
+
CHAPTER 7: More on Multi-Dimensional Arrays
|
1315 |
+
|
1316 |
+
In the previous chapter we noted that given
|
1317 |
+
|
1318 |
+
#define ROWS 5
|
1319 |
+
#define COLS 10
|
1320 |
+
|
1321 |
+
int multi[ROWS][COLS];
|
1322 |
+
we can access individual elements of the array multi using either:
|
1323 |
+
|
1324 |
+
multi[row][col]
|
1325 |
+
or
|
1326 |
+
|
1327 |
+
*(*(multi + row) + col)
|
1328 |
+
|
1329 |
+
To understand more fully what is going on, let us replace
|
1330 |
+
|
1331 |
+
*(multi + row)
|
1332 |
+
|
1333 |
+
with X as in:
|
1334 |
+
|
1335 |
+
*(X + col)
|
1336 |
+
|
1337 |
+
Now, from this we see that X is like a pointer since the expression is de-referenced and
|
1338 |
+
we know that col is an integer. Here the arithmetic being used is of a special kind called
|
1339 |
+
"pointer arithmetic" is being used. That means that, since we are talking about an integer
|
1340 |
+
array, the address pointed to by (i.e. value of) X + col + 1 must be greater than the
|
1341 |
+
address X + col by and amount equal to sizeof(int).
|
1342 |
+
|
1343 |
+
Since we know the memory layout for 2 dimensional arrays, we can determine that in the
|
1344 |
+
expression multi + row as used above, multi + row + 1 must increase by value an
|
1345 |
+
amount equal to that needed to "point to" the next row, which in this case would be an
|
1346 |
+
amount equal to COLS * sizeof(int).
|
1347 |
+
|
1348 |
+
That says that if the expression *(*(multi + row) + col) is to be evaluated correctly at run
|
1349 |
+
time, the compiler must generate code which takes into consideration the value of COLS,
|
1350 |
+
i.e. the 2nd dimension. Because of the equivalence of the two forms of expression, this is
|
1351 |
+
true whether we are using the pointer expression as here or the array expression
|
1352 |
+
multi[row][col].
|
1353 |
+
|
1354 |
+
Thus, to evaluate either expression, a total of 5 values must be known:
|
1355 |
+
|
1356 |
+
1. The address of the first element of the array, which is returned by the expression
|
1357 |
+
|
1358 |
+
multi, i.e., the name of the array.
|
1359 |
+
|
1360 |
+
2. The size of the type of the elements of the array, in this case sizeof(int).
|
1361 |
+
3. The 2nd dimension of the array
|
1362 |
+
4. The specific index value for the first dimension, row in this case.
|
1363 |
+
5. The specific index value for the second dimension, col in this case.
|
1364 |
+
|
1365 |
+
30
|
1366 |
+
|
1367 |
+
|
1368 |
+
|
1369 |
+
|
1370 |
+
|
1371 |
+
|
1372 |
+
|
1373 |
+
|
1374 |
+
|
1375 |
+
|
1376 |
+
|
1377 |
+
Given all of that, consider the problem of designing a function to manipulate the element
|
1378 |
+
values of a previously declared array. For example, one which would set all the elements
|
1379 |
+
of the array multi to the value 1.
|
1380 |
+
|
1381 |
+
void set_value(int m_array[][COLS])
|
1382 |
+
{
|
1383 |
+
int row, col;
|
1384 |
+
for (row = 0; row < ROWS; row++)
|
1385 |
+
{
|
1386 |
+
for (col = 0; col < COLS; col++)
|
1387 |
+
{
|
1388 |
+
m_array[row][col] = 1;
|
1389 |
+
}
|
1390 |
+
}
|
1391 |
+
}
|
1392 |
+
|
1393 |
+
And to call this function we would then use:
|
1394 |
+
|
1395 |
+
set_value(multi);
|
1396 |
+
|
1397 |
+
Now, within the function we have used the values #defined by ROWS and COLS that set
|
1398 |
+
the limits on the for loops. But, these #defines are just constants as far as the compiler is
|
1399 |
+
concerned, i.e. there is nothing to connect them to the array size within the function. row
|
1400 |
+
and col are local variables, of course. The formal parameter definition permits the
|
1401 |
+
compiler to determine the characteristics associated with the pointer value that will be
|
1402 |
+
passed at run time. We really don’t need the first dimension and, as will be seen later,
|
1403 |
+
there are occasions where we would prefer not to define it within the parameter
|
1404 |
+
definition, out of habit or consistency, I have not used it here. But, the second dimension
|
1405 |
+
must be used as has been shown in the expression for the parameter. The reason is that
|
1406 |
+
we need this in the evaluation of m_array[row][col] as has been described. While the
|
1407 |
+
parameter defines the data type (int in this case) and the automatic variables for row and
|
1408 |
+
column are defined in the for loops, only one value can be passed using a single
|
1409 |
+
parameter. In this case, that is the value of multi as noted in the call statement, i.e. the
|
1410 |
+
address of the first element, often referred to as a pointer to the array. Thus, the only way
|
1411 |
+
we have of informing the compiler of the 2nd dimension is by explicitly including it in
|
1412 |
+
the parameter definition.
|
1413 |
+
|
1414 |
+
In fact, in general all dimensions of higher order than one are needed when dealing with
|
1415 |
+
multi-dimensional arrays. That is if we are talking about 3 dimensional arrays, the 2nd
|
1416 |
+
and 3rd dimension must be specified in the parameter definition.
|
1417 |
+
|
1418 |
+
31
|
1419 |
+
|
1420 |
+
|
1421 |
+
|
1422 |
+
|
1423 |
+
|
1424 |
+
|
1425 |
+
|
1426 |
+
CHAPTER 8: Pointers to Arrays
|
1427 |
+
|
1428 |
+
Pointers, of course, can be "pointed at" any type of data object, including arrays. While
|
1429 |
+
that was evident when we discussed program 3.1, it is important to expand on how we do
|
1430 |
+
this when it comes to multi-dimensional arrays.
|
1431 |
+
|
1432 |
+
To review, in Chapter 2 we stated that given an array of integers we could point an
|
1433 |
+
integer pointer at that array using:
|
1434 |
+
|
1435 |
+
int *ptr;
|
1436 |
+
ptr = &my_array[0]; /* point our pointer at the first
|
1437 |
+
integer in our array */
|
1438 |
+
As we stated there, the type of the pointer variable must match the type of the first
|
1439 |
+
element of the array.
|
1440 |
+
|
1441 |
+
In addition, we can use a pointer as a formal parameter of a function which is designed to
|
1442 |
+
manipulate an array. e.g.
|
1443 |
+
|
1444 |
+
Given:
|
1445 |
+
|
1446 |
+
int array[3] = {'1', '5', '7'};
|
1447 |
+
void a_func(int *p);
|
1448 |
+
|
1449 |
+
Some programmers might prefer to write the function prototype as:
|
1450 |
+
|
1451 |
+
void a_func(int p[]);
|
1452 |
+
|
1453 |
+
which would tend to inform others who might use this function that the function is
|
1454 |
+
designed to manipulate the elements of an array. Of course, in either case, what actually
|
1455 |
+
gets passed is the value of a pointer to the first element of the array, independent of which
|
1456 |
+
notation is used in the function prototype or definition. Note that if the array notation is
|
1457 |
+
used, there is no need to pass the actual dimension of the array since we are not passing
|
1458 |
+
the whole array, only the address to the first element.
|
1459 |
+
|
1460 |
+
We now turn to the problem of the 2 dimensional array. As stated in the last chapter, C
|
1461 |
+
interprets a 2 dimensional array as an array of one dimensional arrays. That being the
|
1462 |
+
case, the first element of a 2 dimensional array of integers is a one dimensional array of
|
1463 |
+
integers. And a pointer to a two dimensional array of integers must be a pointer to that
|
1464 |
+
data type. One way of accomplishing this is through the use of the keyword "typedef".
|
1465 |
+
typedef assigns a new name to a specified data type. For example:
|
1466 |
+
|
1467 |
+
typedef unsigned char byte;
|
1468 |
+
|
1469 |
+
causes the name byte to mean type unsigned char. Hence
|
1470 |
+
|
1471 |
+
byte b[10]; would be an array of unsigned characters.
|
1472 |
+
|
1473 |
+
32
|
1474 |
+
|
1475 |
+
|
1476 |
+
|
1477 |
+
|
1478 |
+
|
1479 |
+
|
1480 |
+
|
1481 |
+
Note that in the typedef declaration, the word byte has replaced that which would
|
1482 |
+
normally be the name of our unsigned char. That is, the rule for using typedef is that the
|
1483 |
+
new name for the data type is the name used in the definition of the data type. Thus in:
|
1484 |
+
|
1485 |
+
typedef int Array[10];
|
1486 |
+
|
1487 |
+
Array becomes a data type for an array of 10 integers. i.e. Array my_arr; declares
|
1488 |
+
my_arr as an array of 10 integers and Array arr2d[5]; makes arr2d an array of 5 arrays
|
1489 |
+
of 10 integers each.
|
1490 |
+
|
1491 |
+
Also note that Array *p1d; makes p1d a pointer to an array of 10 integers. Because
|
1492 |
+
*p1d points to the same type as arr2d, assigning the address of the two dimensional
|
1493 |
+
array arr2d to p1d, the pointer to a one dimensional array of 10 integers is acceptable.
|
1494 |
+
i.e. p1d = &arr2d[0]; or p1d = arr2d; are both correct.
|
1495 |
+
|
1496 |
+
Since the data type we use for our pointer is an array of 10 integers we would expect that
|
1497 |
+
incrementing p1d by 1 would change its value by 10*sizeof(int), which it does. That is,
|
1498 |
+
sizeof(*p1d) is 20. You can prove this to yourself by writing and running a simple short
|
1499 |
+
program.
|
1500 |
+
|
1501 |
+
Now, while using typedef makes things clearer for the reader and easier on the
|
1502 |
+
programmer, it is not really necessary. What we need is a way of declaring a pointer like
|
1503 |
+
p1d without the need of the typedef keyword. It turns out that this can be done and that
|
1504 |
+
|
1505 |
+
int (*p1d)[10];
|
1506 |
+
|
1507 |
+
is the proper declaration, i.e. p1d here is a pointer to an array of 10 integers just as it was
|
1508 |
+
under the declaration using the Array type. Note that this is different from
|
1509 |
+
|
1510 |
+
int *p1d[10];
|
1511 |
+
|
1512 |
+
which would make p1d the name of an array of 10 pointers to type int.
|
1513 |
+
|
1514 |
+
33
|
1515 |
+
|
1516 |
+
|
1517 |
+
|
1518 |
+
|
1519 |
+
|
1520 |
+
|
1521 |
+
|
1522 |
+
|
1523 |
+
CHAPTER 9: Pointers and Dynamic Allocation of
|
1524 |
+
Memory
|
1525 |
+
|
1526 |
+
There are times when it is convenient to allocate memory at run time using malloc(),
|
1527 |
+
calloc(), or other allocation functions. Using this approach permits postponing the
|
1528 |
+
decision on the size of the memory block need to store an array, for example, until run
|
1529 |
+
time. Or it permits using a section of memory for the storage of an array of integers at
|
1530 |
+
one point in time, and then when that memory is no longer needed it can be freed up for
|
1531 |
+
other uses, such as the storage of an array of structures.
|
1532 |
+
|
1533 |
+
When memory is allocated, the allocating function (such as malloc(), calloc(), etc.)
|
1534 |
+
returns a pointer. The type of this pointer depends on whether you are using an older
|
1535 |
+
K&R compiler or the newer ANSI type compiler. With the older compiler the type of the
|
1536 |
+
returned pointer is char, with the ANSI compiler it is void.
|
1537 |
+
|
1538 |
+
If you are using an older compiler, and you want to allocate memory for an array of
|
1539 |
+
integers you will have to cast the char pointer returned to an integer pointer. For example,
|
1540 |
+
to allocate space for 10 integers we might write:
|
1541 |
+
|
1542 |
+
int *iptr;
|
1543 |
+
iptr = (int *)malloc(10 * sizeof(int));
|
1544 |
+
if (iptr == NULL)
|
1545 |
+
|
1546 |
+
{ .. ERROR ROUTINE GOES HERE .. }
|
1547 |
+
|
1548 |
+
If you are using an ANSI compliant compiler, malloc() returns a void pointer and since a
|
1549 |
+
void pointer can be assigned to a pointer variable of any object type, the (int *) cast
|
1550 |
+
shown above is not needed. The array dimension can be determined at run time and is not
|
1551 |
+
needed at compile time. That is, the 10 above could be a variable read in from a data file
|
1552 |
+
or keyboard, or calculated based on some need, at run time.
|
1553 |
+
|
1554 |
+
Because of the equivalence between array and pointer notation, once iptr has been
|
1555 |
+
assigned as above, one can use the array notation. For example, one could write:
|
1556 |
+
|
1557 |
+
int k;
|
1558 |
+
for (k = 0; k < 10; k++)
|
1559 |
+
iptr[k] = 2;
|
1560 |
+
|
1561 |
+
to set the values of all elements to 2.
|
1562 |
+
|
1563 |
+
Even with a reasonably good understanding of pointers and arrays, one place the
|
1564 |
+
newcomer to C is likely to stumble at first is in the dynamic allocation of multi-
|
1565 |
+
dimensional arrays. In general, we would like to be able to access elements of such arrays
|
1566 |
+
using array notation, not pointer notation, wherever possible. Depending on the
|
1567 |
+
application we may or may not know both dimensions at compile time. This leads to a
|
1568 |
+
variety of ways to go about our task.
|
1569 |
+
|
1570 |
+
34
|
1571 |
+
|
1572 |
+
|
1573 |
+
|
1574 |
+
|
1575 |
+
|
1576 |
+
As we have seen, when dynamically allocating a one dimensional array its dimension can
|
1577 |
+
be determined at run time. Now, when using dynamic allocation of higher order arrays,
|
1578 |
+
we never need to know the first dimension at compile time. Whether we need to know the
|
1579 |
+
higher dimensions depends on how we go about writing the code. Here I will discuss
|
1580 |
+
various methods of dynamically allocating room for 2 dimensional arrays of integers.
|
1581 |
+
|
1582 |
+
First we will consider cases where the 2nd dimension is known at compile time.
|
1583 |
+
|
1584 |
+
METHOD 1:
|
1585 |
+
|
1586 |
+
One way of dealing with the problem is through the use of the typedef keyword. To
|
1587 |
+
allocate a 2 dimensional array of integers recall that the following two notations result in
|
1588 |
+
the same object code being generated:
|
1589 |
+
|
1590 |
+
multi[row][col] = 1; *(*(multi + row) + col) = 1;
|
1591 |
+
|
1592 |
+
It is also true that the following two notations generate the same code:
|
1593 |
+
|
1594 |
+
multi[row] *(multi + row)
|
1595 |
+
|
1596 |
+
Since the one on the right must evaluate to a pointer, the array notation on the left must
|
1597 |
+
also evaluate to a pointer. In fact multi[0] will return a pointer to the first integer in the
|
1598 |
+
first row, multi[1] a pointer to the first integer of the second row, etc. Actually, multi[n]
|
1599 |
+
evaluates to a pointer to that array of integers that make up the n-th row of our 2
|
1600 |
+
dimensional array. That is, multi can be thought of as an array of arrays and multi[n] as
|
1601 |
+
a pointer to the n-th array of this array of arrays. Here the word pointer is being used to
|
1602 |
+
represent an address value. While such usage is common in the literature, when reading
|
1603 |
+
such statements one must be careful to distinguish between the constant address of an
|
1604 |
+
array and a variable pointer which is a data object in itself.
|
1605 |
+
|
1606 |
+
Consider now:
|
1607 |
+
|
1608 |
+
--------------- Program 9.1 --------------------------------
|
1609 |
+
|
1610 |
+
/* Program 9.1 from PTRTUT10.HTM 6/13/97 */
|
1611 |
+
|
1612 |
+
#include <stdio.h>
|
1613 |
+
#include <stdlib.h>
|
1614 |
+
|
1615 |
+
#define COLS 5
|
1616 |
+
|
1617 |
+
typedef int RowArray[COLS];
|
1618 |
+
RowArray *rptr;
|
1619 |
+
|
1620 |
+
int main(void)
|
1621 |
+
{
|
1622 |
+
int nrows = 10;
|
1623 |
+
int row, col;
|
1624 |
+
rptr = malloc(nrows * COLS * sizeof(int));
|
1625 |
+
for (row = 0; row < nrows; row++)
|
1626 |
+
|
1627 |
+
35
|
1628 |
+
|
1629 |
+
|
1630 |
+
|
1631 |
+
|
1632 |
+
|
1633 |
+
|
1634 |
+
|
1635 |
+
|
1636 |
+
|
1637 |
+
|
1638 |
+
|
1639 |
+
|
1640 |
+
{
|
1641 |
+
for (col = 0; col < COLS; col++)
|
1642 |
+
{
|
1643 |
+
rptr[row][col] = 17;
|
1644 |
+
}
|
1645 |
+
}
|
1646 |
+
|
1647 |
+
return 0;
|
1648 |
+
}
|
1649 |
+
------------- End of Prog. 9.1 --------------------------------
|
1650 |
+
|
1651 |
+
Here I have assumed an ANSI compiler so a cast on the void pointer returned by malloc()
|
1652 |
+
is not required. If you are using an older K&R compiler you will have to cast using:
|
1653 |
+
|
1654 |
+
rptr = (RowArray *)malloc(.... etc.
|
1655 |
+
|
1656 |
+
Using this approach, rptr has all the characteristics of an array name name, (except that
|
1657 |
+
rptr is modifiable), and array notation may be used throughout the rest of the program.
|
1658 |
+
That also means that if you intend to write a function to modify the array contents, you
|
1659 |
+
must use COLS as a part of the formal parameter in that function, just as we did when
|
1660 |
+
discussing the passing of two dimensional arrays to a function.
|
1661 |
+
|
1662 |
+
METHOD 2:
|
1663 |
+
|
1664 |
+
In the METHOD 1 above, rptr turned out to be a pointer to type "one dimensional array
|
1665 |
+
of COLS integers". It turns out that there is syntax which can be used for this type
|
1666 |
+
without the need of typedef. If we write:
|
1667 |
+
|
1668 |
+
int (*xptr)[COLS];
|
1669 |
+
|
1670 |
+
the variable xptr will have all the same characteristics as the variable rptr in METHOD
|
1671 |
+
1 above, and we need not use the typedef keyword. Here xptr is a pointer to an array of
|
1672 |
+
integers and the size of that array is given by the #defined COLS. The parenthesis
|
1673 |
+
placement makes the pointer notation predominate, even though the array notation has
|
1674 |
+
higher precedence. i.e. had we written
|
1675 |
+
|
1676 |
+
int *xptr[COLS];
|
1677 |
+
|
1678 |
+
we would have defined xptr as an array of pointers holding the number of pointers equal
|
1679 |
+
to that #defined by COLS. That is not the same thing at all. However, arrays of pointers
|
1680 |
+
have their use in the dynamic allocation of two dimensional arrays, as will be seen in the
|
1681 |
+
next 2 methods.
|
1682 |
+
|
1683 |
+
METHOD 3:
|
1684 |
+
|
1685 |
+
Consider the case where we do not know the number of elements in each row at compile
|
1686 |
+
time, i.e. both the number of rows and number of columns must be determined at run
|
1687 |
+
time. One way of doing this would be to create an array of pointers to type int and then
|
1688 |
+
allocate space for each row and point these pointers at each row. Consider:
|
1689 |
+
|
1690 |
+
36
|
1691 |
+
|
1692 |
+
|
1693 |
+
|
1694 |
+
|
1695 |
+
|
1696 |
+
|
1697 |
+
|
1698 |
+
|
1699 |
+
|
1700 |
+
|
1701 |
+
|
1702 |
+
-------------- Program 9.2 ------------------------------------
|
1703 |
+
|
1704 |
+
/* Program 9.2 from PTRTUT10.HTM 6/13/97 */
|
1705 |
+
|
1706 |
+
#include <stdio.h>
|
1707 |
+
#include <stdlib.h>
|
1708 |
+
|
1709 |
+
int main(void)
|
1710 |
+
{
|
1711 |
+
int nrows = 5; /* Both nrows and ncols could be evaluated */
|
1712 |
+
int ncols = 10; /* or read in at run time */
|
1713 |
+
int row;
|
1714 |
+
int **rowptr;
|
1715 |
+
rowptr = malloc(nrows * sizeof(int *));
|
1716 |
+
if (rowptr == NULL)
|
1717 |
+
{
|
1718 |
+
puts("\nFailure to allocate room for row pointers.\n");
|
1719 |
+
exit(0);
|
1720 |
+
}
|
1721 |
+
|
1722 |
+
printf("\n\n\nIndex Pointer(hex) Pointer(dec) Diff.(dec)");
|
1723 |
+
|
1724 |
+
for (row = 0; row < nrows; row++)
|
1725 |
+
{
|
1726 |
+
rowptr[row] = malloc(ncols * sizeof(int));
|
1727 |
+
if (rowptr[row] == NULL)
|
1728 |
+
{
|
1729 |
+
printf("\nFailure to allocate for row[%d]\n",row);
|
1730 |
+
exit(0);
|
1731 |
+
}
|
1732 |
+
printf("\n%d %p %d", row, rowptr[row],
|
1733 |
+
rowptr[row]);
|
1734 |
+
if (row > 0)
|
1735 |
+
printf(" %d",(int)(rowptr[row] - rowptr[row-1]));
|
1736 |
+
}
|
1737 |
+
|
1738 |
+
return 0;
|
1739 |
+
}
|
1740 |
+
|
1741 |
+
--------------- End 9.2 ------------------------------------
|
1742 |
+
|
1743 |
+
In the above code rowptr is a pointer to pointer to type int. In this case it points to the
|
1744 |
+
first element of an array of pointers to type int. Consider the number of calls to malloc():
|
1745 |
+
|
1746 |
+
To get the array of pointers 1 call
|
1747 |
+
To get space for the rows 5 calls
|
1748 |
+
-----
|
1749 |
+
Total 6 calls
|
1750 |
+
|
1751 |
+
If you choose to use this approach note that while you can use the array notation to access
|
1752 |
+
individual elements of the array, e.g. rowptr[row][col] = 17;, it does not mean that the
|
1753 |
+
data in the "two dimensional array" is contiguous in memory.
|
1754 |
+
|
1755 |
+
37
|
1756 |
+
|
1757 |
+
|
1758 |
+
|
1759 |
+
|
1760 |
+
|
1761 |
+
|
1762 |
+
|
1763 |
+
|
1764 |
+
|
1765 |
+
|
1766 |
+
|
1767 |
+
|
1768 |
+
|
1769 |
+
You can, however, use the array notation just as if it were a continuous block of memory.
|
1770 |
+
For example, you can write:
|
1771 |
+
|
1772 |
+
rowptr[row][col] = 176;
|
1773 |
+
|
1774 |
+
just as if rowptr were the name of a two dimensional array created at compile time. Of
|
1775 |
+
course row and col must be within the bounds of the array you have created, just as with
|
1776 |
+
an array created at compile time.
|
1777 |
+
|
1778 |
+
If you want to have a contiguous block of memory dedicated to the storage of the
|
1779 |
+
elements in the array you can do it as follows:
|
1780 |
+
|
1781 |
+
METHOD 4:
|
1782 |
+
|
1783 |
+
In this method we allocate a block of memory to hold the whole array first. We then
|
1784 |
+
create an array of pointers to point to each row. Thus even though the array of pointers is
|
1785 |
+
being used, the actual array in memory is contiguous. The code looks like this:
|
1786 |
+
|
1787 |
+
----------------- Program 9.3 -----------------------------------
|
1788 |
+
|
1789 |
+
/* Program 9.3 from PTRTUT10.HTM 6/13/97 */
|
1790 |
+
|
1791 |
+
#include <stdio.h>
|
1792 |
+
#include <stdlib.h>
|
1793 |
+
|
1794 |
+
int main(void)
|
1795 |
+
{
|
1796 |
+
int **rptr;
|
1797 |
+
int *aptr;
|
1798 |
+
int *testptr;
|
1799 |
+
int k;
|
1800 |
+
int nrows = 5; /* Both nrows and ncols could be evaluated */
|
1801 |
+
int ncols = 8; /* or read in at run time */
|
1802 |
+
int row, col;
|
1803 |
+
|
1804 |
+
/* we now allocate the memory for the array */
|
1805 |
+
|
1806 |
+
aptr = malloc(nrows * ncols * sizeof(int));
|
1807 |
+
if (aptr == NULL)
|
1808 |
+
{
|
1809 |
+
puts("\nFailure to allocate room for the array");
|
1810 |
+
exit(0);
|
1811 |
+
}
|
1812 |
+
|
1813 |
+
/* next we allocate room for the pointers to the rows */
|
1814 |
+
|
1815 |
+
rptr = malloc(nrows * sizeof(int *));
|
1816 |
+
if (rptr == NULL)
|
1817 |
+
{
|
1818 |
+
puts("\nFailure to allocate room for pointers");
|
1819 |
+
exit(0);
|
1820 |
+
}
|
1821 |
+
|
1822 |
+
38
|
1823 |
+
|
1824 |
+
|
1825 |
+
|
1826 |
+
|
1827 |
+
|
1828 |
+
|
1829 |
+
|
1830 |
+
|
1831 |
+
|
1832 |
+
|
1833 |
+
|
1834 |
+
|
1835 |
+
/* and now we 'point' the pointers */
|
1836 |
+
|
1837 |
+
for (k = 0; k < nrows; k++)
|
1838 |
+
{
|
1839 |
+
rptr[k] = aptr + (k * ncols);
|
1840 |
+
}
|
1841 |
+
|
1842 |
+
/* Now we illustrate how the row pointers are incremented */
|
1843 |
+
printf("\n\nIllustrating how row pointers are incremented");
|
1844 |
+
printf("\n\nIndex Pointer(hex) Diff.(dec)");
|
1845 |
+
|
1846 |
+
for (row = 0; row < nrows; row++)
|
1847 |
+
{
|
1848 |
+
printf("\n%d %p", row, rptr[row]);
|
1849 |
+
if (row > 0)
|
1850 |
+
printf(" %d",(rptr[row] - rptr[row-1]));
|
1851 |
+
}
|
1852 |
+
printf("\n\nAnd now we print out the array\n");
|
1853 |
+
for (row = 0; row < nrows; row++)
|
1854 |
+
{
|
1855 |
+
for (col = 0; col < ncols; col++)
|
1856 |
+
{
|
1857 |
+
rptr[row][col] = row + col;
|
1858 |
+
printf("%d ", rptr[row][col]);
|
1859 |
+
}
|
1860 |
+
putchar('\n');
|
1861 |
+
}
|
1862 |
+
|
1863 |
+
puts("\n");
|
1864 |
+
|
1865 |
+
/* and here we illustrate that we are, in fact, dealing with
|
1866 |
+
a 2 dimensional array in a contiguous block of memory. */
|
1867 |
+
printf("And now we demonstrate that they are contiguous in
|
1868 |
+
memory\n");
|
1869 |
+
|
1870 |
+
testptr = aptr;
|
1871 |
+
for (row = 0; row < nrows; row++)
|
1872 |
+
{
|
1873 |
+
for (col = 0; col < ncols; col++)
|
1874 |
+
{
|
1875 |
+
printf("%d ", *(testptr++));
|
1876 |
+
}
|
1877 |
+
putchar('\n');
|
1878 |
+
}
|
1879 |
+
|
1880 |
+
return 0;
|
1881 |
+
}
|
1882 |
+
|
1883 |
+
------------- End Program 9.3 -----------------
|
1884 |
+
|
1885 |
+
Consider again, the number of calls to malloc()
|
1886 |
+
|
1887 |
+
To get room for the array itself 1 call
|
1888 |
+
To get room for the array of ptrs 1 call
|
1889 |
+
----
|
1890 |
+
Total 2 calls
|
1891 |
+
|
1892 |
+
39
|
1893 |
+
|
1894 |
+
|
1895 |
+
|
1896 |
+
|
1897 |
+
|
1898 |
+
|
1899 |
+
|
1900 |
+
|
1901 |
+
|
1902 |
+
|
1903 |
+
|
1904 |
+
|
1905 |
+
Now, each call to malloc() creates additional space overhead since malloc() is generally
|
1906 |
+
implemented by the operating system forming a linked list which contains data
|
1907 |
+
concerning the size of the block. But, more importantly, with large arrays (several
|
1908 |
+
hundred rows) keeping track of what needs to be freed when the time comes can be more
|
1909 |
+
cumbersome. This, combined with the contiguousness of the data block that permits
|
1910 |
+
initialization to all zeroes using memset() would seem to make the second alternative the
|
1911 |
+
preferred one.
|
1912 |
+
|
1913 |
+
As a final example on multidimensional arrays we will illustrate the dynamic allocation
|
1914 |
+
of a three dimensional array. This example will illustrate one more thing to watch when
|
1915 |
+
doing this kind of allocation. For reasons cited above we will use the approach outlined in
|
1916 |
+
alternative two. Consider the following code:
|
1917 |
+
|
1918 |
+
------------------- Program 9.4 -------------------------------------
|
1919 |
+
|
1920 |
+
/* Program 9.4 from PTRTUT10.HTM 6/13/97 */
|
1921 |
+
|
1922 |
+
#include <stdio.h>
|
1923 |
+
#include <stdlib.h>
|
1924 |
+
#include <stddef.h>
|
1925 |
+
|
1926 |
+
int X_DIM=16;
|
1927 |
+
int Y_DIM=5;
|
1928 |
+
int Z_DIM=3;
|
1929 |
+
|
1930 |
+
int main(void)
|
1931 |
+
{
|
1932 |
+
char *space;
|
1933 |
+
char ***Arr3D;
|
1934 |
+
int y, z;
|
1935 |
+
ptrdiff_t diff;
|
1936 |
+
|
1937 |
+
/* first we set aside space for the array itself */
|
1938 |
+
|
1939 |
+
space = malloc(X_DIM * Y_DIM * Z_DIM * sizeof(char));
|
1940 |
+
|
1941 |
+
/* next we allocate space of an array of pointers, each
|
1942 |
+
to eventually point to the first element of a
|
1943 |
+
2 dimensional array of pointers to pointers */
|
1944 |
+
|
1945 |
+
Arr3D = malloc(Z_DIM * sizeof(char **));
|
1946 |
+
|
1947 |
+
/* and for each of these we assign a pointer to a newly
|
1948 |
+
allocated array of pointers to a row */
|
1949 |
+
|
1950 |
+
for (z = 0; z < Z_DIM; z++)
|
1951 |
+
{
|
1952 |
+
Arr3D[z] = malloc(Y_DIM * sizeof(char *));
|
1953 |
+
|
1954 |
+
/* and for each space in this array we put a pointer to
|
1955 |
+
the first element of each row in the array space
|
1956 |
+
originally allocated */
|
1957 |
+
|
1958 |
+
40
|
1959 |
+
|
1960 |
+
|
1961 |
+
|
1962 |
+
|
1963 |
+
|
1964 |
+
|
1965 |
+
|
1966 |
+
|
1967 |
+
|
1968 |
+
|
1969 |
+
|
1970 |
+
|
1971 |
+
|
1972 |
+
|
1973 |
+
|
1974 |
+
for (y = 0; y < Y_DIM; y++)
|
1975 |
+
{
|
1976 |
+
Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM);
|
1977 |
+
}
|
1978 |
+
}
|
1979 |
+
|
1980 |
+
/* And, now we check each address in our 3D array to see if
|
1981 |
+
the indexing of the Arr3d pointer leads through in a
|
1982 |
+
continuous manner */
|
1983 |
+
|
1984 |
+
for (z = 0; z < Z_DIM; z++)
|
1985 |
+
{
|
1986 |
+
printf("Location of array %d is %p\n", z, *Arr3D[z]);
|
1987 |
+
for ( y = 0; y < Y_DIM; y++)
|
1988 |
+
{
|
1989 |
+
printf(" Array %d and Row %d starts at %p", z, y,
|
1990 |
+
Arr3D[z][y]);
|
1991 |
+
diff = Arr3D[z][y] - space;
|
1992 |
+
printf(" diff = %d ",diff);
|
1993 |
+
printf(" z = %d y = %d\n", z, y);
|
1994 |
+
}
|
1995 |
+
}
|
1996 |
+
return 0;
|
1997 |
+
}
|
1998 |
+
|
1999 |
+
------------------- End of Prog. 9.4 ----------------------------
|
2000 |
+
|
2001 |
+
If you have followed this tutorial up to this point you should have no problem
|
2002 |
+
deciphering the above on the basis of the comments alone. There are a couple of points
|
2003 |
+
that should be made however. Let's start with the line which reads:
|
2004 |
+
|
2005 |
+
Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM);
|
2006 |
+
Note that here space is a character pointer, which is the same type as Arr3D[z][y]. It is
|
2007 |
+
important that when adding an integer, such as that obtained by evaluation of the
|
2008 |
+
expression (z*(X_DIM * Y_DIM) + y*X_DIM), to a pointer, the result is a new pointer
|
2009 |
+
value. And when assigning pointer values to pointer variables the data types of the value
|
2010 |
+
and variable must match.
|
2011 |
+
|
2012 |
+
41
|
2013 |
+
|
2014 |
+
|
2015 |
+
|
2016 |
+
|
2017 |
+
|
2018 |
+
|
2019 |
+
|
2020 |
+
|
2021 |
+
|
2022 |
+
CHAPTER 10: Pointers to Functions
|
2023 |
+
|
2024 |
+
Up to this point we have been discussing pointers to data objects. C also permits the
|
2025 |
+
declaration of pointers to functions. Pointers to functions have a variety of uses and some
|
2026 |
+
of them will be discussed here.
|
2027 |
+
|
2028 |
+
Consider the following real problem. You want to write a function that is capable of
|
2029 |
+
sorting virtually any collection of data that can be stored in an array. This might be an
|
2030 |
+
array of strings, or integers, or floats, or even structures. The sorting algorithm can be the
|
2031 |
+
same for all. For example, it could be a simple bubble sort algorithm, or the more
|
2032 |
+
complex shell or quick sort algorithm. We'll use a simple bubble sort for demonstration
|
2033 |
+
purposes.
|
2034 |
+
|
2035 |
+
Sedgewick [1] has described the bubble sort using C code by setting up a function which
|
2036 |
+
when passed a pointer to the array would sort it. If we call that function bubble(), a sort
|
2037 |
+
program is described by bubble_1.c, which follows:
|
2038 |
+
|
2039 |
+
/*-------------------- bubble_1.c --------------------*/
|
2040 |
+
|
2041 |
+
/* Program bubble_1.c from PTRTUT10.HTM 6/13/97 */
|
2042 |
+
|
2043 |
+
#include <stdio.h>
|
2044 |
+
|
2045 |
+
int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
|
2046 |
+
|
2047 |
+
void bubble(int a[], int N);
|
2048 |
+
|
2049 |
+
int main(void)
|
2050 |
+
{
|
2051 |
+
int i;
|
2052 |
+
putchar('\n');
|
2053 |
+
for (i = 0; i < 10; i++)
|
2054 |
+
{
|
2055 |
+
printf("%d ", arr[i]);
|
2056 |
+
}
|
2057 |
+
bubble(arr,10);
|
2058 |
+
putchar('\n');
|
2059 |
+
|
2060 |
+
for (i = 0; i < 10; i++)
|
2061 |
+
{
|
2062 |
+
printf("%d ", arr[i]);
|
2063 |
+
}
|
2064 |
+
return 0;
|
2065 |
+
}
|
2066 |
+
|
2067 |
+
void bubble(int a[], int N)
|
2068 |
+
{
|
2069 |
+
int i, j, t;
|
2070 |
+
for (i = N-1; i >= 0; i--)
|
2071 |
+
{
|
2072 |
+
for (j = 1; j <= i; j++)
|
2073 |
+
|
2074 |
+
42
|
2075 |
+
|
2076 |
+
|
2077 |
+
|
2078 |
+
|
2079 |
+
|
2080 |
+
|
2081 |
+
|
2082 |
+
|
2083 |
+
|
2084 |
+
{
|
2085 |
+
if (a[j-1] > a[j])
|
2086 |
+
{
|
2087 |
+
t = a[j-1];
|
2088 |
+
a[j-1] = a[j];
|
2089 |
+
a[j] = t;
|
2090 |
+
}
|
2091 |
+
}
|
2092 |
+
}
|
2093 |
+
}
|
2094 |
+
|
2095 |
+
/*---------------------- end bubble_1.c -----------------------*/
|
2096 |
+
|
2097 |
+
The bubble sort is one of the simpler sorts. The algorithm scans the array from the second
|
2098 |
+
to the last element comparing each element with the one which precedes it. If the one that
|
2099 |
+
precedes it is larger than the current element, the two are swapped so the larger one is
|
2100 |
+
closer to the end of the array. On the first pass, this results in the largest element ending
|
2101 |
+
up at the end of the array. The array is now limited to all elements except the last and the
|
2102 |
+
process repeated. This puts the next largest element at a point preceding the largest
|
2103 |
+
element. The process is repeated for a number of times equal to the number of elements
|
2104 |
+
minus 1. The end result is a sorted array.
|
2105 |
+
|
2106 |
+
Here our function is designed to sort an array of integers. Thus in line 1 we are
|
2107 |
+
comparing integers and in lines 2 through 4 we are using temporary integer storage to
|
2108 |
+
store integers. What we want to do now is see if we can convert this code so we can use
|
2109 |
+
any data type, i.e. not be restricted to integers.
|
2110 |
+
|
2111 |
+
At the same time we don't want to have to analyze our algorithm and the code associated
|
2112 |
+
with it each time we use it. We start by removing the comparison from within the
|
2113 |
+
function bubble() so as to make it relatively easy to modify the comparison function
|
2114 |
+
without having to re-write portions related to the actual algorithm. This results in
|
2115 |
+
bubble_2.c:
|
2116 |
+
|
2117 |
+
/*---------------------- bubble_2.c -------------------------*/
|
2118 |
+
|
2119 |
+
/* Program bubble_2.c from PTRTUT10.HTM 6/13/97 */
|
2120 |
+
|
2121 |
+
/* Separating the comparison function */
|
2122 |
+
|
2123 |
+
#include <stdio.h>
|
2124 |
+
|
2125 |
+
int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
|
2126 |
+
|
2127 |
+
void bubble(int a[], int N);
|
2128 |
+
int compare(int m, int n);
|
2129 |
+
|
2130 |
+
int main(void)
|
2131 |
+
{
|
2132 |
+
int i;
|
2133 |
+
putchar('\n');
|
2134 |
+
|
2135 |
+
43
|
2136 |
+
|
2137 |
+
|
2138 |
+
|
2139 |
+
|
2140 |
+
|
2141 |
+
|
2142 |
+
|
2143 |
+
|
2144 |
+
|
2145 |
+
|
2146 |
+
|
2147 |
+
|
2148 |
+
for (i = 0; i < 10; i++)
|
2149 |
+
{
|
2150 |
+
printf("%d ", arr[i]);
|
2151 |
+
}
|
2152 |
+
bubble(arr,10);
|
2153 |
+
putchar('\n');
|
2154 |
+
|
2155 |
+
for (i = 0; i < 10; i++)
|
2156 |
+
{
|
2157 |
+
printf("%d ", arr[i]);
|
2158 |
+
}
|
2159 |
+
return 0;
|
2160 |
+
}
|
2161 |
+
|
2162 |
+
void bubble(int a[], int N)
|
2163 |
+
|
2164 |
+
{
|
2165 |
+
int i, j, t;
|
2166 |
+
for (i = N-1; i >= 0; i--)
|
2167 |
+
{
|
2168 |
+
for (j = 1; j <= i; j++)
|
2169 |
+
{
|
2170 |
+
if (compare(a[j-1], a[j]))
|
2171 |
+
{
|
2172 |
+
t = a[j-1];
|
2173 |
+
a[j-1] = a[j];
|
2174 |
+
a[j] = t;
|
2175 |
+
}
|
2176 |
+
}
|
2177 |
+
}
|
2178 |
+
}
|
2179 |
+
|
2180 |
+
int compare(int m, int n)
|
2181 |
+
{
|
2182 |
+
return (m > n);
|
2183 |
+
}
|
2184 |
+
/*--------------------- end of bubble_2.c -----------------------*/
|
2185 |
+
If our goal is to make our sort routine data type independent, one way of doing this is to
|
2186 |
+
use pointers to type void to point to the data instead of using the integer data type. As a
|
2187 |
+
start in that direction let's modify a few things in the above so that pointers can be used.
|
2188 |
+
To begin with, we'll stick with pointers to type integer.
|
2189 |
+
|
2190 |
+
/*----------------------- bubble_3.c -------------------------*/
|
2191 |
+
|
2192 |
+
/* Program bubble_3.c from PTRTUT10.HTM 6/13/97 */
|
2193 |
+
|
2194 |
+
#include <stdio.h>
|
2195 |
+
|
2196 |
+
int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
|
2197 |
+
|
2198 |
+
void bubble(int *p, int N);
|
2199 |
+
int compare(int *m, int *n);
|
2200 |
+
|
2201 |
+
int main(void)
|
2202 |
+
{
|
2203 |
+
|
2204 |
+
44
|
2205 |
+
|
2206 |
+
|
2207 |
+
|
2208 |
+
|
2209 |
+
|
2210 |
+
|
2211 |
+
|
2212 |
+
|
2213 |
+
|
2214 |
+
|
2215 |
+
|
2216 |
+
|
2217 |
+
|
2218 |
+
int i;
|
2219 |
+
putchar('\n');
|
2220 |
+
|
2221 |
+
for (i = 0; i < 10; i++)
|
2222 |
+
{
|
2223 |
+
printf("%d ", arr[i]);
|
2224 |
+
}
|
2225 |
+
bubble(arr,10);
|
2226 |
+
putchar('\n');
|
2227 |
+
|
2228 |
+
for (i = 0; i < 10; i++)
|
2229 |
+
{
|
2230 |
+
printf("%d ", arr[i]);
|
2231 |
+
}
|
2232 |
+
return 0;
|
2233 |
+
}
|
2234 |
+
|
2235 |
+
void bubble(int *p, int N)
|
2236 |
+
{
|
2237 |
+
int i, j, t;
|
2238 |
+
for (i = N-1; i >= 0; i--)
|
2239 |
+
{
|
2240 |
+
for (j = 1; j <= i; j++)
|
2241 |
+
{
|
2242 |
+
if (compare(&p[j-1], &p[j]))
|
2243 |
+
{
|
2244 |
+
t = p[j-1];
|
2245 |
+
p[j-1] = p[j];
|
2246 |
+
p[j] = t;
|
2247 |
+
}
|
2248 |
+
}
|
2249 |
+
}
|
2250 |
+
}
|
2251 |
+
|
2252 |
+
int compare(int *m, int *n)
|
2253 |
+
{
|
2254 |
+
return (*m > *n);
|
2255 |
+
}
|
2256 |
+
|
2257 |
+
/*------------------ end of bubble3.c -------------------------*/
|
2258 |
+
|
2259 |
+
Note the changes. We are now passing a pointer to an integer (or array of integers) to
|
2260 |
+
bubble(). And from within bubble we are passing pointers to the elements of the array
|
2261 |
+
that we want to compare to our comparison function. And, of course we are dereferencing
|
2262 |
+
these pointer in our compare() function in order to make the actual comparison. Our next
|
2263 |
+
step will be to convert the pointers in bubble() to pointers to type void so that that
|
2264 |
+
function will become more type insensitive. This is shown in bubble_4.
|
2265 |
+
|
2266 |
+
/*------------------ bubble_4.c ----------------------------*/
|
2267 |
+
|
2268 |
+
/* Program bubble_4.c from PTRTUT10,HTM 6/13/97 */
|
2269 |
+
|
2270 |
+
#include <stdio.h>
|
2271 |
+
|
2272 |
+
45
|
2273 |
+
|
2274 |
+
|
2275 |
+
|
2276 |
+
|
2277 |
+
|
2278 |
+
|
2279 |
+
|
2280 |
+
|
2281 |
+
|
2282 |
+
|
2283 |
+
|
2284 |
+
|
2285 |
+
|
2286 |
+
int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
|
2287 |
+
|
2288 |
+
void bubble(int *p, int N);
|
2289 |
+
int compare(void *m, void *n);
|
2290 |
+
|
2291 |
+
int main(void)
|
2292 |
+
{
|
2293 |
+
int i;
|
2294 |
+
putchar('\n');
|
2295 |
+
|
2296 |
+
for (i = 0; i < 10; i++)
|
2297 |
+
{
|
2298 |
+
printf("%d ", arr[i]);
|
2299 |
+
}
|
2300 |
+
bubble(arr,10);
|
2301 |
+
putchar('\n');
|
2302 |
+
|
2303 |
+
for (i = 0; i < 10; i++)
|
2304 |
+
{
|
2305 |
+
printf("%d ", arr[i]);
|
2306 |
+
}
|
2307 |
+
return 0;
|
2308 |
+
}
|
2309 |
+
|
2310 |
+
void bubble(int *p, int N)
|
2311 |
+
{
|
2312 |
+
int i, j, t;
|
2313 |
+
for (i = N-1; i >= 0; i--)
|
2314 |
+
{
|
2315 |
+
for (j = 1; j <= i; j++)
|
2316 |
+
{
|
2317 |
+
if (compare((void *)&p[j-1], (void *)&p[j]))
|
2318 |
+
{
|
2319 |
+
t = p[j-1];
|
2320 |
+
p[j-1] = p[j];
|
2321 |
+
p[j] = t;
|
2322 |
+
}
|
2323 |
+
}
|
2324 |
+
}
|
2325 |
+
}
|
2326 |
+
|
2327 |
+
int compare(void *m, void *n)
|
2328 |
+
{
|
2329 |
+
int *m1, *n1;
|
2330 |
+
m1 = (int *)m;
|
2331 |
+
n1 = (int *)n;
|
2332 |
+
return (*m1 > *n1);
|
2333 |
+
}
|
2334 |
+
|
2335 |
+
/*------------------ end of bubble_4.c ---------------------*/
|
2336 |
+
|
2337 |
+
Note that, in doing this, in compare() we had to introduce the casting of the void pointer
|
2338 |
+
types passed to the actual type being sorted. But, as we'll see later that's okay. And since
|
2339 |
+
what is being passed to bubble() is still a pointer to an array of integers, we had to cast
|
2340 |
+
these pointers to void pointers when we passed them as parameters in our call to
|
2341 |
+
compare().
|
2342 |
+
|
2343 |
+
46
|
2344 |
+
|
2345 |
+
|
2346 |
+
|
2347 |
+
|
2348 |
+
|
2349 |
+
|
2350 |
+
|
2351 |
+
|
2352 |
+
|
2353 |
+
|
2354 |
+
We now address the problem of what we pass to bubble(). We want to make the first
|
2355 |
+
parameter of that function a void pointer also. But, that means that within bubble() we
|
2356 |
+
need to do something about the variable t, which is currently an integer. Also, where we
|
2357 |
+
use t = p[j-1]; the type of p[j-1] needs to be known in order to know how many bytes to
|
2358 |
+
copy to the variable t (or whatever we replace t with).
|
2359 |
+
|
2360 |
+
Currently, in bubble_4.c, knowledge within bubble() as to the type of the data being
|
2361 |
+
sorted (and hence the size of each individual element) is obtained from the fact that the
|
2362 |
+
first parameter is a pointer to type integer. If we are going to be able to use bubble() to
|
2363 |
+
sort any type of data, we need to make that pointer a pointer to type void. But, in doing so
|
2364 |
+
we are going to lose information concerning the size of individual elements within the
|
2365 |
+
array. So, in bubble_5.c we will add a separate parameter to handle this size information.
|
2366 |
+
|
2367 |
+
These changes, from bubble4.c to bubble5.c are, perhaps, a bit more extensive than those
|
2368 |
+
we have made in the past. So, compare the two modules carefully for differences.
|
2369 |
+
|
2370 |
+
/*---------------------- bubble5.c ---------------------------*/
|
2371 |
+
|
2372 |
+
/* Program bubble_5.c from PTRTUT10.HTM 6/13/97 */
|
2373 |
+
|
2374 |
+
#include <stdio.h>
|
2375 |
+
#include <string.h>
|
2376 |
+
|
2377 |
+
long arr[10] = { 3,6,1,2,3,8,4,1,7,2};
|
2378 |
+
|
2379 |
+
void bubble(void *p, size_t width, int N);
|
2380 |
+
int compare(void *m, void *n);
|
2381 |
+
|
2382 |
+
int main(void)
|
2383 |
+
{
|
2384 |
+
int i;
|
2385 |
+
putchar('\n');
|
2386 |
+
|
2387 |
+
for (i = 0; i < 10; i++)
|
2388 |
+
{
|
2389 |
+
printf("%d ", arr[i]);
|
2390 |
+
}
|
2391 |
+
bubble(arr, sizeof(long), 10);
|
2392 |
+
putchar('\n');
|
2393 |
+
|
2394 |
+
for (i = 0; i < 10; i++)
|
2395 |
+
{
|
2396 |
+
printf("%ld ", arr[i]);
|
2397 |
+
}
|
2398 |
+
|
2399 |
+
return 0;
|
2400 |
+
}
|
2401 |
+
|
2402 |
+
void bubble(void *p, size_t width, int N)
|
2403 |
+
{
|
2404 |
+
int i, j;
|
2405 |
+
unsigned char buf[4];
|
2406 |
+
unsigned char *bp = p;
|
2407 |
+
|
2408 |
+
47
|
2409 |
+
|
2410 |
+
|
2411 |
+
|
2412 |
+
|
2413 |
+
|
2414 |
+
|
2415 |
+
|
2416 |
+
|
2417 |
+
|
2418 |
+
|
2419 |
+
|
2420 |
+
for (i = N-1; i >= 0; i--)
|
2421 |
+
{
|
2422 |
+
for (j = 1; j <= i; j++)
|
2423 |
+
{
|
2424 |
+
if (compare((void *)(bp + width*(j-1)),
|
2425 |
+
(void *)(bp + j*width))) /* 1 */
|
2426 |
+
{
|
2427 |
+
/* t = p[j-1]; */
|
2428 |
+
memcpy(buf, bp + width*(j-1), width);
|
2429 |
+
/* p[j-1] = p[j]; */
|
2430 |
+
memcpy(bp + width*(j-1), bp + j*width , width);
|
2431 |
+
/* p[j] = t; */
|
2432 |
+
memcpy(bp + j*width, buf, width);
|
2433 |
+
}
|
2434 |
+
}
|
2435 |
+
}
|
2436 |
+
}
|
2437 |
+
|
2438 |
+
int compare(void *m, void *n)
|
2439 |
+
{
|
2440 |
+
long *m1, *n1;
|
2441 |
+
m1 = (long *)m;
|
2442 |
+
n1 = (long *)n;
|
2443 |
+
return (*m1 > *n1);
|
2444 |
+
}
|
2445 |
+
|
2446 |
+
/*--------------------- end of bubble5.c ---------------------*/
|
2447 |
+
|
2448 |
+
Note that I have changed the data type of the array from int to long to illustrate the
|
2449 |
+
changes needed in the compare() function. Within bubble() I've done away with the
|
2450 |
+
variable t (which we would have had to change from type int to type long). I have added
|
2451 |
+
a buffer of size 4 unsigned characters, which is the size needed to hold a long (this will
|
2452 |
+
change again in future modifications to this code). The unsigned character pointer *bp is
|
2453 |
+
used to point to the base of the array to be sorted, i.e. to the first element of that array.
|
2454 |
+
|
2455 |
+
We also had to modify what we passed to compare(), and how we do the swapping of
|
2456 |
+
elements that the comparison indicates need swapping. Use of memcpy() and pointer
|
2457 |
+
notation instead of array notation work towards this reduction in type sensitivity.
|
2458 |
+
|
2459 |
+
Again, making a careful comparison of bubble5.c with bubble4.c can result in improved
|
2460 |
+
understanding of what is happening and why.
|
2461 |
+
|
2462 |
+
We move now to bubble6.c where we use the same function bubble() that we used in
|
2463 |
+
bubble5.c to sort strings instead of long integers. Of course we have to change the
|
2464 |
+
comparison function since the means by which strings are compared is different from that
|
2465 |
+
by which long integers are compared. And,in bubble6.c we have deleted the lines within
|
2466 |
+
bubble() that were commented out in bubble5.c.
|
2467 |
+
|
2468 |
+
/*--------------------- bubble6.c ---------------------*/
|
2469 |
+
/* Program bubble_6.c from PTRTUT10.HTM 6/13/97 */
|
2470 |
+
|
2471 |
+
48
|
2472 |
+
|
2473 |
+
|
2474 |
+
|
2475 |
+
|
2476 |
+
|
2477 |
+
|
2478 |
+
|
2479 |
+
#include <stdio.h>
|
2480 |
+
#include <string.h>
|
2481 |
+
|
2482 |
+
#define MAX_BUF 256
|
2483 |
+
|
2484 |
+
char arr2[5][20] = { "Mickey Mouse",
|
2485 |
+
"Donald Duck",
|
2486 |
+
"Minnie Mouse",
|
2487 |
+
"Goofy",
|
2488 |
+
"Ted Jensen" };
|
2489 |
+
|
2490 |
+
void bubble(void *p, int width, int N);
|
2491 |
+
int compare(void *m, void *n);
|
2492 |
+
|
2493 |
+
int main(void)
|
2494 |
+
{
|
2495 |
+
int i;
|
2496 |
+
putchar('\n');
|
2497 |
+
|
2498 |
+
for (i = 0; i < 5; i++)
|
2499 |
+
{
|
2500 |
+
printf("%s\n", arr2[i]);
|
2501 |
+
}
|
2502 |
+
bubble(arr2, 20, 5);
|
2503 |
+
putchar('\n\n');
|
2504 |
+
|
2505 |
+
for (i = 0; i < 5; i++)
|
2506 |
+
{
|
2507 |
+
printf("%s\n", arr2[i]);
|
2508 |
+
}
|
2509 |
+
return 0;
|
2510 |
+
}
|
2511 |
+
|
2512 |
+
void bubble(void *p, int width, int N)
|
2513 |
+
{
|
2514 |
+
int i, j, k;
|
2515 |
+
unsigned char buf[MAX_BUF];
|
2516 |
+
unsigned char *bp = p;
|
2517 |
+
|
2518 |
+
for (i = N-1; i >= 0; i--)
|
2519 |
+
{
|
2520 |
+
for (j = 1; j <= i; j++)
|
2521 |
+
{
|
2522 |
+
k = compare((void *)(bp + width*(j-1)), (void *)(bp +
|
2523 |
+
j*width));
|
2524 |
+
if (k > 0)
|
2525 |
+
{
|
2526 |
+
memcpy(buf, bp + width*(j-1), width);
|
2527 |
+
memcpy(bp + width*(j-1), bp + j*width , width);
|
2528 |
+
memcpy(bp + j*width, buf, width);
|
2529 |
+
}
|
2530 |
+
}
|
2531 |
+
}
|
2532 |
+
}
|
2533 |
+
|
2534 |
+
int compare(void *m, void *n)
|
2535 |
+
|
2536 |
+
49
|
2537 |
+
|
2538 |
+
|
2539 |
+
|
2540 |
+
|
2541 |
+
|
2542 |
+
|
2543 |
+
|
2544 |
+
|
2545 |
+
|
2546 |
+
|
2547 |
+
|
2548 |
+
|
2549 |
+
{
|
2550 |
+
char *m1 = m;
|
2551 |
+
char *n1 = n;
|
2552 |
+
return (strcmp(m1,n1));
|
2553 |
+
}
|
2554 |
+
|
2555 |
+
/*------------------- end of bubble6.c ---------------------*/
|
2556 |
+
|
2557 |
+
But, the fact that bubble() was unchanged from that used in bubble5.c indicates that that
|
2558 |
+
function is capable of sorting a wide variety of data types. What is left to do is to pass to
|
2559 |
+
bubble() the name of the comparison function we want to use so that it can be truly
|
2560 |
+
universal. Just as the name of an array is the address of the first element of the array in
|
2561 |
+
the data segment, the name of a function decays into the address of that function in the
|
2562 |
+
code segment. Thus we need to use a pointer to a function. In this case the comparison
|
2563 |
+
function.
|
2564 |
+
|
2565 |
+
Pointers to functions must match the functions pointed to in the number and types of the
|
2566 |
+
parameters and the type of the return value. In our case, we declare our function pointer
|
2567 |
+
as:
|
2568 |
+
|
2569 |
+
int (*fptr)(const void *p1, const void *p2);
|
2570 |
+
|
2571 |
+
Note that were we to write:
|
2572 |
+
|
2573 |
+
int *fptr(const void *p1, const void *p2);
|
2574 |
+
|
2575 |
+
we would have a function prototype for a function which returned a pointer to type int.
|
2576 |
+
That is because in C the parenthesis () operator have a higher precedence than the pointer
|
2577 |
+
* operator. By putting the parenthesis around the string (*fptr) we indicate that we are
|
2578 |
+
declaring a function pointer.
|
2579 |
+
|
2580 |
+
We now modify our declaration of bubble() by adding, as its 4th parameter, a function
|
2581 |
+
pointer of the proper type. It's function prototype becomes:
|
2582 |
+
|
2583 |
+
void bubble(void *p, int width, int N,
|
2584 |
+
int(*fptr)(const void *, const void *));
|
2585 |
+
|
2586 |
+
When we call the bubble(), we insert the name of the comparison function that we want
|
2587 |
+
to use. bubble7.c illustrate how this approach permits the use of the same bubble()
|
2588 |
+
function for sorting different types of data.
|
2589 |
+
|
2590 |
+
/*------------------- bubble7.c ------------------*/
|
2591 |
+
|
2592 |
+
/* Program bubble_7.c from PTRTUT10.HTM 6/10/97 */
|
2593 |
+
|
2594 |
+
#include <stdio.h>
|
2595 |
+
#include <string.h>
|
2596 |
+
|
2597 |
+
#define MAX_BUF 256
|
2598 |
+
|
2599 |
+
50
|
2600 |
+
|
2601 |
+
|
2602 |
+
|
2603 |
+
|
2604 |
+
|
2605 |
+
|
2606 |
+
|
2607 |
+
|
2608 |
+
|
2609 |
+
|
2610 |
+
|
2611 |
+
|
2612 |
+
|
2613 |
+
|
2614 |
+
long arr[10] = { 3,6,1,2,3,8,4,1,7,2};
|
2615 |
+
char arr2[5][20] = { "Mickey Mouse",
|
2616 |
+
"Donald Duck",
|
2617 |
+
"Minnie Mouse",
|
2618 |
+
"Goofy",
|
2619 |
+
"Ted Jensen" };
|
2620 |
+
|
2621 |
+
void bubble(void *p, int width, int N,
|
2622 |
+
int(*fptr)(const void *, const void *));
|
2623 |
+
int compare_string(const void *m, const void *n);
|
2624 |
+
int compare_long(const void *m, const void *n);
|
2625 |
+
|
2626 |
+
int main(void)
|
2627 |
+
{
|
2628 |
+
int i;
|
2629 |
+
puts("\nBefore Sorting:\n");
|
2630 |
+
|
2631 |
+
for (i = 0; i < 10; i++) /* show the long ints */
|
2632 |
+
{
|
2633 |
+
printf("%ld ",arr[i]);
|
2634 |
+
}
|
2635 |
+
puts("\n");
|
2636 |
+
|
2637 |
+
for (i = 0; i < 5; i++) /* show the strings */
|
2638 |
+
{
|
2639 |
+
printf("%s\n", arr2[i]);
|
2640 |
+
}
|
2641 |
+
bubble(arr, 4, 10, compare_long); /* sort the longs */
|
2642 |
+
bubble(arr2, 20, 5, compare_string); /* sort the strings */
|
2643 |
+
puts("\n\nAfter Sorting:\n");
|
2644 |
+
|
2645 |
+
for (i = 0; i < 10; i++) /* show the sorted longs */
|
2646 |
+
{
|
2647 |
+
printf("%d ",arr[i]);
|
2648 |
+
}
|
2649 |
+
puts("\n");
|
2650 |
+
|
2651 |
+
for (i = 0; i < 5; i++) /* show the sorted strings */
|
2652 |
+
{
|
2653 |
+
printf("%s\n", arr2[i]);
|
2654 |
+
}
|
2655 |
+
return 0;
|
2656 |
+
}
|
2657 |
+
|
2658 |
+
void bubble(void *p, int width, int N,
|
2659 |
+
int(*fptr)(const void *, const void *))
|
2660 |
+
{
|
2661 |
+
int i, j, k;
|
2662 |
+
unsigned char buf[MAX_BUF];
|
2663 |
+
unsigned char *bp = p;
|
2664 |
+
|
2665 |
+
for (i = N-1; i >= 0; i--)
|
2666 |
+
{
|
2667 |
+
for (j = 1; j <= i; j++)
|
2668 |
+
{
|
2669 |
+
k = fptr((void *)(bp + width*(j-1)), (void *)(bp +
|
2670 |
+
j*width));
|
2671 |
+
|
2672 |
+
51
|
2673 |
+
|
2674 |
+
|
2675 |
+
|
2676 |
+
|
2677 |
+
|
2678 |
+
|
2679 |
+
|
2680 |
+
|
2681 |
+
|
2682 |
+
|
2683 |
+
if (k > 0)
|
2684 |
+
{
|
2685 |
+
memcpy(buf, bp + width*(j-1), width);
|
2686 |
+
memcpy(bp + width*(j-1), bp + j*width , width);
|
2687 |
+
memcpy(bp + j*width, buf, width);
|
2688 |
+
}
|
2689 |
+
}
|
2690 |
+
}
|
2691 |
+
}
|
2692 |
+
|
2693 |
+
int compare_string(const void *m, const void *n)
|
2694 |
+
{
|
2695 |
+
char *m1 = (char *)m;
|
2696 |
+
char *n1 = (char *)n;
|
2697 |
+
return (strcmp(m1,n1));
|
2698 |
+
}
|
2699 |
+
|
2700 |
+
int compare_long(const void *m, const void *n)
|
2701 |
+
{
|
2702 |
+
long *m1, *n1;
|
2703 |
+
m1 = (long *)m;
|
2704 |
+
n1 = (long *)n;
|
2705 |
+
return (*m1 > *n1);
|
2706 |
+
}
|
2707 |
+
|
2708 |
+
/*----------------- end of bubble7.c -----------------*/
|
2709 |
+
|
2710 |
+
References for Chapter 10:
|
2711 |
+
|
2712 |
+
1. "Algorithms in C"
|
2713 |
+
Robert Sedgewick
|
2714 |
+
Addison-Wesley
|
2715 |
+
ISBN 0-201-51425-7
|
2716 |
+
|
2717 |
+
52
|
2718 |
+
|
2719 |
+
|
2720 |
+
|
2721 |
+
|
2722 |
+
|
2723 |
+
|
2724 |
+
EPILOG
|
2725 |
+
|
2726 |
+
I have written the preceding material to provide an introduction to pointers for
|
2727 |
+
newcomers to C. In C, the more one understands about pointers the greater flexibility one
|
2728 |
+
has in the writing of code. The above expands on my first effort at this which was entitled
|
2729 |
+
ptr_help.txt and found in an early version of Bob Stout's collection of C code SNIPPETS.
|
2730 |
+
The content in this version has been updated from that in PTRTUTOT.ZIP included in
|
2731 |
+
SNIP9510.ZIP.
|
2732 |
+
|
2733 |
+
I am always ready to accept constructive criticism on this material, or review requests for
|
2734 |
+
the addition of other relevant material. Therefore, if you have questions, comments,
|
2735 |
+
criticisms, etc. concerning that which has been presented, I would greatly appreciate your
|
2736 |
+
contacting me via email me at tjensen@ix.netcom.com.
|
2737 |
+
|
2738 |
+
53
|
2739 |
+
|
2740 |
+
|
2741 |
+
|
2742 |
+
|
COBOL/GNU_Cobol_Programmers_Guide_2.1.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
COBOL/OpenCOBOL%2520Programmers%2520Guide.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
COBOL/sc092539.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
CUDA/CUDA_C_Best_Practices_Guide.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
CUDA/CUDA_C_Programming_Guide.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
CUDA/NVIDIA_OpenCL_ProgrammingGuide.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
CakePHP/CakePHPCookbook.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Clojure/clojure.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Codename+One/developer-guide.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ColdFusion/coldfusion.pdf.txt
ADDED
@@ -0,0 +1,3002 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
coldfusion
|
2 |
+
|
3 |
+
#coldfusion
|
4 |
+
|
5 |
+
Table of Contents
|
6 |
+
|
7 |
+
About
|
8 |
+
|
9 |
+
Chapter 1: Getting started with coldfusion
|
10 |
+
|
11 |
+
Remarks
|
12 |
+
|
13 |
+
Versions
|
14 |
+
|
15 |
+
Examples
|
16 |
+
|
17 |
+
Installation or Setup
|
18 |
+
|
19 |
+
Linux (Ubuntu) Installation
|
20 |
+
|
21 |
+
Lucee (Open Source)
|
22 |
+
|
23 |
+
ColdFusion / CFML Interpretor
|
24 |
+
|
25 |
+
Nginx
|
26 |
+
|
27 |
+
Adobe (Closed Source)
|
28 |
+
|
29 |
+
ColdFusion / CFML Interpretor
|
30 |
+
|
31 |
+
Nginx
|
32 |
+
|
33 |
+
Hello World
|
34 |
+
|
35 |
+
Chapter 2: CFLOOP How-To
|
36 |
+
|
37 |
+
Remarks
|
38 |
+
|
39 |
+
Examples
|
40 |
+
|
41 |
+
Looping through a collection using CFML tags.
|
42 |
+
|
43 |
+
Looping through a collection using CFSCRIPT.
|
44 |
+
|
45 |
+
Index
|
46 |
+
|
47 |
+
Parameters
|
48 |
+
|
49 |
+
Basic index loop
|
50 |
+
|
51 |
+
Increase step to 2
|
52 |
+
|
53 |
+
Decrement step by 1
|
54 |
+
|
55 |
+
CFLoop in a Function
|
56 |
+
|
57 |
+
ColdFusion 11 through current
|
58 |
+
|
59 |
+
Condition
|
60 |
+
|
61 |
+
Tag syntax
|
62 |
+
|
63 |
+
Parameters
|
64 |
+
|
65 |
+
Generated HTML
|
66 |
+
|
67 |
+
1
|
68 |
+
|
69 |
+
2
|
70 |
+
|
71 |
+
2
|
72 |
+
|
73 |
+
2
|
74 |
+
|
75 |
+
3
|
76 |
+
|
77 |
+
3
|
78 |
+
|
79 |
+
3
|
80 |
+
|
81 |
+
3
|
82 |
+
|
83 |
+
3
|
84 |
+
|
85 |
+
3
|
86 |
+
|
87 |
+
4
|
88 |
+
|
89 |
+
4
|
90 |
+
|
91 |
+
4
|
92 |
+
|
93 |
+
5
|
94 |
+
|
95 |
+
7
|
96 |
+
|
97 |
+
7
|
98 |
+
|
99 |
+
7
|
100 |
+
|
101 |
+
7
|
102 |
+
|
103 |
+
7
|
104 |
+
|
105 |
+
7
|
106 |
+
|
107 |
+
7
|
108 |
+
|
109 |
+
8
|
110 |
+
|
111 |
+
8
|
112 |
+
|
113 |
+
9
|
114 |
+
|
115 |
+
9
|
116 |
+
|
117 |
+
10
|
118 |
+
|
119 |
+
10
|
120 |
+
|
121 |
+
10
|
122 |
+
|
123 |
+
10
|
124 |
+
|
125 |
+
10
|
126 |
+
|
127 |
+
CFScript
|
128 |
+
|
129 |
+
Previous to ColdFusion 8
|
130 |
+
|
131 |
+
ColdFusion 8 through current
|
132 |
+
|
133 |
+
ColdFusion 11 through current
|
134 |
+
|
135 |
+
Generated HTML
|
136 |
+
|
137 |
+
Date or time range
|
138 |
+
|
139 |
+
Query
|
140 |
+
|
141 |
+
Parameters
|
142 |
+
|
143 |
+
Example query
|
144 |
+
|
145 |
+
Tag syntax
|
146 |
+
|
147 |
+
Generated HTML
|
148 |
+
|
149 |
+
Limiting output to specific rows
|
150 |
+
|
151 |
+
Grouping Output
|
152 |
+
|
153 |
+
CFScript
|
154 |
+
|
155 |
+
ColdFusion 6 (MX) though current
|
156 |
+
|
157 |
+
ColdFusion 8 though current
|
158 |
+
|
159 |
+
ColdFusion 10 though current
|
160 |
+
|
161 |
+
ColdFusion 11 though current
|
162 |
+
|
163 |
+
List
|
164 |
+
|
165 |
+
Tag syntax
|
166 |
+
|
167 |
+
Parameters
|
168 |
+
|
169 |
+
Generated HTML
|
170 |
+
|
171 |
+
CFScript
|
172 |
+
|
173 |
+
Previous to ColdFusion 8
|
174 |
+
|
175 |
+
ColdFusion 8 through current
|
176 |
+
|
177 |
+
ColdFusion 9 through current
|
178 |
+
|
179 |
+
ColdFusion 11 through current
|
180 |
+
|
181 |
+
Generated HTML
|
182 |
+
|
183 |
+
Array
|
184 |
+
|
185 |
+
Tag syntax
|
186 |
+
|
187 |
+
ColdFusion 8 through current
|
188 |
+
|
189 |
+
10
|
190 |
+
|
191 |
+
11
|
192 |
+
|
193 |
+
11
|
194 |
+
|
195 |
+
11
|
196 |
+
|
197 |
+
11
|
198 |
+
|
199 |
+
11
|
200 |
+
|
201 |
+
11
|
202 |
+
|
203 |
+
11
|
204 |
+
|
205 |
+
12
|
206 |
+
|
207 |
+
12
|
208 |
+
|
209 |
+
12
|
210 |
+
|
211 |
+
13
|
212 |
+
|
213 |
+
13
|
214 |
+
|
215 |
+
14
|
216 |
+
|
217 |
+
15
|
218 |
+
|
219 |
+
15
|
220 |
+
|
221 |
+
15
|
222 |
+
|
223 |
+
15
|
224 |
+
|
225 |
+
16
|
226 |
+
|
227 |
+
16
|
228 |
+
|
229 |
+
16
|
230 |
+
|
231 |
+
16
|
232 |
+
|
233 |
+
16
|
234 |
+
|
235 |
+
16
|
236 |
+
|
237 |
+
17
|
238 |
+
|
239 |
+
17
|
240 |
+
|
241 |
+
17
|
242 |
+
|
243 |
+
17
|
244 |
+
|
245 |
+
17
|
246 |
+
|
247 |
+
17
|
248 |
+
|
249 |
+
17
|
250 |
+
|
251 |
+
Parameters
|
252 |
+
|
253 |
+
Generated HTML
|
254 |
+
|
255 |
+
ColdFusion 2016 through current
|
256 |
+
|
257 |
+
Parameters
|
258 |
+
|
259 |
+
Generated HTML
|
260 |
+
|
261 |
+
CFScript
|
262 |
+
|
263 |
+
Previous to ColdFusion 8
|
264 |
+
|
265 |
+
ColdFusion 8 through current
|
266 |
+
|
267 |
+
ColdFusion 9 through current
|
268 |
+
|
269 |
+
ColdFusion 11 through current
|
270 |
+
|
271 |
+
Generated HTML
|
272 |
+
|
273 |
+
File
|
274 |
+
|
275 |
+
Structure
|
276 |
+
|
277 |
+
Tag syntax
|
278 |
+
|
279 |
+
Parameters
|
280 |
+
|
281 |
+
Using Structure Functions
|
282 |
+
|
283 |
+
Implicit Structure Syntax
|
284 |
+
|
285 |
+
Generated HTML
|
286 |
+
|
287 |
+
CFScript
|
288 |
+
|
289 |
+
Output the structure's keys
|
290 |
+
|
291 |
+
Generated HTML
|
292 |
+
|
293 |
+
Output the value of the structure's keys
|
294 |
+
|
295 |
+
Using Structure Functions
|
296 |
+
|
297 |
+
Implicit Structure Syntax
|
298 |
+
|
299 |
+
ColdFusion 11 through current
|
300 |
+
|
301 |
+
Generated HTML
|
302 |
+
|
303 |
+
Index Loop
|
304 |
+
|
305 |
+
Conditional Loop
|
306 |
+
|
307 |
+
Query Loop
|
308 |
+
|
309 |
+
List Loop
|
310 |
+
|
311 |
+
File Loop
|
312 |
+
|
313 |
+
COM Collection/Structure Loops
|
314 |
+
|
315 |
+
18
|
316 |
+
|
317 |
+
18
|
318 |
+
|
319 |
+
18
|
320 |
+
|
321 |
+
18
|
322 |
+
|
323 |
+
19
|
324 |
+
|
325 |
+
19
|
326 |
+
|
327 |
+
19
|
328 |
+
|
329 |
+
19
|
330 |
+
|
331 |
+
19
|
332 |
+
|
333 |
+
19
|
334 |
+
|
335 |
+
19
|
336 |
+
|
337 |
+
20
|
338 |
+
|
339 |
+
20
|
340 |
+
|
341 |
+
20
|
342 |
+
|
343 |
+
20
|
344 |
+
|
345 |
+
20
|
346 |
+
|
347 |
+
20
|
348 |
+
|
349 |
+
21
|
350 |
+
|
351 |
+
21
|
352 |
+
|
353 |
+
21
|
354 |
+
|
355 |
+
21
|
356 |
+
|
357 |
+
21
|
358 |
+
|
359 |
+
21
|
360 |
+
|
361 |
+
21
|
362 |
+
|
363 |
+
22
|
364 |
+
|
365 |
+
22
|
366 |
+
|
367 |
+
22
|
368 |
+
|
369 |
+
22
|
370 |
+
|
371 |
+
22
|
372 |
+
|
373 |
+
23
|
374 |
+
|
375 |
+
23
|
376 |
+
|
377 |
+
23
|
378 |
+
|
379 |
+
Chapter 3: cfquery
|
380 |
+
|
381 |
+
Parameters
|
382 |
+
|
383 |
+
Examples
|
384 |
+
|
385 |
+
Using cfquery within a Function
|
386 |
+
|
387 |
+
Query of Query
|
388 |
+
|
389 |
+
Function Calls
|
390 |
+
|
391 |
+
User.cfc
|
392 |
+
|
393 |
+
Chapter 4: ColdFusion Arrays
|
394 |
+
|
395 |
+
Syntax
|
396 |
+
|
397 |
+
Parameters
|
398 |
+
|
399 |
+
Remarks
|
400 |
+
|
401 |
+
Examples
|
402 |
+
|
403 |
+
Creating Arrays
|
404 |
+
|
405 |
+
Creating arrays explicitly using ArrayNew()
|
406 |
+
|
407 |
+
History
|
408 |
+
|
409 |
+
Declaration
|
410 |
+
|
411 |
+
Using ArrayAppend()
|
412 |
+
|
413 |
+
Creating 1-D Array Implicitly
|
414 |
+
|
415 |
+
Create 2-D Array Implicitly
|
416 |
+
|
417 |
+
Array in CFScript
|
418 |
+
|
419 |
+
Similarly, for 2 Dimension Array:
|
420 |
+
|
421 |
+
General information
|
422 |
+
|
423 |
+
Chapter 5: Creating REST APIs in coldfusion
|
424 |
+
|
425 |
+
Introduction
|
426 |
+
|
427 |
+
Examples
|
428 |
+
|
429 |
+
Creating backend
|
430 |
+
|
431 |
+
The interface
|
432 |
+
|
433 |
+
Chapter 6: Database Queries
|
434 |
+
|
435 |
+
Examples
|
436 |
+
|
437 |
+
Working with databases
|
438 |
+
|
439 |
+
Basic Example
|
440 |
+
|
441 |
+
24
|
442 |
+
|
443 |
+
24
|
444 |
+
|
445 |
+
24
|
446 |
+
|
447 |
+
24
|
448 |
+
|
449 |
+
24
|
450 |
+
|
451 |
+
24
|
452 |
+
|
453 |
+
24
|
454 |
+
|
455 |
+
26
|
456 |
+
|
457 |
+
26
|
458 |
+
|
459 |
+
26
|
460 |
+
|
461 |
+
26
|
462 |
+
|
463 |
+
26
|
464 |
+
|
465 |
+
26
|
466 |
+
|
467 |
+
26
|
468 |
+
|
469 |
+
26
|
470 |
+
|
471 |
+
26
|
472 |
+
|
473 |
+
27
|
474 |
+
|
475 |
+
28
|
476 |
+
|
477 |
+
29
|
478 |
+
|
479 |
+
30
|
480 |
+
|
481 |
+
31
|
482 |
+
|
483 |
+
31
|
484 |
+
|
485 |
+
32
|
486 |
+
|
487 |
+
32
|
488 |
+
|
489 |
+
32
|
490 |
+
|
491 |
+
32
|
492 |
+
|
493 |
+
32
|
494 |
+
|
495 |
+
33
|
496 |
+
|
497 |
+
33
|
498 |
+
|
499 |
+
33
|
500 |
+
|
501 |
+
33
|
502 |
+
|
503 |
+
Authentication
|
504 |
+
|
505 |
+
Cached Queries
|
506 |
+
|
507 |
+
Limiting the Number of Records Returned
|
508 |
+
|
509 |
+
Timeouts
|
510 |
+
|
511 |
+
Chapter 7: How to invoke a private method dynamically
|
512 |
+
|
513 |
+
Remarks
|
514 |
+
|
515 |
+
Examples
|
516 |
+
|
517 |
+
CFML
|
518 |
+
|
519 |
+
CFSCRIPT (CF10+)
|
520 |
+
|
521 |
+
Chapter 8: Scopes in Coldfusion
|
522 |
+
|
523 |
+
Introduction
|
524 |
+
|
525 |
+
Examples
|
526 |
+
|
527 |
+
Request Scopes
|
528 |
+
|
529 |
+
Global Scopes
|
530 |
+
|
531 |
+
Components and functions
|
532 |
+
|
533 |
+
Custom tags
|
534 |
+
|
535 |
+
Common scopes
|
536 |
+
|
537 |
+
Overview
|
538 |
+
|
539 |
+
Chapter 9: Variables
|
540 |
+
|
541 |
+
Parameters
|
542 |
+
|
543 |
+
Examples
|
544 |
+
|
545 |
+
Using cfset
|
546 |
+
|
547 |
+
Using cfparam
|
548 |
+
|
549 |
+
Checking if a Variable Exists
|
550 |
+
|
551 |
+
Setting a variable scope
|
552 |
+
|
553 |
+
Chapter 10: Working with RegExp Replace callbacks
|
554 |
+
|
555 |
+
Introduction
|
556 |
+
|
557 |
+
Parameters
|
558 |
+
|
559 |
+
Remarks
|
560 |
+
|
561 |
+
Examples
|
562 |
+
|
563 |
+
User defined REReplaceCallback function
|
564 |
+
|
565 |
+
Using REReplaceCallback function
|
566 |
+
|
567 |
+
34
|
568 |
+
|
569 |
+
34
|
570 |
+
|
571 |
+
35
|
572 |
+
|
573 |
+
35
|
574 |
+
|
575 |
+
36
|
576 |
+
|
577 |
+
36
|
578 |
+
|
579 |
+
36
|
580 |
+
|
581 |
+
36
|
582 |
+
|
583 |
+
36
|
584 |
+
|
585 |
+
37
|
586 |
+
|
587 |
+
37
|
588 |
+
|
589 |
+
37
|
590 |
+
|
591 |
+
37
|
592 |
+
|
593 |
+
37
|
594 |
+
|
595 |
+
37
|
596 |
+
|
597 |
+
37
|
598 |
+
|
599 |
+
38
|
600 |
+
|
601 |
+
38
|
602 |
+
|
603 |
+
39
|
604 |
+
|
605 |
+
39
|
606 |
+
|
607 |
+
39
|
608 |
+
|
609 |
+
39
|
610 |
+
|
611 |
+
39
|
612 |
+
|
613 |
+
40
|
614 |
+
|
615 |
+
40
|
616 |
+
|
617 |
+
42
|
618 |
+
|
619 |
+
42
|
620 |
+
|
621 |
+
42
|
622 |
+
|
623 |
+
42
|
624 |
+
|
625 |
+
42
|
626 |
+
|
627 |
+
43
|
628 |
+
|
629 |
+
43
|
630 |
+
|
631 |
+
Credits
|
632 |
+
|
633 |
+
44
|
634 |
+
|
635 |
+
About
|
636 |
+
|
637 |
+
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
|
638 |
+
from: coldfusion
|
639 |
+
|
640 |
+
It is an unofficial and free coldfusion ebook created for educational purposes. All the content is
|
641 |
+
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
|
642 |
+
Stack Overflow. It is neither affiliated with Stack Overflow nor official coldfusion.
|
643 |
+
|
644 |
+
The content is released under Creative Commons BY-SA, and the list of contributors to each
|
645 |
+
chapter are provided in the credits section at the end of this book. Images may be copyright of
|
646 |
+
their respective owners unless otherwise specified. All trademarks and registered trademarks are
|
647 |
+
the property of their respective company owners.
|
648 |
+
|
649 |
+
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
|
650 |
+
accurate, please send your feedback and corrections to info@zzzprojects.com
|
651 |
+
|
652 |
+
https://riptutorial.com/
|
653 |
+
|
654 |
+
1
|
655 |
+
|
656 |
+
Chapter 1: Getting started with coldfusion
|
657 |
+
|
658 |
+
Remarks
|
659 |
+
|
660 |
+
This section provides an overview of what coldfusion is, and why a developer might want to use it.
|
661 |
+
|
662 |
+
It should also mention any large subjects within coldfusion, and link out to the related topics. Since
|
663 |
+
the Documentation for coldfusion is new, you may need to create initial versions of those related
|
664 |
+
topics.
|
665 |
+
|
666 |
+
Versions
|
667 |
+
|
668 |
+
Version
|
669 |
+
|
670 |
+
Release Date
|
671 |
+
|
672 |
+
Cold Fusion version 1.0
|
673 |
+
|
674 |
+
1995-07-02
|
675 |
+
|
676 |
+
Cold Fusion version 1.5
|
677 |
+
|
678 |
+
1996-01-01
|
679 |
+
|
680 |
+
Cold Fusion version 2.0
|
681 |
+
|
682 |
+
1996-10-01
|
683 |
+
|
684 |
+
Cold Fusion version 3.0
|
685 |
+
|
686 |
+
1997-06-01
|
687 |
+
|
688 |
+
Cold Fusion version 3.1
|
689 |
+
|
690 |
+
1998-01-01
|
691 |
+
|
692 |
+
ColdFusion version 4.0
|
693 |
+
|
694 |
+
1998-11-01
|
695 |
+
|
696 |
+
ColdFusion version 4.5.1
|
697 |
+
|
698 |
+
1999-11-01
|
699 |
+
|
700 |
+
ColdFusion version 5.0
|
701 |
+
|
702 |
+
2001-06-01
|
703 |
+
|
704 |
+
ColdFusion MX version 6.0 2002-05-01
|
705 |
+
|
706 |
+
ColdFusion MX version 6.1 2003-07-01
|
707 |
+
|
708 |
+
ColdFusion MX 7
|
709 |
+
|
710 |
+
2005-02-07
|
711 |
+
|
712 |
+
ColdFusion 8
|
713 |
+
|
714 |
+
ColdFusion 9
|
715 |
+
|
716 |
+
2007-07-30
|
717 |
+
|
718 |
+
2009-10-05
|
719 |
+
|
720 |
+
ColdFusion 10
|
721 |
+
|
722 |
+
2012-05-15
|
723 |
+
|
724 |
+
ColdFusion 11
|
725 |
+
|
726 |
+
2014-04-29
|
727 |
+
|
728 |
+
ColdFusion 2016
|
729 |
+
|
730 |
+
2016-02-16
|
731 |
+
|
732 |
+
https://riptutorial.com/
|
733 |
+
|
734 |
+
2
|
735 |
+
|
736 |
+
Examples
|
737 |
+
|
738 |
+
Installation or Setup
|
739 |
+
|
740 |
+
Linux (Ubuntu) Installation
|
741 |
+
|
742 |
+
Lucee (Open Source)
|
743 |
+
|
744 |
+
ColdFusion / CFML Interpretor
|
745 |
+
|
746 |
+
Download the appropriate file from their site (http://lucee.org/downloads.html) and execute their
|
747 |
+
installer
|
748 |
+
|
749 |
+
wget http://cdn.lucee.org/downloader.cfm/id/155/file/lucee-5.0.0.252-pl0-linux-x64-
|
750 |
+
installer.run
|
751 |
+
sudo chmod +x lucee-5.0.0.252-pl0-linux-x64-installer.run
|
752 |
+
sudo ./lucee-5.0.0.252-pl0-linux-x64-installer.run
|
753 |
+
|
754 |
+
Step through installer.
|
755 |
+
|
756 |
+
Nginx
|
757 |
+
|
758 |
+
Install Nginx on your server
|
759 |
+
|
760 |
+
sudo apt-get install nginx
|
761 |
+
|
762 |
+
Edit your /etc/nginx/sites-available/default
|
763 |
+
|
764 |
+
server {
|
765 |
+
listen 80;
|
766 |
+
server_name _;
|
767 |
+
|
768 |
+
root /opt/lucee/tomcat/webapps/ROOT;
|
769 |
+
index index.cfm index.html index.htm;
|
770 |
+
|
771 |
+
#Lucee Admin should always proxy to Lucee
|
772 |
+
location /lucee {
|
773 |
+
include lucee.conf;
|
774 |
+
}
|
775 |
+
|
776 |
+
#Pretty URLs
|
777 |
+
location / {
|
778 |
+
try_files $uri /index.cfm$uri?$is_args$args;
|
779 |
+
include lucee.conf;
|
780 |
+
}
|
781 |
+
|
782 |
+
location ~ \.cfm {
|
783 |
+
include lucee.conf;
|
784 |
+
}
|
785 |
+
|
786 |
+
https://riptutorial.com/
|
787 |
+
|
788 |
+
3
|
789 |
+
|
790 |
+
|
791 |
+
|
792 |
+
|
793 |
+
|
794 |
+
|
795 |
+
location ~ \.cfc {
|
796 |
+
include lucee.conf;
|
797 |
+
}
|
798 |
+
}
|
799 |
+
|
800 |
+
Edit /etc/nginx/lucee.conf
|
801 |
+
|
802 |
+
proxy_pass http://127.0.0.1:8888;
|
803 |
+
proxy_set_header Host $http_host;
|
804 |
+
proxy_set_header X-Real-IP $remote_addr;
|
805 |
+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
806 |
+
proxy_set_header X-Forwarded-Proto $scheme;
|
807 |
+
|
808 |
+
Reload nginx
|
809 |
+
|
810 |
+
sudo service nginx reload
|
811 |
+
|
812 |
+
Access the Lucee Server admin here:
|
813 |
+
|
814 |
+
127.0.0.1/lucee/admin/server.cfm
|
815 |
+
|
816 |
+
or
|
817 |
+
|
818 |
+
127.0.0.1:8888/lucee/admin/server.cfm
|
819 |
+
|
820 |
+
Your root web directory lives here:
|
821 |
+
|
822 |
+
/opt/lucee/tomcat/webapps/ROOT
|
823 |
+
|
824 |
+
Adobe (Closed Source)
|
825 |
+
|
826 |
+
ColdFusion / CFML Interpretor
|
827 |
+
|
828 |
+
Download the appropriate file from their site (
|
829 |
+
https://www.adobe.com/products/coldfusion/download-trial/try.html) and execute their installer
|
830 |
+
|
831 |
+
wget <URL>/ColdFusion_2016_WWEJ_linux64.bin
|
832 |
+
sudo chmod +x ColdFusion_2016_WWEJ_linux64.bin
|
833 |
+
sudo ./ColdFusion_2016_WWEJ_linux64.bin
|
834 |
+
|
835 |
+
Step through installer. Make sure you select the internal web server (port 8500)
|
836 |
+
|
837 |
+
Nginx
|
838 |
+
|
839 |
+
Install Nginx on your server
|
840 |
+
|
841 |
+
sudo apt-get install nginx
|
842 |
+
|
843 |
+
https://riptutorial.com/
|
844 |
+
|
845 |
+
4
|
846 |
+
|
847 |
+
Edit your /etc/nginx/sites-available/default
|
848 |
+
|
849 |
+
server {
|
850 |
+
listen 80;
|
851 |
+
server_name _;
|
852 |
+
|
853 |
+
root /opt/coldfusion2016/cfusion/wwwroot;
|
854 |
+
index index.cfm index.html index.htm;
|
855 |
+
|
856 |
+
location / {
|
857 |
+
try_files $uri $uri/ =404;
|
858 |
+
}
|
859 |
+
|
860 |
+
location ^~ /CFIDE/administrator {
|
861 |
+
deny all;
|
862 |
+
}
|
863 |
+
|
864 |
+
location ~* \.(cfm|cfml|cfc|html)$ {
|
865 |
+
include /etc/nginx/conf/dc_tomcat_connector.conf;
|
866 |
+
}
|
867 |
+
|
868 |
+
location ^~ /rest {
|
869 |
+
include tomcatconf;
|
870 |
+
}
|
871 |
+
}
|
872 |
+
|
873 |
+
Edit /etc/nginx/tomcat.conf
|
874 |
+
|
875 |
+
proxy_pass http://127.0.0.1:8500;
|
876 |
+
proxy_set_header Host $host;
|
877 |
+
proxy_set_header X-Forwarded-Host $host;
|
878 |
+
proxy_set_header X-Forwarded-Server $host;
|
879 |
+
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
|
880 |
+
proxy_set_header X-Real-IP $remote_addr;
|
881 |
+
|
882 |
+
Reload nginx
|
883 |
+
|
884 |
+
sudo service nginx reload
|
885 |
+
|
886 |
+
Access the Adobe ColdFusion Server admin here:
|
887 |
+
|
888 |
+
127.0.0.1:8500/CFIDE/administrator/index.cfm
|
889 |
+
|
890 |
+
Your root web directory lives here:
|
891 |
+
|
892 |
+
/opt/coldfusion2016/cfusion/wwwroot
|
893 |
+
|
894 |
+
Hello World
|
895 |
+
|
896 |
+
File: test.cfm
|
897 |
+
|
898 |
+
Tag Implementation
|
899 |
+
|
900 |
+
https://riptutorial.com/
|
901 |
+
|
902 |
+
5
|
903 |
+
|
904 |
+
|
905 |
+
|
906 |
+
|
907 |
+
|
908 |
+
|
909 |
+
<cfoutput>Hello World!</cfoutput>
|
910 |
+
|
911 |
+
CFScript Implementation
|
912 |
+
|
913 |
+
<cfscript>
|
914 |
+
writeOutput("Hello World!");
|
915 |
+
</cfscript>
|
916 |
+
|
917 |
+
Read Getting started with coldfusion online: https://riptutorial.com/coldfusion/topic/913/getting-
|
918 |
+
started-with-coldfusion
|
919 |
+
|
920 |
+
https://riptutorial.com/
|
921 |
+
|
922 |
+
6
|
923 |
+
|
924 |
+
Chapter 2: CFLOOP How-To
|
925 |
+
|
926 |
+
Remarks
|
927 |
+
|
928 |
+
Big thanks to
|
929 |
+
|
930 |
+
•
|
931 |
+
•
|
932 |
+
|
933 |
+
Pete Freitag for his CFScript Cheat Sheet
|
934 |
+
Adam Cameron for CF 11: CFLOOP in CFScript is Very Broken (and it still is in CF 2016).
|
935 |
+
|
936 |
+
Examples
|
937 |
+
|
938 |
+
Looping through a collection using CFML tags.
|
939 |
+
|
940 |
+
<!--- Define collection --->
|
941 |
+
<cfset attributes = {
|
942 |
+
"name": "Sales",
|
943 |
+
"type": "text",
|
944 |
+
"value": "Connection"
|
945 |
+
}>
|
946 |
+
|
947 |
+
<!---
|
948 |
+
cfloop tag with attribute collection can be used to
|
949 |
+
loop through the elements of a structure
|
950 |
+
--->
|
951 |
+
<cfloop collection=#attributes# item="attribute">
|
952 |
+
<cfoutput>
|
953 |
+
Key : #attribute#, Value : #attributes[attribute]#
|
954 |
+
</cfoutput>
|
955 |
+
</cfloop>
|
956 |
+
|
957 |
+
Looping through a collection using CFSCRIPT.
|
958 |
+
|
959 |
+
<cfscript>
|
960 |
+
/*define collection*/
|
961 |
+
attributes = {
|
962 |
+
"name": "Sales",
|
963 |
+
"type": "text",
|
964 |
+
"value": "Connection"
|
965 |
+
};
|
966 |
+
for(attribute in attributes){
|
967 |
+
/* attribute variable will contain the key name of each key value pair in loop */
|
968 |
+
WriteOutput('Key : ' & attribute & ', Value : ' & attributes[attribute] & '<br/>');
|
969 |
+
}
|
970 |
+
</cfscript>
|
971 |
+
|
972 |
+
Index
|
973 |
+
|
974 |
+
Parameters
|
975 |
+
|
976 |
+
https://riptutorial.com/
|
977 |
+
|
978 |
+
7
|
979 |
+
|
980 |
+
|
981 |
+
Attribute Required Type
|
982 |
+
|
983 |
+
Default Description
|
984 |
+
|
985 |
+
index
|
986 |
+
|
987 |
+
true
|
988 |
+
|
989 |
+
string
|
990 |
+
|
991 |
+
Variable name for the loop's index. Defaults to
|
992 |
+
the variables scope.
|
993 |
+
|
994 |
+
from
|
995 |
+
|
996 |
+
to
|
997 |
+
|
998 |
+
true
|
999 |
+
|
1000 |
+
true
|
1001 |
+
|
1002 |
+
numeric
|
1003 |
+
|
1004 |
+
numeric
|
1005 |
+
|
1006 |
+
Starting value for the index.
|
1007 |
+
|
1008 |
+
Ending value for the index.
|
1009 |
+
|
1010 |
+
step
|
1011 |
+
|
1012 |
+
false
|
1013 |
+
|
1014 |
+
numeric 1
|
1015 |
+
|
1016 |
+
Value by which to increase or decrease the
|
1017 |
+
index per iteration.
|
1018 |
+
|
1019 |
+
Basic index loop
|
1020 |
+
|
1021 |
+
Final value of x is 10.
|
1022 |
+
|
1023 |
+
<!--- Tags --->
|
1024 |
+
<cfoutput>
|
1025 |
+
<cfloop index="x" from="1" to="10">
|
1026 |
+
<li>#x#</li>
|
1027 |
+
</cfloop>
|
1028 |
+
</cfoutput>
|
1029 |
+
<!--- cfscript --->
|
1030 |
+
<cfscript>
|
1031 |
+
for (x = 1; x <= 10; x++) {
|
1032 |
+
writeOutput('<li>' & x & '</li>');
|
1033 |
+
}
|
1034 |
+
</cfscript>
|
1035 |
+
<!--- HTML Output --->
|
1036 |
+
- 1
|
1037 |
+
- 2
|
1038 |
+
- 3
|
1039 |
+
- 4
|
1040 |
+
- 5
|
1041 |
+
- 6
|
1042 |
+
- 7
|
1043 |
+
- 8
|
1044 |
+
- 9
|
1045 |
+
- 10
|
1046 |
+
|
1047 |
+
Increase step to 2
|
1048 |
+
|
1049 |
+
Final value of x is 11.
|
1050 |
+
|
1051 |
+
<!--- Tags --->
|
1052 |
+
<cfoutput>
|
1053 |
+
<cfloop index="x" from="1" to="10" step="2">
|
1054 |
+
<li>#x#</li>
|
1055 |
+
</cfloop>
|
1056 |
+
</cfoutput>
|
1057 |
+
<!--- cfscript --->
|
1058 |
+
<cfscript>
|
1059 |
+
for (x = 1; x <= 10; x += 2) {
|
1060 |
+
|
1061 |
+
https://riptutorial.com/
|
1062 |
+
|
1063 |
+
8
|
1064 |
+
|
1065 |
+
writeOutput('<li>' & x & '</li>');
|
1066 |
+
}
|
1067 |
+
</cfscript>
|
1068 |
+
<!--- HTML Output --->
|
1069 |
+
- 1
|
1070 |
+
- 3
|
1071 |
+
- 5
|
1072 |
+
- 7
|
1073 |
+
- 9
|
1074 |
+
|
1075 |
+
Decrement step by 1
|
1076 |
+
|
1077 |
+
Final value of x is 0.
|
1078 |
+
|
1079 |
+
<!--- Tags --->
|
1080 |
+
<cfoutput>
|
1081 |
+
<cfloop index="x" from="10" to="1" step="-1">
|
1082 |
+
<li>#x#</li>
|
1083 |
+
</cfloop>
|
1084 |
+
</cfoutput>
|
1085 |
+
<!--- cfscript --->
|
1086 |
+
<cfscript>
|
1087 |
+
for (x = 10; x > 0; x--) {
|
1088 |
+
writeOutput('<li>' & x & '</li>');
|
1089 |
+
}
|
1090 |
+
</cfscript>
|
1091 |
+
<!--- HTML Output --->
|
1092 |
+
- 10
|
1093 |
+
- 9
|
1094 |
+
- 8
|
1095 |
+
- 7
|
1096 |
+
- 6
|
1097 |
+
- 5
|
1098 |
+
- 4
|
1099 |
+
- 3
|
1100 |
+
- 2
|
1101 |
+
- 1
|
1102 |
+
|
1103 |
+
CFLoop in a Function
|
1104 |
+
|
1105 |
+
Make sure to var or local scope the index inside a function. Foo() returns 11.
|
1106 |
+
|
1107 |
+
<!--- var scope --->
|
1108 |
+
<cffunction name="foo" access="public" output="false" returntype="numeric">
|
1109 |
+
<cfset var x = 0 />
|
1110 |
+
<cfloop index="x" from="1" to="10" step="1">
|
1111 |
+
<cfset x++ />
|
1112 |
+
</cfloop>
|
1113 |
+
<cfreturn x />
|
1114 |
+
</cffunction>
|
1115 |
+
|
1116 |
+
<!--- Local scope --->
|
1117 |
+
<cffunction name="foo" access="public" output="false" returntype="numeric">
|
1118 |
+
<cfloop index="local.x" from="1" to="10" step="1">
|
1119 |
+
<cfset local.x++ />
|
1120 |
+
|
1121 |
+
https://riptutorial.com/
|
1122 |
+
|
1123 |
+
9
|
1124 |
+
|
1125 |
+
|
1126 |
+
</cfloop>
|
1127 |
+
<cfreturn local.x />
|
1128 |
+
</cffunction>
|
1129 |
+
|
1130 |
+
ColdFusion 11 through current
|
1131 |
+
|
1132 |
+
The cfscript function cfloop has no support for index as a stand alone counter
|
1133 |
+
mechanism.
|
1134 |
+
|
1135 |
+
Condition
|
1136 |
+
|
1137 |
+
Tag syntax
|
1138 |
+
|
1139 |
+
Parameters
|
1140 |
+
|
1141 |
+
Attribute Required Type Default Description
|
1142 |
+
|
1143 |
+
Condition that manages the loop. Cannot contain
|
1144 |
+
math symbols like <, > or =. Must use ColdFusion
|
1145 |
+
text implementations like less than, lt, greater than
|
1146 |
+
, gt, equals or eq.
|
1147 |
+
|
1148 |
+
condition
|
1149 |
+
|
1150 |
+
true
|
1151 |
+
|
1152 |
+
string
|
1153 |
+
|
1154 |
+
Final value of x is 5.
|
1155 |
+
|
1156 |
+
<cfset x = 0 />
|
1157 |
+
<cfoutput>
|
1158 |
+
<cfloop condition="x LT 5">
|
1159 |
+
<cfset x++ />
|
1160 |
+
<li>#x#</li>
|
1161 |
+
</cfloop>
|
1162 |
+
</cfoutput>
|
1163 |
+
|
1164 |
+
Generated HTML
|
1165 |
+
|
1166 |
+
This will also have a line break between each line of HTML.
|
1167 |
+
|
1168 |
+
<li>1</li>
|
1169 |
+
<li>2</li>
|
1170 |
+
<li>3</li>
|
1171 |
+
<li>4</li>
|
1172 |
+
<li>5</li>
|
1173 |
+
|
1174 |
+
CFScript
|
1175 |
+
|
1176 |
+
https://riptutorial.com/
|
1177 |
+
|
1178 |
+
10
|
1179 |
+
|
1180 |
+
Previous to ColdFusion 8
|
1181 |
+
|
1182 |
+
<cfscript>
|
1183 |
+
x = 0;
|
1184 |
+
while (x LT 5) {
|
1185 |
+
x = x + 1;
|
1186 |
+
writeOutput('<li>' & x & '</li>');
|
1187 |
+
}
|
1188 |
+
</cfscript>
|
1189 |
+
|
1190 |
+
ColdFusion 8 through current
|
1191 |
+
|
1192 |
+
<cfscript>
|
1193 |
+
x = 0;
|
1194 |
+
while (x LT 5) {
|
1195 |
+
x = x++;
|
1196 |
+
writeOutput('<li>' & x & '</li>');
|
1197 |
+
}
|
1198 |
+
</cfscript>
|
1199 |
+
|
1200 |
+
ColdFusion 11 through current
|
1201 |
+
|
1202 |
+
The cfscript function cfloop has no support for condition.
|
1203 |
+
|
1204 |
+
Generated HTML
|
1205 |
+
|
1206 |
+
Notice that the cfscript output is all on one line.
|
1207 |
+
|
1208 |
+
<li>one</li><li>two</li><li>three</li><li>four</li>
|
1209 |
+
|
1210 |
+
Date or time range
|
1211 |
+
|
1212 |
+
Example for date or time range.
|
1213 |
+
|
1214 |
+
Query
|
1215 |
+
|
1216 |
+
Consider the table dbo.state_zip, which contains the columns city, statecode and zipcode and has
|
1217 |
+
over 80,000 records.
|
1218 |
+
|
1219 |
+
Parameters
|
1220 |
+
|
1221 |
+
Attribute Required Type
|
1222 |
+
|
1223 |
+
Default Description
|
1224 |
+
|
1225 |
+
query
|
1226 |
+
|
1227 |
+
true
|
1228 |
+
|
1229 |
+
string
|
1230 |
+
|
1231 |
+
The variable name of a query object.
|
1232 |
+
|
1233 |
+
startrow
|
1234 |
+
|
1235 |
+
false
|
1236 |
+
|
1237 |
+
numeric
|
1238 |
+
|
1239 |
+
The starting row index of the query object.
|
1240 |
+
|
1241 |
+
https://riptutorial.com/
|
1242 |
+
|
1243 |
+
11
|
1244 |
+
|
1245 |
+
Attribute Required Type
|
1246 |
+
|
1247 |
+
Default Description
|
1248 |
+
|
1249 |
+
endrow
|
1250 |
+
|
1251 |
+
false
|
1252 |
+
|
1253 |
+
numeric
|
1254 |
+
|
1255 |
+
The ending row index of the query object.
|
1256 |
+
|
1257 |
+
group
|
1258 |
+
|
1259 |
+
false
|
1260 |
+
|
1261 |
+
string
|
1262 |
+
|
1263 |
+
The query column name on which to group
|
1264 |
+
records.
|
1265 |
+
|
1266 |
+
Example query
|
1267 |
+
|
1268 |
+
<cfquery name="geo" datasource="reotrans-dev">
|
1269 |
+
SELECT city, stateCode, zipCode
|
1270 |
+
FROM dbo.state_zip
|
1271 |
+
</cfquery>
|
1272 |
+
|
1273 |
+
Tag syntax
|
1274 |
+
|
1275 |
+
Using the query object geo as the source for cfloop. Since the table dbo.state_zip has so many
|
1276 |
+
records, the HTML generated will take quite some time. This example shows only the first 20
|
1277 |
+
records' worth of HTML.
|
1278 |
+
|
1279 |
+
<cfoutput>
|
1280 |
+
<ul>
|
1281 |
+
<cfloop query="geo">
|
1282 |
+
<!--- Scope the column names with the query name. --->
|
1283 |
+
<li>#geo.city# | #geo.stateCode# | #geo.zipCode#</li>
|
1284 |
+
</cfloop>
|
1285 |
+
</ul>
|
1286 |
+
</cfoutput>
|
1287 |
+
|
1288 |
+
Generated HTML
|
1289 |
+
|
1290 |
+
<ul>
|
1291 |
+
<li>100 PALMS | CA | 92274</li>
|
1292 |
+
<li>1000 PALMS | CA | 92276</li>
|
1293 |
+
<li>12 MILE | IN | 46988</li>
|
1294 |
+
<li>1ST NATIONAL BANK OF OMAHA | NE | 68197</li>
|
1295 |
+
<li>29 PALMS | CA | 92277</li>
|
1296 |
+
<li>29 PALMS | CA | 92278</li>
|
1297 |
+
<li>3 STATE FARM PLAZA | IL | 61710</li>
|
1298 |
+
<li>3 STATE FARM PLAZA | IL | 61791</li>
|
1299 |
+
<li>30TH STREET | PA | 19104</li>
|
1300 |
+
<li>3M CORP | MN | 55144</li>
|
1301 |
+
<li>65TH INFANTRY | PR | 00923</li>
|
1302 |
+
<li>65TH INFANTRY | PR | 00924</li>
|
1303 |
+
<li>65TH INFANTRY | PR | 00929</li>
|
1304 |
+
<li>65TH INFANTRY | PR | 00936</li>
|
1305 |
+
<li>7 CORNERS | VA | 22044</li>
|
1306 |
+
<li>88 | KY | 42130</li>
|
1307 |
+
<li>9 MILE POINT | LA | 70094</li>
|
1308 |
+
<li>A A R P INS | PA | 19187</li>
|
1309 |
+
<li>A A R P PHARMACY | CT | 06167</li>
|
1310 |
+
|
1311 |
+
https://riptutorial.com/
|
1312 |
+
|
1313 |
+
12
|
1314 |
+
|
1315 |
+
<li>A H MCCOY FEDERAL BLDG | MS | 39269</li>
|
1316 |
+
</ul>
|
1317 |
+
|
1318 |
+
Limiting output to specific rows
|
1319 |
+
|
1320 |
+
To limit the query's output to a specific range of rows, specify startrow and endrow.
|
1321 |
+
|
1322 |
+
<cfloop query="geo" startrow="100" endrow="150">
|
1323 |
+
<li>#geo.city# | #geo.stateCode# | #geo.zipCode#</li>
|
1324 |
+
</cfloop>
|
1325 |
+
|
1326 |
+
Grouping Output
|
1327 |
+
|
1328 |
+
In the example data, the same state listed multiple times in relation to the multiple cities that are
|
1329 |
+
associated to each state. You can also see the same city listed multiple times in relation to the
|
1330 |
+
multiple zip codes associated to each city.
|
1331 |
+
|
1332 |
+
Let's group the output by state first. Notice the 2nd instance of cfloop wrapped around the content
|
1333 |
+
that will be output under the stateCode grouped content.
|
1334 |
+
|
1335 |
+
<cfoutput>
|
1336 |
+
<ul>
|
1337 |
+
<cfloop query="geo" group="stateCode">
|
1338 |
+
<!--- Scope the column names with the query name. --->
|
1339 |
+
<li>#geo.stateCode#
|
1340 |
+
<ul>
|
1341 |
+
<cfloop>
|
1342 |
+
<li>#geo.city# | #geo.zipCode#</li>
|
1343 |
+
</cfloop>
|
1344 |
+
</ul>
|
1345 |
+
</li>
|
1346 |
+
</cfloop>
|
1347 |
+
</ul>
|
1348 |
+
</cfoutput>
|
1349 |
+
|
1350 |
+
Generated HTML (extract) from one grouped cfloop tag.
|
1351 |
+
|
1352 |
+
<ul>
|
1353 |
+
<li>AK
|
1354 |
+
<ul>
|
1355 |
+
<li>KONGIGANAK | 99545</li>
|
1356 |
+
<li>ADAK | 99546</li>
|
1357 |
+
<li>ATKA | 99547</li>
|
1358 |
+
<!-- etc. -->
|
1359 |
+
</ul>
|
1360 |
+
</li>
|
1361 |
+
<li>AL
|
1362 |
+
<ul>
|
1363 |
+
<li>ALEX CITY | 35010</li>
|
1364 |
+
<li>ALEXANDER CITY | 35010</li>
|
1365 |
+
<li>ALEX CITY | 35011</li>
|
1366 |
+
<!-- etc. -->
|
1367 |
+
</ul>
|
1368 |
+
|
1369 |
+
https://riptutorial.com/
|
1370 |
+
|
1371 |
+
13
|
1372 |
+
|
1373 |
+
</li>
|
1374 |
+
<!-- etc. -->
|
1375 |
+
</ul>
|
1376 |
+
|
1377 |
+
Finally, let's group the output by stateCode, then by city in order to see all the zipCode entries per
|
1378 |
+
city. Notice the 2nd cfloop is now grouped by city and a 3rd cfloop exists to output the zipCode
|
1379 |
+
data.
|
1380 |
+
|
1381 |
+
<cfoutput>
|
1382 |
+
<ul>
|
1383 |
+
<cfloop query="geo" group="stateCode">
|
1384 |
+
<li>#geo.stateCode#
|
1385 |
+
<ul>
|
1386 |
+
<cfloop group="city">
|
1387 |
+
<li>#geo.city#
|
1388 |
+
<ul>
|
1389 |
+
<cfloop>
|
1390 |
+
<li>#geo.zipCode#</li>
|
1391 |
+
</cfloop>
|
1392 |
+
</ul>
|
1393 |
+
</li>
|
1394 |
+
</cfloop>
|
1395 |
+
</ul>
|
1396 |
+
</li>
|
1397 |
+
</cfloop>
|
1398 |
+
</ul>
|
1399 |
+
</cfoutput>
|
1400 |
+
|
1401 |
+
Generated HTML (extract) from two grouped cfloop tags.
|
1402 |
+
|
1403 |
+
<ul>
|
1404 |
+
<li>AK
|
1405 |
+
<ul>
|
1406 |
+
<li>ADAK
|
1407 |
+
<ul>
|
1408 |
+
<li>99546</li>
|
1409 |
+
<li>99571</li>
|
1410 |
+
</ul>
|
1411 |
+
</li>
|
1412 |
+
<li>AKHIOK
|
1413 |
+
<ul>
|
1414 |
+
<li>99615</li>
|
1415 |
+
</ul>
|
1416 |
+
</li>
|
1417 |
+
<!--- etc. --->
|
1418 |
+
<li>BARROW
|
1419 |
+
<ul>
|
1420 |
+
<li>99723</li>
|
1421 |
+
<li>99759</li>
|
1422 |
+
<li>99789</li>
|
1423 |
+
<li>99791</li>
|
1424 |
+
</ul>
|
1425 |
+
</li>
|
1426 |
+
<!--- etc. --->
|
1427 |
+
</ul>
|
1428 |
+
</li>
|
1429 |
+
<!--- stateCodes etc. --->
|
1430 |
+
</ul>
|
1431 |
+
|
1432 |
+
https://riptutorial.com/
|
1433 |
+
|
1434 |
+
14
|
1435 |
+
|
1436 |
+
CFScript
|
1437 |
+
|
1438 |
+
ColdFusion 6 (MX) though current
|
1439 |
+
|
1440 |
+
<cfscript>
|
1441 |
+
for (x = 1; x LTE geo.recordcount; x = x + 1) {
|
1442 |
+
writeOutput( '<li>' & geo.city[x] & ' | ' &
|
1443 |
+
geo.stateCode[x] & ' | ' & geo.zipCode[x] & '</li>');
|
1444 |
+
}
|
1445 |
+
</cfscript>
|
1446 |
+
|
1447 |
+
ColdFusion 8 though current
|
1448 |
+
|
1449 |
+
<cfscript>
|
1450 |
+
for (x = 1; x <= geo.recordcount; x++) {
|
1451 |
+
writeOutput( '<li>' & geo.city[x] & ' | ' &
|
1452 |
+
geo.stateCode[x] & ' | ' & geo.zipCode[x] & '</li>');
|
1453 |
+
}
|
1454 |
+
</cfscript>
|
1455 |
+
|
1456 |
+
ColdFusion 10 though current
|
1457 |
+
|
1458 |
+
With the FOR IN syntax, x is a query row object, not the row index.
|
1459 |
+
|
1460 |
+
<cfscript>
|
1461 |
+
for (x in geo) {
|
1462 |
+
writeOutput( '<li>' & x.city & ' | ' &
|
1463 |
+
x.stateCode & ' | ' & x.zipCode & '</li>');
|
1464 |
+
}
|
1465 |
+
</cfscript>
|
1466 |
+
|
1467 |
+
ColdFusion 11 though current
|
1468 |
+
|
1469 |
+
ColdFusion 11 allows most tags to be written as cfscript.
|
1470 |
+
|
1471 |
+
<cfscript>
|
1472 |
+
cfloop(query: geo, startrow: 1, endrow: 2) {
|
1473 |
+
writeOutput( '<li>' & geo.city & ' | ' &
|
1474 |
+
geo.stateCode & ' | ' & geo.zipCode & '</li>');
|
1475 |
+
}
|
1476 |
+
</cfscript>
|
1477 |
+
|
1478 |
+
With group.
|
1479 |
+
|
1480 |
+
<cfscript>
|
1481 |
+
cfloop(query: geo, group: 'city') {
|
1482 |
+
writeOutput( '<li>' & geo.city & '<ul>');
|
1483 |
+
cfloop() { // no arguments, just as in the tag syntax.
|
1484 |
+
|
1485 |
+
https://riptutorial.com/
|
1486 |
+
|
1487 |
+
15
|
1488 |
+
|
1489 |
+
writeOutput('<li>' & geo.zipCode & '</li>');
|
1490 |
+
}
|
1491 |
+
writeOutput('</ul></li>');
|
1492 |
+
}
|
1493 |
+
</cfscript>
|
1494 |
+
|
1495 |
+
List
|
1496 |
+
|
1497 |
+
Consider this list:
|
1498 |
+
|
1499 |
+
<cfset foo = "one,two,three,four" />
|
1500 |
+
|
1501 |
+
Tag syntax
|
1502 |
+
|
1503 |
+
Parameters
|
1504 |
+
|
1505 |
+
Attribute Required Default Description
|
1506 |
+
|
1507 |
+
list
|
1508 |
+
|
1509 |
+
true
|
1510 |
+
|
1511 |
+
A list object. The variable must be evaluated (wrapped with
|
1512 |
+
##)
|
1513 |
+
|
1514 |
+
index
|
1515 |
+
|
1516 |
+
true
|
1517 |
+
|
1518 |
+
The current element of the list.
|
1519 |
+
|
1520 |
+
<cfoutput>
|
1521 |
+
<cfloop list="#foo#" index="x">
|
1522 |
+
<li>#x#</li>
|
1523 |
+
</cfloop>
|
1524 |
+
</cfoutput>
|
1525 |
+
|
1526 |
+
Generated HTML
|
1527 |
+
|
1528 |
+
This will also have a line break between each line of HTML.
|
1529 |
+
|
1530 |
+
<li>one</li>
|
1531 |
+
<li>two</li>
|
1532 |
+
<li>three</li>
|
1533 |
+
<li>four</li>
|
1534 |
+
|
1535 |
+
CFScript
|
1536 |
+
|
1537 |
+
Previous to ColdFusion 8
|
1538 |
+
|
1539 |
+
<cfscript>
|
1540 |
+
for (x = 1; x LTE listLen(foo); x = x + 1) {
|
1541 |
+
writeOutput("<li>" & listGetAt(foo, x) & "</li>");
|
1542 |
+
|
1543 |
+
https://riptutorial.com/
|
1544 |
+
|
1545 |
+
16
|
1546 |
+
|
1547 |
+
}
|
1548 |
+
</cfscript>
|
1549 |
+
|
1550 |
+
ColdFusion 8 through current
|
1551 |
+
|
1552 |
+
<cfscript>
|
1553 |
+
for (x = 1; x <= listLen(foo); x++) {
|
1554 |
+
writeOutput("<li>" & listGetAt(foo, x) & "</li>");
|
1555 |
+
}
|
1556 |
+
</cfscript>
|
1557 |
+
|
1558 |
+
ColdFusion 9 through current
|
1559 |
+
|
1560 |
+
<cfscript>
|
1561 |
+
for (x in foo) {
|
1562 |
+
writeOutput("<li>" & x & "</li>");
|
1563 |
+
}
|
1564 |
+
</cfscript>
|
1565 |
+
|
1566 |
+
ColdFusion 11 through current
|
1567 |
+
|
1568 |
+
The cfscript function cfloop has no support for list.
|
1569 |
+
|
1570 |
+
Generated HTML
|
1571 |
+
|
1572 |
+
Notice that the cfscript output is all on one line.
|
1573 |
+
|
1574 |
+
<li>one</li><li>two</li><li>three</li><li>four</li>
|
1575 |
+
|
1576 |
+
Array
|
1577 |
+
|
1578 |
+
The ability to directly use an array object with cfloop was added in ColdFusion 8.
|
1579 |
+
|
1580 |
+
Consider this array;
|
1581 |
+
|
1582 |
+
<cfset aFoo = [
|
1583 |
+
"one"
|
1584 |
+
, "two"
|
1585 |
+
, "three"
|
1586 |
+
, "four"
|
1587 |
+
] />
|
1588 |
+
|
1589 |
+
Tag syntax
|
1590 |
+
|
1591 |
+
ColdFusion 8 through current
|
1592 |
+
|
1593 |
+
https://riptutorial.com/
|
1594 |
+
|
1595 |
+
17
|
1596 |
+
|
1597 |
+
Using the attribute index by itself.
|
1598 |
+
|
1599 |
+
Parameters
|
1600 |
+
|
1601 |
+
Attribute Required Default Description
|
1602 |
+
|
1603 |
+
array
|
1604 |
+
|
1605 |
+
true
|
1606 |
+
|
1607 |
+
An array object. The variable must be evaluated (wrapped
|
1608 |
+
with ##)
|
1609 |
+
|
1610 |
+
index
|
1611 |
+
|
1612 |
+
true
|
1613 |
+
|
1614 |
+
The current element of the array.
|
1615 |
+
|
1616 |
+
<cfoutput>
|
1617 |
+
<cfloop array="#aFoo#" index="x">
|
1618 |
+
<li>#x#</li>
|
1619 |
+
</cfloop>
|
1620 |
+
</cfoutput>
|
1621 |
+
|
1622 |
+
Generated HTML
|
1623 |
+
|
1624 |
+
This will also have a line break between each line of HTML.
|
1625 |
+
|
1626 |
+
<li>one</li>
|
1627 |
+
<li>two</li>
|
1628 |
+
<li>three</li>
|
1629 |
+
<li>four</li>
|
1630 |
+
|
1631 |
+
ColdFusion 2016 through current
|
1632 |
+
|
1633 |
+
The attribute item changes the behavior of cfloop as of Coldfusion 2016.
|
1634 |
+
|
1635 |
+
Using the attribute item instead of or in addition to index.
|
1636 |
+
|
1637 |
+
Parameters
|
1638 |
+
|
1639 |
+
Attribute Required Default Description
|
1640 |
+
|
1641 |
+
array
|
1642 |
+
|
1643 |
+
true
|
1644 |
+
|
1645 |
+
An array object. The variable must be evaluated (wrapped
|
1646 |
+
with ##)
|
1647 |
+
|
1648 |
+
item
|
1649 |
+
|
1650 |
+
true
|
1651 |
+
|
1652 |
+
The current element of the array.
|
1653 |
+
|
1654 |
+
index
|
1655 |
+
|
1656 |
+
false
|
1657 |
+
|
1658 |
+
The current index of the array.
|
1659 |
+
|
1660 |
+
<cfoutput>
|
1661 |
+
<cfloop array="#aFoo#" item="x" index="y">
|
1662 |
+
<li>#x# | #y#</li>
|
1663 |
+
</cfloop>
|
1664 |
+
</cfoutput>
|
1665 |
+
|
1666 |
+
https://riptutorial.com/
|
1667 |
+
|
1668 |
+
18
|
1669 |
+
|
1670 |
+
Generated HTML
|
1671 |
+
|
1672 |
+
This will also have a line break between each line of HTML.
|
1673 |
+
|
1674 |
+
<li>one | 1</li>
|
1675 |
+
<li>two | 2</li>
|
1676 |
+
<li>three | 3</li>
|
1677 |
+
<li>four | 4</li>
|
1678 |
+
|
1679 |
+
CFScript
|
1680 |
+
|
1681 |
+
Previous to ColdFusion 8
|
1682 |
+
|
1683 |
+
<cfscript>
|
1684 |
+
for (i = 1; x LTE arrayLen(aFoo); i = i + 1) {
|
1685 |
+
writeOutput("<li>" & aFoo[i] & "</li>");
|
1686 |
+
}
|
1687 |
+
</cfscript>
|
1688 |
+
|
1689 |
+
ColdFusion 8 through current
|
1690 |
+
|
1691 |
+
<cfscript>
|
1692 |
+
for (i = 1; i <= arrayLen(aFoo); i = i++) {
|
1693 |
+
writeOutput("<li>" & aFoo[i] & "</li>");
|
1694 |
+
}
|
1695 |
+
</cfscript>
|
1696 |
+
|
1697 |
+
ColdFusion 9 through current
|
1698 |
+
|
1699 |
+
With the FOR IN syntax, x is the current array element, not the array index.
|
1700 |
+
|
1701 |
+
<cfscript>
|
1702 |
+
for (x in aFoo) {
|
1703 |
+
writeOutput("<li>" & x & "</li>");
|
1704 |
+
}
|
1705 |
+
</cfscript>
|
1706 |
+
|
1707 |
+
ColdFusion 11 through current
|
1708 |
+
|
1709 |
+
The cfscript function cfloop has no support for array.
|
1710 |
+
|
1711 |
+
Generated HTML
|
1712 |
+
|
1713 |
+
Notice that the cfscript output is all on one line.
|
1714 |
+
|
1715 |
+
https://riptutorial.com/
|
1716 |
+
|
1717 |
+
19
|
1718 |
+
|
1719 |
+
<li>one</li><li>two</li><li>three</li><li>four</li>
|
1720 |
+
|
1721 |
+
File
|
1722 |
+
|
1723 |
+
<cfloop list="#myFile#" index="FileItem" delimiters="#chr(10)##chr(13)#">
|
1724 |
+
<cfoutput>
|
1725 |
+
#FileItem#<br />
|
1726 |
+
</cfoutput>
|
1727 |
+
</cfloop>
|
1728 |
+
|
1729 |
+
Structure
|
1730 |
+
|
1731 |
+
Consider this structure:
|
1732 |
+
|
1733 |
+
<cfset stFoo = {
|
1734 |
+
a = "one"
|
1735 |
+
, b = "two"
|
1736 |
+
, c = "three"
|
1737 |
+
, d = "foue"
|
1738 |
+
} />
|
1739 |
+
|
1740 |
+
Tag syntax
|
1741 |
+
|
1742 |
+
Parameters
|
1743 |
+
|
1744 |
+
Notice the use of the attribute item instead of index.
|
1745 |
+
|
1746 |
+
Attribute Required Type
|
1747 |
+
|
1748 |
+
Default Description
|
1749 |
+
|
1750 |
+
collection true
|
1751 |
+
|
1752 |
+
structure
|
1753 |
+
|
1754 |
+
A struct object. The variable must be evaluated
|
1755 |
+
(wrapped with ##).
|
1756 |
+
|
1757 |
+
item
|
1758 |
+
|
1759 |
+
true
|
1760 |
+
|
1761 |
+
string
|
1762 |
+
|
1763 |
+
The current structure key,
|
1764 |
+
|
1765 |
+
Using Structure Functions
|
1766 |
+
|
1767 |
+
<cfoutput>
|
1768 |
+
<cfloop collection="#stFoo#" item="x">
|
1769 |
+
<li>#structFind(stFoo, x)#</li>
|
1770 |
+
</cfloop>
|
1771 |
+
</cfoutput>
|
1772 |
+
|
1773 |
+
Implicit Structure Syntax
|
1774 |
+
|
1775 |
+
<cfoutput>
|
1776 |
+
<cfloop collection="#stFoo#" item="x">
|
1777 |
+
|
1778 |
+
https://riptutorial.com/
|
1779 |
+
|
1780 |
+
20
|
1781 |
+
|
1782 |
+
<li>#stFoo[x]#</li>
|
1783 |
+
</cfloop>
|
1784 |
+
</cfoutput>
|
1785 |
+
|
1786 |
+
Generated HTML
|
1787 |
+
|
1788 |
+
This will also have a line break between each line of HTML.
|
1789 |
+
|
1790 |
+
<li>one</li>
|
1791 |
+
<li>two</li>
|
1792 |
+
<li>three</li>
|
1793 |
+
<li>four</li>
|
1794 |
+
|
1795 |
+
CFScript
|
1796 |
+
|
1797 |
+
With the FOR IN syntax, x is a key of the structure object.
|
1798 |
+
|
1799 |
+
Output the structure's keys
|
1800 |
+
|
1801 |
+
<cfscript>
|
1802 |
+
for (x in stFoo) {
|
1803 |
+
writeOutput("<li>" & x & "</li>");
|
1804 |
+
}
|
1805 |
+
</cfscript>
|
1806 |
+
|
1807 |
+
Generated HTML
|
1808 |
+
|
1809 |
+
<li>A</li><li>B</li><li>C</li><li>D</li>
|
1810 |
+
|
1811 |
+
Output the value of the structure's keys
|
1812 |
+
|
1813 |
+
Using Structure Functions
|
1814 |
+
|
1815 |
+
<cfscript>
|
1816 |
+
for (x in stFoo) {
|
1817 |
+
writeOutput("<li>" & structFind(stFoo, x) & "</li>");
|
1818 |
+
}
|
1819 |
+
</cfscript>
|
1820 |
+
|
1821 |
+
Implicit Structure Syntax
|
1822 |
+
|
1823 |
+
<cfscript>
|
1824 |
+
for (x in stFoo) {
|
1825 |
+
writeOutput("<li>" & stFoo[x] & "</li>");
|
1826 |
+
}
|
1827 |
+
</cfscript>
|
1828 |
+
|
1829 |
+
https://riptutorial.com/
|
1830 |
+
|
1831 |
+
21
|
1832 |
+
|
1833 |
+
ColdFusion 11 through current
|
1834 |
+
|
1835 |
+
The cfscript function cfloop has no support for collection.
|
1836 |
+
|
1837 |
+
Generated HTML
|
1838 |
+
|
1839 |
+
Notice that the cfscript output is all on one line.
|
1840 |
+
|
1841 |
+
<li>one</li><li>two</li><li>three</li><li>four</li>
|
1842 |
+
|
1843 |
+
Index Loop
|
1844 |
+
|
1845 |
+
Use the from and to attributes to specify how many iterations should occur. The (optional) step
|
1846 |
+
attribute allows you to determine how big the increments will be.
|
1847 |
+
|
1848 |
+
<cfloop from="1" to="10" index="i" step="2">
|
1849 |
+
<cfoutput>
|
1850 |
+
#i#<br />
|
1851 |
+
</cfoutput>
|
1852 |
+
</cfloop>
|
1853 |
+
|
1854 |
+
Conditional Loop
|
1855 |
+
|
1856 |
+
You use the condition attribute to specify the condition to use.
|
1857 |
+
|
1858 |
+
<cfset myVar=false>
|
1859 |
+
<cfloop condition="myVar eq false">
|
1860 |
+
<cfoutput>
|
1861 |
+
myVar = <b>#myVar#</b> (still in loop)<br />
|
1862 |
+
</cfoutput>
|
1863 |
+
<cfif RandRange(1,10) eq 10>
|
1864 |
+
<cfset myVar="true">
|
1865 |
+
</cfif>
|
1866 |
+
</cfloop>
|
1867 |
+
<cfoutput>
|
1868 |
+
myVar = <b>#myVar#</b> (loop has finished)
|
1869 |
+
</cfoutput>
|
1870 |
+
|
1871 |
+
Query Loop
|
1872 |
+
|
1873 |
+
You can loop over the results of a ColdFusion query.
|
1874 |
+
|
1875 |
+
<cfquery name="getMovies" datasource="Entertainment">
|
1876 |
+
select top 4 movieName
|
1877 |
+
from Movies
|
1878 |
+
</cfquery>
|
1879 |
+
<cfloop query="getMovies">
|
1880 |
+
#movieName#
|
1881 |
+
</cfloop>
|
1882 |
+
|
1883 |
+
https://riptutorial.com/
|
1884 |
+
|
1885 |
+
22
|
1886 |
+
|
1887 |
+
List Loop
|
1888 |
+
|
1889 |
+
You can use the (optional) delimiters attribute to specify which characters are used as separators
|
1890 |
+
in the list.
|
1891 |
+
|
1892 |
+
<cfloop list="ColdFusion,HTML;XML" index="ListItem" delimiters=",;">
|
1893 |
+
<cfoutput>
|
1894 |
+
#ListItem#<br />
|
1895 |
+
</cfoutput>
|
1896 |
+
</cfloop>
|
1897 |
+
|
1898 |
+
File Loop
|
1899 |
+
|
1900 |
+
You can loop over a file.
|
1901 |
+
|
1902 |
+
<cfloop file="#myFile#" index="line">
|
1903 |
+
<cfoutput>
|
1904 |
+
#line#<br />
|
1905 |
+
</cfoutput>
|
1906 |
+
</cfloop>
|
1907 |
+
|
1908 |
+
COM Collection/Structure Loops
|
1909 |
+
|
1910 |
+
You can loop over a Structure or COM collection.
|
1911 |
+
|
1912 |
+
<cfset myBooks = StructNew()>
|
1913 |
+
<cfset myVariable = StructInsert(myBooks,"ColdFusion","ColdFusion MX Bible")>
|
1914 |
+
<cfset myVariable = StructInsert(myBooks,"HTML","HTML Visual QuickStart")>
|
1915 |
+
<cfset myVariable = StructInsert(myBooks,"XML","Inside XML")>
|
1916 |
+
<cfloop collection="#myBooks#" item="subject">
|
1917 |
+
<cfoutput>
|
1918 |
+
<b>#subject#:</b> #StructFind(myBooks,subject)#<br />
|
1919 |
+
</cfoutput>
|
1920 |
+
</cfloop>
|
1921 |
+
|
1922 |
+
Read CFLOOP How-To online: https://riptutorial.com/coldfusion/topic/3035/cfloop-how-to
|
1923 |
+
|
1924 |
+
https://riptutorial.com/
|
1925 |
+
|
1926 |
+
23
|
1927 |
+
|
1928 |
+
Chapter 3: cfquery
|
1929 |
+
|
1930 |
+
Parameters
|
1931 |
+
|
1932 |
+
Parameter Details
|
1933 |
+
|
1934 |
+
name
|
1935 |
+
|
1936 |
+
Value: string, Default: yes
|
1937 |
+
|
1938 |
+
dbtype
|
1939 |
+
|
1940 |
+
Value: query/hql, Default: no, Remarks: when left blank, it's a normal query
|
1941 |
+
|
1942 |
+
datasource Default: no, Remarks: database
|
1943 |
+
|
1944 |
+
params
|
1945 |
+
|
1946 |
+
Value: structure, Default: no, Remarks: cfscript syntax only! In cfml they are
|
1947 |
+
written inside SLQ stament using <cfqueryparam />
|
1948 |
+
|
1949 |
+
Examples
|
1950 |
+
|
1951 |
+
Using cfquery within a Function
|
1952 |
+
|
1953 |
+
<cffunction name="getUserById" access="public" returntype="query">
|
1954 |
+
<cfargument name="userId" type="numeric" required="yes" hint="The ID of the user">
|
1955 |
+
|
1956 |
+
<cfquery name="local.qryGetUser" datasource="DATABASE_NAME">
|
1957 |
+
SELECT id,
|
1958 |
+
name
|
1959 |
+
FROM user
|
1960 |
+
WHERE id = <cfqueryparam value="#arguments.userId#" cfsqltype="cf_sql_integer">
|
1961 |
+
</cfquery>
|
1962 |
+
|
1963 |
+
<cfreturn local.qryGetUser>
|
1964 |
+
</cffunction>
|
1965 |
+
|
1966 |
+
Query of Query
|
1967 |
+
|
1968 |
+
Function Calls
|
1969 |
+
|
1970 |
+
<!--- Load the user object based on the component path. --->
|
1971 |
+
<cfset local.user = new com.User() />
|
1972 |
+
<cfset local.allUsers = user.getAllUsers()>
|
1973 |
+
<cfset local.specificUser = user.getUserIdFromQry(qry = local.allUsers, userId = 1)>
|
1974 |
+
|
1975 |
+
User.cfc
|
1976 |
+
|
1977 |
+
<cfcomponent>
|
1978 |
+
<cffunction name="getAllUsers" access="public" returntype="query">
|
1979 |
+
<cfquery name="local.qryGetAllUsers" datasource="DATABASE_NAME">
|
1980 |
+
|
1981 |
+
https://riptutorial.com/
|
1982 |
+
|
1983 |
+
24
|
1984 |
+
|
1985 |
+
|
1986 |
+
|
1987 |
+
SELECT id,
|
1988 |
+
name
|
1989 |
+
FROM user
|
1990 |
+
</cfquery>
|
1991 |
+
|
1992 |
+
<cfreturn local.qryGetAllUsers>
|
1993 |
+
</cffunction>
|
1994 |
+
|
1995 |
+
<cffunction name="getUserIdFromQry" access="public" returntype="query">
|
1996 |
+
<cfargument name="qry" type="query" required="Yes" hint="Query to fetch from">
|
1997 |
+
<cfargument name="userId" type="numeric" required="Yes" hint="The ID of the user">
|
1998 |
+
|
1999 |
+
<cfquery name="local.qryGetUserIdFromQry" dbtype="query">
|
2000 |
+
SELECT id,
|
2001 |
+
name
|
2002 |
+
FROM arguments.qry
|
2003 |
+
WHERE id = <cfqueryparam value="#arguments.userId#" cfsqltype="cf_sql_integer">
|
2004 |
+
</cfquery>
|
2005 |
+
|
2006 |
+
<cfreturn local.qryGetUserIdFromQry>
|
2007 |
+
</cffunction>
|
2008 |
+
</component>
|
2009 |
+
|
2010 |
+
Read cfquery online: https://riptutorial.com/coldfusion/topic/6452/cfquery
|
2011 |
+
|
2012 |
+
https://riptutorial.com/
|
2013 |
+
|
2014 |
+
25
|
2015 |
+
|
2016 |
+
|
2017 |
+
|
2018 |
+
|
2019 |
+
|
2020 |
+
Chapter 4: ColdFusion Arrays
|
2021 |
+
|
2022 |
+
Syntax
|
2023 |
+
|
2024 |
+
•
|
2025 |
+
|
2026 |
+
ArrayNew(dimension, isSynchronized)
|
2027 |
+
|
2028 |
+
Parameters
|
2029 |
+
|
2030 |
+
Name
|
2031 |
+
|
2032 |
+
Description
|
2033 |
+
|
2034 |
+
Dimension
|
2035 |
+
|
2036 |
+
Number of dimensions in new array: 1, 2, or 3
|
2037 |
+
|
2038 |
+
isSynchronized
|
2039 |
+
|
2040 |
+
When false, creates an unsynchronized array, When true, the function
|
2041 |
+
returns a synchronized array.
|
2042 |
+
|
2043 |
+
Remarks
|
2044 |
+
|
2045 |
+
In a synchronized array, more than two threads cannot access the array simultaneously. Other
|
2046 |
+
threads has to wait until the active thread completes its job, resulting in significant performance.
|
2047 |
+
|
2048 |
+
In 2016 ColdFusion release, you can use an unsynchronized array and let multiple threads access
|
2049 |
+
the same array object simultaneously.
|
2050 |
+
|
2051 |
+
Examples
|
2052 |
+
|
2053 |
+
Creating Arrays
|
2054 |
+
|
2055 |
+
Creating arrays explicitly using ArrayNew()
|
2056 |
+
|
2057 |
+
Declare an array with the ArrayNew function. Specify the number of dimensions as an argument.
|
2058 |
+
|
2059 |
+
•
|
2060 |
+
•
|
2061 |
+
•
|
2062 |
+
|
2063 |
+
ArrayNew(dimension) creates an array of 1–3 dimensions.
|
2064 |
+
ColdFusion arrays expand dynamically as data is added.
|
2065 |
+
ArrayNew() returns an array.
|
2066 |
+
|
2067 |
+
History
|
2068 |
+
|
2069 |
+
Introduced in ColdFusion MX 6
|
2070 |
+
|
2071 |
+
Declaration
|
2072 |
+
|
2073 |
+
CFML
|
2074 |
+
|
2075 |
+
https://riptutorial.com/
|
2076 |
+
|
2077 |
+
26
|
2078 |
+
|
2079 |
+
<!--- One Dimension Array--->
|
2080 |
+
<cfset oneDimensionArray = ArrayNew(1)>
|
2081 |
+
|
2082 |
+
CFScript Note that inside a function you should use var scoping. Earlier versions of CF required
|
2083 |
+
var scoping to be the first thing in a function; later versions allow it anywhere in a function.
|
2084 |
+
|
2085 |
+
<cfscript>
|
2086 |
+
oneDimensionArray = ArrayNew(1);
|
2087 |
+
|
2088 |
+
public void function myFunc() {
|
2089 |
+
var oneDimensionArray = ArrayNew(1);
|
2090 |
+
}
|
2091 |
+
</cfscript>
|
2092 |
+
|
2093 |
+
After creating the array, add elements by using the element indexes. The Coldfusion Array index
|
2094 |
+
starts from 1:
|
2095 |
+
|
2096 |
+
CFML
|
2097 |
+
|
2098 |
+
<cfset oneDimensionArray[1] = 1>
|
2099 |
+
<cfset oneDimensionArray[2] = 'one'>
|
2100 |
+
<cfset oneDimensionArray[3] = '1'>
|
2101 |
+
|
2102 |
+
CFScript
|
2103 |
+
|
2104 |
+
<cfscript>
|
2105 |
+
oneDimensionArray[1] = 1;
|
2106 |
+
oneDimensionArray[2] = 'one';
|
2107 |
+
oneDimensionArray[3] = '1';
|
2108 |
+
</cfscript>
|
2109 |
+
|
2110 |
+
Using ArrayAppend()
|
2111 |
+
|
2112 |
+
You can add elements to an array using the function ArrayAppend(array, value).
|
2113 |
+
|
2114 |
+
<cfscript>
|
2115 |
+
ArrayAppend(oneDimensionArray, 1);
|
2116 |
+
ArrayAppend(oneDimensionArray, 'one');
|
2117 |
+
ArrayAppend(oneDimensionArray, '1');
|
2118 |
+
</cfscript>
|
2119 |
+
|
2120 |
+
Output the array contents using <cfdump>:
|
2121 |
+
|
2122 |
+
<cfdump var="#oneDimensionArray#">
|
2123 |
+
|
2124 |
+
Results:
|
2125 |
+
|
2126 |
+
https://riptutorial.com/
|
2127 |
+
|
2128 |
+
27
|
2129 |
+
|
2130 |
+
|
2131 |
+
CFML
|
2132 |
+
|
2133 |
+
<!--- Two Dimension Array--->
|
2134 |
+
<cfset twoDimensionArray = ArrayNew(2)>
|
2135 |
+
<cfset twoDimensionArray[1][1] = 1>
|
2136 |
+
<cfset twoDimensionArray[1][2] = 2>
|
2137 |
+
<cfset twoDimensionArray[2][1] = 3>
|
2138 |
+
<cfset twoDimensionArray[2][2] = 4>
|
2139 |
+
|
2140 |
+
CFScript
|
2141 |
+
|
2142 |
+
<cfscript>
|
2143 |
+
twoDimensionArray = ArrayNew(2);
|
2144 |
+
|
2145 |
+
twoDimensionArray[1][1] = 1;
|
2146 |
+
twoDimensionArray[1][2] = 2;
|
2147 |
+
twoDimensionArray[2][1] = 3;
|
2148 |
+
twoDimensionArray[2][2] = 4;
|
2149 |
+
</cfscript>
|
2150 |
+
|
2151 |
+
Outputting the contents of array using <cfdump>
|
2152 |
+
|
2153 |
+
<cfdump var="#twoDimensionArray#">
|
2154 |
+
|
2155 |
+
Result:
|
2156 |
+
|
2157 |
+
Each element contains another Array, which will store the values.
|
2158 |
+
|
2159 |
+
Creating 1-D Array Implicitly
|
2160 |
+
|
2161 |
+
When creating an array implicitly, brackets ([]) surround the array contents with comma
|
2162 |
+
separators.
|
2163 |
+
|
2164 |
+
<cfset oneDimensionArrayImplicit = [ 1 ,'one','1' ]>
|
2165 |
+
|
2166 |
+
https://riptutorial.com/
|
2167 |
+
|
2168 |
+
28
|
2169 |
+
|
2170 |
+
|
2171 |
+
This statement is equivalent to the four statements used to create the above oneDimensionArray.
|
2172 |
+
The result are the same when using:
|
2173 |
+
|
2174 |
+
<cfdump var="#oneDimensionArrayImplicit#">
|
2175 |
+
|
2176 |
+
Create 2-D Array Implicitly
|
2177 |
+
|
2178 |
+
<cfset twoDimensionArrayImplicit = [[ 1 , 2 ],[ 3 , 4 ],[ 5 , 6 ]]>
|
2179 |
+
|
2180 |
+
Or:
|
2181 |
+
|
2182 |
+
<cfset firstElement = ["1", "2"]>
|
2183 |
+
<cfset secondElement= ["3", "4"]>
|
2184 |
+
<cfset thirdElement = ["5", "6"]>
|
2185 |
+
<cfset twoDimensionArrayImplicit = [firstElement , secondElement, thirdElement]>
|
2186 |
+
|
2187 |
+
Outputting the content using
|
2188 |
+
|
2189 |
+
<cfdump var="#twoDimensionArrayImplicit#">
|
2190 |
+
|
2191 |
+
Alternative Explicit Declaration
|
2192 |
+
|
2193 |
+
Also you can declare 1 Dimension Array as
|
2194 |
+
|
2195 |
+
<cfset oneDimensionArray = []>
|
2196 |
+
|
2197 |
+
<cfscript>
|
2198 |
+
oneDimensionArray = [];
|
2199 |
+
</cfscript>
|
2200 |
+
|
2201 |
+
This declaration is same as that of using ArrayNew(1).
|
2202 |
+
|
2203 |
+
But if you try declaring 2 Dimension Array as
|
2204 |
+
|
2205 |
+
<cfset twoDimensionArray =[][]> //Invalid CFML construct
|
2206 |
+
|
2207 |
+
https://riptutorial.com/
|
2208 |
+
|
2209 |
+
29
|
2210 |
+
|
2211 |
+
|
2212 |
+
an error will occur while processing this request.
|
2213 |
+
|
2214 |
+
Following statement will process the request:
|
2215 |
+
|
2216 |
+
<cfset twoDimensionArray =[]>
|
2217 |
+
|
2218 |
+
but variable twoDimensionArray will not actually an Array within Array (or 2-Dimension Array). It
|
2219 |
+
actually contains structure within Array.
|
2220 |
+
|
2221 |
+
<cfset twoDimensionArray =[]>
|
2222 |
+
<cfset twoDimensionArray[1][1] = 1>
|
2223 |
+
<cfset twoDimensionArray[1][2] = 2>
|
2224 |
+
<cfset twoDimensionArray[2][1] = 3>
|
2225 |
+
<cfset twoDimensionArray[2][2] = 4>
|
2226 |
+
|
2227 |
+
<cfdump var="#twoDimensionArray#">
|
2228 |
+
|
2229 |
+
Result:
|
2230 |
+
|
2231 |
+
Array in CFScript
|
2232 |
+
|
2233 |
+
<cfscript>
|
2234 |
+
oneDimensionArray = ArrayNew(1);
|
2235 |
+
oneDimensionArray[1] = 1;
|
2236 |
+
oneDimensionArray[2] = 'one';
|
2237 |
+
oneDimensionArray[3] = '1';
|
2238 |
+
</cfscript>
|
2239 |
+
|
2240 |
+
<cfif IsDefined("oneDimensionArray")>
|
2241 |
+
<cfdump var="#oneDimensionArray#">
|
2242 |
+
</cfif>
|
2243 |
+
|
2244 |
+
Result:
|
2245 |
+
|
2246 |
+
Also, we can declare an one Dimension Array as:
|
2247 |
+
|
2248 |
+
https://riptutorial.com/
|
2249 |
+
|
2250 |
+
30
|
2251 |
+
|
2252 |
+
|
2253 |
+
|
2254 |
+
oneDimensionArray = [];
|
2255 |
+
|
2256 |
+
Alternatively, CF introduced WriteDump() from CF9 as a function equivalent to the <cfdump> tag
|
2257 |
+
which can be used in <cfscript>.
|
2258 |
+
|
2259 |
+
<cfscript>
|
2260 |
+
WriteDump(oneDimensionArray);
|
2261 |
+
</cfscript>
|
2262 |
+
|
2263 |
+
Similarly, for 2 Dimension Array:
|
2264 |
+
|
2265 |
+
<cfscript>
|
2266 |
+
twoDimensionArray = ArrayNew(2);
|
2267 |
+
twoDimensionArray[1][1] = 1;
|
2268 |
+
twoDimensionArray[1][2] = 2;
|
2269 |
+
twoDimensionArray[2][1] = 3;
|
2270 |
+
twoDimensionArray[2][2] = 4;
|
2271 |
+
</cfscript>
|
2272 |
+
<cfdump var="#twoDimensionArray#">
|
2273 |
+
|
2274 |
+
Result:
|
2275 |
+
|
2276 |
+
General information
|
2277 |
+
|
2278 |
+
First some general information about how arrays behave in Coldfusion as compared to other
|
2279 |
+
programming languages.
|
2280 |
+
|
2281 |
+
•
|
2282 |
+
|
2283 |
+
•
|
2284 |
+
•
|
2285 |
+
|
2286 |
+
Arrays can have numeric indexes only (if you want to have a string index use structs
|
2287 |
+
instead)
|
2288 |
+
Arrays begin at index [1]
|
2289 |
+
Arrays can have one ore more dimensions
|
2290 |
+
|
2291 |
+
Read ColdFusion Arrays online: https://riptutorial.com/coldfusion/topic/6896/coldfusion-arrays
|
2292 |
+
|
2293 |
+
https://riptutorial.com/
|
2294 |
+
|
2295 |
+
31
|
2296 |
+
|
2297 |
+
Chapter 5: Creating REST APIs in coldfusion
|
2298 |
+
|
2299 |
+
Introduction
|
2300 |
+
|
2301 |
+
REST APIs are interesting when data should be accessed from everywhere including different
|
2302 |
+
languages (server and client side). That requires separation from data and processing.
|
2303 |
+
|
2304 |
+
Examples
|
2305 |
+
|
2306 |
+
Creating backend
|
2307 |
+
|
2308 |
+
<cfcomponent displayname="myAPI" output="false">
|
2309 |
+
<cffunction name="init" access="public" output="no">
|
2310 |
+
<!--- do some basic stuff --->
|
2311 |
+
<cfreturn this>
|
2312 |
+
</cffunction>
|
2313 |
+
|
2314 |
+
<cffunction name="welcome">
|
2315 |
+
<cfreturn "Hello World!">
|
2316 |
+
</cffunction>
|
2317 |
+
</cfcomponent>
|
2318 |
+
|
2319 |
+
The interface
|
2320 |
+
|
2321 |
+
<cfscript>
|
2322 |
+
api_request = GetHttpRequestData();
|
2323 |
+
api = createObject("component","myAPI").init();
|
2324 |
+
</cfscript>
|
2325 |
+
|
2326 |
+
<cfif api_request.method is 'GET'>
|
2327 |
+
<cfoutput>#api.welcome()#</cfoutput>
|
2328 |
+
<cfelseif api_request.method is 'POST'>
|
2329 |
+
<cfheader statuscode="500" statustext="Internal Server Error" />
|
2330 |
+
</cfif>
|
2331 |
+
|
2332 |
+
Read Creating REST APIs in coldfusion online:
|
2333 |
+
https://riptutorial.com/coldfusion/topic/10698/creating-rest-apis-in-coldfusion
|
2334 |
+
|
2335 |
+
https://riptutorial.com/
|
2336 |
+
|
2337 |
+
32
|
2338 |
+
|
2339 |
+
|
2340 |
+
|
2341 |
+
Chapter 6: Database Queries
|
2342 |
+
|
2343 |
+
Examples
|
2344 |
+
|
2345 |
+
Working with databases
|
2346 |
+
|
2347 |
+
One of ColdFusion's strengths is how easy it is to work with databases. And of course, query
|
2348 |
+
inputs can and should be parameterized.
|
2349 |
+
|
2350 |
+
Tag Implementation
|
2351 |
+
|
2352 |
+
<cfquery name="myQuery" datasource="myDatasource" result="myResult">
|
2353 |
+
select firstName, lastName
|
2354 |
+
from users
|
2355 |
+
where lastName = <cfqueryparam value="Allaire" cfsqltype="cf_sql_varchar">
|
2356 |
+
</cfquery>
|
2357 |
+
|
2358 |
+
CFScript Implementation
|
2359 |
+
|
2360 |
+
// ColdFusion 9+
|
2361 |
+
var queryService = new query(name="myQuery", datasource="myDatasource");
|
2362 |
+
queryService.addParam(name="lName", value="Allaire", cfsqltype="cf_sql_varchar");
|
2363 |
+
var result = queryService.execute(sql="select firstName, lastName from users where lastName =
|
2364 |
+
:lName");
|
2365 |
+
var myQuery = result.getResult();
|
2366 |
+
var myResult = result.getPrefix();
|
2367 |
+
|
2368 |
+
// ColdFusion 11+
|
2369 |
+
var queryParams = {lName = {value="Allaire", cfsqltype="cf_sql_varchar"}};
|
2370 |
+
var queryOptions = {datasource="myDatasource", result="myResult"};
|
2371 |
+
var myQuery = queryExecute("select firstName, lastName from users", queryParams,
|
2372 |
+
queryOptions);
|
2373 |
+
|
2374 |
+
Inserting values is just as easy:
|
2375 |
+
|
2376 |
+
queryExecute("
|
2377 |
+
insert into user( firstname, lastname )
|
2378 |
+
values( :firstname, :lastname )
|
2379 |
+
",{
|
2380 |
+
firstname: { cfsqltype: "cf_sql_varchar", value: "Dwayne" }
|
2381 |
+
,lastname: { cfsqltype: "cf_sql_varchar", value: "Camacho" }
|
2382 |
+
},{
|
2383 |
+
result: "local.insertResult"
|
2384 |
+
});
|
2385 |
+
|
2386 |
+
return local.insertResult.generated_key;
|
2387 |
+
|
2388 |
+
Basic Example
|
2389 |
+
|
2390 |
+
Database connections are set up using the CF Administrator tool. See Database Connections for
|
2391 |
+
how to connect a datasource.
|
2392 |
+
|
2393 |
+
https://riptutorial.com/
|
2394 |
+
|
2395 |
+
33
|
2396 |
+
|
2397 |
+
|
2398 |
+
|
2399 |
+
To execute queries all you need is the <cfquery> tag. The <cfquery> tag connects to and opens the
|
2400 |
+
database for you, all you need to do is supply it with the name of the datasource.
|
2401 |
+
|
2402 |
+
<cfquery name="Movies" datasource="Entertainment">
|
2403 |
+
SELECT title
|
2404 |
+
FROM Movies
|
2405 |
+
</cfquery>
|
2406 |
+
|
2407 |
+
To display the query results:
|
2408 |
+
|
2409 |
+
<cfoutput query="Movies">
|
2410 |
+
#title#<BR>
|
2411 |
+
</cfoutput>
|
2412 |
+
|
2413 |
+
Authentication
|
2414 |
+
|
2415 |
+
Many database configurations require authentication (in the form of a username and password)
|
2416 |
+
before you can query the database. You can supply these using the username and password
|
2417 |
+
attributes.
|
2418 |
+
|
2419 |
+
Note: the username and password can also be configured against the datasource in the
|
2420 |
+
ColdFusion Administrator. Supplying these details in your query overrides the username and
|
2421 |
+
password in the ColdFusion Administrator.
|
2422 |
+
|
2423 |
+
<cfquery datasource="Entertainment" username="webuser" password="letmein">
|
2424 |
+
select *
|
2425 |
+
from Movies
|
2426 |
+
</cfquery>
|
2427 |
+
|
2428 |
+
Cached Queries
|
2429 |
+
|
2430 |
+
A cached query is a query that has its results stored in the server's memory. The results are
|
2431 |
+
stored when the query is first run. From then on, whenever that query is requested again,
|
2432 |
+
ColdFusion will retrieve the results from memory.
|
2433 |
+
|
2434 |
+
You can cache a query using the cachedAfter attribute. If the query was last run after the supplied
|
2435 |
+
date, cached data is used. Otherwise the query is re-run.
|
2436 |
+
|
2437 |
+
<cfquery datasource="Entertainment" cachedAfter="July 20, 2016">
|
2438 |
+
select *
|
2439 |
+
from Movies
|
2440 |
+
</cfquery>
|
2441 |
+
|
2442 |
+
In order for the cache to be used, and multiple calls to the database be avoided the current query
|
2443 |
+
must use the same SQL statement, data source, query name, user name, and password as the
|
2444 |
+
cached query used. This includes whitespace in the query.
|
2445 |
+
|
2446 |
+
As such the following queries create different caches, even though the trimmed characters are the
|
2447 |
+
same and the query results are identical:
|
2448 |
+
|
2449 |
+
https://riptutorial.com/
|
2450 |
+
|
2451 |
+
34
|
2452 |
+
|
2453 |
+
<cfquery datasource="Entertainment" cachedAfter="July 20, 2016">
|
2454 |
+
select *
|
2455 |
+
from Movies
|
2456 |
+
<cfif false>
|
2457 |
+
where 1 = 1
|
2458 |
+
</cfif>
|
2459 |
+
<cfif true>
|
2460 |
+
where 1 = 1
|
2461 |
+
</cfif>
|
2462 |
+
</cfquery>
|
2463 |
+
|
2464 |
+
<cfquery datasource="Entertainment" cachedAfter="July 20, 2016">
|
2465 |
+
select *
|
2466 |
+
from Movies
|
2467 |
+
<cfif true>
|
2468 |
+
where 1 = 1
|
2469 |
+
</cfif>
|
2470 |
+
<cfif false>
|
2471 |
+
where 1 = 1
|
2472 |
+
</cfif>
|
2473 |
+
</cfquery>
|
2474 |
+
|
2475 |
+
Limiting the Number of Records Returned
|
2476 |
+
|
2477 |
+
You can limit the number of rows to be returned by using the maxrows attribute.
|
2478 |
+
|
2479 |
+
<cfquery datasource="Entertainment" maxrows="50">
|
2480 |
+
select *
|
2481 |
+
from Movies
|
2482 |
+
</cfquery>
|
2483 |
+
|
2484 |
+
Timeouts
|
2485 |
+
|
2486 |
+
You can set a timeout limit using the timeout attribute. This can be useful in preventing requests
|
2487 |
+
running far longer than they should and impacting on the whole application as a result.
|
2488 |
+
|
2489 |
+
The timeout attribute sets the maximum number of seconds that each action of a query is allowed
|
2490 |
+
to execute before returning an error.
|
2491 |
+
|
2492 |
+
<cfquery datasource="Entertainment" timeout="30">
|
2493 |
+
select *
|
2494 |
+
from Movies
|
2495 |
+
</cfquery>
|
2496 |
+
|
2497 |
+
Read Database Queries online: https://riptutorial.com/coldfusion/topic/4582/database-queries
|
2498 |
+
|
2499 |
+
https://riptutorial.com/
|
2500 |
+
|
2501 |
+
35
|
2502 |
+
|
2503 |
+
|
2504 |
+
Chapter 7: How to invoke a private method
|
2505 |
+
dynamically
|
2506 |
+
|
2507 |
+
Remarks
|
2508 |
+
|
2509 |
+
Use of <cfinvoke> or invoke() should be faster than evaluate()
|
2510 |
+
|
2511 |
+
Examples
|
2512 |
+
|
2513 |
+
CFML
|
2514 |
+
|
2515 |
+
<cfinvoke method="#somePrivateMethodName#">
|
2516 |
+
<cfinvokeargument name="argument1" value="one">
|
2517 |
+
</cfinvoke>
|
2518 |
+
|
2519 |
+
CFSCRIPT (CF10+)
|
2520 |
+
|
2521 |
+
invoke("", somePrivateMethodName, {argument1='one'});
|
2522 |
+
|
2523 |
+
Read How to invoke a private method dynamically online:
|
2524 |
+
https://riptutorial.com/coldfusion/topic/6110/how-to-invoke-a-private-method-dynamically
|
2525 |
+
|
2526 |
+
https://riptutorial.com/
|
2527 |
+
|
2528 |
+
36
|
2529 |
+
|
2530 |
+
Chapter 8: Scopes in Coldfusion
|
2531 |
+
|
2532 |
+
Introduction
|
2533 |
+
|
2534 |
+
A scope is "the range in which a variable can be referenced". ColdFusion knows — as well as
|
2535 |
+
most other programming and script languages — several scopes. The following text deals with
|
2536 |
+
these types and trys to bring clarity about them, their differences and their characteristics.
|
2537 |
+
|
2538 |
+
Examples
|
2539 |
+
|
2540 |
+
Request Scopes
|
2541 |
+
|
2542 |
+
request
|
2543 |
+
|
2544 |
+
variables
|
2545 |
+
|
2546 |
+
form
|
2547 |
+
|
2548 |
+
url
|
2549 |
+
|
2550 |
+
cgi
|
2551 |
+
|
2552 |
+
Global Scopes
|
2553 |
+
|
2554 |
+
Server
|
2555 |
+
|
2556 |
+
Application
|
2557 |
+
|
2558 |
+
Session
|
2559 |
+
|
2560 |
+
Components and functions
|
2561 |
+
|
2562 |
+
variables
|
2563 |
+
|
2564 |
+
this
|
2565 |
+
|
2566 |
+
local
|
2567 |
+
|
2568 |
+
arguments
|
2569 |
+
|
2570 |
+
Custom tags
|
2571 |
+
|
2572 |
+
attributes
|
2573 |
+
|
2574 |
+
thisTag
|
2575 |
+
|
2576 |
+
caller
|
2577 |
+
|
2578 |
+
https://riptutorial.com/
|
2579 |
+
|
2580 |
+
37
|
2581 |
+
|
2582 |
+
Common scopes
|
2583 |
+
|
2584 |
+
Mostly you're probably working with these scopes:
|
2585 |
+
|
2586 |
+
•
|
2587 |
+
|
2588 |
+
•
|
2589 |
+
|
2590 |
+
•
|
2591 |
+
•
|
2592 |
+
•
|
2593 |
+
|
2594 |
+
•
|
2595 |
+
|
2596 |
+
Variables scopeis the scope where all variables are assigned to when nothing else is
|
2597 |
+
intentionally declared (like the window scope in JavaScript).
|
2598 |
+
Form scopeWhen you send a form to your server, all the form fields which can be identified
|
2599 |
+
(by setting the name/id property) are accessible in this scope for further server-side
|
2600 |
+
processing.
|
2601 |
+
URL scopeAll url query params are stored in that scope
|
2602 |
+
this scopeInside a component the this refers to the component itself
|
2603 |
+
local scopeVariables declared inside a function using the local statement are encapsulated
|
2604 |
+
and only accessible inside that specific function (this is made to avoid pollution of other
|
2605 |
+
sopes)
|
2606 |
+
Arguments scopeArguments passed to a function inside a component declared by the
|
2607 |
+
cfargument tag are accessible with that scope
|
2608 |
+
|
2609 |
+
Overview
|
2610 |
+
|
2611 |
+
•
|
2612 |
+
|
2613 |
+
Components and functions
|
2614 |
+
|
2615 |
+
○
|
2616 |
+
|
2617 |
+
○
|
2618 |
+
|
2619 |
+
○
|
2620 |
+
|
2621 |
+
○
|
2622 |
+
|
2623 |
+
variables
|
2624 |
+
this
|
2625 |
+
local
|
2626 |
+
arguments
|
2627 |
+
|
2628 |
+
•
|
2629 |
+
|
2630 |
+
Custom tags
|
2631 |
+
|
2632 |
+
○
|
2633 |
+
|
2634 |
+
○
|
2635 |
+
|
2636 |
+
○
|
2637 |
+
|
2638 |
+
attributes
|
2639 |
+
thisTag
|
2640 |
+
caller
|
2641 |
+
|
2642 |
+
•
|
2643 |
+
|
2644 |
+
Global Scopes
|
2645 |
+
|
2646 |
+
○
|
2647 |
+
|
2648 |
+
○
|
2649 |
+
|
2650 |
+
○
|
2651 |
+
|
2652 |
+
Server
|
2653 |
+
Application
|
2654 |
+
Session
|
2655 |
+
|
2656 |
+
•
|
2657 |
+
|
2658 |
+
Request Scopes
|
2659 |
+
|
2660 |
+
○
|
2661 |
+
|
2662 |
+
○
|
2663 |
+
|
2664 |
+
○
|
2665 |
+
|
2666 |
+
○
|
2667 |
+
|
2668 |
+
○
|
2669 |
+
|
2670 |
+
request
|
2671 |
+
variables
|
2672 |
+
form
|
2673 |
+
url
|
2674 |
+
cgi
|
2675 |
+
|
2676 |
+
Read Scopes in Coldfusion online: https://riptutorial.com/coldfusion/topic/7864/scopes-in-
|
2677 |
+
coldfusion
|
2678 |
+
|
2679 |
+
https://riptutorial.com/
|
2680 |
+
|
2681 |
+
38
|
2682 |
+
|
2683 |
+
Chapter 9: Variables
|
2684 |
+
|
2685 |
+
Parameters
|
2686 |
+
|
2687 |
+
Attribute Description
|
2688 |
+
|
2689 |
+
name
|
2690 |
+
|
2691 |
+
(Required) Name of the parameter/variable.
|
2692 |
+
|
2693 |
+
default
|
2694 |
+
|
2695 |
+
(Optional) Value to set parameter to if it does not exist.
|
2696 |
+
|
2697 |
+
max
|
2698 |
+
|
2699 |
+
min
|
2700 |
+
|
2701 |
+
(Optional) The maximum valid value; used only for range validation.
|
2702 |
+
|
2703 |
+
(Optional) The minimum valid value; used only for range validation.
|
2704 |
+
|
2705 |
+
pattern
|
2706 |
+
|
2707 |
+
(Optional) A JavaScript regular expression that the parameter must match; used
|
2708 |
+
only for regex or regular_expression validation.
|
2709 |
+
|
2710 |
+
type
|
2711 |
+
|
2712 |
+
(Optional) The valid format for the data.
|
2713 |
+
|
2714 |
+
Examples
|
2715 |
+
|
2716 |
+
Using cfset
|
2717 |
+
|
2718 |
+
You can set a ColdFusion variable using the <cfset> tag. To output the variable, you need to
|
2719 |
+
surround the variable name with hash # symbols and enclose it within <cfoutput> tags.
|
2720 |
+
|
2721 |
+
<cfset variablename="World!">
|
2722 |
+
<cfoutput>
|
2723 |
+
Hello #variablename#
|
2724 |
+
</cfoutput>
|
2725 |
+
|
2726 |
+
Using cfparam
|
2727 |
+
|
2728 |
+
The <cfparam> tag creates a variable if it does not already exist. You can assign a default value
|
2729 |
+
using the default attribute. This can be used if you want to create a variable, but don't want to
|
2730 |
+
overwrite it if it has been previously created elsewhere.
|
2731 |
+
|
2732 |
+
Here the variable hasn't been set previously, so it will be assigned with the <cfparam> tag.
|
2733 |
+
|
2734 |
+
<cfparam name="firstName" default="Justin">
|
2735 |
+
<cfoutput>
|
2736 |
+
Hello #firstName#
|
2737 |
+
</cfoutput>
|
2738 |
+
|
2739 |
+
Here the variable has already been assigned using the <cfset> tag, so this value will override the
|
2740 |
+
default value in the <cfparam> tag.
|
2741 |
+
|
2742 |
+
https://riptutorial.com/
|
2743 |
+
|
2744 |
+
39
|
2745 |
+
|
2746 |
+
<cfset firstname="Justin">
|
2747 |
+
|
2748 |
+
<cfparam name="firstName" default="Barney">
|
2749 |
+
<cfoutput>
|
2750 |
+
Hello #firstName#
|
2751 |
+
</cfoutput>
|
2752 |
+
|
2753 |
+
Checking if a Variable Exists
|
2754 |
+
|
2755 |
+
You can check if a variable has been defined in a scope by using ColdFusion's built in
|
2756 |
+
StructKeyExists() function. This can be used inside a <cfif> tag to prevent error messages in the
|
2757 |
+
event you attempt to refer to a variable that does not exist. You can also use this function to
|
2758 |
+
determine whether a user has performed a certain action or not. The syntax for the function is
|
2759 |
+
|
2760 |
+
StructKeyExists(structure, "key")
|
2761 |
+
|
2762 |
+
The following example checks if the variable firstName exists in the variables scope.
|
2763 |
+
|
2764 |
+
<cfif StructKeyExists(variables, "firstName")>
|
2765 |
+
Hello #variables.firstname#!
|
2766 |
+
<cfelse>
|
2767 |
+
Hello stranger!
|
2768 |
+
</cfif>
|
2769 |
+
|
2770 |
+
Alternatively, you may use the function:
|
2771 |
+
|
2772 |
+
isDefined("scopeName.varName")
|
2773 |
+
|
2774 |
+
To avoid ambiguity, it is recommended to declare the scope. For example, If you have a variable
|
2775 |
+
in the scope test
|
2776 |
+
|
2777 |
+
<cfset test.name = "Tracy" />
|
2778 |
+
|
2779 |
+
and you test for name in the global scope, you will get a result of true.
|
2780 |
+
|
2781 |
+
isDefined("name") <!--- true --->
|
2782 |
+
isDefined("x.name") <!--- false--->
|
2783 |
+
isDefined("test.name") <!--- true --->
|
2784 |
+
|
2785 |
+
Setting a variable scope
|
2786 |
+
|
2787 |
+
It is a common practice to set application variables to an object scope. This keeps them easy to
|
2788 |
+
identify and distinguish from variables in other scopes.
|
2789 |
+
|
2790 |
+
The Variables scope in a CFC is private to the CFC. When you set variables in this scope, they
|
2791 |
+
cannot be seen by pages that invoke the CFC.
|
2792 |
+
|
2793 |
+
<cfparam name="variables.firstName" default="Timmy">
|
2794 |
+
<cfset variables.firstName="Justin">
|
2795 |
+
|
2796 |
+
https://riptutorial.com/
|
2797 |
+
|
2798 |
+
40
|
2799 |
+
|
2800 |
+
|
2801 |
+
Scopes shared with the calling page include: Form, URL, Request, CGI, Cookie, Client, Session,
|
2802 |
+
Application, Server, and Flash. Variables in these scopes are also available to all pages that are
|
2803 |
+
included by a CFC.
|
2804 |
+
|
2805 |
+
CFC:
|
2806 |
+
|
2807 |
+
<cfset url.sessionId="23b5ly17">
|
2808 |
+
|
2809 |
+
<cfinclude template="check_session.cfm">
|
2810 |
+
|
2811 |
+
check_session.cfm
|
2812 |
+
|
2813 |
+
<cfif url.sessionId eq "23b5ly17">
|
2814 |
+
<p>Welcome back!</p>
|
2815 |
+
</cfif>
|
2816 |
+
|
2817 |
+
Read Variables online: https://riptutorial.com/coldfusion/topic/4904/variables
|
2818 |
+
|
2819 |
+
https://riptutorial.com/
|
2820 |
+
|
2821 |
+
41
|
2822 |
+
|
2823 |
+
|
2824 |
+
Chapter 10: Working with RegExp Replace
|
2825 |
+
callbacks
|
2826 |
+
|
2827 |
+
Introduction
|
2828 |
+
|
2829 |
+
If you want more than a simple string replacement with common regular expressions you certainly
|
2830 |
+
run into trouble and hit the wall when discovering the limits of the regex functions Coldfusion has.
|
2831 |
+
There is no build-in function like php's preg_replace_callback.
|
2832 |
+
|
2833 |
+
Parameters
|
2834 |
+
|
2835 |
+
Parameter Details
|
2836 |
+
|
2837 |
+
re
|
2838 |
+
|
2839 |
+
str
|
2840 |
+
|
2841 |
+
The regular expression
|
2842 |
+
|
2843 |
+
The string which should be applyed the the regex
|
2844 |
+
|
2845 |
+
callback
|
2846 |
+
|
2847 |
+
The function where the captured grouped will be passed in if a match was
|
2848 |
+
found. There the matches can be processed
|
2849 |
+
|
2850 |
+
Remarks
|
2851 |
+
|
2852 |
+
Because Coldfusion itself does not offer what we want, we make recourse to the variety of Java,
|
2853 |
+
which is — as we all know — on top of Coldfusion. Java offers us java.util.regex.Pattern.
|
2854 |
+
|
2855 |
+
So here is what we actually do:
|
2856 |
+
|
2857 |
+
1.
|
2858 |
+
|
2859 |
+
2.
|
2860 |
+
|
2861 |
+
3.
|
2862 |
+
|
2863 |
+
Invoke the Compile method from the Pattern Class object and passing the regex pattern to it
|
2864 |
+
(which probably deposits the regex pattern for later use).
|
2865 |
+
Invoke the Matcher method on what the Compile method returned and passing the string
|
2866 |
+
where the pattern should be executed.
|
2867 |
+
Test if matching was successfull by invoking the find method on what the Matcher method
|
2868 |
+
returned.
|
2869 |
+
|
2870 |
+
If matcher.find() returns true, we could say "That's it", but there is one little thing we have to
|
2871 |
+
consider: Java's Pattern object stores the groups and gives us access via another function, which
|
2872 |
+
is not always the best way for further processing and not that consistent regarding how other
|
2873 |
+
programming languages handle this case. Therefore we loop over matcher.group() so that we can
|
2874 |
+
pass an array containing the captured groups to the callback function. And now we can say:
|
2875 |
+
"That's it!"
|
2876 |
+
|
2877 |
+
Examples
|
2878 |
+
|
2879 |
+
https://riptutorial.com/
|
2880 |
+
|
2881 |
+
42
|
2882 |
+
|
2883 |
+
User defined REReplaceCallback function
|
2884 |
+
|
2885 |
+
function REReplaceCallback(re,str,callback) {
|
2886 |
+
/*
|
2887 |
+
Thanks to Ben Nadel
|
2888 |
+
"Learning ColdFusion 8: REMatch() For Regular Expression Matching"
|
2889 |
+
from 2007-06-13
|
2890 |
+
https://www.bennadel.com/blog/769-learning-coldfusion-8-rematch-for-regular-
|
2891 |
+
expression-matching.htm
|
2892 |
+
*/
|
2893 |
+
pattern = CreateObject("java","java.util.regex.Pattern").Compile(Arguments.re);
|
2894 |
+
matcher = pattern.Matcher(Arguments.str);
|
2895 |
+
if(matcher.find()) {
|
2896 |
+
groups = [];
|
2897 |
+
for(var i = 1; i lte matcher.groupCount(); i++) {
|
2898 |
+
ArrayAppend(groups,matcher.group(Val(i)));
|
2899 |
+
}
|
2900 |
+
return Arguments.callback(groups);
|
2901 |
+
}
|
2902 |
+
else {
|
2903 |
+
return Arguments.callback(false);
|
2904 |
+
}
|
2905 |
+
}
|
2906 |
+
|
2907 |
+
Using REReplaceCallback function
|
2908 |
+
|
2909 |
+
REReplaceCallback('YOUR REGEX GOES HERE','AND YOUR STRING HERE',function(groups) {
|
2910 |
+
//now you can access the 'groups' array containing all the captured groups
|
2911 |
+
return result; //return whatever you've processed inside
|
2912 |
+
});
|
2913 |
+
|
2914 |
+
Read Working with RegExp Replace callbacks online:
|
2915 |
+
https://riptutorial.com/coldfusion/topic/10655/working-with-regexp-replace-callbacks
|
2916 |
+
|
2917 |
+
https://riptutorial.com/
|
2918 |
+
|
2919 |
+
43
|
2920 |
+
|
2921 |
+
Credits
|
2922 |
+
|
2923 |
+
S.
|
2924 |
+
No
|
2925 |
+
|
2926 |
+
1
|
2927 |
+
|
2928 |
+
2
|
2929 |
+
|
2930 |
+
3
|
2931 |
+
|
2932 |
+
4
|
2933 |
+
|
2934 |
+
5
|
2935 |
+
|
2936 |
+
6
|
2937 |
+
|
2938 |
+
7
|
2939 |
+
|
2940 |
+
8
|
2941 |
+
|
2942 |
+
9
|
2943 |
+
|
2944 |
+
Chapters
|
2945 |
+
|
2946 |
+
Contributors
|
2947 |
+
|
2948 |
+
Getting started with
|
2949 |
+
coldfusion
|
2950 |
+
|
2951 |
+
Adam Tuttle, Adrian J. Moreno, Community, Justin Duhaime,
|
2952 |
+
mhatch, RamenChef, shaedrich, Steven Benjamin,
|
2953 |
+
user3071284, William Giles
|
2954 |
+
|
2955 |
+
CFLOOP How-To
|
2956 |
+
|
2957 |
+
Adrian J. Moreno, Bonanza, mhatch, RRK
|
2958 |
+
|
2959 |
+
cfquery
|
2960 |
+
|
2961 |
+
Bubblesphere, shaedrich
|
2962 |
+
|
2963 |
+
ColdFusion Arrays
|
2964 |
+
|
2965 |
+
4444, Justin Duhaime, mhatch, Mishra Shreyanshu, shaedrich
|
2966 |
+
|
2967 |
+
Creating REST APIs
|
2968 |
+
in coldfusion
|
2969 |
+
|
2970 |
+
shaedrich
|
2971 |
+
|
2972 |
+
Database Queries
|
2973 |
+
|
2974 |
+
Adam Tuttle, Leigh, mhatch, nosilleg, shaedrich, user3071284
|
2975 |
+
|
2976 |
+
How to invoke a
|
2977 |
+
private method
|
2978 |
+
dynamically
|
2979 |
+
|
2980 |
+
Henry
|
2981 |
+
|
2982 |
+
Scopes in Coldfusion
|
2983 |
+
|
2984 |
+
James A Mohler, shaedrich
|
2985 |
+
|
2986 |
+
Variables
|
2987 |
+
|
2988 |
+
mhatch
|
2989 |
+
|
2990 |
+
10
|
2991 |
+
|
2992 |
+
Working with
|
2993 |
+
RegExp Replace
|
2994 |
+
callbacks
|
2995 |
+
|
2996 |
+
shaedrich
|
2997 |
+
|
2998 |
+
https://riptutorial.com/
|
2999 |
+
|
3000 |
+
44
|
3001 |
+
|
3002 |
+
|
Cool/cool-manual.pdf.txt
ADDED
@@ -0,0 +1,1787 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
CoolAid: The Cool Reference Manual∗
|
2 |
+
|
3 |
+
1
|
4 |
+
|
5 |
+
Introduction
|
6 |
+
|
7 |
+
This manual describes the programming language Cool: the Classroom Object-Oriented Language. Cool
|
8 |
+
is a small language that can be implemented with reasonable effort in a one semester course. Still, Cool
|
9 |
+
retains many of the features of modern programming languages including objects, static typing, and
|
10 |
+
automatic memory management.
|
11 |
+
|
12 |
+
Cool programs are sets of classes. A class encapsulates the variables and procedures of a data type.
|
13 |
+
Instances of a class are objects. In Cool, classes and types are identified; i.e., every class defines a type.
|
14 |
+
Classes permit programmers to define new types and associated procedures (or methods) specific to those
|
15 |
+
types. Inheritance allows new types to extend the behavior of existing types.
|
16 |
+
|
17 |
+
Cool is an expression language. Most Cool constructs are expressions, and every expression has a
|
18 |
+
value and a type. Cool is type safe: procedures are guaranteed to be applied to data of the correct type.
|
19 |
+
While static typing imposes a strong discipline on programming in Cool, it guarantees that no runtime
|
20 |
+
type errors can arise in the execution of Cool programs.
|
21 |
+
|
22 |
+
This manual is divided into informal and formal components. For a short, informal overview, the first
|
23 |
+
|
24 |
+
12 pages (through Section 9) suffices. The formal description begins with Section 10.
|
25 |
+
|
26 |
+
2 Getting Started
|
27 |
+
|
28 |
+
The reader who wants to get a sense for Cool at the outset should begin by reading, and then write their
|
29 |
+
own cool-programs and run them. Cool source files have extension .cl and Cool assembly files have
|
30 |
+
extension .s. The Cool compiler is coolc (note that cool is a Linux-binary file). To compile a program:
|
31 |
+
|
32 |
+
coolc [ -o fileout ] file1.cl file2.cl ... filen.cl
|
33 |
+
|
34 |
+
The compiler compiles the files file1.cl through filen.cl as if they were concatenated together.
|
35 |
+
Each file must define a set of complete classes—class definitions may not be split across files. The -o
|
36 |
+
option specifies an optional name to use for the output assembly code. If fileout is not supplied, the
|
37 |
+
output assembly is named file1.s.
|
38 |
+
|
39 |
+
The coolc compiler generates MIPS assembly code. Because not all of the machines the course is
|
40 |
+
using are MIPS-based, Cool programs are run on a MIPS simulator called spim. To run a cool program,
|
41 |
+
type
|
42 |
+
|
43 |
+
% spim
|
44 |
+
(spim) load "file.s"
|
45 |
+
(spim) run
|
46 |
+
|
47 |
+
∗Copyright c(cid:176)1995-2000 by Alex Aiken. All rights reserved.
|
48 |
+
|
49 |
+
1
|
50 |
+
|
51 |
+
To run a different program during the same spim session, it is necessary to reinitialize the state of the
|
52 |
+
simulator before loading the new assembly file:
|
53 |
+
|
54 |
+
(spim) reinit
|
55 |
+
|
56 |
+
An alternative—and faster—way to invoke spim is with a file:
|
57 |
+
|
58 |
+
spim -file file.s
|
59 |
+
|
60 |
+
This form loads the file, runs the program, and exits spim when the program terminates. Be sure that
|
61 |
+
the spim we provided is actually used. There may be another version of spim installed in on some
|
62 |
+
systems, but it will not execute Cool programs. The spim manual is available in the resources folder of
|
63 |
+
the repository.
|
64 |
+
|
65 |
+
The following is a complete transcript of the compilation and execution of list.cl. This program is
|
66 |
+
|
67 |
+
very silly, but it does serve to illustrate many of the features of Cool.
|
68 |
+
|
69 |
+
% coolc list.cl
|
70 |
+
% spim
|
71 |
+
SPIM Version 5.4 of Jan. 17, 1994
|
72 |
+
Copyright 1990-1994 by James R. Larus (larus@cs.wisc.edu).
|
73 |
+
All Rights Reserved.
|
74 |
+
See the file README a full copyright notice.
|
75 |
+
Loaded: /usa/pollock/public/cool02/lib/trap.handler
|
76 |
+
|
77 |
+
(spim) load "list.s"
|
78 |
+
(spim) run
|
79 |
+
How many numbers to sort?5
|
80 |
+
0
|
81 |
+
1
|
82 |
+
2
|
83 |
+
3
|
84 |
+
4
|
85 |
+
COOL program successfully executed
|
86 |
+
(spim) exit
|
87 |
+
%
|
88 |
+
|
89 |
+
3 Classes
|
90 |
+
|
91 |
+
All code in Cool is organized into classes. Each class definition must be contained in a single source file,
|
92 |
+
but multiple classes may be defined in the same file. Class definitions have the form:
|
93 |
+
|
94 |
+
class <type> [ inherits <type> ] {
|
95 |
+
|
96 |
+
<feature_list>
|
97 |
+
|
98 |
+
};
|
99 |
+
|
100 |
+
The notation [ ...] denotes an optional construct. All class names are globally visible. Class names
|
101 |
+
|
102 |
+
begin with an uppercase letter. Classes may not be redefined.
|
103 |
+
|
104 |
+
2
|
105 |
+
|
106 |
+
3.1 Features
|
107 |
+
|
108 |
+
The body of a class definition consists of a list of feature definitions. A feature is either an attribute or
|
109 |
+
a method. An attribute of class A specifies a variable that is part of the state of objects of class A. A
|
110 |
+
method of class A is a procedure that may manipulate the variables and objects of class A.
|
111 |
+
|
112 |
+
One of the major themes of modern programming languages is information hiding, which is the idea
|
113 |
+
that certain aspects of a data type’s implementation should be abstract and hidden from users of the
|
114 |
+
data type. Cool supports information hiding through a simple mechanism: all attributes have scope local
|
115 |
+
to the class, and all methods have global scope. Thus, the only way to provide access to object state in
|
116 |
+
Cool is through methods.
|
117 |
+
|
118 |
+
Feature names must begin with a lowercase letter. No method name may be defined multiple times in
|
119 |
+
a class, and no attribute name may be defined multiple times in a class, but a method and an attribute
|
120 |
+
may have the same name.
|
121 |
+
|
122 |
+
A fragment from list.cl illustrates simple cases of both attributes and methods:
|
123 |
+
|
124 |
+
class Cons inherits List {
|
125 |
+
xcar : Int;
|
126 |
+
xcdr : List;
|
127 |
+
|
128 |
+
isNil() : Bool { false };
|
129 |
+
|
130 |
+
init(hd : Int, tl : List) : Cons {
|
131 |
+
|
132 |
+
xcar <- hd;
|
133 |
+
xcdr <- tl;
|
134 |
+
self;
|
135 |
+
|
136 |
+
{
|
137 |
+
|
138 |
+
}
|
139 |
+
|
140 |
+
}
|
141 |
+
...
|
142 |
+
};
|
143 |
+
|
144 |
+
In this example, the class Cons has two attributes xcar and xcdr and two methods isNil and init.
|
145 |
+
Note that the types of attributes, as well as the types of formal parameters and return types of methods,
|
146 |
+
are explicitly declared by the programmer.
|
147 |
+
|
148 |
+
Given object c of class Cons and object l of class List, we can set the xcar and xcdr fields by using
|
149 |
+
|
150 |
+
the method init:
|
151 |
+
|
152 |
+
c.init(1,l)
|
153 |
+
|
154 |
+
This notation is object-oriented dispatch. There may be many definitions of init methods in many
|
155 |
+
different classes. The dispatch looks up the class of the object c to decide which init method to invoke.
|
156 |
+
Because the class of c is Cons, the init method in the Cons class is invoked. Within the invocation, the
|
157 |
+
variables xcar and xcdr refer to c’s attributes. The special variable self refers to the object on which
|
158 |
+
the method was dispatched, which, in the example, is c itself.
|
159 |
+
|
160 |
+
There is a special form new C that generates a fresh object of class C. An object can be thought of as
|
161 |
+
a record that has a slot for each of the attributes of the class as well as pointers to the methods of the
|
162 |
+
class. A typical dispatch for the init method is:
|
163 |
+
|
164 |
+
3
|
165 |
+
|
166 |
+
(new Cons).init(1,new Nil)
|
167 |
+
|
168 |
+
This example creates a new cons cell and initializes the “car” of the cons cell to be 1 and the “cdr” to
|
169 |
+
be new Nil.1 There is no mechanism in Cool for programmers to deallocate objects. Cool has automatic
|
170 |
+
memory management; objects that cannot be used by the program are deallocated by a runtime garbage
|
171 |
+
collector.
|
172 |
+
|
173 |
+
Attributes are discussed further in Section 5 and methods are discussed further in Section 6.
|
174 |
+
|
175 |
+
3.2 Inheritance
|
176 |
+
|
177 |
+
If a class definition has the form
|
178 |
+
|
179 |
+
class A inherits B { ... };
|
180 |
+
|
181 |
+
then class A inherits the features of B. In this case B is the parent class of A and A is a child class of B.
|
182 |
+
|
183 |
+
The semantics of A inherits B is that A has all of the features defined in B in addition to its own
|
184 |
+
features. In the case that a parent and child both define the same method name, then the definition
|
185 |
+
given in the child class takes precedence. It is illegal to redefine attribute names. Furthermore, for type
|
186 |
+
safety, it is necessary to place some restrictions on how methods may be redefined (see Section 6).
|
187 |
+
|
188 |
+
There is a distinguished class Object. If a class definition does not specify a parent class, then the
|
189 |
+
class inherits from Object by default. A class may inherit only from a single class; this is aptly called
|
190 |
+
“single inheritance.”2 The parent-child relation on classes defines a graph. This graph may not contain
|
191 |
+
cycles. For example, if A inherits from B, then B must not inherit from A. Furthermore, if A inherits from
|
192 |
+
B, then B must have a class definition somewhere in the program. Because Cool has single inheritance, it
|
193 |
+
follows that if both of these restrictions are satisfied, then the inheritance graph forms a tree with Object
|
194 |
+
as the root.
|
195 |
+
|
196 |
+
In addition to Object, Cool has four other basic classes: Int, String, Bool, and IO. The basic classes
|
197 |
+
|
198 |
+
are discussed in Section 8.
|
199 |
+
|
200 |
+
4 Types
|
201 |
+
|
202 |
+
In Cool, every class name is also a type. In addition, there is a type SELF TYPE that can be used in
|
203 |
+
special circumstances.
|
204 |
+
|
205 |
+
A type declaration has the form x:C, where x is a variable and C is a type. Every variable must have a
|
206 |
+
type declaration at the point it is introduced, whether that is in a let, case, or as the formal parameter
|
207 |
+
of a method. The types of all attributes must also be declared.
|
208 |
+
|
209 |
+
The basic type rule in Cool is that if a method or variable expects a value of type A, then any value
|
210 |
+
of type B may be used instead, provided that A is an ancestor of B in the class hierarchy. In other words,
|
211 |
+
if B inherits from A, either directly or indirectly, then a B can be used wherever an A would suffice.
|
212 |
+
|
213 |
+
When an object of class B may be used in place of an object of class A, we say that B conforms to A
|
214 |
+
|
215 |
+
or that B ≤ A. As discussed above, conformance is defined in terms of the inheritance graph.
|
216 |
+
|
217 |
+
Definition 4.1 (Conformance) Let A, B, and C be types.
|
218 |
+
|
219 |
+
• A ≤ A for all types A
|
220 |
+
|
221 |
+
1In this example, Nil is assumed to be a subtype of List.
|
222 |
+
2Some object-oriented languages allow a class to inherit from multiple classes, which is equally aptly called “multiple
|
223 |
+
|
224 |
+
inheritance.”
|
225 |
+
|
226 |
+
4
|
227 |
+
|
228 |
+
• if A inherits from B, then A ≤ B
|
229 |
+
|
230 |
+
• if A ≤ B and B ≤ C then A ≤ C
|
231 |
+
|
232 |
+
Because Object is the root of the class hierarchy, it follows that A ≤ Object for all types A.
|
233 |
+
|
234 |
+
4.1 SELF TYPE
|
235 |
+
|
236 |
+
The type SELF TYPE is used to refer to the type of the self variable. This is useful in classes that will
|
237 |
+
be inherited by other classes, because it allows the programmer to avoid specifying a fixed final type at
|
238 |
+
the time the class is written. For example, the program
|
239 |
+
|
240 |
+
class Silly {
|
241 |
+
|
242 |
+
copy() : SELF_TYPE { self };
|
243 |
+
|
244 |
+
};
|
245 |
+
|
246 |
+
class Sally inherits Silly { };
|
247 |
+
|
248 |
+
class Main {
|
249 |
+
|
250 |
+
x : Sally <- (new Sally).copy();
|
251 |
+
|
252 |
+
main() : Sally { x };
|
253 |
+
|
254 |
+
};
|
255 |
+
|
256 |
+
Because SELF TYPE is used in the definition of the copy method, we know that the result of copy is the
|
257 |
+
same as the type of the self parameter. Thus, it follows that (new Sally).copy() has type Sally,
|
258 |
+
which conforms to the declaration of attribute x.
|
259 |
+
|
260 |
+
Note that the meaning of SELF TYPE is not fixed, but depends on the class in which it is used. In
|
261 |
+
general, SELF TYPE may refer to the class C in which it appears, or any class that conforms to C. When it
|
262 |
+
is useful to make explicit what SELF TYPE may refer to, we use the name of the class C in which SELF TYPE
|
263 |
+
appears as an index SELF TYPEC. This subscript notation is not part of Cool syntax—it is used merely
|
264 |
+
to make clear in what class a particular occurrence of SELF TYPE appears.
|
265 |
+
|
266 |
+
From Definition 4.1, it follows that SELF TYPEX ≤ SELF TYPEX. There is also a special conformance
|
267 |
+
|
268 |
+
rule for SELF TYPE:
|
269 |
+
|
270 |
+
SELF TYPEC ≤ B if C ≤ B
|
271 |
+
|
272 |
+
Finally, SELF TYPE may be used in the following places: new SELF TYPE, as the return type of a
|
273 |
+
method, as the declared type of a let variable, or as the declared type of an attribute. No other uses of
|
274 |
+
SELF TYPE are permitted.
|
275 |
+
|
276 |
+
4.2 Type Checking
|
277 |
+
|
278 |
+
The Cool type system guarantees at compile time that execution of a program cannot result in runtime
|
279 |
+
type errors. Using the type declarations for identifiers supplied by the programmer, the type checker
|
280 |
+
infers a type for every expression in the program.
|
281 |
+
|
282 |
+
It is important to distinguish between the type assigned by the type checker to an expression at compile
|
283 |
+
time, which we shall call the static type of the expression, and the type(s) to which the expression may
|
284 |
+
evaluate during execution, which we shall call the dynamic types.
|
285 |
+
|
286 |
+
5
|
287 |
+
|
288 |
+
The distinction between static and dynamic types is needed because the type checker cannot, at
|
289 |
+
compile time, have perfect information about what values will be computed at runtime. Thus, in general,
|
290 |
+
the static and dynamic types may be different. What we require, however, is that the type checker’s
|
291 |
+
static types be sound with respect to the dynamic types.
|
292 |
+
|
293 |
+
Definition 4.2 For any expression e, let De be a dynamic type of e and let Se be the static type inferred
|
294 |
+
by the type checker. Then the type checker is sound if for all expressions e it is the case that De ≤ Se.
|
295 |
+
|
296 |
+
Put another way, we require that the type checker err on the side of overestimating the type of an
|
297 |
+
expression in those cases where perfect accuracy is not possible. Such a type checker will never accept
|
298 |
+
a program that contains type errors. However, the price paid is that the type checker will reject some
|
299 |
+
programs that would actually execute without runtime errors.
|
300 |
+
|
301 |
+
5 Attributes
|
302 |
+
|
303 |
+
An attribute definition has the form
|
304 |
+
|
305 |
+
<id> : <type> [ <- <expr> ];
|
306 |
+
|
307 |
+
The expression is optional initialization that is executed when a new object is created. The static type
|
308 |
+
of the expression must conform to the declared type of the attribute. If no initialization is supplied, then
|
309 |
+
the default initialization is used (see below).
|
310 |
+
|
311 |
+
When a new object of a class is created, all of the inherited and local attributes must be initialized.
|
312 |
+
Inherited attributes are initialized first in inheritance order beginning with the attributes of the greatest
|
313 |
+
ancestor class. Within a given class, attributes are initialized in the order they appear in the source text.
|
314 |
+
Attributes are local to the class in which they are defined or inherited. Inherited attributes cannot
|
315 |
+
|
316 |
+
be redefined.
|
317 |
+
|
318 |
+
5.1 Void
|
319 |
+
|
320 |
+
All variables in Cool are initialized to contain values of the appropriate type. The special value void
|
321 |
+
is a member of all types and is used as the default initialization for variables where no initialization is
|
322 |
+
supplied by the user. Note that there is no name for void in Cool; the only way to create a void value
|
323 |
+
is to declare a variable of some class other than Int, String, or Bool and allow the default initialization
|
324 |
+
to occur.
|
325 |
+
|
326 |
+
There is a special form isvoid expr that tests whether a value is void (see Section 7.11). In addition,
|
327 |
+
void values may be tested for equality. A void value may be passed as an argument, assigned to a variable,
|
328 |
+
or otherwise used in any context where any value is legitimate, except that a dispatch to or case on void
|
329 |
+
generates a runtime error.
|
330 |
+
|
331 |
+
Variables of the basic classes Int, Bool, and String are initialized specially; see Section 8.
|
332 |
+
|
333 |
+
6 Methods
|
334 |
+
|
335 |
+
A method definition has the form
|
336 |
+
|
337 |
+
<id>(<id> : <type>,...,<id> : <type>): <type> { <expr> };
|
338 |
+
|
339 |
+
6
|
340 |
+
|
341 |
+
There may be zero or more formal parameters. The identifiers used in the formal parameter list must
|
342 |
+
be distinct. The type of the method body must conform to the declared return type. When a method is
|
343 |
+
invoked, the formal parameters are bound to the actual arguments and the expression is evaluated; the
|
344 |
+
resulting value is the meaning of the method invocation. A formal parameter hides any definition of an
|
345 |
+
attribute of the same name.
|
346 |
+
|
347 |
+
To ensure type safety, there are restrictions on the redefinition of inherited methods. The rule is
|
348 |
+
simple: If a class A inherits a method f from an ancestor class B, then A may override the inherited
|
349 |
+
definition of f provided the number of arguments, the types of the formal parameters, and the return
|
350 |
+
type are exactly the same in both definitions.
|
351 |
+
|
352 |
+
To see why some restriction is necessary on the redefinition of inherited methods, consider the following
|
353 |
+
|
354 |
+
example:
|
355 |
+
|
356 |
+
class A {
|
357 |
+
|
358 |
+
f(): Int { 1 };
|
359 |
+
|
360 |
+
};
|
361 |
+
|
362 |
+
class B inherits A {
|
363 |
+
|
364 |
+
f(): String { "1" };
|
365 |
+
|
366 |
+
};
|
367 |
+
|
368 |
+
Let a be an object with dynamic type A. Then
|
369 |
+
|
370 |
+
a.f() + 1
|
371 |
+
|
372 |
+
is a well-formed expression with value 2. However, we cannot substitute a value of type B for a, as it would
|
373 |
+
result in adding a string to a number. Thus, if methods can be redefined arbitrarily, then subclasses may
|
374 |
+
not simply extend the behavior of their parents, and much of the usefulness of inheritance, as well as
|
375 |
+
type safety, is lost.
|
376 |
+
|
377 |
+
7 Expressions
|
378 |
+
|
379 |
+
Expressions are the largest syntactic category in Cool.
|
380 |
+
|
381 |
+
7.1 Constants
|
382 |
+
|
383 |
+
The simplest expressions are constants. The boolean constants are true and false. Integer constants are
|
384 |
+
unsigned strings of digits such as 0, 123, and 007. String constants are sequences of characters enclosed
|
385 |
+
in double quotes, such as "This is a string." String constants may be at most 1024 characters long.
|
386 |
+
There are other restrictions on strings; see Section 10.
|
387 |
+
|
388 |
+
The constants belong to the basic classes Bool, Int, and String. The value of a constant is an object
|
389 |
+
|
390 |
+
of the appropriate basic class.
|
391 |
+
|
392 |
+
7.2 Identifiers
|
393 |
+
|
394 |
+
The names of local variables, formal parameters of methods, self, and class attributes are all expressions.
|
395 |
+
The identifier self may be referenced, but it is an error to assign to self or to bind self in a let, a
|
396 |
+
case, or as a formal parameter. It is also illegal to have attributes named self.
|
397 |
+
|
398 |
+
7
|
399 |
+
|
400 |
+
Local variables and formal parameters have lexical scope. Attributes are visible throughout a class in
|
401 |
+
which they are declared or inherited, although they may be hidden by local declarations within expres-
|
402 |
+
sions. The binding of an identifier reference is the innermost scope that contains a declaration for that
|
403 |
+
identifier, or to the attribute of the same name if there is no other declaration. The exception to this
|
404 |
+
rule is the identifier self, which is implicitly bound in every class.
|
405 |
+
|
406 |
+
7.3 Assignment
|
407 |
+
|
408 |
+
An assignment has the form
|
409 |
+
|
410 |
+
<id> <- <expr>
|
411 |
+
|
412 |
+
The static type of the expression must conform to the declared type of the identifier. The value is the
|
413 |
+
value of the expression. The static type of an assignment is the static type of <expr>.
|
414 |
+
|
415 |
+
7.4 Dispatch
|
416 |
+
|
417 |
+
There are three forms of dispatch in Cool. The three forms differ only in how the called method is
|
418 |
+
selected. The most commonly used form of dispatch is
|
419 |
+
|
420 |
+
<expr>.<id>(<expr>,...,<expr>)
|
421 |
+
|
422 |
+
Consider the dispatch e0.f(e1, . . . , en). To evaluate this expression, the arguments are evaluated in left-
|
423 |
+
to-right order, from e1 to en. Next, e0 is evaluated and its class C noted (if e0 is void a runtime error is
|
424 |
+
generated). Finally, the method f in class C is invoked, with the value of e0 bound to self in the body
|
425 |
+
of f and the actual arguments bound to the formals as usual. The value of the expression is the value
|
426 |
+
returned by the method invocation.
|
427 |
+
|
428 |
+
Type checking a dispatch involves several steps. Assume e0 has static type A. (Recall that this type
|
429 |
+
is not necessarily the same as the type C above. A is the type inferred by the type checker; C is the class
|
430 |
+
of the object computed at runtime, which is potentially any subclass of A.) Class A must have a method
|
431 |
+
f, the dispatch and the definition of f must have the same number of arguments, and the static type of
|
432 |
+
the ith actual parameter must conform to the declared type of the ith formal parameter.
|
433 |
+
|
434 |
+
If f has return type B and B is a class name, then the static type of the dispatch is B. Otherwise, if f
|
435 |
+
has return type SELF TYPE, then the static type of the dispatch is A. To see why this is sound, note that
|
436 |
+
the self parameter of the method f conforms to type A. Therefore, because f returns SELF TYPE, we can
|
437 |
+
infer that the result must also conform to A. Inferring accurate static types for dispatch expressions is
|
438 |
+
what justifies including SELF TYPE in the Cool type system.
|
439 |
+
|
440 |
+
The other forms of dispatch are:
|
441 |
+
|
442 |
+
<id>(<expr>,...,<expr>)
|
443 |
+
<expr>@<type>.id(<expr>,...,<expr>)
|
444 |
+
|
445 |
+
The first form is shorthand for self.<id>(<expr>,...,<expr>).
|
446 |
+
|
447 |
+
The second form provides a way of accessing methods of parent classes that have been hidden by
|
448 |
+
redefinitions in child classes.
|
449 |
+
Instead of using the class of the leftmost expression to determine the
|
450 |
+
method, the method of the class explicitly specified is used. For example, e@B.f() invokes the method
|
451 |
+
f in class B on the object that is the value of e. For this form of dispatch, the static type to the left of
|
452 |
+
“@”must conform to the type specified to the right of “@”.
|
453 |
+
|
454 |
+
8
|
455 |
+
|
456 |
+
7.5 Conditionals
|
457 |
+
|
458 |
+
A conditional has the form
|
459 |
+
|
460 |
+
if <expr> then <expr> else <expr> fi
|
461 |
+
|
462 |
+
The semantics of conditionals is standard. The predicate is evaluated first. If the predicate is true,
|
463 |
+
then the then branch is evaluated. If the predicate is false, then the else branch is evaluated. The
|
464 |
+
value of the conditional is the value of the evaluated branch.
|
465 |
+
|
466 |
+
The predicate must have static type Bool. The branches may have any static types. To specify the
|
467 |
+
static type of the conditional, we define an operation (cid:116) (pronounced “join”) on types as follows. Let
|
468 |
+
A,B,D be any types other than SELF TYPE. The least type of a set of types means the least element with
|
469 |
+
respect to the conformance relation ≤.
|
470 |
+
|
471 |
+
A (cid:116) B = the least type C such that A ≤ C and B ≤ C
|
472 |
+
|
473 |
+
SELF TYPED (cid:116) SELF TYPED = SELF TYPED
|
474 |
+
|
475 |
+
SELF TYPED (cid:116) A = D (cid:116) A
|
476 |
+
A (cid:116) SELF TYPED = A (cid:116) D
|
477 |
+
|
478 |
+
Let T and F be the static types of the branches of the conditional. Then the static type of the
|
479 |
+
|
480 |
+
conditional is T (cid:116) F.
|
481 |
+
|
482 |
+
7.6 Loops
|
483 |
+
|
484 |
+
A loop has the form
|
485 |
+
|
486 |
+
while <expr> loop <expr> pool
|
487 |
+
|
488 |
+
The predicate is evaluated before each iteration of the loop. If the predicate is false, the loop terminates
|
489 |
+
and void is returned. If the predicate is true, the body of the loop is evaluated and the process repeats.
|
490 |
+
The predicate must have static type Bool. The body may have any static type. The static type of a
|
491 |
+
|
492 |
+
loop expression is Object.
|
493 |
+
|
494 |
+
7.7 Blocks
|
495 |
+
|
496 |
+
A block has the form
|
497 |
+
|
498 |
+
{ <expr>; ... <expr>; }
|
499 |
+
|
500 |
+
The expressions are evaluated in left-to-right order. Every block has at least one expression; the value
|
501 |
+
of a block is the value of the last expression. The expressions of a block may have any static types. The
|
502 |
+
static type of a block is the static type of the last expression.
|
503 |
+
|
504 |
+
An occasional source of confusion in Cool is the use of semi-colons. Semi-colons are used as terminators
|
505 |
+
in lists of expressions (e.g., the block syntax above) and not as expression separators. Semi-colons also
|
506 |
+
terminate other Cool constructs, see Section 11 for details.
|
507 |
+
|
508 |
+
9
|
509 |
+
|
510 |
+
7.8 Let
|
511 |
+
|
512 |
+
A let expression has the form
|
513 |
+
|
514 |
+
let <id1> : <type1> [ <- <expr1> ], ..., <idn> : <typen> [ <- <exprn> ] in <expr>
|
515 |
+
|
516 |
+
The optional expressions are initialization; the other expression is the body. A let is evaluated as
|
517 |
+
follows. First <expr1> is evaluated and the result bound to <id1>. Then <expr2> is evaluated and the
|
518 |
+
result bound to <id2>, and so on, until all of the variables in the let are initialized. (If the initialization
|
519 |
+
of <idk> is omitted, the default initialization of type <typek> is used.) Next the body of the let is
|
520 |
+
evaluated. The value of the let is the value of the body.
|
521 |
+
|
522 |
+
The let identifiers <id1>,...,<idn> are visible in the body of the let. Furthermore, identifiers
|
523 |
+
|
524 |
+
<id1>,...,<idk> are visible in the initialization of <idm> for any m > k.
|
525 |
+
|
526 |
+
If an identifier is defined multiple times in a let, later bindings hide earlier ones. Identifiers introduced
|
527 |
+
by let also hide any definitions for the same names in containing scopes. Every let expression must
|
528 |
+
introduce at least one identifier.
|
529 |
+
|
530 |
+
The type of an initialization expression must conform to the declared type of the identifier. The type
|
531 |
+
|
532 |
+
of let is the type of the body.
|
533 |
+
|
534 |
+
The scope of a let extends as far (encompasses as many tokens) as possible.
|
535 |
+
|
536 |
+
7.9 Case
|
537 |
+
|
538 |
+
A case expression has the form
|
539 |
+
|
540 |
+
case <expr0> of
|
541 |
+
|
542 |
+
<id1> : <type1> => <expr1>;
|
543 |
+
. . .
|
544 |
+
<idn> : <typen> => <exprn>;
|
545 |
+
|
546 |
+
esac
|
547 |
+
|
548 |
+
Case expressions provide runtime type tests on objects. First, expr0 is evaluated and its dynamic type
|
549 |
+
C noted (if expr0 evaluates to void a run-time error is produced). Next, from among the branches the
|
550 |
+
branch with the least type <typek> such that C ≤ <typek> is selected. The identifier <idk> is bound
|
551 |
+
to the value of <expr0> and the expression <exprk> is evaluated. The result of the case is the value
|
552 |
+
of <exprk>.
|
553 |
+
If no branch can be selected for evaluation, a run-time error is generated. Every case
|
554 |
+
expression must have at least one branch.
|
555 |
+
|
556 |
+
For each branch, let Ti be the static type of <expri>. The static type of a case expression is
|
557 |
+
|
558 |
+
1≤i≤n Ti.
|
559 |
+
The identifier id introduced by a branch of a case hides any variable or attribute definition for id visible
|
560 |
+
in the containing scope.
|
561 |
+
|
562 |
+
(cid:70)
|
563 |
+
|
564 |
+
The case expression has no special construct for a “default” or “otherwise” branch. The same affect
|
565 |
+
|
566 |
+
is achieved by including a branch
|
567 |
+
|
568 |
+
x : Object => ...
|
569 |
+
|
570 |
+
because every type is ≤ to Object.
|
571 |
+
|
572 |
+
The case expression provides programmers a way to insert explicit runtime type checks in situa-
|
573 |
+
tions where static types inferred by the type checker are too conservative. A typical situation is that
|
574 |
+
a programmer writes an expression e and type checking infers that e has static type A. However, the
|
575 |
+
programmer may know that, in fact, the dynamic type of e is always B for some B ≤ A. This information
|
576 |
+
can be captured using a case expression:
|
577 |
+
|
578 |
+
10
|
579 |
+
|
580 |
+
case e of x : B => ...
|
581 |
+
|
582 |
+
In the branch the variable x is bound to the value of e but has the more specific static type B.
|
583 |
+
|
584 |
+
7.10 New
|
585 |
+
|
586 |
+
A new expression has the form
|
587 |
+
|
588 |
+
new <type>
|
589 |
+
|
590 |
+
The value is a fresh object of the appropriate class. If the type is SELF TYPE, then the value is a fresh
|
591 |
+
object of the class of self in the current scope. The static type is <type>.
|
592 |
+
|
593 |
+
7.11 Isvoid
|
594 |
+
|
595 |
+
The expression
|
596 |
+
|
597 |
+
isvoid expr
|
598 |
+
|
599 |
+
evaluates to true if expr is void and evaluates to false if expr is not void.
|
600 |
+
|
601 |
+
7.12 Arithmetic and Comparison Operations
|
602 |
+
|
603 |
+
Cool has four binary arithmetic operations: +, -, *, /. The syntax is
|
604 |
+
|
605 |
+
expr1 <op> expr2
|
606 |
+
|
607 |
+
To evaluate such an expression first expr1 is evaluated and then expr2. The result of the operation is
|
608 |
+
the result of the expression.
|
609 |
+
|
610 |
+
The static types of the two sub-expressions must be Int. The static type of the expression is Int.
|
611 |
+
|
612 |
+
Cool has only integer division.
|
613 |
+
|
614 |
+
Cool has three comparison operations: <, <=, =. For < and <= the rules are exactly the same as
|
615 |
+
for the binary arithmetic operations, except that the result is a Bool. The comparison = is a special
|
616 |
+
case. If either <expr1> or <expr2> has static type Int, Bool, or String, then the other must have the
|
617 |
+
same static type. Any other types, including SELF TYPE, may be freely compared. On non-basic objects,
|
618 |
+
equality simply checks for pointer equality (i.e., whether the memory addresses of the objects are the
|
619 |
+
same). Equality is defined for void.
|
620 |
+
|
621 |
+
In principle, there is nothing wrong with permitting equality tests between, for example, Bool and
|
622 |
+
Int. However, such a test must always be false and almost certainly indicates some sort of programming
|
623 |
+
error. The Cool type checking rules catch such errors at compile-time instead of waiting until runtime.
|
624 |
+
|
625 |
+
Finally, there is one arithmetic and one logical unary operator. The expression ~<expr> is the integer
|
626 |
+
complement of <expr>. The expression <expr> must have static type Int and the entire expression
|
627 |
+
has static type Int. The expression not <expr> is the boolean complement of <expr>. The expression
|
628 |
+
<expr> must have static type Bool and the entire expression has static type Bool.
|
629 |
+
|
630 |
+
11
|
631 |
+
|
632 |
+
8 Basic Classes
|
633 |
+
|
634 |
+
8.1 Object
|
635 |
+
|
636 |
+
The Object class is the root of the inheritance graph. Methods with the following declarations are
|
637 |
+
defined:
|
638 |
+
|
639 |
+
abort() : Object
|
640 |
+
type_name() : String
|
641 |
+
copy() : SELF_TYPE
|
642 |
+
|
643 |
+
The method abort halts program execution with an error message. The method type name returns a
|
644 |
+
string with the name of the class of the object. The method copy produces a shallow copy of the object.3
|
645 |
+
|
646 |
+
8.2 IO
|
647 |
+
|
648 |
+
The IO class provides the following methods for performing simple input and output operations:
|
649 |
+
|
650 |
+
out_string(x : String) : SELF_TYPE
|
651 |
+
out_int(x : Int) : SELF_TYPE
|
652 |
+
in_string() : String
|
653 |
+
in_int() : Int
|
654 |
+
|
655 |
+
The methods out string and out int print their argument and return their self parameter. The
|
656 |
+
method in string reads a string from the standard input, up to but not including a newline character.
|
657 |
+
The method in int reads a single integer, which may be preceded by whitespace. Any characters following
|
658 |
+
the integer, up to and including the next newline, are discarded by in int.
|
659 |
+
|
660 |
+
A class can make use of the methods in the IO class by inheriting from IO. It is an error to redefine
|
661 |
+
|
662 |
+
the IO class.
|
663 |
+
|
664 |
+
8.3 Int
|
665 |
+
|
666 |
+
The Int class provides integers. There are no methods special to Int. The default initialization for
|
667 |
+
variables of type Int is 0 (not void). It is an error to inherit from or redefine Int.
|
668 |
+
|
669 |
+
8.4 String
|
670 |
+
|
671 |
+
The String class provides strings. The following methods are defined:
|
672 |
+
|
673 |
+
length() : Int
|
674 |
+
concat(s : String) : String
|
675 |
+
substr(i : Int, l : Int) : String
|
676 |
+
|
677 |
+
The method length returns the length of the self parameter. The method concat returns the string
|
678 |
+
formed by concatenating s after self. The method substr returns the substring of its self parameter
|
679 |
+
beginning at position i with length l; string positions are numbered beginning at 0. A runtime error is
|
680 |
+
generated if the specified substring is out of range.
|
681 |
+
|
682 |
+
The default initialization for variables of type String is "" (not void). It is an error to inherit from
|
683 |
+
|
684 |
+
or redefine String.
|
685 |
+
|
686 |
+
3A shallow copy of a copies a itself, but does not recursively copy objects that a points to.
|
687 |
+
|
688 |
+
12
|
689 |
+
|
690 |
+
8.5 Bool
|
691 |
+
|
692 |
+
The Bool class provides true and false. The default initialization for variables of type Bool is false
|
693 |
+
(not void). It is an error to inherit from or redefine Bool.
|
694 |
+
|
695 |
+
9 Main Class
|
696 |
+
|
697 |
+
Every program must have a class Main. Furthermore, the Main class must have a method main that
|
698 |
+
takes no formal parameters. The main method must be defined in class Main (not inherited from another
|
699 |
+
class). A program is executed by evaluating (new Main).main().
|
700 |
+
|
701 |
+
The remaining sections of this manual provide a more formal definition of Cool. There are four sections
|
702 |
+
covering lexical structure (Section 10), grammar (Section 11), type rules (Section 12), and operational
|
703 |
+
semantics (Section 13).
|
704 |
+
|
705 |
+
10 Lexical Structure
|
706 |
+
|
707 |
+
The lexical units of Cool are integers, type identifiers, object identifiers, special notation, strings, key-
|
708 |
+
words, and white space.
|
709 |
+
|
710 |
+
10.1 Integers, Identifiers, and Special Notation
|
711 |
+
|
712 |
+
Integers are non-empty strings of digits 0-9. Identifiers are strings (other than keywords) consisting of
|
713 |
+
letters, digits, and the underscore character. Type identifiers begin with a capital letter; object identifiers
|
714 |
+
begin with a lower case letter. There are two other identifiers, self and SELF TYPE that are treated
|
715 |
+
specially by Cool but are not treated as keywords. The special syntactic symbols (e.g., parentheses,
|
716 |
+
assignment operator, etc.) are given in Figure 1.
|
717 |
+
|
718 |
+
10.2 Strings
|
719 |
+
|
720 |
+
Strings are enclosed in double quotes "...". Within a string, a sequence ‘\c’ denotes the character ‘c’,
|
721 |
+
with the exception of the following:
|
722 |
+
|
723 |
+
\b backspace
|
724 |
+
tab
|
725 |
+
\t
|
726 |
+
\n newline
|
727 |
+
\f
|
728 |
+
|
729 |
+
formfeed
|
730 |
+
|
731 |
+
A non-escaped newline character may not appear in a string:
|
732 |
+
|
733 |
+
"This is not
|
734 |
+
OK"
|
735 |
+
|
736 |
+
A string may not contain EOF. A string may not contain the null (character \0). Any other character
|
737 |
+
|
738 |
+
may be included in a string. Strings cannot cross file boundaries.
|
739 |
+
|
740 |
+
13
|
741 |
+
|
742 |
+
10.3 Comments
|
743 |
+
|
744 |
+
There are two forms of comments in Cool. Any characters between two dashes “ – –” and the next
|
745 |
+
newline (or EOF, if there is no next newline) are treated as comments. Comments may also be written
|
746 |
+
by enclosing text in (∗ . . . ∗). The latter form of comment may be nested. Comments cannot cross file
|
747 |
+
boundaries.
|
748 |
+
|
749 |
+
10.4 Keywords
|
750 |
+
|
751 |
+
The keywords of cool are: class, else, false, fi, if, in, inherits, isvoid, let, loop, pool, then, while,
|
752 |
+
case, esac, new, of, not, true. Except for the constants true and false, keywords are case insensitive.
|
753 |
+
To conform to the rules for other objects, the first letter of true and false must be lowercase; the trailing
|
754 |
+
letters may be upper or lower case.
|
755 |
+
|
756 |
+
10.5 White Space
|
757 |
+
|
758 |
+
White space consists of any sequence of the characters: blank, newline, \f, \r, \t, \v.
|
759 |
+
|
760 |
+
11 Cool Syntax
|
761 |
+
|
762 |
+
Figure 1 provides a specification of Cool syntax. The specification is not context-free; for convenience,
|
763 |
+
we also use some regular expression notation. Specifically, A∗ means zero or more A’s in succession; A+
|
764 |
+
means one or more A’s. The special notation A;∗ means zero or more A’s terminated by semicolons. The
|
765 |
+
special notation A,∗ means zero or more A’s separated by commas. Separators differ from terminators
|
766 |
+
in that the terminator always appears at the end of the list; a separator is never included at the end of
|
767 |
+
a list. In Cool, semicolons are always terminators and commas are always separators. Items in square
|
768 |
+
brackets [. . .] are optional. Double braces [[ ]] are not part of Cool; they are used in the grammar as a
|
769 |
+
meta-symbol to show association of grammar operations.
|
770 |
+
|
771 |
+
11.1 Precedence
|
772 |
+
|
773 |
+
The precedence of infix binary and prefix unary operations, from highest to lowest, is given by the
|
774 |
+
following table:
|
775 |
+
|
776 |
+
.
|
777 |
+
@
|
778 |
+
~
|
779 |
+
isvoid
|
780 |
+
* /
|
781 |
+
+ -
|
782 |
+
<=
|
783 |
+
not
|
784 |
+
<-
|
785 |
+
|
786 |
+
< =
|
787 |
+
|
788 |
+
All binary operations are left-associative, with the exception of assignment, which is right-associative,
|
789 |
+
and the three comparison operations, which do not associate.
|
790 |
+
|
791 |
+
14
|
792 |
+
|
793 |
+
program ::= class;+
|
794 |
+
|
795 |
+
class
|
796 |
+
|
797 |
+
::= class TYPE [inherits TYPE] { feature;∗ }
|
798 |
+
|
799 |
+
feature ::= ID(formal,∗ ) : TYPE { expr }
|
800 |
+
|
801 |
+
|
|
802 |
+
|
803 |
+
ID : TYPE [ <- expr ]
|
804 |
+
|
805 |
+
formal
|
806 |
+
|
807 |
+
::= ID : TYPE
|
808 |
+
|
809 |
+
expr
|
810 |
+
|
811 |
+
::= ID <- expr
|
812 |
+
|
813 |
+
|
|
814 |
+
|
815 |
+
|
|
816 |
+
|
817 |
+
|
|
818 |
+
|
819 |
+
expr[@TYPE].ID(expr,∗ )
|
820 |
+
ID(expr,∗ )
|
821 |
+
if expr then expr else expr fi
|
822 |
+
|
823 |
+
| while expr loop expr pool
|
824 |
+
|
825 |
+
|
|
826 |
+
|
827 |
+
|
|
828 |
+
|
829 |
+
|
|
830 |
+
|
831 |
+
|
|
832 |
+
|
833 |
+
|
|
834 |
+
|
835 |
+
|
|
836 |
+
|
837 |
+
|
|
838 |
+
|
839 |
+
|
|
840 |
+
|
841 |
+
|
|
842 |
+
|
843 |
+
|
|
844 |
+
|
845 |
+
|
|
846 |
+
|
847 |
+
|
|
848 |
+
|
849 |
+
|
|
850 |
+
|
851 |
+
|
|
852 |
+
|
853 |
+
|
|
854 |
+
|
855 |
+
|
|
856 |
+
|
857 |
+
|
|
858 |
+
|
859 |
+
|
|
860 |
+
|
861 |
+
|
|
862 |
+
|
863 |
+
|
|
864 |
+
|
865 |
+
{ expr;+ }
|
866 |
+
let [[ID : TYPE [ <- expr ], ]]+ in expr
|
867 |
+
case expr of [[ID : TYPE => expr; ]]+esac
|
868 |
+
new TYPE
|
869 |
+
|
870 |
+
isvoid expr
|
871 |
+
|
872 |
+
expr + expr
|
873 |
+
|
874 |
+
expr − expr
|
875 |
+
|
876 |
+
expr ∗ expr
|
877 |
+
|
878 |
+
expr / expr
|
879 |
+
|
880 |
+
˜expr
|
881 |
+
|
882 |
+
expr < expr
|
883 |
+
|
884 |
+
expr <= expr
|
885 |
+
|
886 |
+
expr = expr
|
887 |
+
|
888 |
+
not expr
|
889 |
+
|
890 |
+
(expr)
|
891 |
+
|
892 |
+
ID
|
893 |
+
|
894 |
+
integer
|
895 |
+
|
896 |
+
string
|
897 |
+
|
898 |
+
true
|
899 |
+
|
900 |
+
false
|
901 |
+
|
902 |
+
Figure 1: Cool syntax.
|
903 |
+
|
904 |
+
15
|
905 |
+
|
906 |
+
12 Type Rules
|
907 |
+
|
908 |
+
This section formally defines the type rules of Cool. The type rules define the type of every Cool expression
|
909 |
+
in a given context. The context is the type environment, which describes the type of every unbound
|
910 |
+
identifier appearing in an expression. The type environment is described in Section 12.1. Section 12.2
|
911 |
+
gives the type rules.
|
912 |
+
|
913 |
+
12.1 Type Environments
|
914 |
+
|
915 |
+
To a first approximation, type checking in Cool can be thought of as a bottom-up algorithm: the type of
|
916 |
+
an expression e is computed from the (previously computed) types of e’s subexpressions. For example,
|
917 |
+
an integer 1 has type Int; there are no subexpressions in this case. As another example, if en has type
|
918 |
+
X, then the expression { e1; . . . ; en; } has type X.
|
919 |
+
|
920 |
+
A complication arises in the case of an expression v, where v is an object identifier. It is not possible
|
921 |
+
to say what the type of v is in a strictly bottom-up algorithm; we need to know the type declared for v
|
922 |
+
in the larger expression. Such a declaration must exist for every object identifier in valid Cool programs.
|
923 |
+
To capture information about the types of identifiers, we use a type environment. The environment
|
924 |
+
consists of three parts: a method environment M , an object environment O, and the name of the
|
925 |
+
current class in which the expression appears. The method environment and object environment are
|
926 |
+
both functions (also called mappings). The object environment is a function of the form
|
927 |
+
|
928 |
+
O(v) = T
|
929 |
+
|
930 |
+
which assigns the type T to object identifier v. The method environment is more complex; it is a function
|
931 |
+
of the form
|
932 |
+
|
933 |
+
M (C, f ) = (T1, . . . , Tn−1, Tn)
|
934 |
+
|
935 |
+
where C is a class name (a type), f is a method name, and t1, . . . , tn are types. The tuple of types is
|
936 |
+
the signature of the method. The interpretation of signatures is that in class C the method f has formal
|
937 |
+
parameters of types (t1, . . . , tn−1)—in that order—and a return type tn.
|
938 |
+
|
939 |
+
Two mappings are required instead of one because object names and method names do not clash—i.e.,
|
940 |
+
|
941 |
+
there may be a method and an object identifier of the same name.
|
942 |
+
|
943 |
+
The third component of the type environment is the name of the current class, which is needed for
|
944 |
+
|
945 |
+
type rules involving SELF TYPE.
|
946 |
+
|
947 |
+
Every expression e is type checked in a type environment; the subexpressions of e may be type
|
948 |
+
checked in the same environment or, if e introduces a new object identifier, in a modified environment.
|
949 |
+
For example, consider the expression
|
950 |
+
|
951 |
+
let c : Int <- 33 in
|
952 |
+
|
953 |
+
...
|
954 |
+
|
955 |
+
The let expression introduces a new variable c with type Int. Let O be the object component of the
|
956 |
+
type environment for the let. Then the body of the let is type checked in the object type environment
|
957 |
+
|
958 |
+
where the notation O[T /c] is defined as follows:
|
959 |
+
|
960 |
+
O[Int/c]
|
961 |
+
|
962 |
+
O[T /c](c) = T
|
963 |
+
|
964 |
+
O[T /c](d) = O(d) if d (cid:54)= c
|
965 |
+
|
966 |
+
16
|
967 |
+
|
968 |
+
12.2 Type Checking Rules
|
969 |
+
|
970 |
+
The general form a type checking rule is:
|
971 |
+
|
972 |
+
...
|
973 |
+
O, M, C (cid:96) e : T
|
974 |
+
|
975 |
+
The rule should be read: In the type environment for objects O, methods M , and containing class C, the
|
976 |
+
expression e has type T . The dots above the horizontal bar stand for other statements about the types
|
977 |
+
of sub-expressions of e. These other statements are hypotheses of the rule; if the hypotheses are satisfied,
|
978 |
+
then the statement below the bar is true.
|
979 |
+
|
980 |
+
The rule for object identifiers is simply that if the environment assigns an identifier Id type T , then
|
981 |
+
|
982 |
+
Id has type T .
|
983 |
+
|
984 |
+
The rule for assignment to a variable is more complex:
|
985 |
+
|
986 |
+
O(Id) = T
|
987 |
+
O, M, C (cid:96) Id : T
|
988 |
+
|
989 |
+
O(Id) = T
|
990 |
+
O, M, C (cid:96) e1 : T (cid:48)
|
991 |
+
T (cid:48) ≤ T
|
992 |
+
|
993 |
+
O, M, C (cid:96) Id ← e1 : T (cid:48)
|
994 |
+
|
995 |
+
[Var]
|
996 |
+
|
997 |
+
[ASSIGN]
|
998 |
+
|
999 |
+
Note that this type rule—as well as others—use the conformance relation ≤ (see Section 3.2). The rule
|
1000 |
+
says that the assigned expression e1 must have a type T (cid:48) that conforms to the type T of the identifier Id
|
1001 |
+
in the type environment. The type of the whole expression is T (cid:48).
|
1002 |
+
|
1003 |
+
The type rules for constants are all easy:
|
1004 |
+
|
1005 |
+
O, M, C (cid:96) true : Bool
|
1006 |
+
|
1007 |
+
O, M, C (cid:96) f alse : Bool
|
1008 |
+
|
1009 |
+
i is an integer constant
|
1010 |
+
O, M, C (cid:96) i : Int
|
1011 |
+
|
1012 |
+
s is a string constant
|
1013 |
+
O, M, C (cid:96) s : String
|
1014 |
+
|
1015 |
+
There are two cases for new, one for new SELF TYPE and one for any other form:
|
1016 |
+
|
1017 |
+
(cid:40)
|
1018 |
+
|
1019 |
+
T (cid:48) =
|
1020 |
+
|
1021 |
+
SELF TYPEC if T = SELF TYPE
|
1022 |
+
T otherwise
|
1023 |
+
O, M, C (cid:96) new T : T (cid:48)
|
1024 |
+
|
1025 |
+
[True]
|
1026 |
+
|
1027 |
+
[False]
|
1028 |
+
|
1029 |
+
[Int]
|
1030 |
+
|
1031 |
+
[String]
|
1032 |
+
|
1033 |
+
[New]
|
1034 |
+
|
1035 |
+
17
|
1036 |
+
|
1037 |
+
Dispatch expressions are the most complex to type check.
|
1038 |
+
|
1039 |
+
O, M, C (cid:96) e0 : T0
|
1040 |
+
O, M, C (cid:96) e1 : T1
|
1041 |
+
...
|
1042 |
+
O, M, C (cid:96) en : Tn
|
1043 |
+
|
1044 |
+
(cid:40)
|
1045 |
+
|
1046 |
+
T (cid:48)
|
1047 |
+
0 =
|
1048 |
+
|
1049 |
+
C if T0 = SELF TYPEC
|
1050 |
+
T0 otherwise
|
1051 |
+
1, . . . , T (cid:48)
|
1052 |
+
|
1053 |
+
n, T (cid:48)
|
1054 |
+
|
1055 |
+
n+1)
|
1056 |
+
|
1057 |
+
M (T (cid:48)
|
1058 |
+
Ti ≤ T (cid:48)
|
1059 |
+
i
|
1060 |
+
|
1061 |
+
0, f ) = (T (cid:48)
|
1062 |
+
(cid:40)
|
1063 |
+
|
1064 |
+
Tn+1 =
|
1065 |
+
|
1066 |
+
1 ≤ i ≤ n
|
1067 |
+
if T (cid:48)
|
1068 |
+
T0
|
1069 |
+
T (cid:48)
|
1070 |
+
n+1 otherwise
|
1071 |
+
O, M, C (cid:96) e0.f (e1, . . . , en) : Tn+1
|
1072 |
+
|
1073 |
+
n+1 = SELF TYPE
|
1074 |
+
|
1075 |
+
O, M, C (cid:96) e0 : T0
|
1076 |
+
O, M, C (cid:96) e1 : T1
|
1077 |
+
...
|
1078 |
+
O, M, C (cid:96) en : Tn
|
1079 |
+
T0 ≤ T
|
1080 |
+
M (T, f ) = (T (cid:48)
|
1081 |
+
Ti ≤ T (cid:48)
|
1082 |
+
i
|
1083 |
+
|
1084 |
+
1, . . . , T (cid:48)
|
1085 |
+
|
1086 |
+
n, T (cid:48)
|
1087 |
+
|
1088 |
+
n+1)
|
1089 |
+
|
1090 |
+
Tn+1 =
|
1091 |
+
|
1092 |
+
(cid:40)
|
1093 |
+
|
1094 |
+
1 ≤ i ≤ n
|
1095 |
+
if T (cid:48)
|
1096 |
+
T0
|
1097 |
+
T (cid:48)
|
1098 |
+
n+1 otherwise
|
1099 |
+
O, M, C (cid:96) e0@T.f (e1, . . . , en) : Tn+1
|
1100 |
+
|
1101 |
+
n+1 = SELF TYPE
|
1102 |
+
|
1103 |
+
[Dispatch]
|
1104 |
+
|
1105 |
+
[StaticDispatch]
|
1106 |
+
|
1107 |
+
To type check a dispatch, each of the subexpressions must first be type checked. The type T0 of e0
|
1108 |
+
determines the which declaration of the method f is used. The argument types of the dispatch must
|
1109 |
+
conform to the declared argument types. Note that the type of the result of the dispatch is either the
|
1110 |
+
declared return type or T0 in the case that the declared return type is SELF TYPE. The only difference in
|
1111 |
+
type checking a static dispatch is that the class T of the method f is given in the dispatch, and the type
|
1112 |
+
T0 must conform to T .
|
1113 |
+
|
1114 |
+
The type checking rules for if and {-} expressions are straightforward. See Section 7.5 for the
|
1115 |
+
|
1116 |
+
definition of the (cid:116) operation.
|
1117 |
+
|
1118 |
+
O, M, C (cid:96) e1 : Bool
|
1119 |
+
O, M, C (cid:96) e2 : T2
|
1120 |
+
O, M, C (cid:96) e3 : T3
|
1121 |
+
O, M, C (cid:96) if e1 then e2 else e3 fi : T2 (cid:116) T3
|
1122 |
+
|
1123 |
+
O, M, C (cid:96) e1 : T1
|
1124 |
+
O, M, C (cid:96) e2 : T2
|
1125 |
+
...
|
1126 |
+
O, M, C (cid:96) en : Tn
|
1127 |
+
O, M, C (cid:96) { e1; e2; . . . en; } : Tn
|
1128 |
+
|
1129 |
+
18
|
1130 |
+
|
1131 |
+
[If]
|
1132 |
+
|
1133 |
+
[Sequence]
|
1134 |
+
|
1135 |
+
The let rule has some interesting aspects.
|
1136 |
+
|
1137 |
+
(cid:40)
|
1138 |
+
|
1139 |
+
T (cid:48)
|
1140 |
+
0 =
|
1141 |
+
|
1142 |
+
SELF TYPEC if T0 = SELF TYPE
|
1143 |
+
T0 otherwise
|
1144 |
+
|
1145 |
+
O, M, C (cid:96) e1 : T1
|
1146 |
+
T1 ≤ T (cid:48)
|
1147 |
+
0
|
1148 |
+
O[T (cid:48)
|
1149 |
+
|
1150 |
+
0/x], M, C (cid:96) e2 : T2
|
1151 |
+
O, M, C (cid:96) let x : T0 ← e1 in e2 : T2
|
1152 |
+
First, the initialization e1 is type checked in an environment without a definition for x. Thus, the variable
|
1153 |
+
x cannot be used in e1 unless it already has a definition in an outer scope. Second, the body e2 is type
|
1154 |
+
checked in the environment O extended with the typing x : T (cid:48)
|
1155 |
+
0. Third, note that the type of x may be
|
1156 |
+
SELF TYPE.
|
1157 |
+
|
1158 |
+
[Let-Init]
|
1159 |
+
|
1160 |
+
(cid:40)
|
1161 |
+
|
1162 |
+
T (cid:48)
|
1163 |
+
0 =
|
1164 |
+
|
1165 |
+
SELF TYPEC if T0 = SELF TYPE
|
1166 |
+
T0 otherwise
|
1167 |
+
|
1168 |
+
O[T (cid:48)
|
1169 |
+
|
1170 |
+
0/x], M, C (cid:96) e1 : T1
|
1171 |
+
|
1172 |
+
O, M, C (cid:96) let x : T0 in e1 : T1
|
1173 |
+
The rule for let with no initialization simply omits the conformance requirement. We give type rules
|
1174 |
+
only for a let with a single variable. Typing a multiple let
|
1175 |
+
|
1176 |
+
[Let-No-Init]
|
1177 |
+
|
1178 |
+
let x1 : T1 [← e1], x2 : T2 [← e2], . . . , xn : Tn [← en] in e
|
1179 |
+
|
1180 |
+
is defined to be the same as typing
|
1181 |
+
|
1182 |
+
let x1 : T1 [← e1] in (let x2 : T2 [← e2], . . . , xn : Tn [← en] in e )
|
1183 |
+
|
1184 |
+
O, M, C (cid:96) e0 : T0
|
1185 |
+
O[T1/x1], M, C (cid:96) e1 : T (cid:48)
|
1186 |
+
1
|
1187 |
+
...
|
1188 |
+
O[Tn/xn], M, C (cid:96) en : T (cid:48)
|
1189 |
+
n
|
1190 |
+
|
1191 |
+
O, M, C (cid:96) case e0 of x1 : T1 ⇒ e1; . . . xn : Tn ⇒ en; esac :
|
1192 |
+
|
1193 |
+
(cid:70)
|
1194 |
+
|
1195 |
+
1≤i≤n T (cid:48)
|
1196 |
+
i
|
1197 |
+
|
1198 |
+
[Case]
|
1199 |
+
|
1200 |
+
Each branch of a case is type checked in an environment where variable xi has type Ti. The type of
|
1201 |
+
the entire case is the join of the types of its branches. The variables declared on each branch of a case
|
1202 |
+
must all have distinct types.
|
1203 |
+
|
1204 |
+
O, M, C (cid:96) while e1 loop e2 pool : Object
|
1205 |
+
The predicate of a loop must have type Bool; the type of the entire loop is always Object. An isvoid
|
1206 |
+
test has type Bool:
|
1207 |
+
|
1208 |
+
[Loop]
|
1209 |
+
|
1210 |
+
[Isvoid]
|
1211 |
+
|
1212 |
+
O, M, C (cid:96) e1 : Bool
|
1213 |
+
O, M, C (cid:96) e2 : T2
|
1214 |
+
|
1215 |
+
O, M, C (cid:96) e1 : T1
|
1216 |
+
O, M, C (cid:96) isvoid e1 : Bool
|
1217 |
+
|
1218 |
+
With the exception of the rule for equality, the type checking rules for the primitive logical, compar-
|
1219 |
+
|
1220 |
+
ison, and arithmetic operations are easy.
|
1221 |
+
|
1222 |
+
O, M, C (cid:96) e1 : Bool
|
1223 |
+
O, M, C (cid:96) ¬e1 : Bool
|
1224 |
+
|
1225 |
+
19
|
1226 |
+
|
1227 |
+
[Not]
|
1228 |
+
|
1229 |
+
O, M, C (cid:96) e1 : Int
|
1230 |
+
O, M, C (cid:96) e2 : Int
|
1231 |
+
op ∈ {<, ≤}
|
1232 |
+
|
1233 |
+
O, M, C (cid:96) e1 op e2 : Bool
|
1234 |
+
|
1235 |
+
O, M, C (cid:96) e1 : Int
|
1236 |
+
O, M, C (cid:96) ˜e1 : Int
|
1237 |
+
|
1238 |
+
O, M, C (cid:96) e1 : Int
|
1239 |
+
O, M, C (cid:96) e2 : Int
|
1240 |
+
op ∈ {∗, +, −, /}
|
1241 |
+
O, M, C (cid:96) e1 op e2 : Int
|
1242 |
+
|
1243 |
+
[Compare]
|
1244 |
+
|
1245 |
+
[Neg]
|
1246 |
+
|
1247 |
+
[Arith]
|
1248 |
+
|
1249 |
+
The wrinkle in the rule for equality is that any types may be freely compared except Int, String
|
1250 |
+
|
1251 |
+
and Bool, which may only be compared with objects of the same type.
|
1252 |
+
|
1253 |
+
O, M, C (cid:96) e1 : T1
|
1254 |
+
O, M, C (cid:96) e2 : T2
|
1255 |
+
T1 ∈ {Int, String, Bool} ∨ T2 ∈ {Int, String, Bool} ⇒ T1 = T2
|
1256 |
+
O, M, C (cid:96) e1 = e2 : Bool
|
1257 |
+
|
1258 |
+
[Equal]
|
1259 |
+
|
1260 |
+
The final cases are type checking rules for attributes and methods. For a class C, let the object
|
1261 |
+
environment OC give the types of all attributes of C (including any inherited attributes). More formally,
|
1262 |
+
if x is an attribute (inherited or not) of C, and the declaration of x is x : T , then
|
1263 |
+
(cid:40)
|
1264 |
+
|
1265 |
+
OC(x) =
|
1266 |
+
|
1267 |
+
SELF TYPEC if T = SELF TYPE
|
1268 |
+
T otherwise
|
1269 |
+
|
1270 |
+
The method environment M is global to the entire program and defines for every class C the signatures
|
1271 |
+
|
1272 |
+
of all of the methods of C (including any inherited methods).
|
1273 |
+
|
1274 |
+
The two rules for type checking attribute defininitions are similar the rules for let. The essential
|
1275 |
+
difference is that attributes are visible within their initialization expressions. Note that self is bound in
|
1276 |
+
the initialization.
|
1277 |
+
|
1278 |
+
OC(x) = T0
|
1279 |
+
OC[SELF TYPEC/self], M, C (cid:96) e1 : T1
|
1280 |
+
T1 ≤ T0
|
1281 |
+
|
1282 |
+
OC, M, C (cid:96) x : T0 ← e1;
|
1283 |
+
|
1284 |
+
OC(x) = T
|
1285 |
+
OC, M, C (cid:96) x : T ;
|
1286 |
+
|
1287 |
+
[Attr-Init]
|
1288 |
+
|
1289 |
+
[Attr-No-Init]
|
1290 |
+
|
1291 |
+
The rule for typing methods checks the body of the method in an environment where OC is extended
|
1292 |
+
with bindings for the formal parameters and self. The type of the method body must conform to the
|
1293 |
+
declared return type.
|
1294 |
+
|
1295 |
+
M (C, f ) = (T1, . . . , Tn, T0)
|
1296 |
+
OC[SELF TYPEC/self][T1/x1] . . . [Tn/xn], M, C (cid:96) e : T (cid:48)
|
1297 |
+
0
|
1298 |
+
|
1299 |
+
(cid:40)
|
1300 |
+
|
1301 |
+
T (cid:48)
|
1302 |
+
0 ≤
|
1303 |
+
|
1304 |
+
SELF TYPEC if T0 = SELF TYPE
|
1305 |
+
T0 otherwise
|
1306 |
+
|
1307 |
+
OC, M, C (cid:96) f (x1 : T1, . . . , xn : Tn) : T0 { e };
|
1308 |
+
|
1309 |
+
20
|
1310 |
+
|
1311 |
+
[Method]
|
1312 |
+
|
1313 |
+
13 Operational Semantics
|
1314 |
+
|
1315 |
+
This section contains a mostly formal presentation of the operational semantics for the Cool language. The
|
1316 |
+
operational semantics define for every Cool expression what value it should produce in a given context.
|
1317 |
+
The context has three components: an environment, a store, and a self object. These components are
|
1318 |
+
described in the next section. Section 13.2 defines the syntax used to refer to Cool objects, and Section
|
1319 |
+
13.3 defines the syntax used to refer to class definitions.
|
1320 |
+
|
1321 |
+
Keep in mind that a formal semantics is a specification only—it does not describe an implementation.
|
1322 |
+
The purpose of presenting the formal semantics is to make clear all the details of the behavior of Cool
|
1323 |
+
expressions. How this behavior is implemented is another matter.
|
1324 |
+
|
1325 |
+
13.1 Environment and the Store
|
1326 |
+
|
1327 |
+
Before we can present a semantics for Cool we need a number of concepts and a considerable amount of
|
1328 |
+
notation. An environment is a mapping of variable identifiers to locations. Intuitively, an environment
|
1329 |
+
tells us for a given identifier the address of the memory location where that identifier’s value is stored.
|
1330 |
+
For a given expression, the environment must assign a location to all identifiers to which the expression
|
1331 |
+
may refer. For the expression, e.g., a + b, we need an environment that maps a to some location and b
|
1332 |
+
to some location. We’ll use the following syntax to describe environments, which is very similar to the
|
1333 |
+
syntax of type assumptions used in Section 12.
|
1334 |
+
|
1335 |
+
E = [a : l1, b : l2]
|
1336 |
+
|
1337 |
+
This environment maps a to location l1, and b to location l2.
|
1338 |
+
|
1339 |
+
The second component of the context for the evaluation of an expression is the store. The store maps
|
1340 |
+
locations to values, where values in Cool are just objects. Intuitively, a store tells us what value is stored
|
1341 |
+
in a given memory location. For the moment, assume all values are integers. A store is similar to an
|
1342 |
+
environment:
|
1343 |
+
|
1344 |
+
S = [l1 → 55, l2 → 77]
|
1345 |
+
|
1346 |
+
This store maps location l1 to value 55 and location l2 to value 77.
|
1347 |
+
|
1348 |
+
Given an environment and a store, the value of an identifier can be found by first looking up the
|
1349 |
+
|
1350 |
+
location that the identifier maps to in the environment and then looking up the location in the store.
|
1351 |
+
|
1352 |
+
E(a) = l1
|
1353 |
+
S(l1) = 55
|
1354 |
+
|
1355 |
+
Together, the environment and the store define the execution state at a particular step of the evaluation
|
1356 |
+
of a Cool expression. The double indirection from identifiers to locations to values allows us to model
|
1357 |
+
variables. Consider what happens if the value 99 is assigned variable a in the environment and store
|
1358 |
+
defined above. Assigning to a variable means changing the value to which it refers but not its location.
|
1359 |
+
To perform the assignment, we look up the location for a in the environment E and then change the
|
1360 |
+
mapping for the obtained location to the new value, giving a new store S(cid:48).
|
1361 |
+
|
1362 |
+
E(a) = l1
|
1363 |
+
|
1364 |
+
S(cid:48) = S[99/l1]
|
1365 |
+
|
1366 |
+
The syntax S[v/l] denotes a new store that is identical to the store S, except that S(cid:48) maps location l to
|
1367 |
+
value v. For all locations l(cid:48) where l(cid:48) (cid:54)= l, we still have S(cid:48)(l(cid:48)) = S(l(cid:48)).
|
1368 |
+
|
1369 |
+
21
|
1370 |
+
|
1371 |
+
The store models the contents of memory of the computer during program execution. Assigning to a
|
1372 |
+
|
1373 |
+
variable modifies the store.
|
1374 |
+
|
1375 |
+
There are also situations in which the environment is modified. Consider the following Cool fragment:
|
1376 |
+
|
1377 |
+
let c : Int <- 33 in
|
1378 |
+
|
1379 |
+
c
|
1380 |
+
|
1381 |
+
When evaluating this expression, we must introduce the new identifier c into the environment before
|
1382 |
+
evaluating the body of the let. If the current environment and state are E and S, then we create a new
|
1383 |
+
environment E(cid:48) and a new store S(cid:48) defined by:
|
1384 |
+
|
1385 |
+
lc = newloc(S)
|
1386 |
+
E(cid:48) = E[lc/c]
|
1387 |
+
S(cid:48) = S[33/lc]
|
1388 |
+
|
1389 |
+
The first step is to allocate a location for the variable c. The location should be fresh, meaning that the
|
1390 |
+
current store does not have a mapping for it. The function newloc() applied to a store gives us an unused
|
1391 |
+
location in that store. We then create a new environment E(cid:48), which maps c to lc but also contains all
|
1392 |
+
of the mappings of E for identifiers other than c. Note that if c already has a mapping in E, the new
|
1393 |
+
environment E(cid:48) hides this old mapping. We must also update the store to map the new location to a
|
1394 |
+
value. In this case lc maps to the value 33, which is the initial value for c as defined by the let-expression.
|
1395 |
+
The example in this subsection oversimplifies Cool environments and stores a bit, because simple
|
1396 |
+
|
1397 |
+
integers are not Cool values. Even integers are full-fledged objects in Cool.
|
1398 |
+
|
1399 |
+
13.2 Syntax for Cool Objects
|
1400 |
+
|
1401 |
+
Every Cool value is an object. Objects contain a list of named attributes, a bit like records in C. In
|
1402 |
+
addition, each object belongs to a class. We use the following syntax for values in Cool:
|
1403 |
+
|
1404 |
+
v = X(a1 = l1, a2 = l2, . . . , an = ln)
|
1405 |
+
|
1406 |
+
Read the syntax as follows: The value v is a member of class X containing the attributes a1, . . . , an whose
|
1407 |
+
locations are l1, . . . , ln. Note that the attributes have an associated location. Intuitively this means that
|
1408 |
+
there is some space in memory reserved for each attribute.
|
1409 |
+
|
1410 |
+
For base objects of Cool (i.e., Ints, Strings, and Bools) we use a special case of the above syntax.
|
1411 |
+
Base objects have a class name, but their attributes are not like attributes of normal classes, because
|
1412 |
+
they cannot be modified. Therefore, we describe base objects using the following syntax:
|
1413 |
+
|
1414 |
+
Int(5)
|
1415 |
+
Bool(true)
|
1416 |
+
String(4, "Cool")
|
1417 |
+
|
1418 |
+
For Ints and Bools, the meaning is obvious. Strings contain two parts, the length and the actual
|
1419 |
+
|
1420 |
+
sequence of ASCII characters.
|
1421 |
+
|
1422 |
+
13.3 Class definitions
|
1423 |
+
|
1424 |
+
In the rules presented in the next section, we need a way to refer to the definitions of attributes and
|
1425 |
+
methods for classes. Suppose we have the following Cool class definition:
|
1426 |
+
|
1427 |
+
22
|
1428 |
+
|
1429 |
+
class B {
|
1430 |
+
|
1431 |
+
s : String <- "Hello";
|
1432 |
+
g (y:String) : Int {
|
1433 |
+
|
1434 |
+
y.concat(s)
|
1435 |
+
|
1436 |
+
};
|
1437 |
+
f (x:Int) : Int {
|
1438 |
+
|
1439 |
+
x+1
|
1440 |
+
|
1441 |
+
};
|
1442 |
+
|
1443 |
+
};
|
1444 |
+
|
1445 |
+
class A inherits B {
|
1446 |
+
|
1447 |
+
a : Int;
|
1448 |
+
b : B <- new B;
|
1449 |
+
f(x:Int) : Int {
|
1450 |
+
|
1451 |
+
x+a
|
1452 |
+
|
1453 |
+
};
|
1454 |
+
|
1455 |
+
};
|
1456 |
+
|
1457 |
+
Two mappings, called class and implementation, are associated with class definitions. The class
|
1458 |
+
|
1459 |
+
mapping is used to get the attributes, as well as their types and initializations, of a particular class:
|
1460 |
+
|
1461 |
+
class(A) = (s : String ← "Hello", a : Int ← 0, b : B ← new B)
|
1462 |
+
|
1463 |
+
Note that the information for class A contains everything that it inherited from class B, as well as its own
|
1464 |
+
definitions. If B had inherited other attributes, those attributes would also appear in the information for
|
1465 |
+
A. The attributes are listed in the order they are inherited and then in source order: all the attributes
|
1466 |
+
from the greatest ancestor are listed first in the order in which they textually appear, then the attributes
|
1467 |
+
of the next greatest ancestor, and so on, on down to the attributes defined in the particular class. We
|
1468 |
+
rely on this order in describing how new objects are initialized.
|
1469 |
+
|
1470 |
+
The general form of a class mapping is:
|
1471 |
+
|
1472 |
+
class(X) = (a1 : T1 ← e1, . . . , an : Tn ← en)
|
1473 |
+
|
1474 |
+
Note that every attribute has an initializing expression, even if the Cool program does not specify one for
|
1475 |
+
each attribute. The default initialization for a variable or attribute is the default of its type. The default
|
1476 |
+
of Int is 0, the default of String is "", the default of Bool is false, and the default of any other type
|
1477 |
+
is void.4 The default of type T is written DT .
|
1478 |
+
|
1479 |
+
The implementation mapping gives information about the methods of a class. For the above example,
|
1480 |
+
|
1481 |
+
implementation of A is defined as follows:
|
1482 |
+
|
1483 |
+
implementation(A, f ) = (x, x + a)
|
1484 |
+
implementation(A, g) = (y, y.concat(s))
|
1485 |
+
|
1486 |
+
In general, for a class X and a method m,
|
1487 |
+
|
1488 |
+
implementation(X, m) = (x1, x2, . . . , xn, ebody)
|
1489 |
+
|
1490 |
+
specifies that method m when invoked from class X, has formal parameters x1, . . . , xn, and the body of
|
1491 |
+
the method is expression ebody.
|
1492 |
+
|
1493 |
+
4A tiny point: We are allowing void to be used as an expression here. There is no expression for void available to Cool
|
1494 |
+
|
1495 |
+
programmers.
|
1496 |
+
|
1497 |
+
23
|
1498 |
+
|
1499 |
+
13.4 Operational Rules
|
1500 |
+
|
1501 |
+
Equipped with environments, stores, objects, and class definitions, we can now attack the operational
|
1502 |
+
semantics for Cool. The operational semantics is described by rules similar to the rules used in type
|
1503 |
+
checking. The general form of the rules is:
|
1504 |
+
|
1505 |
+
...
|
1506 |
+
so, S, E (cid:96) e1 : v, S(cid:48)
|
1507 |
+
|
1508 |
+
The rule should be read as: In the context where self is the object so, the store is S, and the environment
|
1509 |
+
is E, the expression e1 evaluates to object v and the new store is S(cid:48). The dots above the horizontal bar
|
1510 |
+
stand for other statements about the evaluation of sub-expressions of e1.
|
1511 |
+
|
1512 |
+
Besides an environment and a store, the evaluation context contains a self object so. The self object
|
1513 |
+
is just the object to which the identifier self refers if self appears in the expression. We do not place
|
1514 |
+
self in the environment and store because self is not a variable—it cannot be assigned to. Note that
|
1515 |
+
the rules specify a new store after the evaluation of an expression. The new store contains all changes to
|
1516 |
+
memory resulting as side effects of evaluating expression e1.
|
1517 |
+
|
1518 |
+
The rest of this section presents and briefly discusses each of the operational rules. A few cases are
|
1519 |
+
|
1520 |
+
not covered; these are discussed at the end of the section.
|
1521 |
+
|
1522 |
+
so, S1, E (cid:96) e1 : v1, S2
|
1523 |
+
E(Id) = l1
|
1524 |
+
S3 = S2[v1/l1]
|
1525 |
+
|
1526 |
+
so, S1, E (cid:96) Id ← e1 : v1, S3
|
1527 |
+
|
1528 |
+
[Assign]
|
1529 |
+
|
1530 |
+
An assignment first evaluates the expression on the right-hand side, yielding a value v1. This value is
|
1531 |
+
stored in memory at the address for the identifier.
|
1532 |
+
|
1533 |
+
The rules for identifier references, self, and constants are straightforward:
|
1534 |
+
|
1535 |
+
E(Id) = l
|
1536 |
+
S(l) = v
|
1537 |
+
so, S, E (cid:96) Id : v, S
|
1538 |
+
|
1539 |
+
so, S, E (cid:96) self : so, S
|
1540 |
+
|
1541 |
+
so, S, E (cid:96) true : Bool(true), S
|
1542 |
+
|
1543 |
+
so, S, E (cid:96) false : Bool(f alse), S
|
1544 |
+
|
1545 |
+
i is an integer constant
|
1546 |
+
so, S, E (cid:96) i : Int(i), S
|
1547 |
+
|
1548 |
+
s is a string constant
|
1549 |
+
l = length(s)
|
1550 |
+
|
1551 |
+
so, S, E (cid:96) s : String(l, s), S
|
1552 |
+
|
1553 |
+
24
|
1554 |
+
|
1555 |
+
[Var]
|
1556 |
+
|
1557 |
+
[Self]
|
1558 |
+
|
1559 |
+
[True]
|
1560 |
+
|
1561 |
+
[False]
|
1562 |
+
|
1563 |
+
[Int]
|
1564 |
+
|
1565 |
+
[String]
|
1566 |
+
|
1567 |
+
A new expression is more complicated than one might expect:
|
1568 |
+
|
1569 |
+
(cid:40)
|
1570 |
+
|
1571 |
+
T0 =
|
1572 |
+
|
1573 |
+
X if T = SELF TYPE and so = X(. . .)
|
1574 |
+
T otherwise
|
1575 |
+
|
1576 |
+
class(T0) = (a1 : T1 ← e1, . . . , an : Tn ← en)
|
1577 |
+
li = newloc(S1), for i = 1 . . . n and each li is diistinct
|
1578 |
+
v1 = T0(a1 = l1, . . . , an = ln)
|
1579 |
+
S2 = S1[DT1/l1, . . . , DTn/ln]
|
1580 |
+
v1, S2, [a1 : l1, . . . , an : ln] (cid:96) {a1 ← e1; . . . ; an ← en; } : v2, S3
|
1581 |
+
so, S1, E (cid:96) new T : v1, S3
|
1582 |
+
|
1583 |
+
[New]
|
1584 |
+
|
1585 |
+
The tricky thing in a new expression is to initialize the attributes in the right order. Note also that,
|
1586 |
+
during initialization, attributes are bound to the default of the appropriate class.
|
1587 |
+
|
1588 |
+
so, S1, E (cid:96) e1 : v1, S2
|
1589 |
+
so, S2, E (cid:96) e2 : v2, S3
|
1590 |
+
...
|
1591 |
+
so, Sn, E (cid:96) en : vn, Sn+1
|
1592 |
+
so, Sn+1, E (cid:96) e0 : v0, Sn+2
|
1593 |
+
v0 = X(a1 = la1, . . . , am = lam)
|
1594 |
+
implementation(X, f ) = (x1, . . . , xn, en+1)
|
1595 |
+
lxi = newloc(Sn+2), for i = 1 . . . n and each lxi is distinct
|
1596 |
+
Sn+3 = Sn+2[v1/lx1, . . . , vn/lxn]
|
1597 |
+
v0, Sn+3, [a1 : la1, . . . , am : lam, x1 : lx1, . . . , xn : lxn] (cid:96) en+1 : vn+1, Sn+4
|
1598 |
+
so, S1, E (cid:96) e0.f (e1, . . . , en) : vn+1, Sn+4
|
1599 |
+
|
1600 |
+
so, S1, E (cid:96) e1 : v1, S2
|
1601 |
+
so, S2, E (cid:96) e2 : v2, S3
|
1602 |
+
...
|
1603 |
+
so, Sn, E (cid:96) en : vn, Sn+1
|
1604 |
+
so, Sn+1, E (cid:96) e0 : v0, Sn+2
|
1605 |
+
v0 = X(a1 = la1, . . . , am = lam)
|
1606 |
+
implementation(T, f ) = (x1, . . . , xn, en+1)
|
1607 |
+
lxi = newloc(Sn+2), for i = 1 . . . n and each lxi is distinct
|
1608 |
+
Sn+3 = Sn+2[v1/lx1, . . . , vn/lxn]
|
1609 |
+
v0, Sn+3, [a1 : la1, . . . , am : lam, x1 : lx1, . . . , xn : lxn] (cid:96) en+1 : vn+1, Sn+4
|
1610 |
+
so, S1, E (cid:96) e0@T.f (e1, . . . , en) : vn+1, Sn+4
|
1611 |
+
|
1612 |
+
[Dispatch]
|
1613 |
+
|
1614 |
+
[StaticDispatch]
|
1615 |
+
|
1616 |
+
The two dispatch rules do what one would expect. The arguments are evaluated and saved. Next, the
|
1617 |
+
expression on the left-hand side of the “.” is evaluated. In a normal dispatch, the class of this expression
|
1618 |
+
is used to determine the method to invoke; otherwise the class is specified in the dispatch itself.
|
1619 |
+
|
1620 |
+
so, S1, E (cid:96) e1 : Bool(true), S2
|
1621 |
+
so, S2, E (cid:96) e2 : v2, S3
|
1622 |
+
|
1623 |
+
so, S1, E (cid:96) if e1 then e2 else e3 fi : v2, S3
|
1624 |
+
|
1625 |
+
[If-True]
|
1626 |
+
|
1627 |
+
25
|
1628 |
+
|
1629 |
+
so, S1, E (cid:96) e1 : Bool(f alse), S2
|
1630 |
+
so, S2, E (cid:96) e3 : v3, S3
|
1631 |
+
|
1632 |
+
so, S1, E (cid:96) if e1 then e2 else e3 fi : v3, S3
|
1633 |
+
There are no surprises in the if-then-else rules. Note that value of the predicate is a Bool object, not a
|
1634 |
+
boolean.
|
1635 |
+
|
1636 |
+
[If-False]
|
1637 |
+
|
1638 |
+
so, S1, E (cid:96) e1 : v1, S2
|
1639 |
+
so, S2, E (cid:96) e2 : v2, S3
|
1640 |
+
...
|
1641 |
+
so, Sn, E (cid:96) en : vn, Sn+1
|
1642 |
+
so, S1, E (cid:96) { e1; e2; . . . ; en; } : vn, Sn+1
|
1643 |
+
Blocks are evaluated from the first expression to the last expression, in order. The result is the result of
|
1644 |
+
the last expression.
|
1645 |
+
|
1646 |
+
[Sequence]
|
1647 |
+
|
1648 |
+
so, S1, E (cid:96) e1 : v1, S2
|
1649 |
+
l1 = newloc(S2)
|
1650 |
+
S3 = S2[v1/l1]
|
1651 |
+
E(cid:48) = E[l1/Id]
|
1652 |
+
so, S3, E(cid:48) (cid:96) e2 : v2, S4
|
1653 |
+
so, S1, E (cid:96) let Id : T1 ← e1 in e2 : v2, S4
|
1654 |
+
A let evaluates any initialization code, assigns the result to the variable at a fresh location, and evaluates
|
1655 |
+
the body of the let. (If there is no initialization, the variable is initialized to the default value of T1.)
|
1656 |
+
We give the operational semantics only for the case of let with a single variable. The semantics of a
|
1657 |
+
multiple let
|
1658 |
+
|
1659 |
+
[Let]
|
1660 |
+
|
1661 |
+
let x1 : T1 ← e1, x2 : T2 ← e2, . . . , xn : Tn ← en in e
|
1662 |
+
|
1663 |
+
is defined to be the same as
|
1664 |
+
|
1665 |
+
let x1 : T1 ← e1 in (let x2 : T2 ← e2, . . . , xn : Tn ← en in e )
|
1666 |
+
|
1667 |
+
so, S1, E (cid:96) e0 : v0, S2
|
1668 |
+
v0 = X(. . .)
|
1669 |
+
Ti = closest ancestor of X in {T1, . . . , Tn}
|
1670 |
+
l0 = newloc(S2)
|
1671 |
+
S3 = S2[v0/l0]
|
1672 |
+
E(cid:48) = E[l0/Idi]
|
1673 |
+
so, S3, E(cid:48) (cid:96) ei : v1, S4
|
1674 |
+
|
1675 |
+
so, S1, E (cid:96) case e0 of Id1 : T1 ⇒ e1; . . . ; Idn : Tn ⇒ en; esac : v1, S4
|
1676 |
+
Note that the case rule requires that the class hierarchy be available in some form at runtime, so that
|
1677 |
+
the correct branch of the case can be selected. This rule is otherwise straightforward.
|
1678 |
+
|
1679 |
+
[Case]
|
1680 |
+
|
1681 |
+
so, S1, E (cid:96) e1 : Bool(true), S2
|
1682 |
+
so, S2, E (cid:96) e2 : v2, S3
|
1683 |
+
so, S3, E (cid:96) while e1 loop e2 pool : void, S4
|
1684 |
+
so, S1, E (cid:96) while e1 loop e2 pool : void, S4
|
1685 |
+
|
1686 |
+
26
|
1687 |
+
|
1688 |
+
[Loop-True]
|
1689 |
+
|
1690 |
+
so, S1, E (cid:96) e1 : Bool(f alse), S2
|
1691 |
+
so, S1, E (cid:96) while e1 loop e2 pool : void, S2
|
1692 |
+
There are two rules for while: one for the case where the predicate is true and one for the case where the
|
1693 |
+
predicate is false. Both cases are straightforward. The two rules for isvoid are also straightforward:
|
1694 |
+
|
1695 |
+
[Loop-False]
|
1696 |
+
|
1697 |
+
so, S1, E (cid:96) e1 : void, S2
|
1698 |
+
so, S1, E (cid:96) isvoid e1 : Bool(true), S2
|
1699 |
+
|
1700 |
+
[IsVoid-True]
|
1701 |
+
|
1702 |
+
so, S1, E (cid:96) e1 : X(. . .), S2
|
1703 |
+
so, S1, E (cid:96) isvoid e1 : Bool(f alse), S2
|
1704 |
+
The remainder of the rules are for the primitive arithmetic, logical, and comparison operations except
|
1705 |
+
equality. These are all easy rules.
|
1706 |
+
|
1707 |
+
[IsVoid-False]
|
1708 |
+
|
1709 |
+
so, S1, E (cid:96) e1 : Bool(b), S2
|
1710 |
+
v1 = Bool(¬b)
|
1711 |
+
so, S1, E (cid:96) not e1 : v1, S2
|
1712 |
+
|
1713 |
+
so, S1, E (cid:96) e1 : Int(i1), S2
|
1714 |
+
so, S2, E (cid:96) e2 : Int(i2), S3
|
1715 |
+
op ∈ {≤, <}
|
1716 |
+
(cid:40)
|
1717 |
+
|
1718 |
+
v1 =
|
1719 |
+
|
1720 |
+
Bool(true), if i1 op i2
|
1721 |
+
Bool(f alse), otherwise
|
1722 |
+
|
1723 |
+
so, S1, E (cid:96) e1 op e2 : v1, S3
|
1724 |
+
|
1725 |
+
so, S1, E (cid:96) e1 : Int(i1), S2
|
1726 |
+
v1 = Int(−i1)
|
1727 |
+
|
1728 |
+
so, S1, E (cid:96) ˜e1 : v1, S2
|
1729 |
+
|
1730 |
+
[Not]
|
1731 |
+
|
1732 |
+
[Comp]
|
1733 |
+
|
1734 |
+
[Neg]
|
1735 |
+
|
1736 |
+
so, S1, E (cid:96) e1 : Int(i1), S2
|
1737 |
+
so, S2, E (cid:96) e2 : Int(i2), S3
|
1738 |
+
op ∈ {∗, +, −, /}
|
1739 |
+
v1 = Int(i1 op i2)
|
1740 |
+
so, S1, E (cid:96) e1 op e2 : v1, S3
|
1741 |
+
Cool Ints are 32-bit two’s complement signed integers; the arithmetic operations are defined accordingly.
|
1742 |
+
The notation and rules given above are not powerful enough to describe how objects are tested for
|
1743 |
+
|
1744 |
+
[Arith]
|
1745 |
+
|
1746 |
+
equality, or how runtime exceptions are handled. For these cases we resort to an English description.
|
1747 |
+
|
1748 |
+
In e1 = e2, first e1 is evaluated and then e2 is evaluated. The two objects are compared for equality
|
1749 |
+
by first comparing their pointers (addresses). If they are the same, the objects are equal. The value
|
1750 |
+
void is not equal to any object except itself. If the two objects are of type String, Bool, or Int, their
|
1751 |
+
respective contents are compared.
|
1752 |
+
|
1753 |
+
In addition, the operational rules do not specify what happens in the event of a runtime error.
|
1754 |
+
|
1755 |
+
Execution aborts when a runtime error occurs. The following list specifies all possible runtime errors.
|
1756 |
+
|
1757 |
+
1. A dispatch (static or dynamic) on void.
|
1758 |
+
|
1759 |
+
2. A case on void.
|
1760 |
+
|
1761 |
+
27
|
1762 |
+
|
1763 |
+
3. Execution of a case statement without a matching branch.
|
1764 |
+
|
1765 |
+
4. Division by zero.
|
1766 |
+
|
1767 |
+
5. Substring out of range.
|
1768 |
+
|
1769 |
+
6. Heap overflow.
|
1770 |
+
|
1771 |
+
Finally, the rules given above do not explain the execution behaviour for dispatches to primitive
|
1772 |
+
methods defined in the Object, IO, or String classes. Descriptions of these primitive methods are given
|
1773 |
+
in Sections 8.3-8.5.
|
1774 |
+
|
1775 |
+
14 Acknowledgements
|
1776 |
+
|
1777 |
+
Cool is based on Sather164, which is itself based on the language Sather. Portions of this document
|
1778 |
+
were cribbed from the Sather164 manual; in turn, portions of the Sather164 manual are based on Sather
|
1779 |
+
documentation written by Stephen M. Omohundro.
|
1780 |
+
|
1781 |
+
A number people have contributed to the design and implementation of Cool, including Manuel
|
1782 |
+
F¨ahndrich, David Gay, Douglas Hauge, Megan Jacoby, Tendo Kayiira, Carleton Miyamoto, and Michael
|
1783 |
+
Stoddart. Joe Darcy updated Cool to the current version.
|
1784 |
+
|
1785 |
+
28
|
1786 |
+
|
1787 |
+
|
DBMS/DATABASE%2520MANAGEMENT%2520SYSTEMS.pdf.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|