Attention! Your ePaper is waiting for publication!
By publishing your document, the content will be optimally indexed by Google via AI and sorted into the right category for over 500 million ePaper readers on YUMPU.
This will ensure high visibility and many readers!
Your ePaper is now published and live on YUMPU!
You can find your publication here:
Share your interactive ePaper on all platforms and on your website with our embed function
Free-ebooks-library - Bahar Ali Khan
Free-ebooks-library - Bahar Ali Khan
Free-ebooks-library - Bahar Ali Khan
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
The easiest way to figure out which expression type to use is to<br />
examine an existing lambda expression in the Visual Studio debugger.<br />
We continue this discussion online, at http://www.albahari.com/expressions/.<br />
366 | Chapter 8: LINQ Queries
The easiest way to figure out which expression type to use is to examine an existing lambda expression in the Visual Studio debugger. We continue this discussion online, at http://www.albahari.com/expressions/. 366 | Chapter 8: LINQ Queries
9 LINQ Operators This chapter describes each of the LINQ query operators. As well as serving as a reference, two of the sections, “Projecting” on page 375 and “Joining” on page 370, cover a number of conceptual areas: • Projecting object hierarchies • Joining with Select, SelectMany, Join, and GroupJoin • Outer range variables in query expressions All of the examples in this chapter assume that a names array is defined as follows: string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" }; Examples that query a database assume that a typed DataContext variable called dataContext is instantiated as follows: var dataContext = new NutshellContext ("connection string..."); ... public class NutshellContext : DataContext { public NutshellContext (string cxString) : base (cxString) {} public Table Customers { get { return GetTable(); } } public Table Purchases { get { return GetTable(); } } } [Table] public class Customer { [Column(IsPrimaryKey=true)] public int ID; [Column] public string Name; [Association (OtherKey="CustomerID")] public EntitySet Purchases = new EntitySet(); } 367
- Page 1 and 2:
www.free-ebooks-library.com
- Page 3:
C# 4.0 www.free-ebooks-library.com
- Page 6 and 7:
C# 4.0 in a Nutshell, Fourth Editio
- Page 8 and 9:
Structs 89 Access Modifiers 90 Inte
- Page 10 and 11:
Annotations 440 Projecting into an
- Page 12 and 13:
Emitting Generic Methods and Types
- Page 14 and 15:
Groups 985 Replacing and Splitting
- Page 16 and 17:
If you’re already familiar with C
- Page 18 and 19:
This icon signifies a tip, suggesti
- Page 20 and 21:
I have the highest praise for Jon S
- Page 22 and 23:
Properties, methods, and events In
- Page 24 and 25:
Figure 1-1. This depicts the topics
- Page 26 and 27:
object o1 = "foo.doc"; object o2 =
- Page 28 and 29:
The first statement computes the ex
- Page 30 and 31:
The name of the C# compiler is csc.
- Page 32 and 33:
With contextual keywords, ambiguity
- Page 34 and 35:
Custom Type Examples Just as we can
- Page 36 and 37:
} } The public keyword The public k
- Page 38 and 39:
Figure 2-2. Assignment copies a val
- Page 40 and 41:
Technically, the CLR positions fiel
- Page 42 and 43:
Numeric literal type inference By d
- Page 44 and 45:
+ Addition − Subtraction * Multip
- Page 46 and 47:
In this case, x and y are implicitl
- Page 48 and 49:
which breaks equality and compariso
- Page 50 and 51:
Strings and Characters C#’s char
- Page 52 and 53:
Arrays An array represents a fixed
- Page 54 and 55:
int[,] matrix = new int[,] { {0,1,2
- Page 56 and 57:
Variables and Parameters A variable
- Page 58 and 59:
The following code outputs 0, becau
- Page 60 and 61:
static void Foo (ref int p) { p = p
- Page 62 and 63:
for (int i = 0; i < ints.Length; i+
- Page 64 and 65:
var—Implicitly Typed Local Variab
- Page 66 and 67:
Operator Precedence and Associativi
- Page 68 and 69:
Category Operator symbol Operator n
- Page 70 and 71:
Expression statements x = 1 + 2; //
- Page 72 and 73:
The switch statement switch stateme
- Page 74 and 75:
For example, the following prints t
- Page 76 and 77:
The return statement The return sta
- Page 78 and 79:
Rules Within a Namespace Name scopi
- Page 80 and 81:
namespace N2 { class Class3 : Class
- Page 82 and 83:
The :: token is used for namespace
- Page 84 and 85:
Fields allow the following modifier
- Page 86 and 87:
Overloading constructors A class or
- Page 88 and 89:
Object Initializers Versus Optional
- Page 90 and 91:
Properties allow the following modi
- Page 92 and 93:
Here’s how we could use this inde
- Page 94 and 95:
If a static constructor throws an u
- Page 96 and 97:
In addition, each participant can i
- Page 98 and 99:
Casting and Reference Conversions A
- Page 100 and 101:
public class Asset { public string
- Page 102 and 103:
Overrider over = new Overrider(); B
- Page 104 and 105:
Constructor and field initializatio
- Page 106 and 107:
Boxing and Unboxing Boxing is the a
- Page 108 and 109:
The ToString Method The ToString me
- Page 110 and 111:
Changing struct to class makes this
- Page 112 and 113:
Interfaces An interface is similar
- Page 114 and 115:
type that implements ISerializable
- Page 116 and 117:
public class RichTextBox : TextBox
- Page 118 and 119:
Center } A translation between the
- Page 120 and 121:
Unfortunately, Enum.IsDefined does
- Page 122 and 123:
Generic Types C# generics and C++ t
- Page 124 and 125:
static void Swap (ref T a, ref T b)
- Page 126 and 127:
Generic Constraints By default, a t
- Page 128 and 129:
Self-Referencing Generic Declaratio
- Page 130 and 131:
Classes Covariance and contravarian
- Page 132 and 133:
The IEnumerator and IEnumerable int
- Page 134 and 135:
The reason is that Max needs to be
- Page 136 and 137:
Technically, we are specifying a me
- Page 138 and 139:
Multicast delegate example Suppose
- Page 140 and 141:
The Func and Action Delegates With
- Page 142 and 143:
The following, however, is permitte
- Page 144 and 145:
Events When using delegates, two em
- Page 146 and 147:
public class PriceChangedEventArgs
- Page 148 and 149:
if (price == value) return; OnPrice
- Page 150 and 151:
Here is an example that illustrates
- Page 152 and 153:
Capturing Outer Variables A lambda
- Page 154 and 155:
Anonymous Methods Anonymous methods
- Page 156 and 157:
OUTPUT: x cannot be zero program co
- Page 158 and 159:
• The try block finishes normally
- Page 160 and 161:
The other common scenario is to ret
- Page 162 and 163:
indeterminate state that is the res
- Page 164 and 165:
class Enumerable // Typically imple
- Page 166 and 167:
Iterator Semantics An iterator is a
- Page 168 and 169:
yield return prevFib; int newFib =
- Page 170 and 171:
object o = "string"; int? x = o as
- Page 172 and 173:
Console.WriteLine (n | f); // (null
- Page 174 and 175:
== != > < >=
- Page 176 and 177:
Note n = (Note)554.37; // explicit
- Page 178 and 179:
Extension Method Chaining Extension
- Page 180 and 181:
static void Main() { string[] strin
- Page 182 and 183:
Now let’s change the static type
- Page 184 and 185:
Dynamic binding also incurs a perfo
- Page 186 and 187:
The static type of a variable decla
- Page 188 and 189:
The call to Foo(o,d) is dynamically
- Page 190 and 191:
parameters. The following attribute
- Page 192 and 193:
Value types declared inline within
- Page 194 and 195:
} } Pointers to Unmanaged Code Poin
- Page 196 and 197:
Compiler warnings can be extremely
- Page 198 and 199:
... Indicates a multiline code sam
- Page 200 and 201:
M:NS.MyClass.Z(System.Char[ ],Syste
- Page 202 and 203:
Table 5-1. C#, CLR, and .NET Framew
- Page 204 and 205:
Text Processing The System.Text nam
- Page 206 and 207:
this metadata at runtime, and do su
- Page 208 and 209:
infrastructure. Web Forms has been
- Page 210 and 211:
Provider layer The provider model d
- Page 212 and 213:
Remoting and Web Services Remoting
- Page 214 and 215:
ecause in Turkey, char.ToUpper ('i'
- Page 216 and 217:
string empty = ""; Console.WriteLin
- Page 218 and 219:
The static Join method does the rev
- Page 220 and 221:
order—but even then not exactly a
- Page 222 and 223:
The following performs a case-insen
- Page 224 and 225:
UTF-32 is the least space-efficient
- Page 226 and 227:
Two-word characters are called surr
- Page 228 and 229:
An excellent article on the rationa
- Page 230 and 231:
You can also construct a DateTime w
- Page 232 and 233:
The Add method adds a TimeSpan to a
- Page 234 and 235:
You can construct a DateTime that d
- Page 236 and 237:
source and destination TimeZoneInfo
- Page 238 and 239:
Western Australia is actually uniqu
- Page 240 and 241:
ToString and Parse The simplest for
- Page 242 and 243:
The next example formats a DateTime
- Page 244 and 245:
The following custom format provide
- Page 246 and 247:
Letter Meaning Sample input Result
- Page 248 and 249:
Figure 6-1. Composite NumberStyles
- Page 250 and 251:
The format strings "r", "R", and "u
- Page 252 and 253:
Other Conversion Mechanisms In the
- Page 254 and 255:
XmlConvert If you’re dealing with
- Page 256 and 257:
The .NET Framework helps you with t
- Page 258 and 259:
The Round method lets you specify t
- Page 260 and 261:
If you don’t want reproducibility
- Page 262 and 263:
static object GetBoxedIntegralValue
- Page 264 and 265:
Tuples Framework 4.0 provides a new
- Page 266 and 267:
Value Versus Referential Equality T
- Page 268 and 269:
Why the Complexity? You might wonde
- Page 270 and 271:
The IEquatable interface A conseque
- Page 272 and 273:
How to override equality semantics
- Page 274 and 275:
Implementing IEquatable For complet
- Page 276 and 277:
The .NET Framework also provides pl
- Page 278 and 279:
if (Equals (other)) return 0; // Fa
- Page 280 and 281:
Environment The static System.Envir
- Page 283 and 284:
7 Collections The .NET Framework pr
- Page 285 and 286:
By defining a single method retunin
- Page 287 and 288:
You can also subclass an existing c
- Page 289 and 290:
{ get { if (currentIndex == −1) t
- Page 291 and 292:
The ICollection and IList Interface
- Page 293 and 294:
IList and IList IList is the standa
- Page 295 and 296:
Because Array is a class, arrays ar
- Page 297 and 298:
void WriteFirstValue (Array a) { Co
- Page 299 and 300:
public static int FindIndex (T[] ar
- Page 301 and 302:
The Comparison delegate follows the
- Page 303 and 304:
List and ArrayList The generic List
- Page 305 and 306:
Such casts cannot be verified by th
- Page 307 and 308:
Here’s a demonstration on the use
- Page 309 and 310:
public sealed class BitArray : ICol
- Page 311 and 312:
public virtual SortedSet GetViewBet
- Page 313 and 314:
IDictionary IDictionary defines the
- Page 315 and 316:
Its underlying hashtable works by c
- Page 317 and 318:
var sorted = new SortedList (); for
- Page 319 and 320:
public class Animal { public string
- Page 321 and 322:
A keyed collection has some resembl
- Page 323 and 324:
clumsy hook methods like Collection
- Page 325 and 326:
Recall the requirements of a hashta
- Page 327 and 328:
IComparer and Comparer Comparers ar
- Page 329 and 330:
{ public abstract int Compare (stri
- Page 331 and 332:
8 LINQ Queries LINQ, or Language In
- Page 333 and 334:
We could further shorten our code b
- Page 335 and 336: We already introduced the Where ope
- Page 337 and 338: output sequence. In the case of the
- Page 339 and 340: Natural Ordering The original order
- Page 341 and 342: Figure 8-2. Query syntax The compil
- Page 343 and 344: With LINQ, data logically flows fro
- Page 345 and 346: Reevaluation Subqueries provide ano
- Page 347 and 348: How Deferred Execution Works Query
- Page 349 and 350: Adding ToList onto the end of this
- Page 351 and 352: The term subquery, in the general s
- Page 353 and 354: Figure 8-8. UML subquery compositio
- Page 355 and 356: select n.Replace ("a", "").Replace
- Page 357 and 358: (The compiler does not emit the fin
- Page 359 and 360: where vowelless.Length > 2 orderby
- Page 361 and 362: IQueryable query = from c in custom
- Page 363 and 364: To work, LINQ to SQL needs some clu
- Page 365 and 366: Figure 8-10. Combining local and in
- Page 367 and 368: LINQ to SQL Versus Entity Framework
- Page 369 and 370: Unlike with L2S, however, a class s
- Page 371 and 372: The Single operator is ideal for re
- Page 373 and 374: You can disable this behavior in L2
- Page 375 and 376: With EF: [EdmRelationshipNavigation
- Page 377 and 378: • It lets you request that certai
- Page 379 and 380: context.SubmitChanges(); // Updates
- Page 381 and 382: Purpose LINQ to SQL Entity Framewor
- Page 383 and 384: void Test() { var dataContext = new
- Page 385: Figure 8-12. Expression tree We can
- Page 389 and 390: Overview In this section, we provid
- Page 391 and 392: Picks a single element from a seque
- Page 393 and 394: In query syntax: IEnumerable query
- Page 395 and 396: TakeWhile enumerates the input sequ
- Page 397 and 398: IEnumerable query = names .Select (
- Page 399 and 400: This is slightly untidy, however, i
- Page 401 and 402: element is the trigger for the intr
- Page 403 and 404: Thinking in query syntax As we just
- Page 405 and 406: from c in dataContext.Customers fro
- Page 407 and 408: Joining If you’re used to writing
- Page 409 and 410: To see the benefit of Join over Sel
- Page 411 and 412: GroupJoin GroupJoin does the same w
- Page 413 and 414: You can create and query lookups ma
- Page 415 and 416: OrderBy, OrderByDescending, ThenBy,
- Page 417 and 418: var query = names.OrderBy (s => s.L
- Page 419 and 420: from file in files group file.ToUpp
- Page 421 and 422: In the next example, we filter the
- Page 423 and 424: public static IEnumerable Cast (IE
- Page 425 and 426: Method Description SQL equivalents
- Page 427 and 428: Count simply enumerates over a sequ
- Page 429 and 430: The first argument to Aggregate is
- Page 431 and 432: Quantifiers IEnumerable→bool Meth
- Page 433 and 434: 10 LINQ to XML The .NET Framework p
- Page 435 and 436: Figure 10-1. Core X-DOM types Figur
- Page 437 and 438:
XElement client = config.Element ("
- Page 439 and 440:
); new XElement ("lastname", c.Last
- Page 441 and 442:
Child Node Navigation Return type M
- Page 443 and 444:
The first call to Elements binds to
- Page 445 and 446:
Return type Members Defined in IEnu
- Page 447 and 448:
The ReplaceXXX methods are equivale
- Page 449 and 450:
Setting Values There are two ways t
- Page 451 and 452:
var e1 = new XElement ("test", "Hel
- Page 453 and 454:
Console.WriteLine (doc.Root.Parent
- Page 455 and 456:
XML file into another. Second, name
- Page 457 and 458:
Specifying Namespaces in the X-DOM
- Page 459 and 460:
foreach (XElement e in data.Descend
- Page 461 and 462:
A public type such as string doesn
- Page 463 and 464:
know about IQueryable, so it forces
- Page 465 and 466:
ObjectGraph.cs Program.cs Propertie
- Page 467 and 468:
11 Other XML Technologies The Syste
- Page 469 and 470:
Reading Nodes The units of an XML s
- Page 471 and 472:
Element----------> quote CDATA-----
- Page 473 and 474:
eader.ReadStartElement ("customerLi
- Page 475 and 476:
The XmlReader must be positioned on
- Page 477 and 478:
XmlWriter XmlWriter is a forward-on
- Page 479 and 480:
Patterns for Using XmlReader/XmlWri
- Page 481 and 482:
if (isEmpty) return; // element! w
- Page 483 and 484:
using (XmlWriter w = XmlWriter.Crea
- Page 485 and 486:
Setting the InnerText property repl
- Page 487 and 488:
XPath queries are expressed in term
- Page 489 and 490:
The [] operator filters a selection
- Page 491 and 492:
OUTPUT: Jim Thomas XSD and Schema V
- Page 493 and 494:
settings.ValidationEventHandler +=
- Page 495 and 496:
12 Disposal and Garbage Collection
- Page 497 and 498:
These rules are also helpful when w
- Page 499 and 500:
The idea is that a consumer of this
- Page 501 and 502:
public void Test() { byte[] myArray
- Page 503 and 504:
Figure 12-1. Roots deleted right aw
- Page 505 and 506:
objects with finalizers (because su
- Page 507 and 508:
public class TempFileRef { public r
- Page 509 and 510:
Figure 12-2. Heap generations The l
- Page 511 and 512:
dynamically tweaks the thresholds f
- Page 513 and 514:
Timers Forgotten timers can also ca
- Page 515 and 516:
var sb = new StringBuilder ("this i
- Page 517 and 518:
public TDelegate Target { get { var
- Page 519 and 520:
13 Diagnostics and Code Contracts W
- Page 521 and 522:
MyCompany.Widgets.Gadget; #endif Yo
- Page 523 and 524:
Both the Debug and Trace classes pr
- Page 525 and 526:
EventLog.CreateEventSource ("DemoAp
- Page 527 and 528:
if (list.Contains(item)) return fal
- Page 529 and 530:
The binary rewriter After compiling
- Page 531 and 532:
Preconditions should access only me
- Page 533 and 534:
• It’s time-consuming. • Call
- Page 535 and 536:
The binary rewriter moves postcondi
- Page 537 and 538:
For the reason just stated, postcon
- Page 539 and 540:
A special mechanism lets specify a
- Page 541 and 542:
Handling this event is particularly
- Page 543 and 544:
3. In the debug configuration of th
- Page 545 and 546:
Attaching and Breaking The static D
- Page 547 and 548:
If you instantiate a StackTrace obj
- Page 549 and 550:
2. Decide on a source name and crea
- Page 551 and 552:
The following sections illustrate h
- Page 553 and 554:
{ if (!PerformanceCounterCategory.E
- Page 555:
If you later want to define more co
- Page 558 and 559:
Figure 14-1. Stream architecture St
- Page 560 and 561:
In the following example, we use a
- Page 562 and 563:
Seeking A stream is seekable if Can
- Page 564 and 565:
OpenWrite and Create differ in beha
- Page 566 and 567:
[Flags] public enum FileAccess { Re
- Page 568 and 569:
Pipes are stream-based, so one proc
- Page 570 and 571:
Console.WriteLine (Encoding.UTF8.Ge
- Page 572 and 573:
Console.WriteLine (fs.Position); //
- Page 574 and 575:
is passed in (optionally through an
- Page 576 and 577:
using (TextWriter w = File.CreateTe
- Page 578 and 579:
public void SaveData (Stream s) { v
- Page 580 and 581:
The File Class File is a static cla
- Page 582 and 583:
using System.Runtime.InteropService
- Page 584 and 585:
FileInfo offers most of the File’
- Page 586 and 587:
Special Folders You must delete the
- Page 588 and 589:
watcher.Created += FileCreatedChang
- Page 590 and 591:
Memory-Mapped Files and Shared Memo
- Page 592 and 593:
using (TextWriter w = new StreamWri
- Page 594 and 595:
Isolation Types Isolated storage ca
- Page 596 and 597:
IsolatedStorageFile is poorly named
- Page 598 and 599:
s.WriteByte (100); f.DeleteFile (@"
- Page 600 and 601:
Figure 15-1. Network architecture I
- Page 602 and 603:
IPAddress a3 = IPAddress.Parse ("[3
- Page 604 and 605:
Uri u = new Uri ("page.html", UriKi
- Page 606 and 607:
2. Assign the Proxy property. 3. As
- Page 608 and 609:
If you don’t have a proxy, you mu
- Page 610 and 611:
Windows protocol that boils down to
- Page 612 and 613:
2. Examine the response object’s
- Page 614 and 615:
System.IO.File.WriteAllBytes ("Sear
- Page 616 and 617:
you greater privileges in browsing
- Page 618 and 619:
In this example, we sleep for 500 m
- Page 620 and 621:
without needing more threads—by f
- Page 622 and 623:
Using DNS In all these examples, yo
- Page 624 and 625:
Using TCP TCP and UDP constitute th
- Page 626 and 627:
Hello Hello right back! In this exa
- Page 628 and 629:
In this example, we write each mail
- Page 630 and 631:
Serialization Engines There are fou
- Page 632 and 633:
an arbitrary XML structure. For ins
- Page 634 and 635:
It requires, however, that you expl
- Page 636 and 637:
Specifying a name and namespace dec
- Page 638 and 639:
The solution is to specify all perm
- Page 640 and 641:
we would see the same address detai
- Page 642 and 643:
Null and Empty Values There are two
- Page 644 and 645:
Subclassed Collection Elements The
- Page 646 and 647:
[DataMember (Name="Addresses")] Ser
- Page 648 and 649:
The following example illustrates a
- Page 650 and 651:
The two formatters are otherwise ex
- Page 652 and 653:
[OnSerializing] and [OnSerialized]
- Page 654 and 655:
Binary Serialization with ISerializ
- Page 656 and 657:
Subclassing Serializable Classes In
- Page 658 and 659:
XmlSerializer xs = new XmlSerialize
- Page 660 and 661:
and you write a reusable method to
- Page 662 and 663:
If, on the other hand, you want the
- Page 664 and 665:
instead add [XmlElement] to the col
- Page 666 and 667:
public void WriteXml (XmlWriter wri
- Page 668 and 669:
Assemblies are structured similarly
- Page 670 and 671:
To embed an application manifest fi
- Page 672 and 673:
Table 17-1. Assembly members Functi
- Page 674 and 675:
Delay Signing In an organization wi
- Page 676 and 677:
If the assembly has no AssemblyVers
- Page 678 and 679:
Figure 17-3. Unsigned file warning
- Page 680 and 681:
Signing with signtool.exe You can A
- Page 682 and 683:
• Updating assemblies in the GAC
- Page 684 and 685:
.mresource public banner.jpg { // O
- Page 686 and 687:
GetManifestResourceNames returns th
- Page 688 and 689:
(The first argument must be namespa
- Page 690 and 691:
We then retrieved the greeting at r
- Page 692 and 693:
where to look. You (or Visual Studi
- Page 694 and 695:
Loading from a filename You can see
- Page 696 and 697:
if (!File.Exists (path)) return nul
- Page 698 and 699:
for the presence of a library in it
- Page 701 and 702:
18 Reflection and Metadata As we sa
- Page 703 and 704:
Obtaining array types As we just sa
- Page 705 and 706:
Base Types and Interfaces Type expo
- Page 707 and 708:
Console.WriteLine (staticD.DynamicI
- Page 709 and 710:
When calling GetMembers, you can pa
- Page 711 and 712:
C# construct Method to use Name to
- Page 713 and 714:
Console.WriteLine (unbound.Property
- Page 715 and 716:
from m in typeof (Enumerable).GetMe
- Page 717 and 718:
The following example retrieves all
- Page 719 and 720:
There’s no nongeneric type we can
- Page 721 and 722:
Modules Calling GetTypes on a multi
- Page 723 and 724:
The AttributeUsage Attribute Attrib
- Page 725 and 726:
Retrieving Attributes at Runtime Th
- Page 727 and 728:
AppDomain.CurrentDomain.ReflectionO
- Page 729 and 730:
gen.Emit (OpCodes.Ldc_I4, 123); //
- Page 731 and 732:
gen.Emit (OpCodes.Mul); // Multiply
- Page 733 and 734:
Type[] strT = { typeof (string) };
- Page 735 and 736:
The DefineType method also accepts
- Page 737 and 738:
We could just as easily call a dyna
- Page 739 and 740:
mb.DefineParameter (1, ParameterAtt
- Page 741 and 742:
ILGenerator setGen = setter.GetILGe
- Page 743 and 744:
myFieldBuilder.SetCustomAttribute (
- Page 745 and 746:
Awkward Emission Targets All the ex
- Page 747 and 748:
and object references. In creating
- Page 749 and 750:
Here is a sample of the output our
- Page 751 and 752:
The next step is to call FormatOper
- Page 753:
The point where we call ResolveMemb
- Page 756 and 757:
trees (the same expression trees in
- Page 758 and 759:
yte b = 3; Console.WriteLine ((b +
- Page 760 and 761:
DynamicVisit on each person in the
- Page 762 and 763:
Anonymously Calling Members of a Ge
- Page 764 and 765:
Notice that we used dynamic member
- Page 766 and 767:
The following does a similar thing
- Page 768 and 769:
In the following example, we use Ir
- Page 771 and 772:
In this chapter, we discuss the two
- Page 773 and 774:
Framework 4.0 deprecates support fo
- Page 775 and 776:
When you call AddPermission, the pe
- Page 777 and 778:
if you access the chosen file by ca
- Page 779 and 780:
Elevation of Privilege Let’s supp
- Page 781 and 782:
The Transparency Model in CLR 4.0 T
- Page 783 and 784:
Figure 20-1. Transparency model; on
- Page 785 and 786:
GC.AddMemoryPressure (1000000); //
- Page 787 and 788:
stack, the WindowFromPoint method w
- Page 789 and 790:
string dir = Path.Combine (System.R
- Page 791 and 792:
The first step in doing this is to
- Page 793 and 794:
A feature called User Access Contro
- Page 795 and 796:
If you replace requireAdministrator
- Page 797 and 798:
Table 20-8. Encryption and hashing
- Page 799 and 800:
The GetBytes method on an Encoding
- Page 801 and 802:
As well as a key, we made up an IV,
- Page 803 and 804:
w.WriteLine ("Small and secure!");
- Page 805 and 806:
pairs. A key pair contains a public
- Page 807 and 808:
using (var rsaPublicPrivate = new R
- Page 809 and 810:
C# allows you to execute code in pa
- Page 811 and 812:
Getting Started A client program (C
- Page 813 and 814:
Thread.Sleep(0) relinquishes the th
- Page 815 and 816:
string text = "t1"; Thread t1 = new
- Page 817 and 818:
If this program is called with no a
- Page 819 and 820:
The try/catch statement in this exa
- Page 821 and 822:
There are a few things to be wary o
- Page 823 and 824:
static void Main() { ThreadPool.Que
- Page 825 and 826:
we’re using it to pass the method
- Page 827 and 828:
Fortunately, the pool manager has a
- Page 829 and 830:
class ThreadUnsafe { static int _va
- Page 831 and 832:
As with the Enter method, it’s ov
- Page 833 and 834:
Instruction atomicity is a differen
- Page 835 and 836:
BeginInvoke instead of Invoke. Alte
- Page 837 and 838:
static void Main() { for (int i = 1
- Page 839 and 840:
class ThreadSafe { static List _li
- Page 841 and 842:
In the absence of documentation, it
- Page 843 and 844:
The code is similar for Windows For
- Page 845 and 846:
It’s also possible to safely assi
- Page 847 and 848:
The following implicitly generate f
- Page 849 and 850:
As it happens, Intel’s X86 and X6
- Page 851 and 852:
Exchange and CompareExchange method
- Page 853 and 854:
former two are based on the common
- Page 855 and 856:
Two-way signaling Let’s say we wa
- Page 857 and 858:
Signaling Constructs and Performanc
- Page 859 and 860:
Signaling worker... Started - Some
- Page 861 and 862:
and the lock statement, you can ach
- Page 863 and 864:
This means that despite appearances
- Page 865 and 866:
using System; using System.Threadin
- Page 867 and 868:
We don’t pulse after dequeuing, a
- Page 869 and 870:
Use of PulseAll would forgo fairnes
- Page 871 and 872:
The Event-Based Asynchronous Patter
- Page 873 and 874:
class Program { static BackgroundWo
- Page 875 and 876:
Reached 20% Reached 40% Reached 60%
- Page 877 and 878:
For a discussion as to why aborting
- Page 879 and 880:
Cancellation Tokens Framework 4.0 p
- Page 881 and 882:
if (_expensive == null) _expensive
- Page 883 and 884:
you want to keep data isolated, ens
- Page 885 and 886:
from under their feet, as long as t
- Page 887 and 888:
Here’s the result: Thread B added
- Page 889 and 890:
var rw = new ReaderWriterLockSlim()
- Page 891 and 892:
class SystemTimer { static void Mai
- Page 893 and 894:
22 Parallel Programming In this cha
- Page 895 and 896:
Data parallelism is also conducive
- Page 897 and 898:
the code that must execute sequenti
- Page 899 and 900:
Why Isn’t AsParallel the Default?
- Page 901 and 902:
Most query operators change the ind
- Page 903 and 904:
.Select (i => wordList [localRandom
- Page 905 and 906:
class Camera { public readonly int
- Page 907 and 908:
foreach (int n in parallelQuery) Do
- Page 909 and 910:
Figure 22-4. Chunk versus range par
- Page 911 and 912:
string text = "Let's suppose this i
- Page 913 and 914:
public static void Invoke (Parallel
- Page 915 and 916:
var random = new Random(); string[]
- Page 917 and 918:
public static ParallelLoopResult Fo
- Page 919 and 920:
• Wait on a set of tasks—withou
- Page 921 and 922:
The task queuing problem arises bec
- Page 923 and 924:
TaskCreationOptions atp = TaskCreat
- Page 925 and 926:
As soon as task1 (the antecedent) f
- Page 927 and 928:
Conditional continuations By defaul
- Page 929 and 930:
This writes “Done” after writin
- Page 931 and 932:
var factory = new TaskFactory ( Tas
- Page 933 and 934:
Flatten and Handle Both PLINQ and t
- Page 935 and 936:
• The concurrent stack, queue, an
- Page 937 and 938:
Concurrent bags are ideal when the
- Page 939 and 940:
public class PCQueue : IDisposable
- Page 941 and 942:
If you leave a spinlock contended f
- Page 943 and 944:
How to use SpinWait There are two w
- Page 945:
spinWait.SpinOnce(); } } Here’s h
- Page 948 and 949:
If you don’t need such concurrenc
- Page 950 and 951:
• The underlying implementation
- Page 952 and 953:
public class Server { public void S
- Page 954 and 955:
void Read() { _stream.BeginRead (_d
- Page 956 and 957:
_stream = c.GetStream(); var task =
- Page 958 and 959:
exception is encountered, it’s no
- Page 960 and 961:
When writing asynchronous methods,
- Page 963 and 964:
24 Application Domains An applicati
- Page 965 and 966:
Creating and Destroying Application
- Page 967 and 968:
When additional application domains
- Page 969 and 970:
static void Main() { AppDomain newD
- Page 971 and 972:
class Client { // Here's a static f
- Page 973 and 974:
it appears as though it was a direc
- Page 975 and 976:
namespace Plugin.Extensions { publi
- Page 977 and 978:
25 Native and COM Interoperability
- Page 979 and 980:
class Test { [DllImport("kernel32.d
- Page 981 and 982:
StringBuilder class require copying
- Page 983 and 984:
Shared Memory Memory-mapped files,
- Page 985 and 986:
The second application subscribes t
- Page 987 and 988:
If you’re targeting Framework 4.0
- Page 989 and 990:
With the first use of the fixed key
- Page 991 and 992:
The root interface in COM is IUnkno
- Page 993 and 994:
workBook.SaveAs (@"c:\test.xlsx", P
- Page 995 and 996:
Embedding Interop Types We said pre
- Page 997 and 998:
26 Regular Expressions The regular
- Page 999 and 1000:
Regex r = new Regex (@"sausages?");
- Page 1001 and 1002:
Character Sets Character sets act a
- Page 1003 and 1004:
The problem is that our * quantifie
- Page 1005 and 1006:
The positive lookahead ensures that
- Page 1007 and 1008:
The following example matches a sim
- Page 1009 and 1010:
Extracting "name = value" pairs (on
- Page 1011 and 1012:
Console.WriteLine (m.Groups ["tag"]
- Page 1013 and 1014:
Expression Meaning Inverse (“not
- Page 1015:
Table 26-11. Miscellaneous construc
- Page 1018 and 1019:
catch A keyword for the clause in a
- Page 1020 and 1021:
goto A jump statement that jumps to
- Page 1022 and 1023:
ef A parameter and argument modifie
- Page 1024 and 1025:
volatile A field modifier instructi
- Page 1026 and 1027:
A with enums, 98 with nullable type
- Page 1028 and 1029:
inary numbers (converting), 233 bin
- Page 1030 and 1031:
COM type system, 970 IUnknown and I
- Page 1032 and 1033:
time zones, 213-218 TimeSpan, 206 D
- Page 1034 and 1035:
Array class, 277 enumerators, 143 I
- Page 1036 and 1037:
formatting, 219-225 composite forma
- Page 1038 and 1039:
IndexOf method, 196, 279 IndexOfAny
- Page 1040 and 1041:
Count and LongCount, 407 Min and Ma
- Page 1042 and 1043:
memory barriers and volatility, 825
- Page 1044 and 1045:
PipeStream class, 547 anonymous pip
- Page 1046 and 1047:
Remoting, 952 remove keyword, 124 R
- Page 1048 and 1049:
two-word characters and, 206 String
- Page 1050 and 1051:
DateTime and, 213 DateTimeOffset an
- Page 1052 and 1053:
loading and parsing, 416 names and
- Page 1055:
About the Authors Joe Albahari is t
Inappropriate
Loading...
Inappropriate
You have already flagged this document.
Thank you, for helping us keep this platform clean.
The editors will have a look at it as soon as possible.
Mail this publication
Loading...
Embed
Loading...
Delete template?
Are you sure you want to delete your template?
DOWNLOAD ePAPER
This ePaper is currently not available for download.
You can find similar magazines on this topic below under ‘Recommendations’.