.NET

in

Samples

 

Jan Šeda

jan.seda@skilldrive.com


1.  Foreword

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.


2.  Terms of Use

© 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

1.      Foreword. 2

2.      Terms of Use. 3

3.      Windows Security. 12

3.1. Basic terms. 12

3.1.1. Principal 12

3.1.2. Authority. 12

3.1.3. Authentication. 12

3.1.4. Authorization. 12

3.1.5. Trust 13

3.1.6. Logon Session. 14

3.1.7. Token. 15

3.1.8. Get SID for current identity. 17

3.1.9. Get object name for SID.. 19

3.2. Protecting system resources. 21

3.2.1. Test yourself on security & protection of system resources. 21

3.2.2. Rules behind propagation of rights on objects. 22

3.2.3. Get ACLs/ACEs for a file. 23

3.2.4. Set DACL for a file. 24

4.      Security Ratings. 25

4.1.1. What is a Common Criteria?. 26

4.1.2. Why is Common Criteria important?. 26

5.      Security Concepts in .NET environment 26

5.1. Basic layout of .NET Framework – Security parts. 26

5.2. Assembly. 27

5.2.1. Runtime security policy. 28

5.2.2. Types of security context for assemblies. 31

5.2.3. Generate key pair with sn.exe tool 32

5.2.4. Give an assembly a strong name. 32

5.2.5. Delayed signing of assembly. 32

5.2.6. List of permissions in policy levels. 33

5.2.7. List of permissions assign to current assembly. 34

5.2.8. Get permission list for a custom evidence. 35

5.2.9. List of declarative permissions of assembly. 36

5.2.10. Output assembly evidence list to XML file. 36

5.2.11. List policy levels and code groups where current assembly belongs. 37

5.3. Type safety, metadata and code verification. 38

5.3.1. Get info about types in assembly. 40

5.4. Application domains. 42

5.4.1. Application domain boundaries and objects. 42

5.4.2. Create application domain programmatically. 44

5.4.3. Shadow copy enabled for application domain. 45

5.5. Security tools available in .NET.. 45

5.6. Code Access Security. 47

5.6.1. Stack-walk. 47

5.6.2. Limit access permissions for a method. 49

5.6.3. Add new code group to runtime security. 50

5.7. Role-based Security. 51

5.7.1. Identity classes (also Whidbey) 51

5.7.2. Principal policy. 51

5.7.3. Principal classes. 54

5.7.4. Using GenericPrincipal class. 54

5.7.5. Get list of groups for current thread’s identity. 55

5.7.6. Get current user name. 56

5.7.7. Impersonate as another user 56

5.7.8. Declarative principal permissions for Windows roles. 58

5.7.9. Declarative principal permissions for custom roles. 59

5.7.10. List running processes and user accounts. 59

6.      Cryptography & Security. 61

6.1. Buffer Overrun. 61

6.1.1. CodeRed Worm, Buffer Overrun attack. 62

6.1.2. SQLSlammer 63

6.2. Algorithms for Encryption. 63

6.2.1. Well Known Algorithms for Symmetric Encryption. 63

6.2.2. Well Known Algorithms for Asymmetric Encryption. 63

6.2.3. Well Known Hash Algorithms. 64

6.3. Digital Certificates. 64

6.4. Secure Communication Standards. 64

6.4.1. IPSec (Internet Protocol Security) 64

6.4.2. Kerberos. 64

6.4.3. SSL (Secure Socket Layer) 64

7.      Cryptography. 68

7.1. Basic terms in cryptography. 68

7.2. A little bit of history. 69

7.2.1. Caesar cipher 69

7.2.2. Progress in cryptography. 71

7.3. PKCS. 72

7.4. CMV (Cryptographic Module validation) 73

7.4.1. Microsoft FIPS 140 certification. 74

7.4.2. .NET classes and FIPS 140. 74

7.5. Cryptography in .NET.. 74

7.6. Configuring .NET cryptography. 75

7.7. Win32 Security API and .NET.. 75

7.8. Random number generators. 76

7.8.1. Generating random values. 76

7.8.2. Generating random nonzero values. 76

7.8.3. Random number generator and other CSPs (Cryptographic Service Provider) 76

7.9. Hashing algorithms. 77

