Your SlideShare is downloading. ×
0
http://netponto.org<br />19ª Reunião Presencial - 16/04/2011<br />O porque das minhas aplicações funcionarem... E o que ac...
Patrocinadores desta reunião<br />
Pedro Rosa<br />LinkedIn<br />http://pt.linkedin.com/in/pedrobarraurosa<br />Twitter<br />http://twitter.com/pedrorosa<br />
Agenda	<br />DLL & GAC<br />Location<br />Tools<br />Assembly Discover<br />Strong Name<br />Delay Signing<br />Garbage Co...
Também disponível em vídeo...<br />Assista!<br />http://vimeo.com/22695640<br />
Tools that we are going to see<br />
Ildasm.exe (MSIL Disassembler)<br />The MSIL Disassembler is a companion tool to the MSIL Assembler (Ilasm.exe).<br />Ilda...
Fuslogvw.exe (Assembly Binding Log Viewer)<br />The Assembly Binding Log Viewer displays details for assembly binds.  <br ...
Ngen.exe (Native Image Generator)<br />The Native Image Generator (Ngen.exe) is a tool that improves the performance of ma...
Sn.exe (Strong Name Tool)<br />The Strong Name tool (Sn.exe) helps sign assemblies with strong names.<br />Sn.exe provides...
Demo<br />Compile &  Languages & IL &ILDASM<br />
Assembly Discoverability<br />
Assembly Location<br />An assembly's location determines whether the common language runtime can locate it when referenced...
Demo<br />Default Assembly Location<br />
How the Runtime Locates Assemblies<br />The runtime uses the following steps to resolve an assembly reference:<br />Determ...
Step 1: Examining the Configuration Files<br />Application Configuration File<configuration><br />   <system.diagnostics><...
Step 1: Examining the Configuration Files<br />Publisher Policy File<br /><configuration><br />    <runtime><br />        ...
Demo<br />Configuration File<br />
Step 1: Examining the Configuration Files<br />Machine Configuration File<br />This file is located in the %runtime instal...
Step 2: Checking for Previously Referenced Assemblies<br />If the requested assembly has also been requested in previous c...
Step 3: Checking the Global Assembly Cache<br />For strong-named assemblies, the binding process continues by looking in t...
Strong-Named Assemblies<br />You can ensure that a name is globally unique by signing an assembly with a strong name. In p...
 Sign an Assembly with a Strong Name<br />The Windows Software Development Kit (SDK) provides several ways to sign an asse...
Demo<br />Global Assembly Cache & Version<br />
Step 4: Locating the Assembly through Codebases or Probing<br />Locating the Assembly through Codebases<br /><configuratio...
Step 4: Locating the Assembly through Codebases or Probing<br />Locating the Assembly through Probing<br />Probing the App...
Step 4: Locating the Assembly through Codebases or Probing<br />Locating the Assembly through Probing<br />Probing with th...
Demo<br />Assemblies Location<br />
Assembly Versions & Binding Redirect<br />
Assembly Versioning<br />Each assembly has a version number as part of its identity. As such, two assemblies that differ b...
BindingRedirect<br />Redirects one assembly version to another.<br /><configuration><br />   <runtime><br />      <assembl...
Demo<br />Binding Redirect<br />
Delay Signing<br />
Delay Signing an Assembly<br />An organization can have a closely guarded key pair that developers do not have access to o...
Delay Signing an Assembly<br />Obtain the public key portion of the key pair from the organization that will do the eventu...
Delay Signing an Assembly<br />The compiler inserts the public key into the assembly manifest and reserves space in the PE...
Delay Signing an Assembly<br />Later, usually just before shipping, you submit the assembly to your organization's signing...
Demo<br />Delay Signing Assemblies<br />
Garbage collection<br />
Fundamentals of Garbage Collection<br />In the common language runtime (CLR), the garbage collector serves as an automatic...
What Happens During a Garbage Collection<br />A garbage collection has the following phases:<br />A marking phase that fin...
Object Graph<br />
GC Happening<br />
Generations<br />The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage colle...
Object.Finalize Method<br />Allows an object to try to free resources and perform other cleanup operations before it is re...
Demo<br />Finalize<br />
IDisposable Interface<br />Defines a method to release allocated resources.<br />The primary use of this interface is to r...
Demo<br />IDisposable<br />
Weak References<br />The garbage collector cannot collect an object in use by an application while the application's code ...
Demo<br />Weak References<br />
Também disponível em vídeo...<br />Assista!<br />http://www.vimeo.com/22076261<br />
Patrocinadores desta reunião<br />
Próximas reuniões presenciais<br />16/04/2011 - Abril<br />21/05/2011 - Maio<br />18/06/2011 - Junho<br />23/07/2011 - Jul...
Obrigado!<br />Pedro Rosa<br />http://pt.linkedin.com/in/pedrobarraurosa<br />http://twitter.com/pedrorosa<br />
Upcoming SlideShare
Loading in...5
×

