SlideShare una empresa de Scribd logo
1 de 54
http://netponto.org 19ª Reunião Presencial - 16/04/2011 O porque das minhas aplicações funcionarem... E o que acontece com os recursos que utilizo?Pedro Rosa
Patrocinadores desta reunião
Pedro Rosa LinkedIn http://pt.linkedin.com/in/pedrobarraurosa Twitter http://twitter.com/pedrorosa
Agenda	 DLL & GAC Location Tools Assembly Discover Strong Name Delay Signing Garbage Collector Disposable Finalize WeakReferences
Também disponível em vídeo... Assista! http://vimeo.com/22695640
Tools that we are going to see
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.
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:INNTicrosoft.NETramework2.0.50727usion.dll Running under executable C:rogram Filesicrosoft.NETrameworkSDKamplesutorialsesourcesandlocalizationraphicsraphicfailtest.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:rogram Filesicrosoft.NETrameworkSDKamplesutorialsesourcesandlocalizationraphicsLOG: 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.
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.
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.snkMyContainer The following command extracts the public key from keyPair.snk and stores it in publicKey.snk. sn -p keyPair.snkpublicKey.snk The following command displays the public key and the token for the public key contained in publicKey.snk. sn -tppublicKey.snk The following command verifies the assembly MyAsm.dll. sn -v MyAsm.dll
Demo Compile &  Languages & IL &ILDASM
Assembly Discoverability
Assembly Location 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: 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.
Demo Default Assembly Location
How the Runtime Locates Assemblies The 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.
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:yListener.log" />          </listeners>       </trace>    </system.diagnostics> </configuration>
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>
Demo Configuration File
Step 1: Examining the Configuration Files Machine Configuration File This file is located in the %runtime install path%onfig directory.  Machine.config contains configuration settings for machine-wide assembly binding
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.
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.
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.
 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.
Demo Global Assembly Cache & Version
Step 4: Locating the Assembly through Codebases or Probing Locating the Assembly through Codebases <configuration>    <runtime>       <assemblyBindingxmlns="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>
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
Step 4: Locating the Assembly through Codebases or Probing Locating the Assembly through Probing Probing with the privatePath Attribute <configuration>    <runtime>       <assemblyBindingxmlns="urn:schemas-microsoft-com:asm.v1">          <probing privatePath="bin;bin2ubbin;bin3"/>       </assemblyBinding>    </runtime> </configuration>
Demo Assemblies Location
Assembly Versions & Binding Redirect
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>
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:ersionsamplein1elper.dll"/>             <codeBase version="2.0.0.0“   href="c:ersionsamplein2elper.dll"/>          </dependentAssembly>       </assemblyBinding>    </runtime> </configuration>  
Demo Binding Redirect
Delay Signing
Delay Signing an Assembly An organization can have a closely guarded key pair that developers do not have access to on a daily basis.
Delay Signing an Assembly 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). Annotate the source code for the assembly with two custom attributes from System.Reflection: AssemblyKeyFileAttribute, which passes the name of the file containing the public key as a parameter to its constructor. AssemblyDelaySignAttribute, which indicates that delay signing is being used by passing true as a parameter to its constructor.
Delay Signing an Assembly 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. 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
Delay Signing an Assembly 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. The example signs an assembly called myAssembly.dll with a strong name using the sgKey.snk key pair. sn -R myAssembly.dll sgKey.snk
Demo Delay Signing Assemblies
Garbage collection
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.
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.
Object Graph
GC Happening
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.
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.
Demo Finalize
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.
Demo IDisposable
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.
Demo Weak References
Também disponível em vídeo... Assista! http://www.vimeo.com/22076261
Patrocinadores desta reunião
Próximas reuniões presenciais 16/04/2011 - Abril 21/05/2011 - Maio 18/06/2011 - Junho 23/07/2011 - JulhoReserva estes dias na agenda! :)
Obrigado! Pedro Rosa http://pt.linkedin.com/in/pedrobarraurosa http://twitter.com/pedrorosa

Más contenido relacionado

La actualidad más candente

Bypassing anti virus scanners
Bypassing anti virus scannersBypassing anti virus scanners
Bypassing anti virus scanners
martacax
 
Ruby Projects and Libraries
Ruby Projects and LibrariesRuby Projects and Libraries
Ruby Projects and Libraries
Vorleak Chy
 

