Framework - Riptutorial

Transcription

.NET Framework#.net

Table of ContentsAbout1Chapter 1: Getting started with .NET Framework2Remarks2Versions2.NET2Compact Framework3Micro Framework3Examples3Hello World in C#3Hello World in Visual Basic .NET4Hello World in F#4Hello World in C /CLI4Hello World in PowerShell4Hello World in Nemerle4Hello World in Oxygene5Hello World in Boo5Hello World in Python (IronPython)5Hello World in IL5Chapter 2: .NET Core7Introduction7Remarks7Examples7Basic Console AppChapter 3: Acronym GlossaryExamples.Net Related AcronymsChapter 4: ADO.NET799910Introduction10Remarks10Examples10

Executing SQL statements as a command10Best Practices - Executing Sql Statements11Best practice for working with ADO.NET12Using common interfaces to abstract away vendor specific classesChapter 5: CLRExamplesAn introduction to Common Language RuntimeChapter 6: Code s15Postconditions15Contracts for Interfaces16Installing and Enabling Code Contracts16Chapter 7: Collections19Remarks19Examples19Creating an initialized List with Custom Types19Queue20Stack22Using collection initializers23Chapter 8: Custom Types25Remarks25Examples25Struct DefinitionStructs inherit from System.ValueType, are value types, and live on the stack. When valueClass DefinitionClasses inherit from System.Object, are reference types, and live on the heap. When refereEnum DefinitionAn enum is a special type of class. The enum keyword tells the compiler that this class inChapter 9: DateTime parsingExamples2525262626262929

ParseExact29TryParse30TryParseExact32Chapter 10: Dependency Injection33Remarks33Examples34Dependency Injection - Simple example34How Dependency Injection Makes Unit Testing Easier35Why We Use Dependency Injection Containers (IoC Containers)36Chapter 11: DictionariesExamples3939Enumerating a Dictionary39Initializing a Dictionary with a Collection Initializer39Adding to a Dictionary40Getting a value from a dictionary40Make a Dictionary with Case-Insensivitve keys.41ConcurrentDictionary (from .NET 4.0)41Creating an instance41Adding or Updating41Getting value42Getting or Adding a value42IEnumerable to Dictionary ( .NET 3.5)42Removing from a Dictionary42ContainsKey(TKey)43Dictionary to List44ConcurrentDictionary augmented with Lazy'1 reduces duplicated computation44Problem44Solution44Chapter 12: Encryption / Cryptography46Remarks46Examples46RijndaelManaged46

