.NET
in
Samples
Jan Šeda
jan.seda@skilldrive.com

Learning and using technologies is sometimes very boring and reading books takes too much time. Many developers use MSDN but there is a big issue - that there are too many articles and other sources that this huge quantity is not possible to absorb and confusing (maybe this is the reason why Russian search engine started a special indexer on MSDN itself, see http://msdn.rambler.ru). This is the reason why I don’t like reading technical books or MSDN articles like they would be bestsellers and searching on MSDN is terrifying experience at least for me).
That is why in December 2003 I have decided to write my own book (just for personal usage) with samples, descriptions and explanation of technologies – just short samples and many images where principles could be seen immediately so learning curve could be as short as possible. Later I’ve provided this book to my friends and they told me that it can be useful for other developers who want to learn fast and see results in a very short time.
So far I have been writing samples on „as-needed“ basis, many chapters are unfinished and cover specific topic just basically. Also my English translation has not being checked by a professional translator and I want to excuse myself for not being able to write perfect English expressions but I hope this book will be helpful to developers.
© 2004-2005 by Jan Šeda, Skilldrive
All rights reserved. Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, people and events depicted herein are fictitious and no association with any real company, organization, product, person or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of the author.
The information in this book is distributed on an “as is” basis, without warranty. While every precaution has been taken in the preparation of this book, the author shall not have any liability to any person or entitle with respect to any liability, loss or damage caused or alleged to be caused directly or indirectly by instructions contained in this book or by the computer software or hardware products described herein.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does o
Active Directory, ActiveX, Authenticode, BizTalk, DirectX, IntelliSense, JScript, Microsoft, MSDN, Visual Basic, Visual C++, Visual J++, Visual SourceSafe, Visual Studio, Windows, Windows Media, Windows NT and Windows Server are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.
All other product names and company names mentioned herein are the property of their respective owners.
Contents
3.1.8. Get SID for current identity
3.1.9. Get object name for SID
3.2. Protecting system resources
3.2.1. Test yourself on security & protection of system resources
3.2.2. Rules behind propagation of rights on objects
3.2.3. Get ACLs/ACEs for a file
4.1.1. What is a Common Criteria?
4.1.2. Why is Common Criteria important?
5. Security Concepts in .NET environment
5.1. Basic layout of .NET Framework – Security parts
5.2.1. Runtime security policy
5.2.2. Types of security context for assemblies
5.2.3. Generate key pair with sn.exe tool
5.2.4. Give an assembly a strong name
5.2.5. Delayed signing of assembly
5.2.6. List of permissions in policy levels
5.2.7. List of permissions assign to current assembly
5.2.8. Get permission list for a custom evidence.
5.2.9. List of declarative permissions of assembly.
5.2.10. Output assembly evidence list to XML file
5.2.11. List policy levels and code groups where current assembly belongs
5.3. Type safety, metadata and code verification.
5.3.1. Get info about types in assembly
5.4.1. Application domain boundaries and objects
5.4.2. Create application domain programmatically
5.4.3. Shadow copy enabled for application domain
5.5. Security tools available in .NET
5.6.2. Limit access permissions for a method
5.6.3. Add new code group to runtime security
5.7.1. Identity classes (also Whidbey)
5.7.4. Using GenericPrincipal class
5.7.5. Get list of groups for current thread’s identity
5.7.7. Impersonate as another user
5.7.8. Declarative principal permissions for Windows roles
5.7.9. Declarative principal permissions for custom roles
5.7.10. List running processes and user accounts
6.1.1. CodeRed Worm, Buffer Overrun attack
6.2. Algorithms for Encryption
6.2.1. Well Known Algorithms for Symmetric Encryption
6.2.2. Well Known Algorithms for Asymmetric Encryption
6.2.3. Well Known Hash Algorithms
6.4. Secure Communication Standards
6.4.1. IPSec (Internet Protocol Security)
6.4.3. SSL (Secure Socket Layer)
7.1. Basic terms in cryptography
7.2.2. Progress in cryptography
7.4. CMV (Cryptographic Module validation)
7.4.1. Microsoft FIPS 140 certification
7.4.2. .NET classes and FIPS 140
7.6. Configuring .NET cryptography
7.7. Win32 Security API and .NET
7.8.1. Generating random values
7.8.2. Generating random nonzero values
7.8.3. Random number generator and other CSPs (Cryptographic Service Provider)
7.10.3. Key distribution problem
7.10.4. Data Encryption Standard (DES)
7.10.9. Ronald Rivest’s (RC) ciphers
7.10.10. Hash value using MD5 and SHA
7.10.11. Collision in MD5 algorithm
7.10.12. Classes for symmetric algorithms in .NET
7.10.13. Deriving symmetric keys from passwords.
7.10.14. Creating symmetric encryption classes.
7.10.15. Symmetric encryption/decryption of plaintext using DES
7.10.16. Symmetric encryption/decryption of plaintext using RC2
7.10.17. Symmetric encryption/decryption of plaintext using Rijndael
7.10.18. Determining weak and semi-weak keys in DES
7.10.19. Deriving symmetric key from password using PBKDF1
7.10.20. Deriving symmetric key & IV from a password using PBKDF1
7.10.21. Deriving symmetric key from a password using PBKDF2
7.10.22. Check valid key size for symmetric encryption
7.10.23. Hybrid usage of symmetric and asymmetric encryption
7.10.24. Hashing of plaintext and encryption/decryption using DES
7.10.25. Keyed hash algorithm HMACSHA1
7.10.26. Keyed hash algorithm MACTripleDES
7.11.1. Certificates & Certification authorities
7.12.1. Classes for asymmetric algorithms in .NET
7.12.2. Storing public and private RSA keys in XML file
7.12.3. Storing keys by CSP (Crypto Service Provider)
7.12.4. Encryption of plaintext using RSA with XML-stored key
7.12.5. Encryption/decryption of plaintext using RSA
7.12.6. Encryption/decryption of plaintext using RSA with XML-stored key
7.12.7. Encryption of plaintext using RSAParameters
7.12.8. Encryption/Decryption of plaintext by RSA
7.12.9. Encryption with public key (exception)
7.12.10. How to encrypt/decrypt large data using RSA?
7.12.11. Calling RSA/DSA from a Web service, ASP or COM+
7.13.1. Sign and verify data with RSA I
7.13.2. Sign and verify data with RSA II
7.13.3. Sign and verify data with RSA using SignatureFormatter
7.13.4. Sign and verify data with DSA
7.14. Key exchange methods and classes
7.14.1. Exchange symmetric key between two clients using OAEP
7.15.1. Create X509Certificate from file generated by makecert.exe
7.15.2. Create X.509 certificate from base64 encoded certificates
7.15.3. Source library with CryptoAPI certificate mappings
7.15.4. List of installed client’s certificates
7.15.5. List of installed intermediate certification authorities
7.15.6. List of installed root certificate authorities
7.17. Basic principles of DPAPI
7.17.2. Source library with DPAPI methods
7.17.3. Use DPAPI to encipher application data into file
7.17.4. Use DPAPI to decipher application data from file
7.17.5. DPAPI used to encrypt data in file in isolated storage
7.17.6. DPAPI used to decrypt data from file in isolated storage
7.17.7. Encrypt/Decrypt database connection string using DPAPI
7.17.8. Issues with user’s store and web services and COM+
7.19.1. Storeadm.exe – administration of isolated storage in .NET
7.19.2. Opening of isolated storages for current user and domain
7.19.3. Store data in file in isolated storage.
8.1.1. Retrieve DNS computer name
8.1.2. Retrieve NetBIOS computer name
8.1.3. Obtain IP address and host
8.1.4. Send email in .NET environment
8.1.5. Getting online stock information
8.1.6. Retrieve email from POP3 mail server
9.1.1. Get executing application’s path with reflection
9.1.2. Get executing application’s path
9.1.3. Classes working with file and directory information
9.1.4. Change file & folder attributes
9.1.5. Recursive list of directories/subdirectories & files
9.2. Reading and writing from/to files
9.2.2. Read from file using BufferedStream
9.2.5. Create file and write to it
9.2.9. Watch file system for changes
10. Text Manipulation & Internationalization
10.1.2. Inserting/Removing string
10.1.5. Reverse string using recursion
10.2.1. Table with number formatting options
10.2.2. Formatting of numeric values to currency
10.2.3. Formatting of numeric values to currency with NumberFormatInfo
10.2.4. Formatting of floating point values to a scientific notation (exponential)
10.2.5. Formatting of floating point values to specific number of decimals (fixed-point)
10.2.6. Formatting of numeric value to local culture specific number
10.2.7. Formatting of floating point value to roundtrip (can be converted back to number)
10.2.8. Formatting of an integer value to a hexadecimal number
10.2.9. Formatting floating point values to a percentage
10.2.10. Formatting floating point values to a percentage with limited number of decimals
10.2.11. Formatting of floating point values to a percentage with NumberFormatInfo
10.3. Formatting date and time
10.3.1. Table with date&time formatting options
10.3.2. Formatting DateTime to the short date&time pattern (dddd, MMMM dd, yyyy, hh:mm)
10.3.3. Formatting DateTime to the full date&time pattern (dddd, MMMM dd, yyyy hh:mm:ss)
10.3.4. Formating DateTime to the short date numerical pattern (M/d/yyyy)
10.3.5. Formatting DateTime to the full date numerical pattern (dddd, MMMM dd, yyyy)
10.3.6. Formatting DateTime to the short date&time numerical pattern (M/d/yyyy hh:mm)
10.3.7. Formatting DateTime to the full date&time numerical pattern (M/d/yyyy hh:mm:ss)
10.3.8. Formatting DateTime to the month name pattern (MMMM dd)
10.3.9. Formatting DateTime to the short date pattern (MMMM, yyyy)
10.3.10. Formatting DateTime to the long time pattern (hh:mm:ss)
10.3.11. Formatting DateTime to the short time pattern (hh:mm)
10.3.12. Formatting DateTime to the RFC1123 pattern (ddd, dd MMM yyyy HH':'mm':'ss 'GMT')
10.3.13. Formatting DateTime to sortable pattern
10.3.14. Formatting DateTime to universal sortable pattern (yyyy'-'MM'-'dd HH':'mm':'ss'Z')
10.3.15. Formatting DateTime to full date&time using universal time
10.3.16. Formatting DateTime to custom format using DateTimeFormatInfo
10.4. Custom number formatting
10.4.1. Formatting of number to specific number of decimals
10.4.2. Formatting of number with adding zeros.
10.4.3. Formatting of number to custom positive, negative and zero sections
10.4.4. Formatting of number using custom CultureInfo and custom format
10.5.1. Simple string formatting with number parameter
10.6.1. Class Convert (many convertion methods)
10.6.2. Convert string to integer
10.6.3. Convert string to double
10.6.4. Convert string to double using CultureInfo
10.6.5. Convert string to date
10.6.6. Use regular expression to find and replace string inside of string
10.6.7. Converting string to DateTime using CultureInfo
10.6.8. Convert time_t to DateTime
10.6.9. Convert time_t to DateTime (shorter code)
10.6.10. Convert base64 encoded number to float
10.6.11. Convert file1/encoding1 into file2/encoding2
10.7.1. American Standard Code for Information Interchange (ASCII)
10.7.2. ISO 10646 & Universal Character Set
12.1.1. Time measuring (TickCount and Ticks property)
12.1.2. Accurate time measuring
13. Windows Management Instrumentation (WMI)
13.3.3. WMI Event Registration Tool
13.4. WMI plug-in for Visual Studio .NET 2003
13.5.1. Working with WMI on remote machine
13.5.2. Get computer info (domain, model etc.)
13.5.3. Get computer info (vendor, UUID, type)
13.5.4. Get data about operating system
13.5.5. Logoff, shutdown, reboot computer
13.5.6. Get user’s desktop info
13.5.7. Determine computer type (workstation, server, controller etc.)
13.5.8. Determine physical computer features
13.5.12. Getting list of file shares on local machine
13.5.13. Get logical disk info
13.5.14. Get environment variables
13.5.15. Get CD-ROM/DVD information
13.5.16. Get boot configuration
13.5.17. Find a service by its name
13.5.18. Get list of running/stopped services
13.5.19. Getting partition info
13.5.20. Get list of user’s account from local machine/domain
13.5.21. Get list of user groups from local machine/domain
13.5.22. Get list of installed codec files
13.6.1. Watching for newly started processes
14.4. Forward-only reading and writing XML
14.5.1. XML file “Sample.xml” used in following samples
14.5.3. XSD file “Sample.xsd” used in following samples
14.5.4. Load and read XML from URL
14.5.5. Load and read XML from file
14.5.6. Load and read XML from memory-stored data
14.5.7. Handle whitespaces in XML
14.5.8. Read specific attribute in XML
14.5.9. Step over attributes in XML
14.5.10. Write string data to XML file
14.5.11. Write characters to XML file
14.5.12. Write comments to XML file
14.5.13. Write processing instructions to XML file
14.5.14. Write attributes to XML file
14.5.15. What is it a XML namespace?
14.5.16. Write namespace to XML file
14.5.17. Write namespace with prefix to XML file
14.5.18. Set format options when writing to XML file
14.5.19. Set a single quote as formatting option for XML file
14.6. Document Object Model (DOM)
14.6.1. What is a XML document?
14.6.2. Open XML document from URL
14.6.3. Open XML document from file
14.6.4. Open XML document with memory-stored data
14.6.5. Insert nodes into XML document
14.6.6. Finding nodes by their names
14.6.7. XPath classes in .NET 1.1
14.6.8. Quering XML using XPath
14.6.9. Sum attribute values using XPath expression
14.6.12. Validate XML against XSD (Schema)
14.6.13. Validate XML against DTD
14.7. Extensible Stylesheet Language for Transformation (XSLT)
15.1.1. Local computer environment properties.
15.1.2. Creating shortcut in special folders (Desktop, StartMenu, Startup)
15.1.3. Determine actual system power status
15.1.4. Enumerate installed printers on local machine
15.1.5. Set default printer on local machine
15.1.6. Enumerate network drives
15.1.7. Integration with Windows (Help, Shotdown, Suspend, Control Panels)
15.1.8. Open Control Panel items
15.1.9. Get folder items using Windows folder dialog
16.1.1. Get string resource from dll library
16.1.2. Handle events from other applications.
16.1.4. Beep in application in Whidbey
16.1.5. Programming access to attributes
16.1.6. Get full-path & name of current process
16.1.7. Programmatically create virtual website in IIS
16.1.8. Get topmost window title using Win32 API
17.1.1. Connecting to SQL Server, Oracle, MySQL and others
17.1.2. Watching connection state events and messages
17.1.3. Executing SQL command and reading data in SqlDataReader
17.1.4. Executing stored procedure and reading data in SqlDataReader
17.1.5. Executing multiple SQL statements (batch)
17.1.6. Executing stored procedure and reading data from multiple result sets in SqlDataReader
17.1.7. Executing stored procedure and getting data in DataSet
17.1.8. Updating database data with changes in DataSet
17.1.9. Accessing Excel data using ADO.NET
17.1.10. List available SQL servers
18. ADO.NET & System.Xml 2.0 (Whidbey)
18.1. Summary of new features in ADO.NET 2.0.
18.1.1. Asynchronous Data Access
18.1.4. MARS (Multiple Active Results Sets)
18.2. Summary of new features in System.Xml
19. Appendix A - Fast-track to C# language
19.1. Basic terms and definitions in .NET & C#.
19.4.1. Locating of assemblies
19.6.9. Implicit conversions of numeric values.
19.7.1. Types of variables & parameters
19.8.2. Overflow check operators
19.12. Exceptions & exception handling
19.12.3. Monitoring of exception performance