SlideShare une entreprise Scribd logo
1  sur  21
C# Advanced
   Part 2
Applications
•   Console Windows apps
•   Windows Forms
•   Web services, WCF services
•   Web forms
•   ASP.NET MVC apps
•   Windows services
•   Libraries
Assembly
• Is a deployment unit
• .EXE or .DLL
• Contains manifest + code
  (metadata tables + IL)
Types
Can contain:
• Constant
• Field
• Instance constructor
• Type constructor
• Method. Method is not virtual by default.
  Virtual, new , override, sealed, abstract
Types (cont’d)
•   Property. Can be virtual
•   Overloaded operator
•   Conversion operator
•   Event. Can be virtual
•   Type
Access modifiers
•   Private
•   Protected (Family)
•   Internal
•   Family and assembly -- Not supported in C#
•   Family or assembly (protected internal)
•   Public
Types
• Value types – stack, inline
• Reference types – heap, by reference
Object lifetime
•   Allocate memory. Fill it with 0x00.
•   Init memory -- constructor.
•   Use the object -- call methods, access fields.
•   Cleanup.
•   Deallocate memory (only GC is responsible for
    this).
Object References
• CLR knows about all references to objects.
• Root reference (in active local var or in static
  field).
• Non-root reference (in instance field)
Finalization
• Mechanism that allows the object to correctly
  cleanup itself before GC releases memory.
• Time when finalizers are called is
  undetermined.
• Order in which finalizers are called is
  undetermined.
• Partially constructed objects are also finalized
IDisposable
• Used when the object needs explicit cleanup
What are Exceptions?
• An exception is any error condition or
  unexpected behavior encountered by an
  executing program.
• In the .NET Framework, an exception is an object
  that inherits from the Exception Class class.
• The exception is passed up the stack until the
  application handles it or the program terminates.
Use Exceptions or not use exceptions?
-
•   Вони невидимі з викликаючого коду.
•   Створюються непередбачувані точки виходу з метода.
•   Exceptions повільні. (exceptions use resources only when an exception occurs.)
+
• Зручність використання.
• Інформативність отриманих помилок більша по відношенні до
  статус-кодів.
• Принцип використання. Throw на самий верхній рівень.
• Більш елегантні архітектурні рішення та зменшення часу
  розробки.
C# Exception handling
•   try…catch…finally
•   throw
•   Catch as high as you can
•   try{ }
     catch(Exception1){ /*exception1 handler*/ }
     catch(Exception2) { /*exception2 handler*/ }
     catch(Exception) { /*exception handler*/ }
IDisposable
• The primary use of this interface is to release
  unmanaged resources.

• When calling a class that implements the
  IDisposable interface, use the try/finally
  pattern to make sure that unmanaged
  resources are disposed of even if an exception
  interrupts your application.
Working with streams
var fileStream = new FileStream(@"PathTofile", FileMode.Open, FileAccess.Read);
try
{
       //Note: read from file stream here
}
finally
{
          fileStream.Dispose();
}
//Note: you can use file stream here, but this is bad idea



using (var fileStream = new FileStream(@"PathTofile", FileMode.Open, FileAccess.Read))
{
            //Note: read from file stream here
}
 //Note: fileStream is not accessible here
Attributes
• Attributes provide a powerful method of
  associating declarative information with C#
  code (types, methods, properties, and so
  forth).
Aspect Oriented Programming
•   Logging
•   Data validating
•   Security mechanism
•   …
Validation sample (AOP sample)
  public class User
 {
        [StringLengthValidator(1, 255, MessageTemplate = "Login cannot be empty.")]
        public string Login { get; set; }

       [StringLengthValidator(1, 127, MessageTemplate = "Domain cannot be empty.")]
       public string Domain { get; set; }

       public string FirstName { get; set; }

       public string LastName { get; set; }

       [StringLengthValidator(1, 50, MessageTemplate = "Email cannot be empty.")]
       public string Email { get; set; }
 }