Encrypt and decrypt data using AES (in C#)47Create a Key from a Password / Random SALT (in C#)50Encryption and Decryption using Cryptography (AES)52Chapter 13: Exceptions54Remarks54Examples54Catching an exception54Using a finally block55Catching and rethrowing caught exceptions55Exception Filters56Rethrowing an exception within a catch block57Throwing an exception from a different method while preserving its information57Chapter 14: Expression Trees59Remarks59Examples59Simple Expression Tree Generated by the C# Compiler59building a predicate of form field value60Expression for retrieving a static field60InvocationExpression Class61Chapter 15: File Input/Output64Parameters64Remarks64Examples64VB WriteAllText64VB StreamWriter64C# StreamWriter64C# WriteAllText()64C# File.Exists()65Chapter 16: ForEach66Remarks66Examples66Calling a method on an object in a list66

Extension method for IEnumerableChapter 17: Garbage Collection6668Introduction68Remarks68Examples68A basic example of (garbage) collection68Live objects and dead objects - the basics69Multiple dead objects70Weak References70Dispose() vs. finalizers71Proper disposal and finalization of objects72Chapter 18: Globalization in ASP.NET MVC using Smart internationalization for ASP.NET74Remarks74Examples74Basic configuration and setupChapter 19: HTTP clients7476Remarks76Examples76Reading GET response as string using System.Net.HttpWebRequest76Reading GET response as string using System.Net.WebClient76Reading GET response as string using System.Net.HttpClient77Sending a POST request with a string payload using System.Net.HttpWebRequest77Sending a POST request with a string payload using System.Net.WebClient77Sending a POST request with a string payload using System.Net.HttpClient78Basic HTTP downloader using System.Net.Http.HttpClient78Chapter 20: HTTP serversExamples8080Basic read-only HTTP file server (HttpListener)80Basic read-only HTTP file server (ASP.NET Core)82Chapter 21: JIT compiler84Introduction84Remarks84

ExamplesIL compilation sampleChapter 22: JSON in .NET with lize object into JSON87Deserialize an object from JSON text87Chapter 23: JSON Serialization88Remarks88Examples88Deserialization using er88Deserialization using Json.NET88Serialization using Json.NET89Serialization-Deserialization using Newtonsoft.Json89Dynamic binding90Serialization using Json.NET with JsonSerializerSettings90Chapter 24: LINQ92Introduction92Syntax92Remarks99Lazy Evaluation99ToArray() or ToList()?100Examples100Select (map)100Where 01Except102Intersect102Concat102First (find)102

FirstOrDefault104Any104All105SelectMany (flat ile112TakeWhile112DefaultIfEmpty112Aggregate (fold)113ToLookup113Join114

GroupJoin115Cast116Empty117ThenBy117Range117Left Outer Join117Repeat118Chapter 25: Managed Extensibility Framework119Remarks119Examples119Exporting a Type (Basic)119Importing (Basic)120Connecting (Basic)120Chapter 26: Memory management122Remarks122Examples122Unmanaged Resources122Use SafeHandle when wrapping unmanaged resources123Chapter 27: Networking124Remarks124Examples124Basic TCP chat (TcpListener, TcpClient, NetworkStream)124Basic SNTP client (UdpClient)125Chapter 28: NuGet packaging system127Remarks127Examples127Installing the NuGet Package Manager127Managing Packages through the UI128Managing Packages through the console129Updating a package129Uninstalling a package130Uninstalling a package from one project in a solution130

Installing a specific version of a package130Adding a package source feed (MyGet, Klondike, ect)130Using different (local) Nuget package sources using UI130uninstall a specific version of package132Chapter 29: Parallel processing using .Net framework133Introduction133Examples133Parallel ExtensionsChapter 30: Platform Invoke133134Syntax134Examples134Calling a Win32 dll function134Using Windows API134Marshalling arrays134Marshaling structs135Marshaling unions137Chapter 31: Process and Thread affinity setting138Parameters138Remarks138Examples138Get process affinity mask138Set process affinity mask139Chapter 32: Reading and writing Zip g ZIP contents140Extracting files from ZIP files141Updating a ZIP file141Chapter 33: s vs ImmutableCollection143

ExamplesCreating a ReadOnlyCollection143143Using the Constructor143Using LINQ143Note144Updating a ReadOnlyCollection144Warning: Elements in a ReadOnlyCollection are not inherently read-only144Chapter 34: ReflectionExamples146146What is an Assembly?146How to create an object of T using Reflection146Creating Object and setting properties using reflection147Getting an attribute of an enum with reflection (and caching it)147Compare two objects with reflection147Chapter 35: Regular Expressions k if pattern matches input149Passing Options149Simple match and replace149Match into groups149Remove non alphanumeric characters from string150Find all matches150Using150Code150Output150Chapter 36: Serial Ports151Examples151Basic operation151List available port names151Asynchronous read151Synchronous text echo service151Asynchronous message receiver152

Chapter 37: SettingsExamples155155AppSettings from ConfigurationSettings in .NET 1.x155Deprecated usage155Reading AppSettings from ConfigurationManager in .NET 2.0 and later155Introduction to strongly-typed application and user settings support from Visual Studio156Reading strongly-typed settings from custom section of configuration file157Under the coversChapter 38: SpeechRecognitionEngine class to recognize es161Asynchronously recognizing speech for free text dictation161Asynchronously recognizing speech based on a restricted set of phrases161Chapter 39: Stack and Heap162Remarks162Examples162Value types in use162Reference types in use163Chapter 40: Strings165Remarks165Examples166Count distinct characters166Count characters166Count occurrences of a character167Split string into fixed length blocks167Convert string to/from another encoding167Examples:168Convert a string to UTF-8168Convert UTF-8 data to a string168Change encoding of an existing text file168

Object.ToString() virtual method168Immutability of strings169omparing strings169Chapter 41: Synchronization Contexts171Remarks171Examples171Execute code on the UI thread after performing background workChapter 42: System.DiagnosticsExamples171173173Stopwatch173Run shell commands173Send Command to CMD and Receive Output174Chapter 43: System.IOExamples176176Reading a text file using StreamReader176Reading/Writing Data Using System.IO.File176Serial Ports using System.IO.SerialPorts177Iterating over connected serial ports177Instantiating a System.IO.SerialPort object177Reading/Writing data over the SerialPort177Chapter 44: System.IO.File class179Syntax179Parameters179Examples179Delete a file179Strip unwanted lines from a text file180Convert text file encoding181"Touch" a large amount of files (to update last write time)181Enumerate files older than a specified amount181Move a File from one location to another182File.Move182Chapter 45: System.Net.Mail184

Remarks184Examples184MailMessage184Mail with Attachment185Chapter 46: System.Reflection.Emit namespaceExamplesCreating an assembly dynamicallyChapter 47: System.Runtime.Caching.MemoryCache (ObjectCache)Examples186186186189189Adding Item to Cache (Set)189System.Runtime.Caching.MemoryCache (ObjectCache)189Chapter 48: Task Parallel Library (TPL)RemarksPurpose And Use CasesExamples191191191191Basic producer-consumer loop (BlockingCollection)191Task: basic instantiation and Wait192Task: WaitAll and variable capturing192Task: WaitAny193Task: handling exceptions (using Wait)193Task: handling exceptions (without using Wait)194Task: cancelling using 96Flowing execution context with AsyncLocal197Parallel.ForEach in VB.NET197Task: Returning a value198Chapter 49: Task Parallel Library (TPL) API OverviewsRemarks199199

ExamplesPerform work in response to a button click and update the UIChapter 50: ThreadingExamplesAccessing form controls from other threadsChapter 51: TPL DataflowRemarks199199200200200202202Libraries Used in Examples202Difference between Post and SendAsync202Examples202Posting to an ActionBlock and waiting for completion202Linking blocks to create a pipeline202Synchronous Producer/Consumer with BufferBlock203Asynchronous Producer Consumer With A Bounded BufferBlock204Chapter 52: Unit testingExamples205205Adding MSTest unit testing project to an existing solution205Creating a sample test method205Chapter 53: Upload file and POST data to webserverExamplesUpload file with WebRequestChapter 54: Using Progress and IProgressExamples206206206208208Simple Progress reporting208Using IProgress208Chapter 55: VB FormsExamples210210Hello World in VB.NET Forms210For Beginners210Forms Timer211Chapter 56: Work with SHA1 in C#214

Introduction214Examples214#Generate SHA1 checksum of a file functionChapter 57: Work with SHA1 in C#214215Introduction215Examples215#Generate SHA1 checksum of a file215#Generate hash of a text215Chapter 58: Write to and read from StdErr streamExamples216216Write to standard error output using Console216Read from standard error of child process216Chapter 59: XmlSerializer217Remarks217Examples217Serialize object217Deserialize object217Behaviour: Map Element name to Property217Behaviour: Map array name to property (XmlArray)217Formatting: Custom DateTime format218Efficiently building multiple serializers with derived types specified dynamically218Where we came from218What can we do218Doing it efficiently219What's in the outputCredits221222

AboutYou can share this PDF with anyone you feel could benefit from it, downloaded the latest versionfrom: -net-frameworkIt is an unofficial and free .NET Framework ebook created for educational purposes. All thecontent is extracted from Stack Overflow Documentation, which is written by many hardworkingindividuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official .NETFramework.The content is released under Creative Commons BY-SA, and the list of contributors to eachchapter are provided in the credits section at the end of this book. Images may be copyright oftheir respective owners unless otherwise specified. All trademarks and registered trademarks arethe property of their respective company owners.Use the content presented in this book at your own risk; it is not guaranteed to be correct noraccurate, please send your feedback and corrections to info@zzzprojects.comhttps://riptutorial.com/1

Chapter 1: Getting started with .NETFrameworkRemarksThe .NET Framework is a set of libraries and a runtime, originally designed by Microsoft. All .NETprograms compile to a bytecode called Microsoft Intermediate Language (MSIL). The MSIL is runby the Common Language Runtime (CLR).Below you can find several examples of "Hello World" in various languages that support the .NETFramework. "Hello World" is a program that displays "Hello World" on the display device. It's usedfor illustrating the basic syntax for constructing a working program. It can also be used as a sanitytest to make sure that a language's compiler, development environment, and runtime environmentare all working correctly.List of languages supported by .NETVersions.NETVersionRelease -11-063.52007-11-193.5 ps://riptutorial.com/2

VersionRelease Date4.6.22016-08-024.72017-04-05Compact FrameworkVersionRelease -01-013.92013-06-01Micro FrameworkVersionRelease sHello World in C#using System;class Program{// The Main() function is the first function to be executed in a programstatic void Main(){// Write the string "Hello World to the standard outConsole.WriteLine("Hello World");}}has several overloads. In this case, the string "Hello World" is the parameter,and it will output the "Hello World" to the standard out stream during execution. Other 3

may call the .ToString of the argument before writing to the stream. See the .NET FrameworkDocumentation for more information.Live Demo in Action at .NET FiddleIntroduction to C#Hello World in Visual Basic .NETImports SystemModule ProgramPublic Sub Main()Console.WriteLine("Hello World")End SubEnd ModuleLive Demo in Action at .NET FiddleIntroduction to Visual Basic .NETHello World in F#open System[ EntryPoint ]let main argv printfn "Hello World"0Live Demo in Action at .NET FiddleIntroduction to F#Hello World in C /CLIusing namespace System;int main(array String args){Console::WriteLine("Hello World");}Hello World in PowerShellWrite-Host "Hello World"Introduction to PowerShellHello World in Nemerlehttps://riptutorial.com/4

System.Console.WriteLine("Hello World");Hello World in Oxygenenamespace HelloWorld;interfacetypeApp classpublicclass method Main(args: array of String);end;implementationclass method App.Main(args: array of String);beginConsole.WriteLine('Hello World');end;end.Hello World in Booprint "Hello World"Hello World in Python (IronPython)print "Hello World"import clrfrom System import ConsoleConsole.WriteLine("Hello World")Hello World in IL.class public auto ansi beforefieldinit Programextends [mscorlib]System.Object{.method public hidebysig static void Main() cil managed{.maxstack 8IL 0000: nopIL 0001: ldstr"Hello World"IL 0006: callvoid [mscorlib]System.Console::WriteLine(string)IL 000b: nopIL 000c: ret}.method public hidebysig specialname rtspecialnameinstance void .ctor() cil managed{https://riptutorial.com/5

.maxstack 8IL 0000: ldarg.0IL 0001: callIL 0006: retinstance void [mscorlib]System.Object::.ctor()}}Read Getting started with .NET Framework online: arted-with--net-frameworkhttps://riptutorial.com/6

Chapter 2: .NET CoreIntroduction.NET Core is a general purpose development platform maintained by Microsoft and the .NETcommunity on GitHub. It is cross-platform, supporting Windows, macOS and Linux, and can beused in device, cloud, and embedded/IoT scenarios.When you think of .NET Core the following should come to mind (flexible deployment, crossplatform, command-line tools, open source).Another great thing is that even if it's open source Microsoft is actively supporting it.RemarksBy itself, .NET Core includes a single application model -- console apps -- which is useful for tools,local services and text-based games. Additional application models have been built on top of .NETCore to extend its functionality, such as: ASP.NET Core Windows 10 Universal Windows Platform (UWP) Xamarin.FormsAlso, .NET Core implements the .NET Standard Library, and therefore supports .NET StandardLibraries.The .NET Standard Library is an API spec that describes the consistent set of .NET APIs thatdevelopers can expect in each .NET implementation. .NET implementations need to implementthis spec in order to be considered .NET Standard Library compliant and to support libraries thattarget the .NET Standard Library.ExamplesBasic Console Apppublic class Program{public static void Main(string[] args){Console.WriteLine("\nWhat is your name? ");var name Console.ReadLine();var date DateTime.Now;Console.WriteLine("\nHello, {0}, on {1:d} at {1:t}", name, date);Console.Write("\nPress any key to l.com/7

Read .NET Core online: rehttps://riptutorial.com/8

Chapter 3: Acronym GlossaryExamples.Net Related AcronymsPlease note that some terms like JIT and GC are generic enough to apply to many programminglanguage environments and runtimes.CLR: Common Language RuntimeIL: Intermediate LanguageEE: Execution EngineJIT: Just-in-time compilerGC: Garbage CollectorOOM: Out of memorySTA: Single-threaded apartmentMTA: Multi-threaded apartmentRead Acronym Glossary online: m-glossaryhttps://riptutorial.com/9

Chapter 4: ADO.NETIntroductionADO(ActiveX Data Objects).Net is a tool provided by Microsoft which provides access to datasources such as SQL Server, Oracle, and XML through its components. .Net front-endapplications can retrieve, create, and manipulate data, once they are connected to a data sourcethrough ADO.Net with appropriate privileges.ADO.Net provides a connection-less architecture. It is a secure approach to interact with adatabase, since, the connection doesn't have to be maintained during the entire session.RemarksA note on parameterizing SQLs with Parameters.AddWithValue: AddWithValue is never a goodstarting point. That method relies on inferring the type of the data from what is passed in. With this,you might end up in a situation where the conversion prevents your query from using an index.Note that some SQL Server data types, such as char/varchar (without preceding "n") or date do nothave a corresponding .NET data type. In those cases, Add with the correct data type should beused instead.ExamplesExecuting SQL statements as a command// Uses Windows authentication. Replace the Trusted Connection parameter with// User Id .;Password .; to use SQL Server authentication instead. You may// want to find the appropriate connection string for your server.string connectionString @"Server myServer\myInstance;Database myDataBase;Trusted Connection True;"string sql "INSERT INTO myTable (myDateTimeField, myIntField) " "VALUES (@someDateTime, @someInt);";// Most ADO.NET objects are disposable and, thus, require the using keyword.using (var connection new SqlConnection(connectionString))using (var command new SqlCommand(sql, connection)){// Use parameters instead of string concatenation to add user-supplied// values to avoid SQL injection and formatting issues. Explicitly supply datatype.// System.Data.SqlDbType is an enumeration. See Note1command.Parameters.Add("@someDateTime", SqlDbType.DateTime).Value t", SqlDbType.Int).Value myInt32Variable;// Execute the SQL statement. Use ExecuteScalar and ExecuteReader instead// for query that return results (or see the more specific examples, once// those have been 0

command.ExecuteNonQuery();}Note 1: Please see SqlDbType Enumeration for the MSFT SQL Server-specific variation.Note 2: Please see MySqlDbType Enumeration for the MySQL-specific variation.Best Practices - Executing Sql Statementspublic void SaveNewEmployee(Employee newEmployee){// best practice - wrap all database connections in a using block so they are alwaysclosed & disposed even in the event of an Exception// best practice - retrieve the connection string by name from the app.config orweb.config (depending on the application type) (note, this requires an assembly reference toSystem.configuration)using(SqlConnection con nectio{// best practice - use column names in your INSERT statement so you are not dependenton the sql schema column order// best practice - always use parameters to avoid sql injection attacks and errors ifmalformed text is used like including a single quote which is the sql equivalent of escapingor starting a string (varchar/nvarchar)// best practice - give your parameters meaningful names just like you do variables inyour codeusing(SqlCommand sc new SqlCommand("INSERT INTO employee (FirstName, LastName,DateOfBirth /*etc*/) VALUES (@firstName, @lastName, @dateOfBirth /*etc*/)", con)){// best practice - always specify the database data type of the column you areusing// best practice - check for valid values in your code and/or use a databaseconstraint, if inserting NULL then use System.DbNull.Valuesc.Parameters.Add(new SqlParameter("@firstName", SqlDbType.VarChar, 200){Value newEmployee.FirstName ? (object) System.DBNull.Value});sc.Parameters.Add(new SqlParameter("@lastName", SqlDbType.VarChar, 200){Value newEmployee.LastName ? (object) System.DBNull.Value});// best practice - always use the correct types when specifying your parameters,Value is assigned to a DateTime instance and not a string representation of a Datesc.Parameters.Add(new SqlParameter("@dateOfBirth", SqlDbType.Date){ Value newEmployee.DateOfBirth });// best practice - open your connection as late as possible unless you need toverify that the database connection is valid and wont fail and the proceeding code executiontakes a long time (not the case here)con.Open();sc.ExecuteNonQuery();}// the end of the using block will close and dispose the SqlConnection// best practice - end the using block as soon as possible to release the databaseconnection}}// supporting class used as parameter for examplepublic class Employeehttps://riptutorial.com/11

{public string FirstName { get; set; }public string LastName { get; set; }public DateTime DateOfBirth { get; set; }}Best practice for working with ADO.NET Rule of thumb is to open connection for minimal time. Close the connection explicitly onceyour procedure execution is over this will return the connection object back to connectionpool. Default connection pool max size 100. As connection pooling enhances theperformance of physical connection to SQL Server.Connection Pooling in SQL Server Wrap all database connections in a using block so they are always closed & disposed evenin the event of an Exception. See using Statement (C# Reference) for more information onusing statements Retrieve the connection strings by name from the app.config or web.config (depending onthe application type)This requires an assembly reference to System.configurationSee Connection Strings and Configuration Files for additional information on how tostructure your configuration file Always use parameters for incoming values toAvoid sql injection attacksAvoid errors if malformed text is used like including a single quote which is the sqlequivalent of escaping or starting a string (varchar/nvarchar)Letting the database provider reuse query plans (not supported by all databaseproviders) which increases efficiency When working with parametersSql parameters type and size mismatch is a common cause of insert/ updated/ selectfailureGive your Sql parameters meaningful names just like you do variables in your codeSpecify the database data type of the column you are using, this ensures the wrongparameter types is not used which could lead to unexpected resultsValidate your incoming parameters before you pass them into the command (as thesaying goes, "garbage in, garbage out"). Validate incoming values as early as possiblein the stackUse the correct types when assigning your parameter values, example: do not assignthe string value of a DateTime, instead assign an actual DateTime instance to thevalue of the parameterSpecify the size of string-type parameters. This is because SQL Server can re-useexecution plans if the parameters match in type and size. Use -1 for MAXDo not use the method AddWithValue, the main reason is it is very easy to forget tospecify the parameter type or the precision/scale when needed. For additionalinformation see Can we stop using AddWithValue already? When using database connectionsOpen the connection as late as possible and close it as soon as possible. This is ageneral guideline when working with any external resource https://riptutorial.com/12

Never share database connection instances (example: having a singleton host ashared instance of type SqlConnection). Have your code always create a new databaseconnection instance when needed and then have the calling code dispose of it and"throw it away" when it is done. The reason for this isMost database providers have some sort of connection pooling so creating newmanaged connections is cheapIt eliminates any future errors if the code starts working with multiple threads Using common interfaces to abstract away vendor specific classesvar providerName .Client, IBM.Data.DB2var connectionString "{your-connection-string}";//you will probably get the above two values in the ConnectionStringSettings object from.config filevar factory (var connection factory.CreateConnection()) {//IDbConnectionconnection.ConnectionString connectionString;connection.Open();using(var command connection.CreateCommand()) {command.CommandText "{query}";using(var reader command.ExecuteReader()) {while(reader.Read()) {.}}//IDbCommand//IDataReader}}Read ADO.NET online: https://riptutorial.com/13

Chapter 5: CLRExamplesAn introduction to Common Language RuntimeThe Common Language Runtime (CLR) is a virtual machine environment and part of the .NETFramework. It contains: A portable bytecode language called Common Intermediate Language (abbreviated CIL,or IL) A Just-In-Time compiler that generates machine code A tracing garbage collector that provides automatic memory management Support for lightweight sub-processes called AppDomains Security mechanisms through the concepts of verifiable code and trust levelsCode that runs in the CLR is referred to as managed code to distinguish it from code runningoutside the CLR (usually native code) which is referred to as unmanaged code. There are variousmechanisms that facilitate interoperability between managed and unmanaged code.Read CLR online: s://riptutorial.com/14

Chapter 6: Code ContractsRemarksCode contracts allow for compile or runtime analysis of pre/post conditions of methods andinvariant conditions for objects. These conditions may be used to ensure callers and return valuematch valid states for application processing. Other uses for Code Contracts includedocumentation generation.ExamplesPreconditionsPreconditions allows methods to provide minimum required values for input parametersExample.void DoWork(string ut));//do work}Static Analysis Result.PostconditionsPostconditions ensure that the returned results from a method will match the provided definition.This provides the caller with a definition of the expected result. Postconditions may allowed forsimplied implmentations as some possible outcomes can be provided by the static analyizer.Example.string GetValue(){Contract.Ensures(Contract.Result string () ! null);return null;}Static Analyis Result.https://riptutorial.com/15

Contracts for InterfacesUsing Code Contracts it is possible to apply a contract to an interface. This is done by declaring anabstract class that implments the interfaces. The interface should be tagged with theContractClassAttribute

Chapter 4: ADO.NET 10 Introduction 10 Remarks 10 Examples 10. Executing SQL statements as a command 10 Best Practices - Executing Sql Statements 11 . Chapter 29: Parallel processing using .Net framework 133 Introduction 133 Examples 133 Parallel Extensions 133 Chapter 30: Platform Invoke 134 Syntax 134 Examples 134 Calling a Win32 dll .