720 AppendixExample: .IronPython The following example shows a Python script called CustomerDB .py.. This is a factory method that constructs a Customer object using the parameters pass
Trang 1720 Appendix
Example: IronPython
The following example shows a Python script called CustomerDB py This class contains four items:
n A class called Customer This class contains three fields, which contain the ID, name, and
telephone number for a customer The constructor initializes these fields with values
passed in as parameters The str method formats the data in the class as a string so
that it can be output
n A class called CustomerDB This class contains a dictionary called customerDatabase The storeCustomer method adds a customer to this dictionary, and the getCustomer method retrieves a customer when given the customer ID The str method iterates
through the customers in the dictionary and formats them as a string For simplicity, none of these methods include any form of error checking
n A function called GetNewCustomer This is a factory method that constructs a Customer
object using the parameters passed in and then returns this object
n A function called GetCustomerDB This is another factory method that constructs a
CustomerDB object and returns it
return str.format("ID: {0}\tName: {1}\tTelephone: {2}",
self.custID, self.custName, self.custTelephone)
for id, cust in self.customerDatabase.iteritems():
list += str.format("{0}", cust) + "\n"
return list
Trang 2Appendix 721
def GetNewCustomer(id, name, telephone):
return Customer(id, name, telephone)
def GetCustomerDB():
return CustomerDB()
The following code example shows a simple C# console application that tests these items You can find this application in the \Microsoft Press\Visual CSharp Step By Step\Appendix\ PythonInteroperability folder under your Documents folder It references the IronPython assemblies, which provide the language binding for Python These assemblies are included with the IronPython download and are not part of the NET Framework Class Library
Note This sample application was built using the version of IronPython that was current when the book went to press If you have a later build of IronPython, you should replace the references
to the IronPython and Microsoft Scripting assemblies in this application with those provided with your installation of IronPython
The static CreateRuntime method of the Python class creates an instance of the Python runtime The UseFile method of the Python runtime opens a script containing Python code,
and it makes the items in this script accessible
Note In this example, the script CustomerDB py is located in the Appendix folder, but the
executable is built under the Appendix\PythonInteroperability\PythonInteroperability\bin\
Debug folder, which accounts for the path to the CustomerDB py script shown in the parameter
to the UseFile method
In this code, notice that the pythonCustomer and pythonCustomerDB variables reference Python types, so they are declared as dynamic The python variable used to invoke the
GetNewCustomer and GetCustomerDB functions is also declared as dynamic In reality, the
type returned by the UseFile method is a Microsoft.Scriping.Hosting.ScriptScope object However, if you declare the python variable using the ScriptScope type, the code will not build because the compiler, quite correctly, spots that the ScriptScope type does not con- tain definitions for the GetNewCustomer and GetCustomerDB methods Specifying dynamic causes the compiler to defer its checking to the DLR at runtime, by which time the python
variable refers to an instance of a Python script, which does include these functions
The code calls the GetNewCustomer Python function to create a new Customer object with the details for Fred It then calls GetCustomerDB to create a CustomerDB object, and then invokes the storeCustomer method to add Fred to the dictionary in the CustomerDB object The code creates another Customer object for a customer called Sid, and adds this cus- tomer to the CustomerDB object as well Finally, the code displays the CustomerDB object The Console WriteLine method expects a string representation of the CustomerDB object
Trang 3dynamic pythonCustomer = python.GetNewCustomer(100, “Fred”, “888”);
dynamic pythonCustomerDB = python.GetCustomerDB();
Trang 4def GetNewCustomer(id, name, telephone)
return Customer.new(id, name, telephone)
end
def GetCustomerDB
return CustomerDB.new
end
Trang 5724 Appendix
The following C# program uses this Ruby script to create two Customer objects, store them
in a CustomerDB object, and then print the contents of the CustomerDB object It operates
in the same way as the Python interoperability application described in the previous section,
and it uses the dynamic type to define the variables for the Ruby script and the Ruby objects
You can find this application in the \Microsoft Press\Visual CSharp Step By Step\Appendix\ RubyInteroperability folder under your Documents folder It references the IronRuby as- semblies, which provide the language binding for Ruby These assemblies are part of the IronRuby download
Note This sample application was built using the version of IronRuby that was current when the book went to press If you have a later build of IronRby, you should replace the references to the IronRuby, IronRuby Libraries, and Microsoft Scripting assemblies in this application with those provided with your installation of IronRuby
dynamic rubyCustomer = ruby.GetNewCustomer(100, “Fred”, “888”);
dynamic rubyCustomerDB = ruby.GetCustomerDB();
Trang 8access keys for menu items, 480
accessors, get and set, 298
Add Window command, 457
Administrator privileges, for
exercises, 535–537
ADO NET, 535connecting to databases with, 564
LINQ to SQL and, 549querying databases with, 535–548, 564
ADO NET class library, 535ADO NET Entity Data Model template, 566, 569, 596ADO NET Entity Framework, 566–583
AggregateException class,
642–644
Handle method, 642 AggregateException exceptions,
647
AggregateException handler,
642–644anchor points of controls, 447–448
AND (&) operator, 316anonymous classes, 147–148anonymous methods, 341anonymous types in arrays, 194–195, 197
APIs, 300App config (application configuration) file, 8, 573connection strings, storing in,
Application xaml cs files, 24App xaml files, code in, 24
ArgumentException class, 220 ArgumentException exceptions,
205, 225
argumentList, 51 ArgumentOutOfRangeException
class, 121arguments
in methods, 52modifying, 159–162named, ambiguities with, 66–71
omitting, 66passing to methods, 159positional, 66
arithmetic operations, 36–43results type, 37
arithmetic operatorschecked and unchecked, 119precedence, 41–42
using, 38–41array arguments, 220–226array elements
accessing, 195, 218types of, 192array indexes, 195, 218integer types for, 201array instancescopying, 197–198creating, 192–193, 218
ArrayList class, 208–209, 217
number of elements in, 209arrays, 191–206
associative, 212card playing application, 199–206
cells in, 198
vs collections, 214copying, 197–198implicitly typed, 194–195initializing elements of, 218inserting elements, 208
of int variables, 207
iterating through, 195–197, 218
keys arrays, 212, 213length of, 218multidimensional, 198–199
declaring, 191–192, 218initializing, 193–194naming conventions, 192
as operator, 169, 236 AsOrdered method, 655 AsParallel method, 650, 681
specifying, 652assemblies, 361definition of, 16namespaces and, 16uses of, 8
Trang 9copying data to, 502–504
for long-running operations,
building using generics, 361
creating generic classes, 371
datum, 358
enumerators, 383
iComparable interface, 362
inserting a node, 362node, 358
sorting data, 359subtrees, 358theory of, 358
TreeEnumerator class, 383
walking, 384
Binding elements, for
associating control properties with control properties, 513
BindingExpression class HasError property, 529–530,
532
UpdateSource method, 529 BindingExpression objects, 532
creating, 529
Binding objects, 526 BindingOperations class GetBinding method, 526
binding paths, 519binding sources, 518specifying, 531, 577
Binding.ValidationRules
elements, 532child elements, 516
bin folder, 13 Black.Hole method, 223 BlockingCollection<T> class, 669 BlockingCollection<T> objects,
670blocking mechanisms of synchronization primitives, 663–665
blocks of statements, 78–79braces in, 98
bool data type, 32, 74
Boolean expressionscreating, 89declaring, 73–74
in if statements, 78
in while statements, 93
Boolean operators, 74–77precedence and associativity, 76–77
short-circuiting, 76Boolean variables, declaring, 89
in class definitions, 130for grouping statements, 78–79, 93, 98
button controlsadding, 21anchoring, 447
Click event handlers, 471–474
mouse over behaviors, 456–457
Width and Height properties,
calculateClick method, 52–53
callback methods, registering, 634
camelCase, 30, 133for method names, 48
CanBeNull parameter, 550 Canceled task state, 638, 641 CancelEventArgs class, 475
cancellation, 632–645
of PLINQ queries, 656synchronization primitives and, 668
CancellationToken objects, 633
specifying, 643, 656
ThrowIfCancellationRequested
method, 640–641cancellation tokens, 633creating, 633–634examining, 641
AssemblyInfo cs files
Trang 10char data type, 32, 542
check box controls, 458
C# keywords See also keywords
IntelliSense lists of, 9
constructors for, 133–134 See also constructors
declaring, 149defining, 130–132definition of, 132derived classes, 232–234encapsulation in, 130generic classes, 358–370inheriting from interfaces, 255–256
instances of, assigning, 131interfaces, implementing, 261–266
method keyword combinations, 276modeling entities with, 513–515
with multiple interfaces, 257naming conventions, 133new, adding, 243partial classes, 136referencing through interfaces, 256–257sealed classes, 232, 271–277static classes, 144–145
vs structures, 181–182, 188–190
testing, 266–269class hierarchies, defining, 242–247
classification, 129–130inheritance and, 231–232
class keyword, 130, 149
class libraries, 361class members drop-down list box, 34
class methods, 144
class scope, defining, 54–55class types, copying, 151–156
clear_Click method, 471 clearName_Click method, 492 Click event handlers, 471–474
for menu items, 485–487
Click events, 25, 345 Clone method, 198 Closing event handler, 474–476
CLS (Common Language Specification), 30code See also execution flowcompiled, 8, 14
compiling, 11
compute-bound, 621–623error-handling, separating out, 110
exception safe, 289–292refactoring, 60, 270trying, 110–117
in WPF forms, viewing, 476
Code and Text Editor pane, 7
keywords in, 29code duplication, 269–270code views, 17
thread-safe, 668–670
Collection Editor: Items dialog
box, 480, 481collection initializers, 214collections
vs arrays, 214counting number of rows, 406enumerable, 381
enumerating elements, 381–389
GetEnumerator methods, 382 IEnumerable interface, 382
iterating through, 218, 650–655
thread-safe, 678–679
of unordered items, 669
Collect method, 283 Colors enumeration, 268 Column attribute, 550, 564
combo box controls, 458adding, 460
populating, 476
Command class, 542 Command objects, 542
command prompt windows, opening, 538
CommandText property, 542,
564
CommandText property
Trang 11computer memory See memory
Concurrency Mode property,
concurrent threads, 600 See
also multitasking; threads
conditional AND operator, precedence and associativity of, 77conditional logical operators, 75short-circuiting, 76
conditional OR operator, precedence and associativity of, 77
564connection strings, 559, 562, 564
building, 540
for DataContext constructor,
551–552storing, 572Console Application icon, 5, 6console applications
assembly references in, 16creating, 8–14, 26definition of, 3Visual Studio-created files, 8–9
Console Application template, 7
Console class, 9 Console.WriteLine method, 186,
219, 224calling, 137–138
Console.Write method, 58 const keyword, 144
constraints, with generics, 358constructed types, 357constructors, 133–134base class constructors, 234–235
calling, 149declaring, 149default, 133–134, 135definition of, 23initializing fields with, 139initializing objects with, 279order of definition, 135overloading, 134–135private, 134
shortcut menu code in, 493–494
for structures, 183, 185writing, 137–140
consumers, 669
Content property, 20, 459, 469 ContextMenu elements, 491
Continue button (Debug toolbar), 63
continue statements, 100 ContinueWith method, 606, 645,
646contravariance, 377
Control class Setter elements,
456controlsadding to forms, 459–461, 476aligning, 460
alignment indicators, 21anchor points, 447
Content property, 469
displaying, 40focus, validation and, 509,
resetting to default values, 466–470
ConvertBack method, 523, 524
converter classes, 578creating, 523–525for data binding, 522converter methods, 522–523creating, 523–525
Convert method, 578
commenting out a block of code
Trang 12Created task state, 638
CREATE TABLE statements, 549
retrieving information, 579–582
user interface for, 574–579database connectionsclosing, 545–547, 553connection pooling, 547creating, 569–570logic for, 572opening, 540database queriesADO NET for, 564deferred, 557–558immediate evaluation of, 553–554
iterating through, 552LINQ to Entities for, 582–583LINQ to SQL for, 564databases
access errors, 539adding and deleting data, 587–594, 596
concurrent connections, 547connecting to, 538–540, 564creating, 536–538
data type mapping, 550disconnecting from, 545–547entity data models, 565fetching and displaying data, 543–544, 551–553
granting access to, 567–568locked data, 544
mapping layer, 565new, creating, 551null values in, 547–548, 550, 564
prompting users for information, 541–543, 562querying, 541–543
querying, with ADO NET, 535–548
querying, with LINQ to SQL, 549–564
referential integrity errors, 588
saving changes to, 584–586, 594–596
saving user information, 562updating data, 583–596 Windows Authentication access, 540, 541
database tables
Column attribute, 550
deleting rows in, 588, 596entity classes, relationships between, 551–552entity data models for, 568–572
joining, 554–558many-to-one relationships, 555–556
modifying information in, 596new, creating, 551
null values in, 550one-to-many relationships, 556–558
primary keys, 550querying, 541–543retrieving data from, 579–582retrieving single rows, 553
Table attribute, 550
underlying type of columns, 550
data bindingbinding control properties
to control properties, 513, 525–526, 531
binding control properties to object properties, 531binding controls to class properties, 515binding sources, 518, 531binding WPF controls to data sources, 580
converter classes, 522–525Entity Framework, using with, 579–582
existing data, updating with, 583–584
fetching and displaying data with, 579–583
modifying data with, 583–596for validation, 511–527
DataMember attribute
Trang 13732
data provider classes for ADO
NET, 539
data providers, 535–536
data sets, partitioning, 650
data sources, joining, 654
DataTemplate, 576
data types
bool data type, 32, 74
char data type, 32, 542
data type mapping, 550
DateTime data type, 81, 84
decimal data type, 31
double data type, 31
of enumerations, 176
float data type, 31
IntelliSense lists of, 9
long data type, 31
defining operator pairs, 426
Definite Assignment Rule, 32
Delegate class, 506
delegates, 329advantages, 332attaching to events, 345calling automatically, 342declaring, 331
defining, 331
DoWorkEventHandler
delegate, 504initializing with a single, specific method, 331invoking, 332
lambda expressions, 338matching shapes, 331scenario for using, 330using, 333
deserialization, 691design views, 17
Design View window, 19
cached information in, 579working in, 19–22WPF forms in, 445
desktop applications See also
applicationsmultitasking in, 602–628destructors
calling, 292
Dispose method, calling from,
288–289recommendations on, 284timing of execution, 283writing, 280–282, 292
collection class, thread-safe version, 669
Dispatcher.Invoke method, 632 Dispatcher objects, 505–507 Invoke method, 506
responsiveness, improving with, 629, 631–632
DispatcherPriority enumeration,
507, 631disposal methods, 285exception-safe, 285–286, 289–292
exceptions, 123division operator, 36precedence of, 41 dll file name extension, 16
DockPanel controls, adding,
479, 508documenting code, 11
Document Outline window,
39–40documents, definition of, 477Documents folder, 6
do statements, 99–108
stepping through, 103–107syntax of, 99
dot notation, 134dot operator ( ), 280
double data type, 31 double.Parse method, 58
double quotation marks (“), 88
DoWork event, subscribing to,
dual-core processors, 602duplication in code, 269–270
DynamicResource keyword, 454
E
ElementName tag, 531 else keyword, 77, 78
encapsulation, 130, 146golden rule, 296
data provider classes for ADO NET
Trang 14entity classes, creating, 596
fetching and displaying data,
updating data with, 583–596
EntityObject class Concurrency
Mode property, 585
entity objects
binding properties of controls
to, 566–583displaying data from, 596modifying, 583
EntityRef<TEntity> types,
555–556
EntitySet<Product> types, 556 EntitySet<TEntity> types,
555–556enumerable collections, 381enumerating collections, 381enumerations, 173–178converting to strings, 522declaring, 173–174, 176–178, 190
integer values for, 175literal names, 174literal values, 175nullable versions of, 174syntax of, 173–174underlying type of, 176using, 174–175enumeration variables, 174assigning to values, 190converting to strings, 174declaring, 190
mathematical operations on, 177–178
enumerator objects, 382
enumerators
Current property, 382
iterators, 389manually implementing, 383
MoveNext method, 382 Reset method, 382 yield keyword, 390 enum keyword, 173, 190 enum types, 173–178
equality (==) operator, 74precedence and associativity
of, 77
Equal method, 431 equal sign (=) operator, 42 See also assignment operator
text descriptions of, 111
errorStyle style, 525
escape character (\), 88
EventArgs argument, 346
event handlersfor about events, 488
for Closing events, 474–476
for menu actions, 508long-running, simulating, 498–499
for new events, 485–486for save events, 487–488testing, 489–490
in WPF applications, 470–476event methods, 471
for menu items, 508naming, 472removing, 472writing, 476events, 342–344attaching delegates, 345declaring, 342
EventArgs argument, 346
menu events, handling, 484–491
null checks, 344raising, 344sender argument, 346sources, 342
subscribers, 342subscribing, 343
vs triggers, 456unsubscribing, 344using a single method, 346waiting for, 661, 681WPF user interface, 345event sources, 342
Example class, 289
exception handling, 110 for tasks, 641–644
Exception inheritance hierarchy,
113catching, 126, exception objects, 121examining, 111–112, 642–643exceptions, 109
DivideByZeroException
exceptions, 123 examining, 111–112
exceptions
Trang 15viewing code causing, 116
exception safe code, 289–292
extensible programming frameworks, building, 253extension methods, 247–251creating, 248–250
Faulted task state, 638, 641
fetching, 543–545deferred, 553–554, 558immediate, 558
with SqlDataReader objects,
564fields, 54–55, 129definition of, 131inheritance of, 234–235initializing, 133, 139, 140naming conventions, 133shared fields, 143–144static and nonstatic, 143–144
See also static fields
FileInfo class, 94 OpenText method, 95 fileName parameter, 500 FileName property, 496
file names, asterisks by, 12files, closing, 96
finalization, 284order of, 283, 284
Finalize method,
compiler-generated, 282
finally blocks, 124–126
database connection close statements in, 545disposal methods in, 285–286execution flow and, 125firehose cursors, 544first-in, first-out (FIFO) mechanisms, 210
float data type, 31
floating-point arithmetic, 119focus of controls, validation and,
509, 518, 527
FontFamily property, 457 FontSize property, 20, 457 FontWeight property, 457 foreach statements, 196, 381
for database queries, 553, 556–558
iterating arrays with, 204iterating database queries with, 552
iterating database tables with, 563
iterating param arrays with, 225
iterating zero-length arrays with, 223
FormatException catch handler,
for statements, 97–99, 108
iterating arrays with, 196omitting parts of, 97–98scope of, 98–99syntax of, 97forward slash (/) operator, 36freachable queue, 284
F type suffix, 34
fully qualified names, 15
Func<T> generic type, 506
G
garbage collection, 156–157, 280
destructors, 280–282guarantees of, 282–283invoking, 283, 292timing of, 283garbage collector, functionality
of, 283–284
GC class Collect method, 283 SuppressFinalize method, 289
generalized class, 357Generate Method Stub Wizard, 57–60, 72
exceptions (continued)