Effective C# 50 Specific Ways to Improve Your C# Item 46~47 2012/09/25 1.

Slides:



Advertisements
Similar presentations
P/Invoke Made Easy Wei-Chen Wang.
Advertisements

Microsoft ® Office 2007 Training Security II: Turn off the Message Bar and run code safely P J Human Resources Pte Ltd presents:
Using.NET Platform Note: Most of the material of these slides have been taken & extended from Nakov’s excellent overview for.NET framework, MSDN and wikipedia.
J-Interop Open Source Java COM Bridge. Contents What is it ? Comparison with Java Native interface Comparison with J-Integra® for COM Benefits of using.
Chapter 9 TRAP Routines and Subroutines. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 9-2 Subroutines.
EXTENSIBILITY, SAFETY AND PERFORMANCE IN THE SPIN OPERATING SYSTEM B. Bershad, S. Savage, P. Pardyak, E. G. Sirer, D. Becker, M. Fiuczynski, C. Chambers,
Extensibility, Safety and Performance in the SPIN Operating System Presented by Allen Kerr.
Best Practices for Interop with Visual C++ Boris Jabes Program Manager Microsoft Corporation.
C# Console Application
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Freenet A Distributed Anonymous Information Storage and Retrieval System I Clarke O Sandberg I Clarke O Sandberg B WileyT W Hong.
Introducing the Common Language Runtime for.NET. The Common Language Runtime The Common Language Runtime (CLR) The Common Language Runtime (CLR) –Execution.
ASP.Net Security: Fundamentals Chapters 1-4 Freeman and Jones Book.
Introducing the Common Language Runtime. The Common Language Runtime The Common Language Runtime (CLR) The Common Language Runtime (CLR) –Execution engine.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Chapter 2: Operating-System Structures Modified from the text book.
Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.
Efficient Software-Based Fault Isolation—sandboxing Presented by Carl Yao.
Java Security. Topics Intro to the Java Sandbox Language Level Security Run Time Security Evolution of Security Sandbox Models The Security Manager.
Chapter 3 Memory Management: Virtual Memory
Lecture Roger Sutton CO530 Automation Tools 5: Class Libraries and Assemblies 1.
System Calls 1.
.NET Framework Introduction: Metadata
CS533 Concepts of Operating Systems Jonathan Walpole.
Computer Security and Penetration Testing
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Threading Models in Visual Basic Language Student Name: Danyu Xu Student ID:98044.
SAMANVITHA RAMAYANAM 18 TH FEBRUARY 2010 CPE 691 LAYERED APPLICATION.
Chapter 1 Introduction. Goal to learn about computers and programming to compile and run your first Java program to recognize compile-time and run-time.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
Managed C++. Objectives Overview to Visual C++.NET Concepts and architecture Developing with Managed Extensions for C++ Use cases Managed C++, Visual.
Java Introduction to JNI Prepared by Humaira Siddiqui.
CSC204 – Programming I Lecture 4 August 28, 2002.
DEV331 Visual C++: Using The.NET Framework In Win32/MFC Applications Kate Gregory Gregory Consulting Limited.
The HDF Group HDF5 Datasets and I/O Dataset storage and its effect on performance May 30-31, 2012HDF5 Workshop at PSI 1.
Lecture 2 COM - Example. Integrate the web Webcam functionality using.Net and COM First let's explain what we should do exactly. First let's explain what.
Introduction to the Windows API n API - Application Programming Interface n an API is the software interface for things such as the OS n an API is the.
INVITATION TO COMPUTER SCIENCE, JAVA VERSION, THIRD EDITION Chapter 6: An Introduction to System Software and Virtual Machines.
Software Engineering in Robotics Interfacing to external functions Henrik I. Christensen –
1 C# A brief overview by Jack Senechal and Bryan Powell.
tom perkins1 XML Web Services -.NET FRAMEWORK – Part 1 CHAPTER 1.1 – 1.3.
CE Operating Systems Lecture 3 Overview of OS functions and structure.
Views Lesson 7.
Operating Systems (CS 340 D) Princess Nora University Faculty of Computer & Information Systems Computer science Department.
PRIOR TO WEB SERVICES THE OTHER TECHNOLOGIES ARE:.
Operating Systems (CS 340 D) Princess Nora University Faculty of Computer & Information Systems Computer science Department.
Managing C++ CHRIS DAHLBERG MID-TIER DEVELOPER SCOTTRADE.
Object Oriented Software Development 4. C# data types, objects and references.
DEV 420 Head-Spinning C++ Managed-Native Interoperability Kate Gregory Gregory Consulting.
Common Language Runtime Introduction  The common language runtime is one of the most essential component of the.Net Framework.  It acts.
DEV394.NET Framework: Migrating To Managed Code Adam Nathan QA Lead Richard Lander Program Manager Microsoft Corporation.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Efficient Software-Based Fault Isolation Authors: Robert Wahbe Steven Lucco Thomas E. Anderson Susan L. Graham Presenter: Gregory Netland.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Copyright © 2010 The HDF Group. All Rights Reserved1 Data Storage and I/O in HDF5.
Memory Management.
Component Object Model
Component Object Model
Multitasking without Compromise: a Virtual Machine Evolution
Virtual Memory CSSE 332 Operating Systems
Module 11: File Structure
Chapter 11: Storage and File Structure
.NET and .NET Core 2. .NET Runtimes Pan Wuming 2017.
Chapter 2: System Structures
Classes and Objects.
SAMANVITHA RAMAYANAM 18TH FEBRUARY 2010 CPE 691
Outline Chapter 2 (cont) OS Design OS structure
Module 10: Implementing Managed Code in the Database
by Santosh Reddy Vuppala
System calls….. C-program->POSIX call
IS 135 Business Programming
Presentation transcript:

