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

54
O porque das minhas aplicações funcionarem... E o que acontece com os recursos que utilizo? Pedro Rosa http://netpont o.org 19ª Reunião Presencial - 16/04/2011

Upload: comunidade-netponto

Post on 01-Jul-2015

1.055 views

Category:

Technology


0 download

DESCRIPTION

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.

TRANSCRIPT

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

O porque das minhas aplicações funcionarem... E o que acontece com

os recursos que utilizo?Pedro Rosa

http://netponto.org19ª Reunião Presencial - 16/04/2011

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

Pedro Rosa

LinkedInhttp://pt.linkedin.com/in/pedrobarraurosa

Twitterhttp://twitter.com/pedrorosa

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

Agenda• DLL & GAC– Location– Tools– Assembly Discover– Strong Name– Delay Signing

• Garbage Collector– Disposable– Finalize– WeakReferences

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

Também disponível em vídeo...

Assista!http://vimeo.com/22695640

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

TOOLS THAT WE ARE GOING TO SEE

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

Ildasm.exe (MSIL Disassembler)• The MSIL Disassembler is a companion tool to the MSIL

Assembler (Ilasm.exe).• 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.

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

Fuslogvw.exe (Assembly Binding Log Viewer)

• The Assembly Binding Log Viewer displays details

for assembly binds. *** 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:\WINNT\Microsoft.NET\Framework\v2.0.50727\fusion.dll Running under executable C:\Program Files\Microsoft.NET\FrameworkSDK\Samples\Tutorials\resourcesandlocalization\graphic\cs\graphicfailtest.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 Files\Microsoft.NET\FrameworkSDK\Samples\Tutorials\resourcesandlocalization\graphic\cs\ 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 LOG:Attempting download of new URL file:///C:/Program Files/Microsoft.NET/FrameworkSDK/Samples/Tutorials/resourcesandlocalization/graphic/cs/en-US/graphicfailtest.resources.DLL. 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.LOG: Attempting download of new URL file:///C:/Program Files/Microsoft.NET/FrameworkSDK/Samples/Tutorials/resourcesandlocalization/graphic/cs/en-US/graphicfailtest.resources.EXE. 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.

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

Ngen.exe (Native Image Generator)

• The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications.

• 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.

• The runtime can use native images from the cache instead of using the just-in-time (JIT) compiler to compile the original assembly.

• Changes to Ngen.exe in the .NET Framework version 4:– Ngen.exe now compiles assemblies with full trust, and code access security

(CAS) policy is no longer evaluated.– Native images that are generated with Ngen.exe can no longer be loaded into

applications that are running in partial trust.

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

Sn.exe (Strong Name Tool)• The Strong Name tool (Sn.exe) helps sign assemblies with strong names.• Sn.exe provides options for key management, signature generation, and

signature verification.

– The following command stores the key in keyPair.snk in the container MyContainer in the strong name CSP.• sn -i keyPair.snk MyContainer

– The following command extracts the public key from keyPair.snk and stores it in publicKey.snk.• sn -p keyPair.snk publicKey.snk

– The following command displays the public key and the token for the public key contained in publicKey.snk.• sn -tp publicKey.snk

– The following command verifies the assembly MyAsm.dll.• sn -v MyAsm.dll

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

DemoCompile & Languages & IL

&ILDASM

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

ASSEMBLY DISCOVERABILITY

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

Assembly LocationAn 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:• The application's directory or subdirectories.

– 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.

• The global assembly cache.– 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.

• On an HTTP server.– 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.

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

DemoDefault Assembly Location

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

How the Runtime Locates AssembliesThe runtime uses the following steps to resolve an assembly reference:

• 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.

• 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.

• Probes for the assembly using the following steps:

– 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.

– 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.

– 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.

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

Step 1: Examining the Configuration Files• Application Configuration File

<configuration>

<system.diagnostics> <trace useGlobalLock="false" autoflush="true" indentsize="0"> <listeners> <add name="myListener" type="System.Diagnostics.TextWriterTraceListener, system version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="c:\myListener.log" /> </listeners> </trace> </system.diagnostics></configuration>

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

Step 1: Examining the Configuration Files• Publisher Policy File

<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="asm6" publicKeyToken="c0305c36380ba429" /> <bindingRedirect oldVersion="3.0.0.0" newVersion="2.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime></configuration>

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

DemoConfiguration File

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

Step 1: Examining the Configuration Files• Machine Configuration File

– This file is located in the %runtime install path%\Config directory.

– Machine.config contains configuration settings for machine-wide assembly binding

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

Step 2: Checking for Previously Referenced Assemblies

• If the requested assembly has also been requested in previous calls, the common language runtime uses the assembly that is already loaded.

• If a previous request for the assembly failed, subsequent requests for the assembly are failed immediately without attempting to load the assembly.

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

Step 3: Checking the Global Assembly Cache

• For strong-named assemblies, the binding process continues by looking in the global assembly cache.

• The global assembly cache stores assemblies that can be used by several applications on a computer.

