Visual Studio 2010 and .NET 4.0 Overview

3,349 views
3,268 views

Published on

Published in: Technology
0 Comments
7 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,349
On SlideShare
0
From Embeds
0
Number of Embeds
379
Actions
Shares
0
Downloads
0
Comments
0
Likes
7
Embeds 0
No embeds

No notes for slide
  • About me
  • One of the coolest new features that you don’t have to do anything to get: Reference Highlighting. When you click on a symbol (variable name, method name, etc…) the IDE will automatically highlight all the references to that symbol.The best part is you can navigate between the highlighted references! NOTE: For demo info, go here-> http://blogs.msdn.com/zainnab/archive/2010/01/18/how-to-use-reference-highlighting.aspx
  • Menu: Edit -> Navigate ToThe new Navigate To dialog allows you to search for symbols by narrowing the search as you type. But it doesn’t stop there! If you use Pascal Case for your symbols then you can use just the upper-case letters to search.NOTE: For demo info, go here-> http://blogs.msdn.com/zainnab/archive/2010/01/20/how-to-use-navigate-to-vstiptool0006.aspx
  • The docking guides are very much improved over the previous experience with an updated Guide Diamond. But that’s not the best part…You can NOW FINALLY pull document windows out of the IDE! NOTE: This demo is very straightforward simply dock and undock windows then pull a document tab out of the IDE.
  • For the C# folks this is one heck of a great tool: Call Hierarchy. It allows you to "visualize all calls to and from a selected method, property, or constructor". To see how it works just right-click on any method, property, or constructor in the Editor and select View Call Hierarchy.It not only allows you to visualize calls To and From but you can Go to references, copy code, and even rearrange the view in the hierarchy.NOTE: Normally you can just stick to right-clicking a method in C# and choosing NOTE: For demo info, go here-> http://blogs.msdn.com/zainnab/archive/2010/01/19/using-the-call-hierarchy-c-only-vstiptool0005.aspx
  • This is the first of the set of enhancements for agile programming. In pair programing scenarios, you often have two people looking at one set of code at the same time. When you want to focus in on a set of code to make it easier to read you can now just use CTRL + Mouse Wheel to zoom your text.NOTE: This demo is very simple just show zooming behavior. Pair programming is the reason given here but this is also very useful for just making code easier to read when you need it.
  • The idea behind this feature is simple, it allows you to use classes and members before you define them.  Why would you want to do that? Well, Test Driven Development folks like to use classes and members before we create them. There are a lot of reasons for this we won’t go into here but this is an awesome new feature for TDD.NOTE: For demo info, go here-> http://blogs.msdn.com/zainnab/archive/2010/01/21/using-generate-from-usage-vstipedit0011.aspx
  • In the last demo you may have noticed that Intellisense kicked in. This can be annoying sometimes if you accidentally use one of its suggestions instead of what you meant to type. For this situation we now have Suggestion Mode. By hitting CTRL + ALT + SPACE or going to Edit -> Intellisense -> Toggle Completion Mode. By using this option you can avoid getting unwanted choices.NOTE: This is an easy demo just use the keyboard shortcut or menu option to enable Suggestion Mode. The hardest part here is getting people to understand why they would want to use it. Agile developers will mostly get it while most others will not so be prepared to have offline discussions for those interested.For demo info, go here-> http://blogs.msdn.com/zainnab/archive/2010/01/22/intellisense-suggestion-mode-vstipedit0012.aspx
  • Breakpoints have undergone some MAJOR improvements to make your life easier. Most notably you can now add labels, search breakpoints, and even do import/export tasks.NOTE: For demo info, go here-> Labels: http://blogs.msdn.com/zainnab/archive/2010/01/26/adding-labels-to-breakpoints-vstipdebug0001.aspxSearching (avail 1/27): http://blogs.msdn.com/zainnab/archive/2010/01/27/searching-breakpoints-vstipdebug0002.aspxImport/Export (avail 1/28): http://blogs.msdn.com/zainnab/archive/2010/01/28/how-to-import-and-export-breakpoints-vstipdebug0003.aspx
  • DataTips are now like a Super Quick Watch. They can be pinned to source, have comments, and tell you values.NOTE: See the demo doc (Pin a DataTip to source.docx) for a sample demo.
  • WPF BasedEditorCode Editing & Navigation(QuickSearch, CallHierarchy, …)IntellisensesuggestionvscompletionExtension ManagerBreakpoints and labels SuperQuickwatchDebug export and import datatipsCleanupweb.configJqueryintegrationJqueryIntelisenseHtml snippetsGeneratedependencygraph Beginnen met VS2010TrainingKit demo
  • Before we get started, I thought it would be a good idea to review where we have come from:In the past we have delivered monolithic releases. You saw this with .NET versions 1.0 and 1.1 before. When .NET 2.0 shipped we decided to make a “layer cake” of improvements where we added on 3.0, 3.5, and finally 3.5 service pack 1. There were a number of reasons for doing this but chief among them was to make sure you didn’t have to completely retest the CLR every time we incremented it. We did this for about 5 years.You can only keep that system up for so long, however, and 4.0 represents some pretty significant changes and updates to the Framework and the CLR. Because of this we decided to make it stand on its own and have incremented the CLR version accordingly. As such, it will probably have to undergo the testing your security teams have in place and we want to set expectations accordingly. NOTE: This is to make sure folks know the bad news up front. We will use the rest of the session to deliver the good news. Here is where you can find the history of .NET Framework versions: http://en.wikipedia.org/wiki/.NET_Framework_version_list
  • Optional and named parameters
  • Optional and named parametersDEMO:Shows how the combination of named and optional parameters combine to allow a developer to write simpler code or to simplify existing code. Use One.SimplifyYourCSharpCode from the LanguagesTenInOne solution.FAQ:[Q] Are optional parameters a compiler feature, or a runtime feature?[A] It is a compiler feature. The value of the optional parameter is compiled into the callsite at compile time. This means that if the value of the optional parameters is changed at a later date and the code isn’t recompiled, you could have code that doesn’t work as you expected and could introduce subtle bugs
  • Tonen code om word doc te openenProblemen is 1 dat we missing moeten gebruiken voor optionele parameters, 2 dat de elementen van het type object moeten zijnDaarna herschrijven naar simpele PIA call
  • Use Three.VbLanguageImprovements from the LanguagesTenInOne solution.
  • Auto-Implemented PropertiesCollection InitializersImplicit Line ContinuationMultiline Lambda Support
  • DynamicDemoAnd Extra Dynamic DynamicObjectCalling the Random shuffler in IronPython from C# (passing in an IEnumerable<int> generated in C#). Use Two.IronPythonInterop from the LanguagesTenInOne solution.
  • Tonenstringarray vragen of de assignment zalwerkenTonen stringlist  vragen of toewijzing aan Ilist werkt, vragen of toewijzing aan Ienumerable werktHanden laten opsteken(Wie denkt dat dit werkt?)
  • Eerst zonder tonenDan code contracts toevoegenDan opzetten in compilerTonen in reflector
  • Microsoft has made a major investment in parallel programming. In Visual Studio 2010 there are major additions that have been made: Task Parallel Library (TPL)Parallel LINQ (PLINQ)Data Structures for Parallel ProgrammingParallel Diagnostic ToolsLet’s look at the TPL:The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces in the .NET Framework version 4. These types rely on a task scheduler that is integrated with the .NET ThreadPool. The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications.The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. Parallel code that is based on the TPL not only works on dual-core and quad-core computers. It will also automatically scale, without recompilation, to manycore computers.When you use the TPL, writing a multithreaded for loop closely resembles writing a sequential for loop. The following code automatically partitions the work into tasks, based on the number of processors on the computer.NOTE:You definitely want them to know about the Concurrency site on MSDN for parallel programming:http://msdn.microsoft.com/en-us/concurrency/My favorite demo to do here is in the training kit. Just show the parallel and non-parallel code samples:C:VS2010TrainingKitDemosParallelForLoopSourceFor more demos, sample code with links to descriptions and pretty much everything else you need can be found here:http://code.msdn.microsoft.com/ParExtSamplesThere is also a parallel demo in the VS2010 Training Kit that can be found here:C:VS2010TrainingKitLabsParallelExtensionsLab.htmlhtmlDocSet_default.html
  • Parallel LINQ (PLINQ) is a parallel implementation of LINQ to Objects. PLINQ implements the full set of LINQ standard query operators as extension methods for the T:System.Linq namespace and has additional operators for parallel operations. PLINQ combines the simplicity and readability of LINQ syntax with the power of parallel programming. Just like code that targets the Task Parallel Library, PLINQ queries scale in the degree of concurrency based on the capabilities of the host computer.NOTE:The perfect demo here is the Baby Names example in the VS2010 Training Kit. This thing is just great for showing parallel and non-parallel code as well as visually seeing performance:C:VS2010TrainingKitDemosParallelBabyNamesSource
  • * TaskDemo:Uitleggen wat we juist gaan doen op elke threadRunPool();  Maaktgebruik van threads op de threadpool  traag en weinigcontroleRunThreads();  Maaktexplicietalle threads aan  weinig efficientRunTasks(); Systeem beslist zelf wat de optimale hoeveelheid tasks is en maakt er optimaal gebruik van* PLinqDemo:Uitvoeren linq query zonder AsParallelDaarna opnieuw uitvoeren met AsParallel toegevoegd* ParallelDemoUitvoeren nonparallelmethod
  • Nearly 80% of software development costs is in the maintenance of software.
  • MESSAGING:So, if a MEF-aware application is built of parts, parts can be thought of as the “heart” of a MEF-aware application. Let’s take a look at a simple Part. In this case, it is a class called SimpleMortgageCalculator that has one dependency it needs satisfied, an ILogger. Let’s see how we would use MEF to declare the needs this part has in order to be composed.
  • MESSAGING:So, if a MEF-aware application is built of parts, parts can be thought of as the “heart” of a MEF-aware application. Let’s take a look at a simple Part. In this case, it is a class called SimpleMortgageCalculator that has one dependency it needs satisfied, an ILogger. Let’s see how we would use MEF to declare the needs this part has in order to be composed.
  • MESSAGING:So, if a MEF-aware application is built of parts, parts can be thought of as the “heart” of a MEF-aware application. Let’s take a look at a simple Part. In this case, it is a class called SimpleMortgageCalculator that has one dependency it needs satisfied, an ILogger. Let’s see how we would use MEF to declare the needs this part has in order to be composed.
  • MESSAGING:Now that we’ve declared all our Imports and Exports, how are they all matched up together? This is the job of the container. The container is the “match maker” if you will. An application will ask the configured container for an object of a given type, then the container will take care of building up the entire object graph and returning the necessary object. All of this matching is handled by the container itself, the user doesn’t have to think about it at all.
  • * Show MEFGameToon App klasse met AggregateCatalogToon Shape klasse in AdditionalShapes met GameShapeAttribute Leg uit dat deze overerft van ExportAttribute* http://devlicio.us/blogs/derik_whittaker/archive/2009/10/27/simple-kick-start-example-using-mef-preview-8.aspx
  • Visual Studio 2010 and .NET 4.0 Overview

    1. 1. Visual Studio 2010 and the .NET 4.0 Framework<br />Bart Wullems<br />Application Architect<br />Ordina Belgium<br />
    2. 2. About me<br /><ul><li>Bart Wullems
    3. 3. Application Architect
    4. 4. OrdinaBelgium</li></ul>http://bartwullems.blogspot.com<br />
    5. 5. ThingsI’ll cover<br />Visual Studio 2010 Improvements<br />.NET 4.0 Framework<br />What’s New In C# 4.0 and Visual Basic 10<br />
    6. 6. !Warning!High Geek Factor<br />
    7. 7.
    8. 8. This is an (almost) demo only presentation<br />DEMO<br />vs<br />slides<br />
    9. 9.
    10. 10. Visual Studio 2010<br />
    11. 11. What’schanged in Visual Studio 2010?<br />
    12. 12. New Visual Studio 2010 Features…<br />Generate From Usage<br />HTML Snippets<br />Breakpoint Grouping<br />Parallel Tasks Window<br />New Look & Feel<br />Extensible Test Runner<br />Dynamic Data Tooling<br />Click-Once Enhancements for Office<br />Highlight References<br />WPF-based Editor<br />Breakpoint Labeling<br />MVC Tooling<br />Call Hierarchy<br />Improved WPF Tooling<br />Sharepoint Tooling<br />Historical Debugging<br />Web Deploy<br />Inline Call Tree<br />Quick Search<br />Concurrency Profiler<br />Breakpoint Import/Export<br />Document Map Margin<br />64-bit Mixed-Mode<br />Parallel Stacks Window<br />Minidump Debugging<br />Improved Multi-Monitor<br />JQueryIntellisense<br />web.config Transformation<br />
    13. 13. What’s changed in VS.NET?<br />Full WPF IDE (including code editors)<br />Multi-targeting<br />Frameworks: 2.0, 3.0, 3.5, 4.0<br />General:<br />F# development<br />F# Explorer<br />No dynamic help<br />No object test bench<br />Design Time:<br />Call Hierarchy Explorer<br />Generate from usage<br />Live semantic errors<br />Intellisense<br />Completion vs. Suggestion Mode<br />
    14. 14. What’s changed in VS.NET? (Cont.)<br />Enhanced editors and project templates.<br />ASP.NET<br />WPF<br />Silverlight <br />WYSIWYG Editors<br />Entity Framework<br />Architecture Modeling<br />UML Editors<br />Debugging<br />Intellitrace<br />
    15. 15. What’s changed in VS.NET? (Cont.)<br />Extensibility<br />Extension Manager<br />MEF<br />
    16. 16. Highlighting References<br />CTRL+SHIFT+DOWN ARROW (forward) CTRL+SHIFT+UP ARROW (reverse) <br />Automatic highlighting of a symbol<br />Can be used with declarations, references, and many other symbols <br />
    17. 17. Navigate To<br />CTRL + ,<br />Provides search-as-you-type support for symbols<br />Enables quick searching based on case usage<br />
    18. 18. Docking Windows<br />New Guide Diamond<br />Windows can be docked anywhere<br />Can now pull document windows outside the IDE<br />
    19. 19. Call Hierarchy (C# only)<br />CTRL + K, T<br />Used to see calls to and from a method<br />Great way to see calls at design time<br />
    20. 20. Zoom<br />CTRL + Mouse Wheel<br />New feature that enhances the size of your code<br />Very useful for pair programming (or similar scenarios)<br />
    21. 21. Generate from Usage<br />Used to automatically create stub code<br />Enables you to use classes and members before you define them<br />
    22. 22. Intellisense Suggestion Mode<br />CTRL + ALT + SPACE<br />Used when classes and members are used before they are defined<br />Helps to reduce situations where IntelliSense inserts unintended text into the editor<br />
    23. 23. Breakpoints<br />Can add labels to breakpoints<br />All breakpoints are now searchable<br />Import / Export now available<br />
    24. 24. Floating Data Tips<br />
    25. 25.
    26. 26. Visual Studio 2010<br />
    27. 27. .NET 4.0 Framework<br />
    28. 28. Base Class Library<br />Core types and services<br />Common Language Runtime<br />Assembly load and execution<br />
    29. 29. Base Class Library Improvements<br />Numerics<br />BigInteger, Complex<br />Data Structures<br />Tuple<br />SortedSet<T>, ISet<T><br />I/O<br />Memory-Mapped File<br />Unified Cancellation Model<br />
    30. 30. .NET 4.0<br />New Runtime<br />First new .NET runtime since 2.0<br />Side by Side Execution<br />Functional Programming – F#<br />Moving towards language parity – C#/VB<br />Dynamic Language Runtime(DLR)<br />Co- and Contra- Variance<br />Code Contracts<br />Parallel Computing<br />
    31. 31. From There to Here…<br />SP1<br />3.5<br />3.0<br />.NET 1.0<br />.NET 1.1<br />.NET 2.0<br />.NET 4<br />2002<br />2003<br />2010<br />2005-08<br />CLR 1.0<br />CLR 1.1<br />CLR 2.0<br />CLR 4<br />
    32. 32. In-Process Side-By-Side (SxS)<br />2.0 add-in<br />3.0 add-in<br />3.5 add-in<br />4.0 add-in<br />3.5<br />.NET 4.0<br />3.0<br />.NET 2.0<br />Host Process (i.e. Outlook)<br />
    33. 33. Functional Programming – F#<br />F# is a functional programming language that runs on top of .NET<br />Function is a first class citizen of a program<br />General PurposeLanguage<br />Important domains<br />Scientific data analysis, data mining, domain-specificmodeling,…<br />open System.IO<br />openSystem.Collections.Generic<br />letreadAllLines(file) =<br />useinp = File.OpenText file<br /> let res = new List<_>()<br /> while not(inp.EndOfStream) do<br />res.Add(inp.ReadLine())<br />res.ToArray()<br />
    34. 34. What’s New InC# 4.0 and Visual Basic 10<br />
    35. 35. Essence versus Ceremony<br />Simple, Concise, Expressive<br />
    36. 36. Ceremony in C# 3.0<br />Removing “magic values” via temporary<br />variables<br />GenerateChart(20, true);<br />varprocessCount = 20;<br />varcopyToWord = true;<br />GenerateChart(processCount, copyToWord);<br />
    37. 37. Ceremony in C# 3.0<br />Removing “magic values” via temporary<br />variables<br />GenerateChart(20, true);<br />GenerateChart(20 /* processCount */, <br />true/* copyToWord */);<br />
    38. 38. Ceremony in C# 3.0<br />Optional parameters via <br />method overloading<br />voidGenerateChart(intprocessCount)<br /> {<br />GenerateChart(processCount, false);<br /> }<br />voidGenerateChart(intprocessCount, boolcopyToWord)<br /> {<br />// Do Something<br /> }<br />
    39. 39. C# Language Enhancements<br />objectfileName = "Test.docx";<br />object missing = System.Reflection.Missing.Value;<br />doc.SaveAs(reffileName,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing);<br />Optional Params<br />doc.SaveAs("Test.docx");<br />Named argument<br />namedRange.Find("dog", xlByRows, MatchCase: True);<br />Named arguments can appear in any order<br />dynamic result = namedRange.Find(MatchCase: True,<br />what: "dog",<br />searchOrder: xlByRows);<br />Late-binding through “dynamic” type<br />Arguments evaluated in order written<br />result.ClearContents();<br />
    40. 40. Optional and Named Parameters<br />publicStreamReaderOpenTextFile(<br /> string path,<br /> Encodingencoding,<br />booldetectEncoding,<br />intbufferSize);<br />Primary method<br />Secondary overloads<br />publicStreamReaderOpenTextFile(<br /> string path,<br /> Encodingencoding,<br />booldetectEncoding);<br />publicStreamReaderOpenTextFile(<br /> string path,<br /> Encodingencoding);<br />publicStreamReaderOpenTextFile(<br /> string path);<br />Call primary with default values<br />
    41. 41. Optional and Named Parameters<br />Optional parameters<br />publicStreamReaderOpenTextFile(<br /> string path,<br /> Encodingencoding,<br />booldetectEncoding,<br />intbufferSize);<br />publicStreamReaderOpenTextFile(<br /> string path,<br /> Encodingencoding = null,<br />booldetectEncoding = true,<br />intbufferSize = 1024);<br />Named argument<br />OpenTextFile("foo.txt", Encoding.UTF8);<br />OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4096);<br />Arguments evaluated in order written<br />Named arguments can appear in any order<br />Named arguments must be last<br />OpenTextFile(<br />bufferSize: 4096,<br /> path: "foo.txt",<br />detectEncoding: false);<br />Non-optional must be specified<br />
    42. 42. C# 4.0<br />
    43. 43. C# 4.0<br />Dynamic typing<br />Covariance/Contravariance<br />Named arguments<br />Optional parameters<br />COM interop enhancements<br />DLR Support<br />
    44. 44. Improved COM Interoperability<br />
    45. 45. Ceremony in C# 3.0<br />Ugly COM Interop and the ever-present <br />“ref Missing.Value”<br />var word = newWord.Application();<br />word.Documents.Add(ref Missing.Value,<br /> ref Missing.Value,<br /> ref Missing.Value,<br /> ref Missing.Value);<br />
    46. 46. Improved COM Interoperability<br />objectfileName = "Test.docx";<br />object missing = System.Reflection.Missing.Value;<br />doc.SaveAs(reffileName,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing);<br />doc.SaveAs("Test.docx");<br />
    47. 47. Improved COM Interoperability<br />Automatic object  dynamic mapping<br />Optional and named parameters<br />Indexed properties<br />Optional “ref” modifier<br />Interop type embedding (“No PIA”)<br />
    48. 48. Improved COM Interoperability<br />
    49. 49. Ceremony in VB 9<br />Backing fields for properties are explicit<br />Privatem_nameAs String<br />Public Property Name() As String<br />Get<br />Name = m_name<br />End Get<br />Set(ByValvalueAs String)<br />m_name = value<br />End<br /> End Property<br />
    50. 50. Ceremony in VB 9<br />Popularity of lambda-based libraries cause problems for VB developers<br />SubMyMethod()<br />LambdaCall(Function(i) TempMethod(i) End Function)<br />End Sub<br />FunctionTempMethod(ByValparamasInteger) As Object<br />Console.WriteLine(param)<br />Return Nothing<br />End Function<br />Introduction of temporary functions<br />“Hacks” since statement lambdas not supported<br />
    51. 51. Ceremony in VB 9<br />Line continuations must be specified<br />by the developer<br />SomeLongMethodCall(firstParam, _<br />secondParam, _<br />thirdParam, _<br />fourthParam, _<br />fifthParam)<br />
    52. 52. Ceremony in VB 9<br />Creating collections takes a lot of code<br />Dimnames = NewList(Of String)<br />names.Add("Jason")<br />names.Add("Drew")<br />names.Add("Jonathan")<br />
    53. 53. VB.NET 10<br />
    54. 54. VB.NET 10<br />Auto-Implemented Properties<br />Collection Initializers<br />Implicit Line Continuation<br />Multiline Lambda Support<br />DLR Support<br />Covariance/Contravariance<br />
    55. 55. DLR<br />
    56. 56. .NET Dynamic Programming<br />IronPython<br />IronRuby<br />C#<br />VB.NET<br />Others…<br />Dynamic Language Runtime<br />Expression Trees<br />Dynamic Dispatch<br />Call Site Caching<br />PythonBinder<br />RubyBinder<br />COMBinder<br />JavaScriptBinder<br />ObjectBinder<br />
    57. 57. Dynamically-Typed<br />Ruby<br />Python<br />Statically-Typed<br />VB<br />C#<br />Common Language Runtime<br />Why the DLR?<br />
    58. 58. Dynamically-Typed<br />Ruby<br />Python<br />Statically-Typed<br />VB<br />Dynamic Language Runtime<br />C#<br />Common Language Runtime<br />Why the DLR?<br />
    59. 59. Ceremony in C# 3.0<br />Dynamic Language interop is<br />painful<br />Calculator calc = GetCalculator();<br />int sum = calc.Add(10, 20);<br />
    60. 60. Ceremony in C# 3.0<br />Dynamic Language interop is<br />painful<br />object calc = GetCalculator();<br />TypecalcType = calc.GetType();<br />object res = calcType.InvokeMember("Add",<br />BindingFlags.InvokeMethod, null,<br /> new object[] { 10, 20 });<br />int sum = Convert.ToInt32(res);<br />
    61. 61. Ceremony in C# 3.0<br />Dynamic Language interop is<br />painful<br />ScriptObject calc = GetCalculator();<br />object res = calc.Invoke("Add", 10, 20);<br />int sum = Convert.ToInt32(res);<br />
    62. 62. Essence in C# 4.0<br />Dynamic Language interop<br />doesn’t have to be painful!<br />Statically typed to be dynamic<br />dynamic calc = GetCalculator();<br />int sum = calc.Add(10, 20);<br />Dynamic method invocation<br />Dynamic conversion<br />
    63. 63. Dynamically Typed Objects<br />Calculator calc = GetCalculator();<br />int sum = calc.Add(10, 20);<br />object calc = GetCalculator();<br />TypecalcType = calc.GetType();<br />object res = calcType.InvokeMember("Add",<br />BindingFlags.InvokeMethod, null,<br />newobject[] { 10, 20 });<br />int sum = Convert.ToInt32(res);<br />ScriptObject calc = GetCalculator();<br />object res = calc.Invoke("Add", 10, 20);<br />int sum = Convert.ToInt32(res);<br />Statically typed to be dynamic<br />dynamic calc = GetCalculator();<br />int sum = calc.Add(10, 20);<br />Dynamic method invocation<br />Dynamic conversion<br />
    64. 64. Dynamically Typed Objects<br />Compile-time typedynamic<br />Run-time typeSystem.Int32<br />dynamic x = 1;<br />dynamic y = "Hello";<br />dynamic z = newList<int> { 1, 2, 3 };<br />When operand(s) are dynamic…<br /><ul><li> Member selection deferred to run-time
    65. 65. At run-time, actual type(s) substituted for dynamic
    66. 66. Static result type of operation is dynamic</li></li></ul><li>public static class Math<br />{<br /> publicstaticdecimal Abs(decimal value);<br /> publicstaticdouble Abs(double value);<br /> publicstaticfloat Abs(float value);<br /> publicstaticint Abs(int value);<br /> publicstaticlong Abs(long value);<br /> publicstaticsbyte Abs(sbyte value);<br /> publicstaticshort Abs(short value);<br /> ...<br />}<br />double x = 1.75;<br />double y = Math.Abs(x);<br />dynamic x = 1.75;<br />dynamic y = Math.Abs(x);<br />Dynamically Typed Objects<br />Method chosen at compile-time:double Abs(double x)<br />Method chosen at run-time: double Abs(double x)<br />Method chosen at run-time:int Abs(int x)<br />dynamic x = 2;<br />dynamic y = Math.Abs(x);<br />
    67. 67. Dynamic Language Runtime<br />Provides a common implementation and interoperation substrate for dynamic languages, similar to what the Common Language Runtime and Common Type System provide for statically typed languages<br />Developed for IronPython and IronRuby<br />Included in .NET 4.0 as part of the runtime and type system (e.g. C# 4 knows about the DLR IDynamicObject convention)<br />
    68. 68. DLR<br />
    69. 69. Co- and Contra-variance<br />
    70. 70. Co- and Contra-variance<br />
    71. 71. Co- and Contra-variance<br />.NET arrays are co-variant<br />string[] strings = GetStringArray();<br />Process(strings);<br />…but not safelyco-variant<br />void Process(object[] objects){ … }<br />void Process(object[] objects) {<br /> objects[0] = "Hello"; // Ok<br /> objects[1] = newButton(); // Exception!<br />}<br />Until now, C# generics have been invariant<br />List<string> strings = GetStringList();<br />Process(strings);<br />C# 4.0 supports safe co- and contra-variance<br />void Process(IEnumerable<object> objects) {<br />// IEnumerable<T> is read-only and<br />// therefore safely co-variant<br />}<br />void Process(IEnumerable<object> objects) { … }<br />
    72. 72. Safe Co- and Contra-variance<br />publicinterfaceIEnumerable<out T><br />{<br />IEnumerator<T> GetEnumerator();<br />}<br />out= Co-variantOutput positions only<br />Can be treated asless derived<br />publicinterfaceIEnumerator<out T><br />{<br /> T Current { get; }<br />boolMoveNext();<br />}<br />IEnumerable<string> strings = GetStrings();<br />IEnumerable<object> objects = strings;<br />in= Contra-variantInput positions only<br />publicinterfaceIComparer<in T><br />{<br />int Compare(T x, T y);<br />}<br />Can be treated asmore derived<br />IComparer<object> objComp = GetComparer();<br />IComparer<string> strComp = objComp;<br />
    73. 73. Generic co- and contravariance<br />If T appears only as an output, it’s safe to passX<TDerived> for X<T><br />We call this covariance<br />If T appears only as an input, it’s safe to passX<TBase> for X<T><br />We call this contravariance<br />
    74. 74. Fixing The Type System…<br />Covariance and Contravariance…<br />sounds complicated…<br />But it’s not!<br />sort of…<br />
    75. 75. Fixing The Type System…<br />How are generic types “broken” today?<br />class Animal { }<br />class Sheep : Animal { }<br />void Speak(IEnumerable<Animal> animals)<br /> {<br /> // Do something with Animals<br /> }<br />Not Allowed:<br />IEnumerable<Animal> != IEnumerable<Sheep><br />var sheep = new List<Sheep>();<br /> Speak(sheep);<br />
    76. 76. Break it down…<br />Covariance – think “out”<br />Contravariance – think “in”<br />
    77. 77. Code Contracts<br />
    78. 78. Why Contracts?<br />Just because something compiles, doesn’t mean it works…<br />
    79. 79. Design By Contract<br />Code Contracts introduce a way to specify contractual information that is not represented by a method or type’s signature alone.<br />
    80. 80. Code Contracts<br />What does it expect? (Preconditions) <br />Contract.Requires()<br />What does it guarantee? (Postconditions) <br />Contract.Ensures()<br />What does it maintain? (Invariants) <br />Contract.Invariant()<br />
    81. 81. A Contract contains…<br />Pre-conditions - must be true before<br />public Rational(int numerator, int denominator)<br />{<br />Contract.Requires(denominator > 0);<br /> …<br />}<br />Post-conditions - must be true after<br />public string GetPassword()<br />{<br />Contract.Ensures(Contract.Result<string>() != null);<br /> …<br /> return password;<br />}<br />
    82. 82. A Contract contains…<br />Invariants - must always be true<br />[ContractInvariantMethod]<br />protectedvoidObjectInvariant()<br />{<br />Contract.Invariant(denominator > 0);<br />}<br />
    83. 83. Let’s Fix It For Once And All!<br />Design-by-Contract meets .NET!<br />stringGetDescription(intx) {<br />Contract.Requires( 0 < x );<br />Contract.Ensures(Contract.Result<string>()!=null);<br /> …<br />}<br />
    84. 84. Code Contracts<br />
    85. 85. Parallel Development<br />
    86. 86.
    87. 87. The Parallel Computing Initiative<br />Letting the brightest developers solve business problems, not concurrency problems.<br />
    88. 88.
    89. 89. Parallel Computing with .NET 4<br />Task Parallel Library (TPL)<br />Parallel LINQ (PLINQ)<br />Coordination Data Structures (CDS)<br />System.Threading Improvements<br />
    90. 90. Task-based Programming<br />ThreadPool<br />ThreadPool.QueueUserWorkItem(…);<br />System.Threading.Tasks<br />Starting<br />Parent/Child<br />Continue/Wait/Cancel<br />Task.Factory.StartNew(…);<br />var p = newTask(() => {<br />vart = newTask(…);});<br />Taskt = …<br />Taskp = t.ContinueWith(…);<br />t.Wait(2000);<br />t.Cancel();<br />Taskswith results<br />Task<int> f = <br />newTask<int>(() => C());<br />…<br />int result = f.Result;<br />
    91. 91. Task Parallel Library (TPL)<br /><ul><li>Set of public types and APIs
    92. 92. System.Threading
    93. 93. System.Threading.Tasks</li></ul>// Sequential<br />foreach (var item in sourceCollection) <br />{ <br /> Process(item); <br />} <br />// Parallel<br />Parallel.ForEach (sourceCollection, item => Process(item)); <br />
    94. 94. Parallel LINQ (PLINQ)<br /><ul><li>Implements the full set of LINQ standard query operators
    95. 95. Extension methods for the IParallelEnumerable interface
    96. 96. Additional operators for parallel operations</li></ul>from n in names.AsParallel().WithDegreeOfParallelism(ProcessorsToUse.Value)<br /> where n.Name.Equals(queryInfo.Name, StringComparison.InvariantCultureIgnoreCase) &&<br />n.State == queryInfo.State && <br />n.Year >= yearStart && n.Year <= yearEnd<br />orderbyn.Year ascending<br /> select n;<br />
    97. 97. Declarative Data Parallelism<br />Parallel LINQ-to-Objects (PLINQ)<br />Built on top of Tasks<br />Enables LINQ devs to leverage multiple cores<br />Fully supports all .NET standard query operators<br />Minimal impact to existing LINQ model<br />var q = from p in people<br />        wherep.Name == queryInfo.Name && <br />p.State == queryInfo.State &&<br />p.Year >= yearStart &&<br />p.Year <= yearEnd<br />        orderbyp.Yearascending<br />        select p;<br />.AsParallel()<br />
    98. 98. Structured Parallelism<br />Parallel class <br />static (overloaded) methods<br />helper methods to create/work with Tasks<br />encapsulates common patterns<br />
    99. 99. Parallel Development<br />
    100. 100. The Problem…<br />Software<br />Maintenance<br />Original Software<br />Development<br />
    101. 101. Managed Extensibility Framework?<br /> The Managed Extensibility Framework (MEF) is a new libraryin the .NET Framework that enables greater reuse of applications and components. Using MEF, .NET applications can make the shift from being statically compiled to dynamically composed<br />
    102. 102. MEF Basics…<br />Export it.<br />Import it.<br />Compose it.<br />
    103. 103. Part, enter stage left…<br />public class SimpleMortgageCalculator : IMortgageCalculator<br />{<br />publicILogger Logger { get; set; }<br />publicfloat Calculate()<br /> {<br />Logger.Log("Calculating Mortgage");<br />return ...;<br /> }<br />}<br />Part <br />A<br />
    104. 104. Exportit…<br />[Export(typeof(IMortgageCalculator))]<br />public class SimpleMortgageCalculator : IMortgageCalculator<br />{<br />publicILogger Logger { get; set; }<br />publicfloat Calculate()<br /> {<br />Logger.Log("Calculating Mortgage");<br />return ...;<br /> }<br />}<br />Part <br />A<br />
    105. 105. Importit…<br />[Export(typeof(IMortgageCalculator))]<br />public class SimpleMortgageCalculator : IMortgageCalculator<br />{<br />[Import(typeof(ILogger))]<br />publicILogger Logger { get; set; }<br />publicfloat Calculate()<br /> {<br />Logger.Log("Calculating Mortgage");<br />return ...;<br /> }<br />}<br />Part <br />A<br />
    106. 106. Compose it.<br />Catalogs provide the parts.<br />Catalog<br />
    107. 107. Compose it.<br />Containeris the matchmaker.<br />Catalog<br />
    108. 108. Compose it.<br />AggregatingCatalog<br />Containeris the matchmaker.<br />DirectoryCatalog<br />AssemblyCatalog<br />Catalog<br />TypeCatalog<br />
    109. 109. MEF<br />
    110. 110. Conclusion<br />
    111. 111. Conclusion<br />Visual Studio 2010 and .NET 4.0 is a major release<br />Essence vsCeremony<br />Generic types are no longer “broken”<br />Design by Contract<br />Parallel Developmentbecomes easy<br />

    ×