Effective C# 50 Specific Ways to Improve Your C# Item 46~ /09/25 1

Agenda Item 46: Minimize Interop Item 46: Minimize Interop Item 47: Prefer Safe Code Item 47: Prefer Safe Code

MINIMIZE INTEROP Item 46:

The cost of Data Transfer The cost and inefficiencies inherent in crossing the boundary between managed and unmanaged code The cost and inefficiencies inherent in crossing the boundary between managed and unmanaged code – The first toll is paid by marshalling data back and forth between the managed heap and the native heap – The second toll is the thunking cost of moving between managed code and unmanaged code – The third toll is yours alone: the amount of work you need to perform to manage this mixed environment. The third toll is the biggest

The cost of Data Transfer The cost and inefficiencies inherent in crossing the boundary between managed and unmanaged code The cost and inefficiencies inherent in crossing the boundary between managed and unmanaged code – The first toll is paid by marshalling data back and forth between the managed heap and the native heap – The second toll is the thunking cost of moving between managed code and unmanaged code – The third toll is yours alone: the amount of work you need to perform to manage this mixed environment. The third toll is the biggest Our design decisions should minimize the third cost. Our design decisions should minimize the third cost.

The cost of Data Transfer Try to limit the data types passed between the managed and unmanaged layers of your code to blittable types Try to limit the data types passed between the managed and unmanaged layers of your code to blittable types – Blittable type

blittable type A blittable type is one in which the managed and unmanaged representations of the type are the same A blittable type is one in which the managed and unmanaged representations of the type are the same The benefit The benefit – The contents can be copied without regard to the internal structure of the object System.ByteSystem.SbyteSystem.Int16 System.UInt16System.Int32System.UInt32 System.Int64System.UInt64System.UIntPtr The blittable types are listed here:

The cost of Data Transfer If you can't restrict your data types to the blittable types If you can't restrict your data types to the blittable types – Use InAttribute and OutAttribute to control when copies are made – Make sure you apply the most restrictive In/Out combination to avoid more copying than necessary

The cost of Data Transfer Increase performance by declaring how data should be marshaled Increase performance by declaring how data should be marshaled – This is most common with strings – Marshalling strings uses BSTRs by default.  That's a safe strategy  It is the least efficient For example: The following declaration marshals the string as a LPWStr, or wchar*: public void SetMsg ( [ MarshalAs( UnmanagedType.LPWStr ) ] string msg [ MarshalAs( UnmanagedType.LPWStr ) ] string msg ); );

Transfer program control How you can transfer program control between managed and unmanaged components How you can transfer program control between managed and unmanaged components – COM interop – Platform Invoke (P/Invoke) – Managed C++

COM interop Benefit Benefit – COM interop is the easiest way to leverage those COM components you are already using Disadvantage Disadvantage – COM interop is the least efficient way to access native code in.NET