La actualidad más candente (20)

Reversing & Malware Analysis Training Part 9 - Advanced Malware Analysis
Reversing & Malware Analysis Training Part 9 -  Advanced Malware AnalysisReversing & Malware Analysis Training Part 9 -  Advanced Malware Analysis
Reversing & Malware Analysis Training Part 9 - Advanced Malware Analysis
 
Infrastructure as Code in your CD pipelines - London Microsoft DevOps 0423
Infrastructure as Code in your CD pipelines - London Microsoft DevOps 0423Infrastructure as Code in your CD pipelines - London Microsoft DevOps 0423
Infrastructure as Code in your CD pipelines - London Microsoft DevOps 0423
 
DNUG Webcast: IBM Notes V10 Performance Boost
DNUG Webcast: IBM Notes V10 Performance BoostDNUG Webcast: IBM Notes V10 Performance Boost
DNUG Webcast: IBM Notes V10 Performance Boost
 
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit MitigationsCaptain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
 
4Developers 2015: Sprytniejsze testowanie kodu Java ze Spock Framework - Marc...
4Developers 2015: Sprytniejsze testowanie kodu Java ze Spock Framework - Marc...4Developers 2015: Sprytniejsze testowanie kodu Java ze Spock Framework - Marc...
4Developers 2015: Sprytniejsze testowanie kodu Java ze Spock Framework - Marc...
 
Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1
Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1  Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1
Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1
 
Hacking Oracle From Web Apps 1 9
Hacking Oracle From Web Apps 1 9Hacking Oracle From Web Apps 1 9
Hacking Oracle From Web Apps 1 9
 
Practice of Android Reverse Engineering
Practice of Android Reverse EngineeringPractice of Android Reverse Engineering
Practice of Android Reverse Engineering
 
Advanced Malware Analysis Training Session 3 - Botnet Analysis Part 2
Advanced Malware Analysis Training Session 3 - Botnet Analysis Part 2Advanced Malware Analysis Training Session 3 - Botnet Analysis Part 2
Advanced Malware Analysis Training Session 3 - Botnet Analysis Part 2
 
What is new in Notes & Domino Deleopment V10.x
What is new in Notes & Domino Deleopment V10.xWhat is new in Notes & Domino Deleopment V10.x
What is new in Notes & Domino Deleopment V10.x
 
Reversing & malware analysis training part 1 lab setup guide
Reversing & malware analysis training part 1   lab setup guideReversing & malware analysis training part 1   lab setup guide
Reversing & malware analysis training part 1 lab setup guide
 
Bypassing anti virus scanners
Bypassing anti virus scannersBypassing anti virus scanners
Bypassing anti virus scanners
 
Advanced Malware Analysis Training Session 7 - Malware Memory Forensics
Advanced Malware Analysis Training Session 7  - Malware Memory ForensicsAdvanced Malware Analysis Training Session 7  - Malware Memory Forensics
Advanced Malware Analysis Training Session 7 - Malware Memory Forensics
 
Delivering High Quality Elixir Code using Gitlab
Delivering High Quality Elixir Code using GitlabDelivering High Quality Elixir Code using Gitlab
Delivering High Quality Elixir Code using Gitlab
 
Ruby Projects and Libraries
Ruby Projects and LibrariesRuby Projects and Libraries
Ruby Projects and Libraries
 
You're Off the Hook: Blinding Security Software
You're Off the Hook: Blinding Security SoftwareYou're Off the Hook: Blinding Security Software
You're Off the Hook: Blinding Security Software
 
Continuous intrusion: Why CI tools are an attacker’s best friends
Continuous intrusion: Why CI tools are an attacker’s best friendsContinuous intrusion: Why CI tools are an attacker’s best friends
Continuous intrusion: Why CI tools are an attacker’s best friends
 
Hacking oracle using metasploit
Hacking oracle using metasploitHacking oracle using metasploit
Hacking oracle using metasploit
 
Advanced Malware Analysis Training Session 1 - Detection and Removal of Malwares
Advanced Malware Analysis Training Session 1 - Detection and Removal of MalwaresAdvanced Malware Analysis Training Session 1 - Detection and Removal of Malwares
Advanced Malware Analysis Training Session 1 - Detection and Removal of Malwares
 