7.10. Symmetric encryption. 78

7.10.1. Block ciphers. 79

7.10.2. Stream ciphers. 79

7.10.3. Key distribution problem.. 80

7.10.4. Data Encryption Standard (DES) 80

7.10.5. Blowfish. 86

7.10.6. Twofish. 86

7.10.7. MARS. 86

7.10.8. Rijndael 87

7.10.9. Ronald Rivest’s (RC) ciphers. 87

7.10.10. Hash value using MD5 and SHA.. 87

7.10.11. Collision in MD5 algorithm.. 88

7.10.12. Classes for symmetric algorithms in .NET.. 90

7.10.13. Deriving symmetric keys from passwords. 90

7.10.14. Creating symmetric encryption classes. 91

7.10.15. Symmetric encryption/decryption of plaintext using DES. 92

7.10.16. Symmetric encryption/decryption of plaintext using RC2. 93

7.10.17. Symmetric encryption/decryption of plaintext using Rijndael 93

7.10.18. Determining weak and semi-weak keys in DES. 94

7.10.19. Deriving symmetric key from password using PBKDF1. 95

7.10.20. Deriving symmetric key & IV from a password using PBKDF1. 95

7.10.21. Deriving symmetric key from a password using PBKDF2. 96

7.10.22. Check valid key size for symmetric encryption. 96

7.10.23. Hybrid usage of symmetric and asymmetric encryption. 97

7.10.24. Hashing of plaintext and encryption/decryption using DES. 98

7.10.25. Keyed hash algorithm HMACSHA1. 99

7.10.26. Keyed hash algorithm MACTripleDES. 100

7.11. Asymmetric encryption. 100

7.11.1. Certificates & Certification authorities. 100

7.12. Assymetric encryption. 101

7.12.1. Classes for asymmetric algorithms in .NET.. 102

7.12.2. Storing public and private RSA keys in XML file. 102

7.12.3. Storing keys by CSP (Crypto Service Provider) 102

7.12.4. Encryption of plaintext using RSA with XML-stored key. 103

7.12.5. Encryption/decryption of plaintext using RSA.. 103

7.12.6. Encryption/decryption of plaintext using RSA with XML-stored key. 104

7.12.7. Encryption of plaintext using RSAParameters. 105

7.12.8. Encryption/Decryption of plaintext by RSA.. 106

7.12.9. Encryption with public key (exception) 106

7.12.10. How to encrypt/decrypt large data using RSA?. 107

7.12.11. Calling RSA/DSA from a Web service, ASP or COM+. 107

7.13. Digital signatures. 108

7.13.1. Sign and verify data with RSA I 108

7.13.2. Sign and verify data with RSA II 110

7.13.3. Sign and verify data with RSA using SignatureFormatter 110

7.13.4. Sign and verify data with DSA.. 111

7.14. Key exchange methods and classes. 112

7.14.1. Exchange symmetric key between two clients using OAEP. 112

7.15. Certificates. 114

7.15.1. Create X509Certificate from file generated by makecert.exe. 114

7.15.2. Create X.509 certificate from base64 encoded certificates. 114

7.15.3. Source library with CryptoAPI certificate mappings. 115

7.15.4. List of installed client’s certificates. 115

7.15.5. List of installed intermediate certification authorities. 116

7.15.6. List of installed root certificate authorities. 116

7.16. Data Protection API 116

7.17. Basic principles of DPAPI 118

7.17.1. User’s profile. 120

7.17.2. Source library with DPAPI methods. 121

7.17.3. Use DPAPI to encipher application data into file. 127

7.17.4. Use DPAPI to decipher application data from file. 127

7.17.5. DPAPI used to encrypt data in file in isolated storage. 128

7.17.6. DPAPI used to decrypt data from file in isolated storage. 129

7.17.7. Encrypt/Decrypt database connection string using DPAPI 130

7.17.8. Issues with user’s store and web services and COM+. 131

7.17.9. Managed DPAPI 131

7.18. XML Signatures. 132

7.18.1. Sign XML. 132

7.19. Isolated storage. 132

7.19.1. Storeadm.exe – administration of isolated storage in .NET.. 134

7.19.2. Opening of isolated storages for current user and domain. 135

7.19.3. Store data in file in isolated storage. 136