• All assemblies in the global assembly cache must have strong names.

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

Strong-Named Assemblies• 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:

– Strong names guarantee name uniqueness by relying on unique key pairs. – Strong names protect the version lineage of an assembly– Strong names provide a strong integrity check.

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

Sign an Assembly with a Strong Name

The Windows Software Development Kit (SDK) provides several ways to sign an assembly with a strong name:

• Using the Assembly Linker (Al.exe) provided by the Windows SDK.

• Using assembly attributes to insert the strong name information in your code.– You can use either the AssemblyKeyFileAttribute or the

AssemblyKeyNameAttribute, depending on where the key file to be used is located.

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

DemoGlobal Assembly Cache &

Version

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

Step 4: Locating the Assembly through Codebases or Probing

• Locating the Assembly through Codebases<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="myAssembly" publicKeyToken="32ab4ba45e0a69a1" culture="neutral" /> <codeBase version="2.0.0.0" href="http://www.litwareinc.com/myAssembly.dll"/> </dependentAssembly> </assemblyBinding> </runtime></configuration>

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

Step 4: Locating the Assembly through Codebases or Probing

• Locating the Assembly through Probing– Probing the Application Base and Culture

Directories• 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. – [application base] / [assembly name].dll– [application base] / [assembly name] / [assembly name].dll

• If culture information is specified for the referenced assembly, only the following directories are probed:– [application base] / [culture] / [assembly name].dll– [application base] / [culture] / [assembly name] / [assembly name].dll

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

Step 4: Locating the Assembly through Codebases or Probing

• Locating the Assembly through Probing–Probing with the privatePath Attribute

<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="bin;bin2\subbin;bin3"/> </assemblyBinding> </runtime></configuration>

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

DemoAssemblies Location

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

ASSEMBLY VERSIONS & BINDING REDIRECT

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

Assembly Versioning• 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.

• This version number is physically represented as a four-part string with the following format:

<major version>.<minor version>.<build number>.<revision>

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

BindingRedirect

Redirects one assembly version to another.<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Helper" publicKeyToken="bcabfaff346163aa" culture="neutral" />

<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>

<codeBase version="1.0.0.0“ href="c:\versionsample\bin\v1\helper.dll"/> <codeBase version="2.0.0.0“ href="c:\versionsample\bin\v2\helper.dll"/> </dependentAssembly> </assemblyBinding> </runtime></configuration>

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

DemoBinding Redirect

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

DELAY SIGNING

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

Delay Signing an Assembly

• An organization can have a closely guarded key pair that developers do not have access to on a daily basis.

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

Delay Signing an Assembly1. 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).

2. Annotate the source code for the assembly with two custom attributes from System.Reflection:

1. AssemblyKeyFileAttribute, which passes the name of the file containing the public key as a parameter to its constructor.

2. AssemblyDelaySignAttribute, which indicates that delay signing is being used by passing true as a parameter to its constructor.

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

Delay Signing an Assembly3. 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.

4. 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.

sn –Vr myAssembly.dll

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

Delay Signing an Assembly5. 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.

1. The example signs an assembly called myAssembly.dll with a strong name using the sgKey.snk key pair.

sn -R myAssembly.dll sgKey.snk

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

DemoDelay Signing Assemblies

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

GARBAGE COLLECTION

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

Fundamentals of Garbage Collection

• In the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits:– Enables you to develop your application without having to free

memory.– Allocates objects on the managed heap efficiently.– 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.

– Provides memory safety by making sure that an object cannot use the content of another object.

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

What Happens During a Garbage Collection

• A garbage collection has the following phases:– A marking phase that finds and creates a list of all live objects.– A relocating phase that updates the references to the objects that will be

compacted.– 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.

– 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.

– The large object heap is not compacted, because this would increase memory usage over an unacceptable length of time.

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

Object Graph

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

GC Happening

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

Generations• 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:

• Generation 0. – 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.

• Generation 1.– This generation contains short-lived objects and serves as a buffer between short-

lived objects and long-lived objects.• Generation 2.

– 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.

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

Object.Finalize Method• Allows an object to try to free resources and perform other cleanup

operations before it is reclaimed by garbage collection.• Finalize operations have the following limitations:

– 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.

– 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.

– The thread on which the finalizer is run is unspecified.

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

DemoFinalize

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

IDisposable Interface• Defines a method to release allocated resources.– 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.

– However, it is not possible to predict when garbage collection will occur.

– Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

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

DemoIDisposable

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

Weak References• 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.– A weak reference permits the garbage collector to collect the object

while still allowing the application to access the object.– 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.

– Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.

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

DemoWeak References

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

Também disponível em vídeo...

Assista!http://www.vimeo.com/22076261

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

Próximas reuniões presenciais

• 16/04/2011 - Abril• 21/05/2011 - Maio• 18/06/2011 - Junho• 23/07/2011 - Julho

Reserva estes dias na agenda! :)

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

Obrigado!

Pedro Rosahttp://pt.linkedin.com/in/pedrobarraurosahttp://twitter.com/pedrorosa