Platform Invoke (P/Invoke) Benefit Benefit – This is the most efficient way to call any of the Win32 APIs because you avoid the overhead associated with COM Disadvantage Disadvantage – You need to hand-code the interface to each method that you call using P/Invoke – The more methods you invoke, the more method declarations you must hand-code

Managed C++ You must build a managed C++ library on top of your legacy code to provide the bridge between the unmanaged and managed types, providing the marshalling support between the managed and unmanaged heaps You must build a managed C++ library on top of your legacy code to provide the bridge between the unmanaged and managed types, providing the marshalling support between the managed and unmanaged heaps

Summary If you have existing COM objects written in any language, use COM interop. If you have existing C++ code, the /CLR switch and managed C++ provide the best strategy to access your existing native codebase from new development created in C#. Pick the strategy that takes the least time If you have existing COM objects written in any language, use COM interop. If you have existing C++ code, the /CLR switch and managed C++ provide the best strategy to access your existing native codebase from new development created in C#. Pick the strategy that takes the least time

PREFER SAFE CODE Item 37:

Prefer Safe Code Avoid accessing unmanaged memory whenever possible Avoid accessing unmanaged memory whenever possible Most common security concern is the file system Most common security concern is the file system

Avoid accessing unmanaged memory whenever possible A safe assembly is one that does not use any pointers to access either the managed or unmanaged heaps A safe assembly is one that does not use any pointers to access either the managed or unmanaged heaps Almost all the C# code that you create is safe Almost all the C# code that you create is safe Unless you turn on the /unsafe C# compiler option, you've created verifiably safe code Unless you turn on the /unsafe C# compiler option, you've created verifiably safe code

Avoid accessing unmanaged memory whenever possible When you use unsafe constructs, understand that unsafe code anywhere in an assembly affects the entire assembly When you use unsafe constructs, understand that unsafe code anywhere in an assembly affects the entire assembly When you create unsafe code blocks, consider isolating those algorithms in their own assembly When you create unsafe code blocks, consider isolating those algorithms in their own assembly – This limits the affect that unsafe code has on your entire application – If it's isolated, only callers who need the particular feature are affected

File system security concern Partially trusted assemblies can access their own specific isolated storage area, but nowhere else on the file system Partially trusted assemblies can access their own specific isolated storage area, but nowhere else on the file system You use isolated storage through the classes in the System.IO.IsolatedStorage namespace You use isolated storage through the classes in the System.IO.IsolatedStorage namespace The IsolatedStorageFile class contains methods very similar to the System.IO.File class The IsolatedStorageFile class contains methods very similar to the System.IO.File class

IsolatedStorageFile IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForDomain( ); IsolatedStorageFileStream myStream = new IsolatedStorageFileStream( "SavedStuff.txt", FileMode.Create, iso ); StreamWriter wr = new StreamWriter( myStream ); wr.Close(); Reading is equally familiar to anyone who has used file I/O IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForDomain( ); string[] files = isoStore.GetFileNames( "SavedStuff.txt" ); if ( files.Length > 0 ) { StreamReader reader = new StreamReader( new IsolatedStorageFileStream( "SavedStuff.txt", FileMode.Open,isoStore ) ); if ( files.Length > 0 ) { StreamReader reader = new StreamReader( new IsolatedStorageFileStream( "SavedStuff.txt", FileMode.Open,isoStore ) ); reader.Close(); }

IsolatedStorageFile The.NET environment defines limits on the size of isolated storage for each application. This prevents malicious code from consuming excessive disk space, rendering a system unusable The.NET environment defines limits on the size of isolated storage for each application. This prevents malicious code from consuming excessive disk space, rendering a system unusable Isolated storage is hidden from other programs and other users Isolated storage is hidden from other programs and other users Even though it is hidden, however, isolated storage is not protected from unmanaged code or from trusted users. Do not use isolated storage for high-value secrets unless you apply additional encryption Even though it is hidden, however, isolated storage is not protected from unmanaged code or from trusted users. Do not use isolated storage for high-value secrets unless you apply additional encryption

Summary Avoid accessing unmanaged memory whenever possible Avoid accessing unmanaged memory whenever possible Use isolated storage whenever possible Use isolated storage whenever possible