Troubleshooting the Windows Installer
Troubleshooting the Windows Installer Troubleshooting the Windows Installer
Troubleshooting the Windows Installer
 

Destacado

PowerShell: (Don't Fear) The Console - Bruno Lopes
PowerShell: (Don't Fear) The Console - Bruno LopesPowerShell: (Don't Fear) The Console - Bruno Lopes
PowerShell: (Don't Fear) The Console - Bruno Lopes
Comunidade NetPonto
 
Novidades Azure (Após o //BUILD)
Novidades Azure (Após o //BUILD)Novidades Azure (Após o //BUILD)
Novidades Azure (Após o //BUILD)
Comunidade NetPonto
 

Destacado (19)

Windows Workflow Foundation 4: Introdução - C. Augusto Proiete
Windows Workflow Foundation 4: Introdução - C. Augusto ProieteWindows Workflow Foundation 4: Introdução - C. Augusto Proiete
Windows Workflow Foundation 4: Introdução - C. Augusto Proiete
 
Windows Azure para Developers
Windows Azure para DevelopersWindows Azure para Developers
Windows Azure para Developers
 
Windows Phone 7 & XNA - Let's play?
Windows Phone 7 & XNA - Let's play?Windows Phone 7 & XNA - Let's play?
Windows Phone 7 & XNA - Let's play?
 
Novidades do SQL Server 2011, "Denali"
Novidades do SQL Server 2011, "Denali"Novidades do SQL Server 2011, "Denali"
Novidades do SQL Server 2011, "Denali"
 
VSTO + LOB Apps Information Matters
VSTO + LOB Apps Information MattersVSTO + LOB Apps Information Matters
VSTO + LOB Apps Information Matters
 
SoapUI: Testes em WebServices
SoapUI: Testes em WebServicesSoapUI: Testes em WebServices
SoapUI: Testes em WebServices
 
Know your SQL Server - DMVs
Know your SQL Server - DMVsKnow your SQL Server - DMVs
Know your SQL Server - DMVs
 
Arquitectura dos Serviços da plataforma Windows Azure
Arquitectura dos Serviços da plataforma Windows AzureArquitectura dos Serviços da plataforma Windows Azure
Arquitectura dos Serviços da plataforma Windows Azure
 
Introdução ao Lucene.net
Introdução ao Lucene.netIntrodução ao Lucene.net
Introdução ao Lucene.net
 
OData – Super Cola W3
OData – Super Cola W3OData – Super Cola W3
OData – Super Cola W3
 
Document Databases e RavenDB
Document Databases e RavenDBDocument Databases e RavenDB
Document Databases e RavenDB
 
PowerShell: (Don't Fear) The Console - Bruno Lopes
PowerShell: (Don't Fear) The Console - Bruno LopesPowerShell: (Don't Fear) The Console - Bruno Lopes
PowerShell: (Don't Fear) The Console - Bruno Lopes
 
MAF - Managed AddIn Framework
MAF - Managed AddIn FrameworkMAF - Managed AddIn Framework
MAF - Managed AddIn Framework
 
Desenvolvimento de Jogos em XNA para Windows Phone 7
Desenvolvimento de Jogos em XNA para Windows Phone 7Desenvolvimento de Jogos em XNA para Windows Phone 7
Desenvolvimento de Jogos em XNA para Windows Phone 7
 
Novidades Azure (Após o //BUILD)
Novidades Azure (Após o //BUILD)Novidades Azure (Após o //BUILD)
Novidades Azure (Após o //BUILD)
 
HTML5 - Pedro Rosa
HTML5 - Pedro RosaHTML5 - Pedro Rosa
HTML5 - Pedro Rosa
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
 
Windows Azure - Uma Plataforma para o Desenvolvimento de Aplicações
Windows Azure - Uma Plataforma para o Desenvolvimento de AplicaçõesWindows Azure - Uma Plataforma para o Desenvolvimento de Aplicações
Windows Azure - Uma Plataforma para o Desenvolvimento de Aplicações
 
NoSQL em Windows Azure Table Storage - Vitor Tomaz
NoSQL em Windows Azure Table Storage - Vitor TomazNoSQL em Windows Azure Table Storage - Vitor Tomaz
NoSQL em Windows Azure Table Storage - Vitor Tomaz
 

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

Talk on .NET assemblies
Talk on .NET assembliesTalk on .NET assemblies
Talk on .NET assemblies
Vidya Agarwal
 
Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworks
phanleson
 
Managing Your Runtime With P2
Managing Your Runtime With P2Managing Your Runtime With P2
Managing Your Runtime With P2
Pascal Rapicault
 
Continuous Integration using Cruise Control
Continuous Integration using Cruise ControlContinuous Integration using Cruise Control
Continuous Integration using Cruise Control
elliando dias
 
System Imager.20051215
System Imager.20051215System Imager.20051215
System Imager.20051215
guest95b42b
 
Free tools for rapidly deploying software
Free tools for rapidly deploying softwareFree tools for rapidly deploying software
Free tools for rapidly deploying software
Concentrated Technology
 
Reversing & malware analysis training part 12 rootkit analysis
Reversing & malware analysis training part 12   rootkit analysisReversing & malware analysis training part 12   rootkit analysis
Reversing & malware analysis training part 12 rootkit analysis
Abdulrahman Bassam
 

Similar a O porque das minhas aplicações funcionarem... E o que acontece com os recursos que utilizo? (20)

THE CLR AND THE .NET FRAMEWORK, C#
THE CLR AND THE .NET FRAMEWORK, C#THE CLR AND THE .NET FRAMEWORK, C#
THE CLR AND THE .NET FRAMEWORK, C#
 
Dot net assembly
Dot net assemblyDot net assembly
Dot net assembly
 
Talk on .NET assemblies
Talk on .NET assembliesTalk on .NET assemblies
Talk on .NET assemblies
 
Salesforce ANT migration
Salesforce ANT migration Salesforce ANT migration
Salesforce ANT migration
 
.Net assembly
.Net assembly.Net assembly
.Net assembly
 
Deployment with ExpressionEngine
Deployment with ExpressionEngineDeployment with ExpressionEngine
Deployment with ExpressionEngine
 
Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworks
 
Rapidly deploying software
Rapidly deploying softwareRapidly deploying software
Rapidly deploying software
 
Net framework session03
Net framework session03Net framework session03
Net framework session03
 
MSI / Windows Installer for NGN 'Dummies'
MSI / Windows Installer for NGN 'Dummies'MSI / Windows Installer for NGN 'Dummies'
MSI / Windows Installer for NGN 'Dummies'
 
Managing Your Runtime With P2
Managing Your Runtime With P2Managing Your Runtime With P2
Managing Your Runtime With P2
 
Continuous Integration using Cruise Control
Continuous Integration using Cruise ControlContinuous Integration using Cruise Control
Continuous Integration using Cruise Control
 
System Imager.20051215
System Imager.20051215System Imager.20051215
System Imager.20051215
 
TechMentor Fall, 2011 - Packaging Software for Automated Deployment with Wind...
TechMentor Fall, 2011 - Packaging Software for Automated Deployment with Wind...TechMentor Fall, 2011 - Packaging Software for Automated Deployment with Wind...
TechMentor Fall, 2011 - Packaging Software for Automated Deployment with Wind...
 
Setting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntuSetting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntu
 
IDAPRO
IDAPROIDAPRO
IDAPRO
 
Free tools for rapidly deploying software
Free tools for rapidly deploying softwareFree tools for rapidly deploying software
Free tools for rapidly deploying software
 
Prepping software for w7 deployment
Prepping software for w7 deploymentPrepping software for w7 deployment
Prepping software for w7 deployment
 
Reversing & malware analysis training part 12 rootkit analysis
Reversing & malware analysis training part 12   rootkit analysisReversing & malware analysis training part 12   rootkit analysis
Reversing & malware analysis training part 12 rootkit analysis
 
Protractor Testing Automation Tool Framework / Jasmine Reporters
Protractor Testing Automation Tool Framework / Jasmine ReportersProtractor Testing Automation Tool Framework / Jasmine Reporters
Protractor Testing Automation Tool Framework / Jasmine Reporters
 

Más de Comunidade NetPonto

Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone AppsComo deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
Comunidade NetPonto
 
Case studies about Layout & View States & Scale in Windows 8 Store Apps
Case studies about Layout & View States & Scale in Windows 8 Store AppsCase studies about Layout & View States & Scale in Windows 8 Store Apps
Case studies about Layout & View States & Scale in Windows 8 Store Apps
Comunidade NetPonto
 
Aspect-oriented Programming (AOP) com PostSharp
Aspect-oriented Programming (AOP) com PostSharpAspect-oriented Programming (AOP) com PostSharp
Aspect-oriented Programming (AOP) com PostSharp
Comunidade NetPonto
 

Más de Comunidade NetPonto (20)

Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...
Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...
Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...
 
Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...
Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...
Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...
 
MVVM Light e Cimbalino Toolkits - Sara Silva
MVVM Light e Cimbalino Toolkits - Sara SilvaMVVM Light e Cimbalino Toolkits - Sara Silva
MVVM Light e Cimbalino Toolkits - Sara Silva
 
Deep dive into Windows Azure Mobile Services - Ricardo Costa
Deep dive into Windows Azure Mobile Services - Ricardo CostaDeep dive into Windows Azure Mobile Services - Ricardo Costa
Deep dive into Windows Azure Mobile Services - Ricardo Costa
 
The power of templating.... with NVelocity - Nuno Cancelo
The power of templating.... with NVelocity - Nuno CanceloThe power of templating.... with NVelocity - Nuno Cancelo
The power of templating.... with NVelocity - Nuno Cancelo
 
ASP.Net Performance – A pragmatic approach - Luis Paulino
ASP.Net Performance – A pragmatic approach - Luis PaulinoASP.Net Performance – A pragmatic approach - Luis Paulino
ASP.Net Performance – A pragmatic approach - Luis Paulino
 
ASP.NET Signal R - Glauco Godoi
ASP.NET Signal R - Glauco GodoiASP.NET Signal R - Glauco Godoi
ASP.NET Signal R - Glauco Godoi
 
De Zero a Produção - João Jesus
De Zero a Produção - João JesusDe Zero a Produção - João Jesus
De Zero a Produção - João Jesus
 
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone AppsComo deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
 
Case studies about Layout & View States & Scale in Windows 8 Store Apps
Case studies about Layout & View States & Scale in Windows 8 Store AppsCase studies about Layout & View States & Scale in Windows 8 Store Apps
Case studies about Layout & View States & Scale in Windows 8 Store Apps
 
Aspect-oriented Programming (AOP) com PostSharp
Aspect-oriented Programming (AOP) com PostSharpAspect-oriented Programming (AOP) com PostSharp
Aspect-oriented Programming (AOP) com PostSharp
 
Utilização de Mock Objects em Testes Unitários
Utilização de Mock Objects em Testes UnitáriosUtilização de Mock Objects em Testes Unitários
Utilização de Mock Objects em Testes Unitários
 
Dinâmica e Motivacao de Equipas de Projecto
Dinâmica e Motivacao de Equipas de ProjectoDinâmica e Motivacao de Equipas de Projecto
Dinâmica e Motivacao de Equipas de Projecto
 
KnockoutJS com ASP.NET MVC3: Utilização na vida real
KnockoutJS com ASP.NET MVC3: Utilização na vida realKnockoutJS com ASP.NET MVC3: Utilização na vida real
KnockoutJS com ASP.NET MVC3: Utilização na vida real
 
Como ser programador durante o dia e mesmo assim dormir bem à noite
Como ser programador durante o dia e mesmo assim dormir bem à noiteComo ser programador durante o dia e mesmo assim dormir bem à noite
Como ser programador durante o dia e mesmo assim dormir bem à noite
 
Windows 8: Desenvolvimento de Metro Style Apps - C. Augusto Proiete
Windows 8: Desenvolvimento de Metro Style Apps - C. Augusto ProieteWindows 8: Desenvolvimento de Metro Style Apps - C. Augusto Proiete
Windows 8: Desenvolvimento de Metro Style Apps - C. Augusto Proiete
 
Uma Introdução a ASP.NET Web API
Uma Introdução a ASP.NET Web APIUma Introdução a ASP.NET Web API
Uma Introdução a ASP.NET Web API
 
Como não entalar os dedos nas janelas: Finger-based apps no Windows 8
Como não entalar os dedos nas janelas: Finger-based apps no Windows 8Como não entalar os dedos nas janelas: Finger-based apps no Windows 8
Como não entalar os dedos nas janelas: Finger-based apps no Windows 8
 
Sessão Especial: PowerPivot com Alberto Ferrari
Sessão Especial: PowerPivot com Alberto FerrariSessão Especial: PowerPivot com Alberto Ferrari
Sessão Especial: PowerPivot com Alberto Ferrari
 
NuGet no Contexto Empresarial
NuGet no Contexto EmpresarialNuGet no Contexto Empresarial
NuGet no Contexto Empresarial
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

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

  • 1. http://netponto.org 19ª Reunião Presencial - 16/04/2011 O porque das minhas aplicações funcionarem... E o que acontece com os recursos que utilizo?Pedro Rosa
  • 3. Pedro Rosa LinkedIn http://pt.linkedin.com/in/pedrobarraurosa Twitter http://twitter.com/pedrorosa
  • 4. Agenda DLL & GAC Location Tools Assembly Discover Strong Name Delay Signing Garbage Collector Disposable Finalize WeakReferences
  • 5. Também disponível em vídeo... Assista! http://vimeo.com/22695640
  • 6. Tools that we are going to see
  • 7. 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.
  • 8. 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:INNTicrosoft.NETramework2.0.50727usion.dll Running under executable C:rogram Filesicrosoft.NETrameworkSDKamplesutorialsesourcesandlocalizationraphicsraphicfailtest.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:rogram Filesicrosoft.NETrameworkSDKamplesutorialsesourcesandlocalizationraphicsLOG: 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.
  • 9. 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.
  • 10. 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.snkMyContainer The following command extracts the public key from keyPair.snk and stores it in publicKey.snk. sn -p keyPair.snkpublicKey.snk The following command displays the public key and the token for the public key contained in publicKey.snk. sn -tppublicKey.snk The following command verifies the assembly MyAsm.dll. sn -v MyAsm.dll
  • 11. Demo Compile & Languages & IL &ILDASM
  • 13. Assembly Location 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: 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.
  • 15. How the Runtime Locates Assemblies The 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.
  • 16. 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:yListener.log" /> </listeners> </trace> </system.diagnostics> </configuration>
  • 17. 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>
  • 19. Step 1: Examining the Configuration Files Machine Configuration File This file is located in the %runtime install path%onfig directory. Machine.config contains configuration settings for machine-wide assembly binding
  • 20. 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.
  • 21. 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.
  • 22. 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.
  • 23. 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.
  • 24. Demo Global Assembly Cache & Version
  • 25. Step 4: Locating the Assembly through Codebases or Probing Locating the Assembly through Codebases <configuration> <runtime> <assemblyBindingxmlns="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>
  • 26. 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
  • 27. Step 4: Locating the Assembly through Codebases or Probing Locating the Assembly through Probing Probing with the privatePath Attribute <configuration> <runtime> <assemblyBindingxmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="bin;bin2ubbin;bin3"/> </assemblyBinding> </runtime> </configuration>
  • 29. Assembly Versions & Binding Redirect
  • 30. 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>
  • 31. 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:ersionsamplein1elper.dll"/>             <codeBase version="2.0.0.0“  href="c:ersionsamplein2elper.dll"/>          </dependentAssembly>       </assemblyBinding>    </runtime> </configuration>  
  • 34. Delay Signing an Assembly An organization can have a closely guarded key pair that developers do not have access to on a daily basis.
  • 35. Delay Signing an Assembly 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). Annotate the source code for the assembly with two custom attributes from System.Reflection: AssemblyKeyFileAttribute, which passes the name of the file containing the public key as a parameter to its constructor. AssemblyDelaySignAttribute, which indicates that delay signing is being used by passing true as a parameter to its constructor.
  • 36. Delay Signing an Assembly 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. 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
  • 37. Delay Signing an Assembly 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. The example signs an assembly called myAssembly.dll with a strong name using the sgKey.snk key pair. sn -R myAssembly.dll sgKey.snk
  • 38. Demo Delay Signing Assemblies
  • 40. 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.
  • 41. 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.
  • 44. 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.
  • 45. 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.
  • 47. 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.
  • 49. 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.
  • 51. Também disponível em vídeo... Assista! http://www.vimeo.com/22076261
  • 53. Próximas reuniões presenciais 16/04/2011 - Abril 21/05/2011 - Maio 18/06/2011 - Junho 23/07/2011 - JulhoReserva estes dias na agenda! :)
  • 54. Obrigado! Pedro Rosa http://pt.linkedin.com/in/pedrobarraurosa http://twitter.com/pedrorosa