http://msdn.microsoft.com/en-us/library/ff648831.aspx - Enterprise Library Validation Application Block
Custom attributes
- Creating
 [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class LoggingRequiredAttribute : Attribute
    {
    }

- Usages
 public class UserService
    {
        [LoggingRequired]
        public static void CreateUser()
        {
            //Note: logic here
        }

           public static void EditUser()
           {
               //Note: logic here
           }
    }
Questions?

Contenu connexe

Tendances

JavaScript unit testing with Jasmine
JavaScript unit testing with JasmineJavaScript unit testing with Jasmine
JavaScript unit testing with Jasmine
Yuval Dagai
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010
Clay Helberg
 
Java serialization
Java serializationJava serialization
Java serialization
Sujit Kumar
 

Tendances (17)

Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Calypso browser
Calypso browserCalypso browser
Calypso browser
 
JavaScript unit testing with Jasmine
JavaScript unit testing with JasmineJavaScript unit testing with Jasmine
JavaScript unit testing with Jasmine
 
Solr Introduction
Solr IntroductionSolr Introduction
Solr Introduction
 
core java
core javacore java
core java
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010
 
25csharp
25csharp25csharp
25csharp
 
Dynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection PromisesDynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection Promises
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
 
Finding Needles in Haystacks
Finding Needles in HaystacksFinding Needles in Haystacks
Finding Needles in Haystacks
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java serialization
Java serializationJava serialization
Java serialization
 
Ruxmon cve 2012-2661
Ruxmon cve 2012-2661Ruxmon cve 2012-2661
Ruxmon cve 2012-2661
 
Helberg acl-final
Helberg acl-finalHelberg acl-final
Helberg acl-final
 
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
 
70 536
70 53670 536
70 536
 

Similaire à 06.1 .Net memory management

Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
Luka Zakrajšek
 
Vulnerabilities on Various Data Processing Levels
Vulnerabilities on Various Data Processing LevelsVulnerabilities on Various Data Processing Levels
Vulnerabilities on Various Data Processing Levels
Positive Hack Days
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
saryu2011
 
Vulnerabilities in data processing levels
Vulnerabilities in data processing levelsVulnerabilities in data processing levels
Vulnerabilities in data processing levels
beched
 

Similaire à 06.1 .Net memory management (20)

java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
CS8392 OOP
CS8392 OOPCS8392 OOP
CS8392 OOP
 
oop unit1.pptx
oop unit1.pptxoop unit1.pptx
oop unit1.pptx
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
Byte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in Java
 
Vulnerabilities on Various Data Processing Levels
Vulnerabilities on Various Data Processing LevelsVulnerabilities on Various Data Processing Levels
Vulnerabilities on Various Data Processing Levels
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
Vulnerabilities in data processing levels
Vulnerabilities in data processing levelsVulnerabilities in data processing levels
Vulnerabilities in data processing levels
 
Eclipse e4
Eclipse e4Eclipse e4
Eclipse e4
 
Advanced debugging
Advanced debuggingAdvanced debugging
Advanced debugging
 
Introduction to Monsoon PHP framework
Introduction to Monsoon PHP frameworkIntroduction to Monsoon PHP framework
Introduction to Monsoon PHP framework
 
C#2
C#2C#2
C#2
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 

Plus de Victor Matyushevskyy (20)

Design patterns part 2
Design patterns part 2Design patterns part 2
Design patterns part 2
 
Design patterns part 1
Design patterns part 1Design patterns part 1
Design patterns part 1
 
Multithreading and parallelism
Multithreading and parallelismMultithreading and parallelism
Multithreading and parallelism
 
Mobile applications development
Mobile applications developmentMobile applications development
Mobile applications development
 
Service oriented programming
Service oriented programmingService oriented programming
Service oriented programming
 
ASP.Net MVC
ASP.Net MVCASP.Net MVC
ASP.Net MVC
 
ASP.Net part 2
ASP.Net part 2ASP.Net part 2
ASP.Net part 2
 
Java script + extjs
Java script + extjsJava script + extjs
Java script + extjs
 
ASP.Net basics
ASP.Net basics ASP.Net basics
ASP.Net basics
 
Automated testing
Automated testingAutomated testing
Automated testing
 
Основи Баз даних та MS SQL Server
Основи Баз даних та MS SQL ServerОснови Баз даних та MS SQL Server
Основи Баз даних та MS SQL Server
 
Usability
UsabilityUsability
Usability
 
Windows forms
Windows formsWindows forms
Windows forms
 
Practices
PracticesPractices
Practices
 
06 LINQ
06 LINQ06 LINQ
06 LINQ
 
05 functional programming
05 functional programming05 functional programming
05 functional programming
 
04 standard class library c#
04 standard class library c#04 standard class library c#
04 standard class library c#
 
#3 Об'єктно орієнтоване програмування (ч. 2)
#3 Об'єктно орієнтоване програмування (ч. 2)#3 Об'єктно орієнтоване програмування (ч. 2)
#3 Об'єктно орієнтоване програмування (ч. 2)
 
#2 Об'єктно орієнтоване програмування (ч. 1)
#2 Об'єктно орієнтоване програмування (ч. 1)#2 Об'єктно орієнтоване програмування (ч. 1)
#2 Об'єктно орієнтоване програмування (ч. 1)
 
#1 C# basics
#1 C# basics#1 C# basics
#1 C# basics
 

Dernier

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
 
+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@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

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
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
+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...
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
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
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"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 ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

06.1 .Net memory management

  • 1. C# Advanced Part 2
  • 2. Applications • Console Windows apps • Windows Forms • Web services, WCF services • Web forms • ASP.NET MVC apps • Windows services • Libraries
  • 3. Assembly • Is a deployment unit • .EXE or .DLL • Contains manifest + code (metadata tables + IL)
  • 4. Types Can contain: • Constant • Field • Instance constructor • Type constructor • Method. Method is not virtual by default. Virtual, new , override, sealed, abstract
  • 5. Types (cont’d) • Property. Can be virtual • Overloaded operator • Conversion operator • Event. Can be virtual • Type
  • 6. Access modifiers • Private • Protected (Family) • Internal • Family and assembly -- Not supported in C# • Family or assembly (protected internal) • Public
  • 7. Types • Value types – stack, inline • Reference types – heap, by reference
  • 8. Object lifetime • Allocate memory. Fill it with 0x00. • Init memory -- constructor. • Use the object -- call methods, access fields. • Cleanup. • Deallocate memory (only GC is responsible for this).
  • 9. Object References • CLR knows about all references to objects. • Root reference (in active local var or in static field). • Non-root reference (in instance field)
  • 10. Finalization • Mechanism that allows the object to correctly cleanup itself before GC releases memory. • Time when finalizers are called is undetermined. • Order in which finalizers are called is undetermined. • Partially constructed objects are also finalized
  • 11. IDisposable • Used when the object needs explicit cleanup
  • 12. What are Exceptions? • An exception is any error condition or unexpected behavior encountered by an executing program. • In the .NET Framework, an exception is an object that inherits from the Exception Class class. • The exception is passed up the stack until the application handles it or the program terminates.
  • 13. Use Exceptions or not use exceptions? - • Вони невидимі з викликаючого коду. • Створюються непередбачувані точки виходу з метода. • Exceptions повільні. (exceptions use resources only when an exception occurs.) + • Зручність використання. • Інформативність отриманих помилок більша по відношенні до статус-кодів. • Принцип використання. Throw на самий верхній рівень. • Більш елегантні архітектурні рішення та зменшення часу розробки.
  • 14. C# Exception handling • try…catch…finally • throw • Catch as high as you can • try{ } catch(Exception1){ /*exception1 handler*/ } catch(Exception2) { /*exception2 handler*/ } catch(Exception) { /*exception handler*/ }
  • 15. IDisposable • The primary use of this interface is to release unmanaged resources. • When calling a class that implements the IDisposable interface, use the try/finally pattern to make sure that unmanaged resources are disposed of even if an exception interrupts your application.
  • 16. Working with streams var fileStream = new FileStream(@"PathTofile", FileMode.Open, FileAccess.Read); try { //Note: read from file stream here } finally { fileStream.Dispose(); } //Note: you can use file stream here, but this is bad idea using (var fileStream = new FileStream(@"PathTofile", FileMode.Open, FileAccess.Read)) { //Note: read from file stream here } //Note: fileStream is not accessible here
  • 17. Attributes • Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth).
  • 18. Aspect Oriented Programming • Logging • Data validating • Security mechanism • …
  • 19. Validation sample (AOP sample) public class User { [StringLengthValidator(1, 255, MessageTemplate = "Login cannot be empty.")] public string Login { get; set; } [StringLengthValidator(1, 127, MessageTemplate = "Domain cannot be empty.")] public string Domain { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [StringLengthValidator(1, 50, MessageTemplate = "Email cannot be empty.")] public string Email { get; set; } } http://msdn.microsoft.com/en-us/library/ff648831.aspx - Enterprise Library Validation Application Block
  • 20. Custom attributes - Creating [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class LoggingRequiredAttribute : Attribute { } - Usages public class UserService { [LoggingRequired] public static void CreateUser() { //Note: logic here } public static void EditUser() { //Note: logic here } }