O porque das minhas aplicações funcionarem... E o que acontece com os recursos que utilizo?

1,046

Published on

Algum de vocês já pensou no que se transforma o código que fazemos? E qual a diferença entre C# e VB? Onde colocamos as nossas dll's, como devemos pensar nas versões e o que é isso do strong name? Se estiverem duas dll's de versões diferentes qual utilizar e como se altera sem recompilar a aplicação? E ainda, como não permitir que essa alteração aconteça? E o que acontece com os recursos que o meu código utiliza e quais são as boas práticas para que tudo funcione bem?

Esta sessão vai nos responder a todas estas perguntas, numa apresentação sobre sobre Global Assembly Cache (GAC), Intermediate Language (IL) e Garbage Collection (GC), alertando para os detalhes que podem fazer a diferença entre uma aplicação que tem que ser reiniciada todos os dias e uma que fica ligada durante anos.

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

  • Be the first to like this

No Downloads
Views
Total Views
1,046
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "O porque das minhas aplicações funcionarem... E o que acontece com os recursos que utilizo?"

  1. 1. http://netponto.org<br />19ª Reunião Presencial - 16/04/2011<br />O porque das minhas aplicações funcionarem... E o que acontece com os recursos que utilizo?Pedro Rosa<br />
  2. 2. Patrocinadores desta reunião<br />
  3. 3. Pedro Rosa<br />LinkedIn<br />http://pt.linkedin.com/in/pedrobarraurosa<br />Twitter<br />http://twitter.com/pedrorosa<br />
  4. 4. Agenda <br />DLL & GAC<br />Location<br />Tools<br />Assembly Discover<br />Strong Name<br />Delay Signing<br />Garbage Collector<br />Disposable<br />Finalize<br />WeakReferences<br />
  5. 5. Também disponível em vídeo...<br />Assista!<br />http://vimeo.com/22695640<br />
  6. 6. Tools that we are going to see<br />
  7. 7. Ildasm.exe (MSIL Disassembler)<br />The MSIL Disassembler is a companion tool to the MSIL Assembler (Ilasm.exe).<br />Ildasm.exe takes a portable executable (PE) file that contains Microsoft intermediate language (MSIL) code and creates a text file suitable as input to Ilasm.exe.<br />
  8. 8. Fuslogvw.exe (Assembly Binding Log Viewer)<br />The Assembly Binding Log Viewer displays details for assembly binds.  <br />*** Assembly Binder Log Entry (3/5/2007 @ 12:54:20 PM) *** The operation failed. Bind result: hr = 0x80070002. The system cannot find the file specified. Assembly manager loaded from: C:WINNTMicrosoft.NETFrameworkv2.0.50727fusion.dll Running under executable C:Program FilesMicrosoft.NETFrameworkSDKSamplesTutorialsresourcesandlocalizationgraphiccsgraphicfailtest.exe --- A detailed error log follows. === Pre-bind state information === LOG: DisplayName = graphicfailtest.resources, Version=0.0.0.0, Culture=en-US, PublicKeyToken=null (Fully-specified) LOG: Appbase = C:Program FilesMicrosoft.NETFrameworkSDKSamplesTutorialsresourcesandlocalizationgraphiccs LOG: Initial PrivatePath = NULL LOG: Dynamic Base = NULL LOG: Cache Base = NULL LOG: AppName = NULL Calling assembly : graphicfailtest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null. === LOG: Processing DEVPATH. LOG: DEVPATH is not set. Falling through to regular bind. LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). LOG: Post-policy reference: graphicfailtest.resources, Version=0.0.0.0, Culture=en-US, PublicKeyToken=null <br />LOG:Attempting download of new URL file:///C:/Program Files/Microsoft.NET/FrameworkSDK/Samples/Tutorials/resourcesandlocalization/graphic/cs/en-US/graphicfailtest.resources.DLL. <br />LOG: Attempting download of new URL file:///C:/Program Files/Microsoft.NET/FrameworkSDK/Samples/Tutorials/resourcesandlocalization/graphic/cs/en-US/graphicfailtest.resources/graphicfailtest.resources.DLL.<br />LOG: Attempting download of new URL file:///C:/Program Files/Microsoft.NET/FrameworkSDK/Samples/Tutorials/resourcesandlocalization/graphic/cs/en-US/graphicfailtest.resources.EXE. <br />LOG: Attempting download of new URL file:///C:/Program Files/Microsoft.NET/FrameworkSDK/Samples/Tutorials/resourcesandlocalization/graphic/cs/en-US/graphicfailtest.resources/graphicfailtest.resources.EXE. LOG: All probing URLs attempted and failed.<br />
  9. 9. Ngen.exe (Native Image Generator)<br />The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. <br />Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer. <br />The runtime can use native images from the cache instead of using the just-in-time (JIT) compiler to compile the original assembly.<br />Changes to Ngen.exe in the .NET Framework version 4:<br />Ngen.exe now compiles assemblies with full trust, and code access security (CAS) policy is no longer evaluated.<br />Native images that are generated with Ngen.exe can no longer be loaded into applications that are running in partial trust.<br />
  10. 10. Sn.exe (Strong Name Tool)<br />The Strong Name tool (Sn.exe) helps sign assemblies with strong names.<br />Sn.exe provides options for key management, signature generation, and signature verification.<br />The following command stores the key in keyPair.snk in the container MyContainer in the strong name CSP.<br />sn -i keyPair.snkMyContainer<br />The following command extracts the public key from keyPair.snk and stores it in publicKey.snk.<br />sn -p keyPair.snkpublicKey.snk<br />The following command displays the public key and the token for the public key contained in publicKey.snk.<br />sn -tppublicKey.snk<br />The following command verifies the assembly MyAsm.dll.<br />sn -v MyAsm.dll<br />
  11. 11. Demo<br />Compile & Languages & IL &ILDASM<br />
  12. 12. Assembly Discoverability<br />
  13. 13. Assembly Location<br />An assembly's location determines whether the common language runtime can locate it when referenced, and can also determine whether the assembly can be shared with other assemblies. You can deploy an assembly in the following locations:<br />The application's directory or subdirectories.<br />This is the most common location for deploying an assembly. The subdirectories of an application's root directory can be based on language or culture. If an assembly has information in the culture attribute, it must be in a subdirectory under the application directory with that culture's name.<br />The global assembly cache.<br />This is a machine-wide code cache that is installed wherever the common language runtime is installed. In most cases, if you intend to share an assembly with multiple applications, you should deploy it into the global assembly cache.<br />On an HTTP server.<br />An assembly deployed on an HTTP server must have a strong name; you point to the assembly in the codebase section of the application's configuration file.<br />
  14. 14. Demo<br />Default Assembly Location<br />
  15. 15. How the Runtime Locates Assemblies<br />The runtime uses the following steps to resolve an assembly reference:<br />Determines the correct assembly version by examining applicable configuration files, including the application configuration file, publisher policy file, and machine configuration file. If the configuration file is located on a remote machine, the runtime must locate and download the application configuration file first.<br />Checks whether the assembly name has been bound to before and, if so, uses the previously loaded assembly. If a previous request to load the assembly failed, the request is failed immediately without attempting to load the assembly.<br />Probes for the assembly using the following steps:<br />If configuration and publisher policy do not affect the original reference and if the bind request was created using the Assembly.LoadFrom method, the runtime checks for location hints.<br />If a codebase is found in the configuration files, the runtime checks only this location. If this probe fails, the runtime determines that the binding request failed and no other probing occurs.<br />Probes for the assembly using the heuristics described in the probing section. If the assembly is not found after probing, the runtime requests the Windows Installer to provide the assembly. This acts as an install-on-demand feature.<br />
  16. 16. Step 1: Examining the Configuration Files<br />Application Configuration File<configuration><br /> <system.diagnostics><br /> <trace useGlobalLock="false" autoflush="true" indentsize="0"><br /> <listeners><br /> <add name="myListener" type="System.Diagnostics.TextWriterTraceListener, system version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="c:myListener.log" /><br /> </listeners><br /> </trace><br /> </system.diagnostics><br /></configuration><br />
  17. 17. Step 1: Examining the Configuration Files<br />Publisher Policy File<br /><configuration><br /> <runtime><br /> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><br /> <dependentAssembly><br /> <assemblyIdentity name="asm6" publicKeyToken="c0305c36380ba429" /> <br /> <bindingRedirect oldVersion="3.0.0.0" newVersion="2.0.0.0"/> <br /> </dependentAssembly><br /> </assemblyBinding><br /> </runtime><br /></configuration><br />
  18. 18. Demo<br />Configuration File<br />
  19. 19. Step 1: Examining the Configuration Files<br />Machine Configuration File<br />This file is located in the %runtime install path%Config directory. <br />Machine.config contains configuration settings for machine-wide assembly binding<br />
  20. 20. Step 2: Checking for Previously Referenced Assemblies<br />If the requested assembly has also been requested in previous calls, the common language runtime uses the assembly that is already loaded. <br />If a previous request for the assembly failed, subsequent requests for the assembly are failed immediately without attempting to load the assembly. <br />
  21. 21. Step 3: Checking the Global Assembly Cache<br />For strong-named assemblies, the binding process continues by looking in the global assembly cache. <br />The global assembly cache stores assemblies that can be used by several applications on a computer. <br />All assemblies in the global assembly cache must have strong names.<br />
  22. 22. Strong-Named Assemblies<br />You can ensure that a name is globally unique by signing an assembly with a strong name. In particular, strong names satisfy the following requirements:<br />Strong names guarantee name uniqueness by relying on unique key pairs. <br />Strong names protect the version lineage of an assembly<br />Strong names provide a strong integrity check. <br />
  23. 23. Sign an Assembly with a Strong Name<br />The Windows Software Development Kit (SDK) provides several ways to sign an assembly with a strong name:<br />Using the Assembly Linker (Al.exe) provided by the Windows SDK.<br />Using assembly attributes to insert the strong name information in your code.<br /> You can use either the AssemblyKeyFileAttribute or the AssemblyKeyNameAttribute, depending on where the key file to be used is located.<br />
  24. 24. Demo<br />Global Assembly Cache & Version<br />
  25. 25. Step 4: Locating the Assembly through Codebases or Probing<br />Locating the Assembly through Codebases<br /><configuration><br /> <runtime><br /> <assemblyBindingxmlns="urn:schemas-microsoft-com:asm.v1"><br /> <dependentAssembly><br /> <assemblyIdentity name="myAssembly"<br />publicKeyToken="32ab4ba45e0a69a1"<br /> culture="neutral" /><br /> <codeBase version="2.0.0.0"<br />href="http://www.litwareinc.com/myAssembly.dll"/><br /> </dependentAssembly><br /> </assemblyBinding><br /> </runtime><br /></configuration><br />
  26. 26. Step 4: Locating the Assembly through Codebases or Probing<br />Locating the Assembly through Probing<br />Probing the Application Base and Culture Directories<br />The runtime always begins probing in the application's base, which can be either a URL or the application's root directory on a computer. <br />   [application base] / [assembly name].dll<br />   [application base] / [assembly name] / [assembly name].dll<br />If culture information is specified for the referenced assembly, only the following directories are probed:<br />   [application base] / [culture] / [assembly name].dll<br />   [application base] / [culture] / [assembly name] / [assembly name].dll<br />
  27. 27. Step 4: Locating the Assembly through Codebases or Probing<br />Locating the Assembly through Probing<br />Probing with the privatePath Attribute<br /><configuration><br /> <runtime><br /> <assemblyBindingxmlns="urn:schemas-microsoft-com:asm.v1"><br /> <probing privatePath="bin;bin2subbin;bin3"/><br /> </assemblyBinding><br /> </runtime><br /></configuration><br />
  28. 28. Demo<br />Assemblies Location<br />
  29. 29. Assembly Versions & Binding Redirect<br />
  30. 30. Assembly Versioning<br />Each assembly has a version number as part of its identity. As such, two assemblies that differ by version number are considered by the runtime to be completely different assemblies. <br />This version number is physically represented as a four-part string with the following format:<br /><major version>.<minor version>.<build number>.<revision><br />
  31. 31. BindingRedirect<br />Redirects one assembly version to another.<br /><configuration><br />   <runtime><br />      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><br />         <dependentAssembly><br />            <assemblyIdentity name="Helper"<br />                              publicKeyToken="bcabfaff346163aa"<br />                              culture="neutral" /><br />            <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/><br />            <codeBase version="1.0.0.0“  href="c:versionsamplebinv1helper.dll"/><br />            <codeBase version="2.0.0.0“  href="c:versionsamplebinv2helper.dll"/><br />         </dependentAssembly><br />      </assemblyBinding><br />   </runtime><br /></configuration><br /> <br />
  32. 32. Demo<br />Binding Redirect<br />
  33. 33. Delay Signing<br />
  34. 34. Delay Signing an Assembly<br />An organization can have a closely guarded key pair that developers do not have access to on a daily basis. <br />
  35. 35. Delay Signing an Assembly<br />Obtain the public key portion of the key pair from the organization that will do the eventual signing. Typically this key is in the form of an .snk file, which can be created using the Strong Name tool (Sn.exe).<br />Annotate the source code for the assembly with two custom attributes from System.Reflection:<br />AssemblyKeyFileAttribute, which passes the name of the file containing the public key as a parameter to its constructor.<br />AssemblyDelaySignAttribute, which indicates that delay signing is being used by passing true as a parameter to its constructor.<br />
  36. 36. Delay Signing an Assembly<br />The compiler inserts the public key into the assembly manifest and reserves space in the PE file for the full strong name signature. The real public key must be stored while the assembly is built so that other assemblies that reference this assembly can obtain the key to store in their own assembly reference.<br />Because the assembly does not have a valid strong name signature, the verification of that signature must be turned off. You can do this by using the –Vr option with the Strong Name tool.<br />sn –Vr myAssembly.dll<br />
  37. 37. Delay Signing an Assembly<br />Later, usually just before shipping, you submit the assembly to your organization's signing authority for the actual strong name signing using the –R option with the Strong Name tool.<br />The example signs an assembly called myAssembly.dll with a strong name using the sgKey.snk key pair.<br />sn -R myAssembly.dll sgKey.snk<br />
  38. 38. Demo<br />Delay Signing Assemblies<br />
  39. 39. Garbage collection<br />
  40. 40. Fundamentals of Garbage Collection<br />In the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits:<br />Enables you to develop your application without having to free memory.<br />Allocates objects on the managed heap efficiently.<br />Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.<br />Provides memory safety by making sure that an object cannot use the content of another object.<br />
  41. 41. What Happens During a Garbage Collection<br />A garbage collection has the following phases:<br />A marking phase that finds and creates a list of all live objects.<br />A relocating phase that updates the references to the objects that will be compacted.<br />A compacting phase that reclaims the space occupied by the dead objects and compacts the surviving objects. The compacting phase moves objects that have survived a garbage collection toward the older end of the segment.<br />Because generation 2 collections can occupy multiple segments, objects that are promoted into generation 2 can be moved into an older segment. Both generation 1 and generation 2 survivors can be moved to a different segment, because they are promoted to generation 2.<br />The large object heap is not compacted, because this would increase memory usage over an unacceptable length of time.<br />
  42. 42. Object Graph<br />
  43. 43. GC Happening<br />
  44. 44. Generations<br />The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:<br />Generation 0. <br />This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation.<br />Generation 1.<br />This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.<br />Generation 2. <br />This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.<br />
  45. 45. Object.Finalize Method<br />Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.<br />Finalize operations have the following limitations:<br />The exact time when the finalizer executes during garbage collection is undefined. Resources are not guaranteed to be released at any specific time, unless calling a Close method or a Dispose method.<br />The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already finalized when the finalizer of Object A starts.<br />The thread on which the finalizer is run is unspecified.<br />
  46. 46. Demo<br />Finalize<br />
  47. 47. IDisposable Interface<br />Defines a method to release allocated resources.<br />The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. <br />However, it is not possible to predict when garbage collection will occur. <br />Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.<br />
  48. 48. Demo<br />IDisposable<br />
  49. 49. Weak References<br />The garbage collector cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object.<br />A weak reference permits the garbage collector to collect the object while still allowing the application to access the object.<br />A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist. When you use a weak reference, the application can still obtain a strong reference to the object, which prevents it from being collected. However, there is always the risk that the garbage collector will get to the object first before a strong reference is reestablished.<br />Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.<br />
  50. 50. Demo<br />Weak References<br />
  51. 51. Também disponível em vídeo...<br />Assista!<br />http://www.vimeo.com/22076261<br />
  52. 52. Patrocinadores desta reunião<br />
  53. 53. Próximas reuniões presenciais<br />16/04/2011 - Abril<br />21/05/2011 - Maio<br />18/06/2011 - Junho<br />23/07/2011 - JulhoReserva estes dias na agenda! :)<br />
  54. 54. Obrigado!<br />Pedro Rosa<br />http://pt.linkedin.com/in/pedrobarraurosa<br />http://twitter.com/pedrorosa<br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×