8.      Network Operations. 137

8.1.1. Retrieve DNS computer name. 137

8.1.2. Retrieve NetBIOS computer name. 137

8.1.3. Obtain IP address and host 137

8.1.4. Send email in .NET environment 137

8.1.5. Getting online stock information. 138

8.1.6. Retrieve email from POP3 mail server 139

9.      File operations. 140

9.1. General IO operations. 140

9.1.1. Get executing application’s path with reflection. 140

9.1.2. Get executing application’s path. 140

9.1.3. Classes working with file and directory information. 141

9.1.4. Change file & folder attributes. 141

9.1.5. Recursive list of directories/subdirectories & files. 142

9.2. Reading and writing from/to files. 142

9.2.1. BufferedStream.. 143

9.2.2. Read from file using BufferedStream.. 143

9.2.3. Read text from file. 144

9.2.4. Write text to file. 144

9.2.5. Create file and write to it 144

9.2.6. Append text to file. 145

9.2.7. Read from binary file. 145

9.2.8. Write to binary file. 146

9.2.9. Watch file system for changes. 146

10.        Text Manipulation & Internationalization. 147

10.1. String operations. 147

10.1.1. Append string. 147

10.1.2. Inserting/Removing string. 148

10.1.3. Replace string. 148

10.1.4. Reverse string. 148

10.1.5. Reverse string using recursion. 149

10.2. Formatting numbers. 149

10.2.1. Table with number formatting options. 149

10.2.2. Formatting of numeric values to currency. 150

10.2.3. Formatting of numeric values to currency with NumberFormatInfo. 150

10.2.4. Formatting of floating point values to a scientific notation (exponential) 151

10.2.5. Formatting of floating point values to specific number of decimals (fixed-point) 151

10.2.6. Formatting of numeric value to local culture specific number 151

10.2.7. Formatting of floating point value to roundtrip (can be converted back to number) 151

10.2.8. Formatting of an integer value to a hexadecimal number 152

10.2.9. Formatting floating point values to a percentage. 152

10.2.10. Formatting floating point values to a percentage with limited number of decimals. 152

10.2.11. Formatting of floating point values to a percentage with NumberFormatInfo. 152

10.3. Formatting date and time. 153

10.3.1. Table with date&time formatting options. 153

10.3.2. Formatting DateTime to the short date&time pattern (dddd, MMMM dd, yyyy, hh:mm) 154

10.3.3. Formatting DateTime to the full date&time pattern (dddd, MMMM dd, yyyy hh:mm:ss) 154

10.3.4. Formating DateTime to the short date numerical pattern (M/d/yyyy) 154

10.3.5. Formatting DateTime to the full date numerical pattern (dddd, MMMM dd, yyyy) 154

10.3.6. Formatting DateTime to the short date&time numerical pattern (M/d/yyyy hh:mm) 154

10.3.7. Formatting DateTime to the full date&time numerical pattern (M/d/yyyy hh:mm:ss) 155

10.3.8. Formatting DateTime to the month name pattern (MMMM dd) 155

10.3.9. Formatting DateTime to the short date pattern (MMMM, yyyy) 155

10.3.10. Formatting DateTime to the long time pattern (hh:mm:ss) 155

10.3.11. Formatting DateTime to the short time pattern (hh:mm) 155

10.3.12. Formatting DateTime to the RFC1123 pattern (ddd, dd MMM yyyy HH':'mm':'ss 'GMT') 156

10.3.13. Formatting DateTime to sortable pattern. 156

10.3.14. Formatting DateTime to universal sortable pattern (yyyy'-'MM'-'dd HH':'mm':'ss'Z') 156

10.3.15. Formatting DateTime to full date&time using universal time. 156

10.3.16. Formatting DateTime to custom format using DateTimeFormatInfo. 156

10.4. Custom number formatting. 157

10.4.1. Formatting of number to specific number of decimals. 158

10.4.2. Formatting of number with adding zeros. 158

10.4.3. Formatting of number to custom positive, negative and zero sections. 158

10.4.4. Formatting of number using custom CultureInfo and custom format 159

10.5. Formatting strings. 159

10.5.1. Simple string formatting with number parameter 159

10.6. Conversions. 160

10.6.1. Class Convert (many convertion methods) 160

10.6.2. Convert string to integer 160

10.6.3. Convert string to double. 160

10.6.4. Convert string to double using CultureInfo. 161

10.6.5. Convert string to date. 161

10.6.6. Use regular expression to find and replace string inside of string. 161

10.6.7. Converting string to DateTime using CultureInfo. 162

10.6.8. Convert time_t to DateTime. 163

10.6.9. Convert time_t to DateTime (shorter code) 163

10.6.10. Convert base64 encoded number to float 163

10.6.11. Convert file1/encoding1 into file2/encoding2. 164

10.7. Internationalization. 165

10.7.1. American Standard Code for Information Interchange (ASCII) 165

10.7.2. ISO 10646 & Universal Character Set 166

10.7.3. Unicode. 166

10.7.4. Class CultureInfo. 167

11.        Collections. 169

11.1.1. ArrayList 169

11.1.2. BitArray. 169

11.1.3. HashTable. 170

11.1.4. Queue. 170

11.1.5. SortedList 171

11.1.6. Stack. 171

12.        Time Operations. 172

12.1.1. Time measuring (TickCount and Ticks property) 172

12.1.2. Accurate time measuring. 172

13.        Windows Management Instrumentation (WMI) 173

13.1. CIM Schema. 174

13.2. WMI Architecture. 175

13.3. WMI tools. 175

13.3.1. WMI Object Browser 175

13.3.2. WMI CIM Studio. 176

13.3.3. WMI Event Registration Tool 177

13.3.4. WMI Event Viewer 177

13.4. WMI plug-in for Visual Studio .NET 2003. 177

13.5. List of WMI Classes. 178

13.5.1. Working with WMI on remote machine. 178

13.5.2. Get computer info (domain, model etc.) 179

13.5.3. Get computer info (vendor, UUID, type) 179

13.5.4. Get data about operating system.. 180

13.5.5. Logoff, shutdown, reboot computer 184

13.5.6. Get user’s desktop info. 186

13.5.7. Determine computer type (workstation, server, controller etc.) 187

13.5.8. Determine physical computer features. 187

13.5.9. Rename computer name. 190

13.5.10. Get processor info. 191

13.5.11. Get memory info. 199

13.5.12. Getting list of file shares on local machine. 200

13.5.13. Get logical disk info. 200

13.5.14. Get environment variables. 201

13.5.15. Get CD-ROM/DVD information. 201

13.5.16. Get boot configuration. 204

13.5.17. Find a service by its name. 205

13.5.18. Get list of running/stopped services. 205

13.5.19. Getting partition info. 206

13.5.20. Get list of user’s account from local machine/domain. 207

13.5.21. Get list of user groups from local machine/domain. 209

13.5.22. Get list of installed codec files. 210

13.6. Watching for event 211

13.6.1. Watching for newly started processes. 211

14.        XML.. 213

14.1. What is SGML?. 213

14.2. What is XML?. 213

14.3. What is XHTML?. 213

14.4. Forward-only reading and writing XML. 214

14.5. XmlTextReader 215

14.5.1. XML file “Sample.xml” used in following samples. 215

14.5.2. What is a XML schema?. 216

14.5.3. XSD file “Sample.xsd” used in following samples. 216

14.5.4. Load and read XML from URL. 217

14.5.5. Load and read XML from file. 217

14.5.6. Load and read XML from memory-stored data. 218

14.5.7. Handle whitespaces in XML. 218

14.5.8. Read specific attribute in XML. 219

14.5.9. Step over attributes in XML. 219

14.5.10. Write string data to XML file. 220

14.5.11. Write characters to XML file. 220

14.5.12. Write comments to XML file. 221

14.5.13. Write processing instructions to XML file. 221

14.5.14. Write attributes to XML file. 221

14.5.15. What is it a XML namespace?. 222

14.5.16. Write namespace to XML file. 222

14.5.17. Write namespace with prefix to XML file. 223

14.5.18. Set format options when writing to XML file. 223

14.5.19. Set a single quote as formatting option for XML file. 224

14.6. Document Object Model (DOM) 224

14.6.1. What is a XML document?. 224

14.6.2. Open XML document from URL. 224

14.6.3. Open XML document from file. 225

14.6.4. Open XML document with memory-stored data. 225

14.6.5. Insert nodes into XML document 225

14.6.6. Finding nodes by their names. 226

14.6.7. XPath classes in .NET 1.1. 227

14.6.8. Quering XML using XPath. 227

14.6.9. Sum attribute values using XPath expression. 228

14.6.10. List of XPath axes. 228

14.6.11. What is DTD?. 229

14.6.12. Validate XML against XSD (Schema) 229

14.6.13. Validate XML against DTD.. 230

14.7. Extensible Stylesheet Language for Transformation (XSLT) 231

14.8. XML Encryption. 231

15.        Computer environment 231

15.1.1. Local computer environment properties. 231

15.1.2. Creating shortcut in special folders (Desktop, StartMenu, Startup) 232

15.1.3. Determine actual system power status. 233

15.1.4. Enumerate installed printers on local machine. 235

15.1.5. Set default printer on local machine. 235

15.1.6. Enumerate network drives. 235

15.1.7. Integration with Windows (Help, Shotdown, Suspend, Control Panels) 236

15.1.8. Open Control Panel items. 237

15.1.9. Get folder items using Windows folder dialog. 238

16.        Other features. 238

16.1.1. Get string resource from dll library. 238

16.1.2. Handle events from other applications. 240

16.1.3. Beep in application. 240

16.1.4. Beep in application in Whidbey. 241

16.1.5. Programming access to attributes. 241

16.1.6. Get full-path & name of current process. 242

16.1.7. Programmatically create virtual website in IIS. 242

16.1.8. Get topmost window title using Win32 API 242

17.        ADO.NET.. 243

17.1. Architecture of ADO.NET.. 243

17.1.1. Connecting to SQL Server, Oracle, MySQL and others. 246

17.1.2. Watching connection state events and messages. 247

17.1.3. Executing SQL command and reading data in SqlDataReader 248

17.1.4. Executing stored procedure and reading data in SqlDataReader 249

17.1.5. Executing multiple SQL statements (batch) 249

17.1.6. Executing stored procedure and reading data from multiple result sets in SqlDataReader 250

17.1.7. Executing stored procedure and getting data in DataSet 251

17.1.8. Updating database data with changes in DataSet 253

17.1.9. Accessing Excel data using ADO.NET.. 254

17.1.10. List available SQL servers. 254

18.        ADO.NET & System.Xml 2.0 (Whidbey) 255

18.1. Summary of new features in ADO.NET 2.0. 255

18.1.1. Asynchronous Data Access. 255

18.1.2. Batch Updates. 255

18.1.3. DataSet Performance. 255

18.1.4. MARS (Multiple Active Results Sets) 255

18.2. Summary of new features in System.Xml 255

19.        Appendix A - Fast-track to C# language. 256

19.1. Basic terms and definitions in .NET & C#. 256

19.2. What is C#?. 257

19.3. Hello world. 257

19.4. Assemblies. 258

19.4.1. Locating of assemblies. 258

19.4.2. Assembly layout 258

19.5. Identifiers. 258

19.6. Types. 259

19.6.1. Hierarchy of types. 259

19.6.2. Predefined types. 260

19.6.3. Integral types. 260

19.6.4. Floating-point types. 262

19.6.5. Decimal type. 262

19.6.6. Bool type. 262

19.6.7. Object type. 262

19.6.8. String type. 263

19.6.9. Implicit conversions of numeric values. 263

19.6.10. Boxing and unboxing. 263

19.7. Variables & parameters. 264

19.7.1. Types of variables & parameters. 264

19.7.2. Default values. 266

19.7.3. Enum.. 267

19.7.4. Struct 267

19.8. Expressions & Operators. 269

19.8.1. Operators. 269

19.8.2. Overflow check operators. 270

19.8.3. Operator typeof 270

19.8.4. Operator is. 271

19.8.5. Operator overloading. 271

19.9. Preprocesor 272

19.10. Statements. 274

19.11. C# namespaces. 277

19.12. Exceptions & exception handling. 279

19.12.1. Throwing exceptions. 280

19.12.2. Exception classes. 280

19.12.3. Monitoring of exception performance. 281

19.12.4. Checked & unchecked exceptions. 282

19.13. Delegates and events. 283</