- Floating Topic
-
11%
- Ch7:
- Ch8:
-
11%
- Ch3
- Ch6
- Ch16
-
11%
- Ch13:
- Ch14:
- Ch15:
-
18%
-
Ch2: I/O
-
DriveInfo
- GetDrives()
-
Props
- AvailableFreeSpace Indicates the amount of available free space on a drive
- DriveFormat Gets the name of the file system, such as NTFS or FAT32
- DriveType Gets the drive type
- IsReady Indicates whether a drive is ready
- Name Gets the name of a drive
- RootDirectory Gets the root directory of a drive
- TotalFreeSpace Gets the total amount of free space available on a drive
- TotalSize Gets the total size of storage space on a drive
- VolumeLabel Gets or sets the volume label of a drive
-
Directory static class;DirectoryInfo class
- GetDirectories()
- GetFiles()
- Create()
-
File static class; FileInfo Class
- Create(str)
- CreateText(str)
- Copy(str, str)
- Move(str,str)
- Delete(str)
-
FileSystemWatcher
- updated files
- new files
- renamed files
- other updates to the file system
-
proccess
- fw=New FileSystemWatcher(filepath)
- fsw.IncludeSubdirectories = True
- fsw.NotifyFilter = NotifyFilters.FileName Or NotifyFilters.LastWrite
- AddHandler fsw.Changed, AddressOf fsw_Changed
- fsw.EnableRaisingEvents = True
-
FileSystem/RenamedEventArgs
- the path to the updated file
- the type of change
- Changed, Created, and Deleted events
-
Props
- Filter
- NotifyFilter
- FileName
- DirectoryName
- Attributes
- Size
- LastWrite
- LastAccess
- CreationTime
- Security
- Path
-
Streams
-
TextReader/Writer, StreamReader/Writer & TextFile
- File.Open/CreateText(filePath) as textReader
- New StreamReader(filePath)
- ReadLine, ReadToEnd
-
BinaryWriter/Reader & FileStream
- fs=New FileStream(filepath, FileMode.Create/Read)
- New BinaryWriter/Reader(fs)
-
StringWriter/Reader & StringBuilder
- New StringWriter(sb)
- New StringReader(sb.ToString())
- using if you have a specific reason to
use streams instead of accessing the strings directly
-
MemoryStream & StreamWriter
- Write/Read(byte()); Write/ReadByte(byte);
- New StreamWriter(ms)
-
BufferedStream & CustomStream
- FileStream has the same logic
- Write/Read(byte()); Write/ReadByte(byte);
- can be used with StreamWriter
-
GZipStream/DeflateStream
- Use StreamReader/Writer to deal with srings
- gz=New GZipStream(fileStream,
CompressionMode.Compress/Decompress))
- New StreamWriter/Reader(gz)
- Close() - close and save
- Flush() - save without close
- StreamReader/Writer for text; Binary Reader/Writer for bytes
-
System.IO.IsolatedStorage
-
IsolatedStorageFile
- access the individual stores,
- GetUserStoreForAssembly()
- GetUserStoreForDomain()
- GetStore(scope,appidentity,evidence)
-
IsolatedStorageFileStream
- individual files within a store
- IsolatedStorageException
-
IsolatedStorageScope enum
- User
- Machine
- App Domain
- Application
- Assembly
-
Proccess
- isoStore=IsolatedStorageFile.GetUserStoreForAssembly()
- New IsolatedStorageFileStream("myfile.txt",FileMode.Create,isoStore)
- not protected from highly trusted code,
unmanaged code, or trusted users of the computer.
- should not be used to store high-value secrets
- requires fewer privileges
- IsolatedStorageFilePermission must be granted to the code
-
Ch5: Serialization
-
Objects
-
Serializing
- the process of converting an object into
a linear sequence of bytes that can be stored or transferred
-
Deserializing
- the process of converting a previously serialized
sequence of bytes into an object
-
BinaryFormatter
- Serialize(stream,object)
- Deserialize(stream) as Object
- backward reference
- forward reference
-
<Serializable()>
- default handling of the serialization, no other code besides
the Serializable attribute is necessary.
- the runtime serializes all members, including private members.
- <NonSerialized()>
- temporary or calculated values to minimize storage
- IDeserializationCallback.OnDeserialization
- implement this interface on the serialisabel class
- <OptionalField()>
- if the member was not serialized, the runtime leaves the member’s value as
null rather than throwing an exception.
-
Version Compatibility
- Never remove a serialized field.
- Never apply the NonSerialized attribute to a field if the attribute was not applied
to the field in a previous version.
- Never change the name or type of a serialized field.
- When adding a new serialized field, apply the OptionalField attribute.
- When removing a NonSerialized attribute from a field that was not serializable in
a previous version, apply the OptionalField attribute.
- For all optional fields, set meaningful defaults using the serialization callbacks
unless 0 or null are acceptable defaults.
-
SecurityPermission with the SerializationFormatter flag
- not given to Internet-downloaded or intranet code
-
IRemotingFormatter
- BinaryFormatter
- writing objects to the disk to be read later
- SoapFormatter
- more likely to successfully
traverse firewalls
- SoapAttribute
- SoapDefaultValue
- SoapElement
- SoapEnum
- SoapIgnore
- SoapType
-
Guidelines
- mark a class as Serializable
- Mark calculated or temporary members as NonSerialized
- Use SoapFormatter when you require portability
- Use BinaryFormatter for greatest efficiency
-
Xml
- serialize only public class and members
- a parameterless constructor.
- cannot serialize object graphs
- do not have to have the Serializable attribute
- New XmlSerializer(Type)
-
Attributes
- XmlAttribute()
- XmlIgnore()
- XmlRoot(Str)
-
IXmlSerializable
- ReadXml, WriteXml to control XmlReader/Writer
- complete control over XML serialization
- separate data into bytes instead of buffering
large data sets,
- avoid the inflation that occurs when the data is encoded
using Base64 encoding
-
XML schema file *.xsd
- Xsd.exe
- produce a set of classes that are strongly typed
to the schema and annotated with attributes
- alternative to using XmlReader and XmlWriter classes,
to parse and write an XML stream
- xsd C:\schema\library.xsd /classes /language:VB
- DataSet, Arrays, Collections and XmlElement or XmlNode classes can be serialized
-
Custom
-
ISerializable
- GetObjectData(SerializationInfo,StreamingContext)
- if not implemented compiler warns
- SerializationFormatter
- Sub New(SerializationInfo,StreamingContext)
- if not implemented serialization exception.
- perform data validation in serialization constructor and
throw a SerializationException if invalid data is provided
- SerializationInfo(IFormatterConverter)
- AddValue(name,value)
- add the variables to be serialized as name/value pairs
- SerializationEntry
- to store the information
- IFormatterConverter
- FormatterConverter
- Binary/SoapFormatter
- Normal constructor is not accessable
- Serializable attribute
-
serialization events for BinaryFormatter
- Events/Attributes
- <OnSerializing()> _
- <OnSerialized()> _
- IDeserializationCallback,
OnDeserialization
- <OnDeserializing()> _
- <OnDeserialized()> _
- Events Signature
- Accept a StreamingContext
- Return void
- Have the attribute that matches the event
- <OnSerializing()> _
Private Sub CalculateTotal(StreamingContext)
- same serialization event to multiple methods
- apply multiple events to a single method
-
StreamingContext
- Context prop
- should be assigned before serializtion or deserialization
- State prop
- CrossProcess
- CrossMachine
- File
- Persistence
- Remoting
- Other
- Clone
- CrossAppDomain
- All
- serialize and deserialize an object differently
depending on the destination
- if the object is going to be deserialized by the same process
- can provide information about the destination of a serialized
object object to classes that implements ISerializable
-
IFormatter
- Binary/SoapFormatter
- FormatterServices
- http://msdn.microsoft.com/en-us
/magazine/cc163902.aspx
- http://msdn.microsoft.com/en-us/library
/cc301761.aspx
- http://geekswithblogs.net/luskan
/archive/2007/07/16/113956.aspx
-
Use Case
- the value of a member variable is invalid after deserialization
but you need to provide the variable with a value to reconstruct the full
state of the object
- has declarative or imperative security at
the class level or on its constructors
- serilized objects can be stored/transferred and then later re-created
-
14%
-
Ch9:Installing&Config apps
-
.NET App Configuration
-
Machine.config
- allowDefinition=
- MachineOnly
- MachineToApplication
- App.Config
-
Defining Config Settings
- ConfigurationManager.OpenExeConfiguration()
as Configuration
- Configuration.Add(Name,Value)
- Configuration.Save(ConfigurationSaveMode.Modified)
-
Read Config Settings
- ConfigurationManager.AppSettings as
NameValueCollection
- ConfigurationManager.ConnectionStrings as
ConnectionStringSettingsCollection
- Name
- ProviderName
- ConnectionString
-
Read Custom Section
- ConfigurationManager.OpenMachineConfiguration
as Configuration
- obj = Configuration.GetSection(SectionName)
as Object
- cast to <Custom>ConfigurationSection
- access props of <Custom>ConfigurationSection
- Each configuration section has a unique class
- obj.ElementInformation.Type.ToString
-
Creating Custom Sections
- IConfigurationSectionHandler
- New Sub()
- Create(parentObj, configContextObj, sectionXmlNode) As Object
- Inherit ConfigurationSection
- use attributes to configure default values,
validators, and other requirements for properties
- allows you to declare properties that the CLR
automatically populates based on the data in the .config file
- <ConfigurationProperty(PropName)> _
- Topic
- Topic
- Topic
- Topic
-
Ch10:Instrumentation
-
Topic
- Topic
- Topic
-
Topic
-
Topic
- Topic
- Topic
-
- Topic
- Topic
- Topic
-
15%
-
Ch1:Framework Fundamentals
- Value types <=16 bytes
- Nullable is a structure
- TypeForwardedTo
- Events
- EventHandler is a predefined delegate
- EventHandler - generic class
- Widening/implicit & Narrowing/explicit conversions
- Implement System.IConvertible
- Implement a TypeConverter class
- Boxing-Value to Ref
-
Ch4: Collections
- Hashtable constructor - IEqualityComparer
- StringComparer.InvariantCulture implements IEqualityComparer
- SortedList constructor - IComparer
- HybridDictionary=ListDictionary+Hashtable
- SortedList is sorted
- OrderedDictionary is not sorted
- BitVector32 and BitPacking to store int32
- CollectionUtil factory will create case insesitive Hashtable and SortedLilst
- NameValueCollection stores comma separated multiple values per key
-
20%
-
Ch11:App Security
-
Code access security (CAS) - .Net system
- CAS -managed app, partially trusted; RBS-unmanaged app, fully trusted
- Evidence -> Code Groups (Zone) -> Permission Set (ACL)
-
Evidence
- host evidence -assembly’s origin; assembly evidence -developer provided
- Types
- location-directory or site or url
- hash of code
- publisher’s signature
- strong name-namespace
- zone -code group
-
Permissions
- Directory Services - Active Directory settings
- Web requests;
- DNS requests;
- File Dialog
- Message queues
- Performance counters
- Reflection
- Security - Enabel Assembly Execution, run unmanaged code, control threads
- Service Conroller -win services
- Socket Access - TCP/IP control
- SQL Client
- User Interface
- User Interface - create new windows, clipboard
- X509 Store - certificate store
- I/O
-
Access control list (ACL) is Permission Set
- FullTrust
- SkipVerification
- Everything
- LocalIntranet - wide ACL
- Internet -restricted ACL
- Execution
- Nothing
-
Code Group is part of Evidence
- My_Computer_Zone
- LocalIntranet_Zone
- Internet_Zone
- Restricted_Zone
- Trusted_Zone
-
Security Policy
- Enterprise
- Machine
- User
- Application Domain
-
.NET Framework Configuration tool
Code Access Security Policy tool (Caspol.exe)
- Evaluating an assembly to determine which code groups it is a member of
- Evaluating an assembly to determine which permissions it will be assigned
- Adding new permission sets
- Adding new code groups
- increasing an assembly’s trust
- Adjusting zone security
- Resetting policy levels
- PermissionState.None/PermissionState.Unrestricted
-
CAS Assembly Declarations
-
SecurityAction.RequestMinimum
- To avoid unxpected exceptions
- System.Security.Policy.PolicyException
-
SecurityAction.RequestOptional
- Refuses all permissions not listed in a
SecurityAction.RequestOptional/SecurityAction.RequestMinimum
- exception will be thrown while accesing (ie READING) the file
-
SecurityAction.RequestRefuse
- No Exception
- The principle of least privilege.
-
Properties
- Action
- Unrestricted
- Permission attribute classes
inherited CodeAccessSecurityAttribute
- DataProtectionPermission
- GacIdentityPermission
- KeyContainerPermission
- StorePermission
- AspNetHostingPermission
- IUnrestrictedPermission
- PrincipalPermission
-
CAS Method Imperative/Declarative
-
Permission.Assert
- Ignore the fact that callers might not have the specified permission
- SecurityPermissionFlag.Assertion assebly setting
- when you want to allow partially trusted code
to call a method that requires permissions the caller might lack. Review your
code carefully for potential security vulnerabilities;
- enable a method to vouch for all callers
- Can be used only ONCE in a method
- to assert multiple permissions, you need to create a custom permission set
-
Permission.Demand
- Throw an exception if the caller and all callers higher in the stack
lack the specified permission.
- assembly implements customized
functionality that does not rely on functionality built into the .NET
Framework, such as calls to unmanaged code.
- Avoid redundant demands
Most .NET classes automatically demands permissions like StreamWriter
-
Permission.LinkDemand
- throw an exception if the immediate caller,
but not callers higher in the stack, lack the specified permission
-
Permission.InheritanceDemand
- throw an exception if the assembly
inheriting from the class lacks the specified permission
-
Permission.Deny
- further refine the permissions available to each method
-
Permission.PermitOnly
- reduce the method’s access by removing all
permissions except for the specified permission
- limit the permissions available toeach method.
List every permission the method requires.
-
CodeAccessPermission.RevertAll/Assert/PermitOnly/Deny
- imperatively reduce permissions when a section of a method requires
fewer permissions than the rest of the method. This is particularly important
when calling objects created by third parties.
-
Imperative vs Declarative
- declarative security demands are less secure than imperative
- declarative demands are faster than imperative demands
- Declarative - compiler performs security checks prior to running code
- Imperative-code itself performs security checks
- imperative demands is that you can catch
the security exception within your method
- Declarative security criteria must be static, imperative - dynamic
- System.Security.SecurityManager.IsGranted
- PermitOnly - error-handling routines
-
SecurityPermissionFlag.Assertion assebly setting
- The FullTrust, LocalIntranet, and Everything permission sets
-
AllowPartiallyTrustedCallersAttribute
- To prevent partially trusted code from bypassing security checks, partially trusted
code can’t call strong-named assemblies by default.
- Access control list (ACL) is Permission Set
-
Ch12: User&Data Security
-
Role-based security (RBS)
-
WindowsIdentity
- Get Anonymous
- Get Current
- Impersonate
- AuthenticationType
- IsAnonymous
- IsAuthenticated
- IsGuest
- IsSystem
- Name
- Token
-
WindowsPrincipal
- Init thru constructor
- New WindowsPrincipal(WindowsIdentity.GetCurrent())
- Init thru CurrentThread
- AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
Dim currentPrincipal As WindowsPrincipal=CType(Thread.CurrentPrincipal, WindowsPrincipal)
- IsInRole()
- accepts WindowsBuiltInRole class
- accepts string like “DOMAIN\Group Name”
-
PrincipalPermission Class/Attribute
- Authenticated
- Name
- Role
- PrincipalPermission.Demand
-
Declarative RBS demands
- Cons
- restrict access to entire methods
- the runtime throwing an exception.
- Elements
- CurrentDomain.SetPrincipalPolicy
- Try/Catch block
- PrincipalPermission attribute
- PrincipalPermission
- System.Security.Permissions.SecurityAction.Demand
- Name/Role/Authenticated
- Multiple declarative demands
-
Imerative RBS demands
- Elements
- CurrentDomain.SetPrincipalPolicy
- Try/Catch block
- PrincipalPermission class instance
- PrincipalPermission.Demand
- PrincipalPermission constructors
-
Custom Users&Roles
- IIdentity
- AuthenticationType
- IsAuthenticated
- Name
- Constructor that defines the props
- IPrincipal
- New( IIdentity, String())
- IsInRole(String) As Boolean
- Identity() as IIdentity
- Roles;IsInAll/AnyRole;IsHigher/LowerThanRole
- GenericIdentity/Principals
- Name;Name,AuthenticationType
- GenericIdentity,Strings()
- props are assigned only thru constructor
- Thread.CurrentPrincipal=IPrincipal object
-
NegotiateStream/SslStream
- AuthenticationException
- InvalidCredentialException
- File System; Registry; Printers;Event Logs; System.Security.Principal
- This applies for usernames and roles stored
either in local user database,
or within an Active Directory domain
-
Access Control List (ACL)
-
Discretionary Access Control Lists (DACL)
- access control entries (ACEs)
- Explicit/Inherited Permissions
- each new folder you create
in the root C:\ folder inherits
the exact permissions assigned to the C:\ folder
- assign a DACL directly to an object,
you create an explicit permission
- Calculates Effective Permissions
- The maximum granted access permission applied
- explicitly denied access in higher priority
- no explicit access means deny by default
- FileSystemRights enum
- Full Control
- Delete
- Read & Execute
- RegistryRights enum
- Full Control
- Delete
- Query Values
- AccessControlType enum
-
Security Access Control List (SACL)
- Enable Audit Object Access security policy
- Open the Local Security Policy console from within Administrative Tools.
- Expand Local Policies and click Audit Policy.
- In the right pane, double-click Audit Object Access. Select Failure to enable failure
auditing, and select Success to enable success auditing.
-
System.Security.AccessControl
- <Type>Security
- GetAccessRules
- collection of DACLs
- GetAuditRules
- Add/RemoveAccessRule ,
Add/RemoveAuditRule
- <Type>AccessRule
- set of access rights allowed or
denied for a user or group.
- <Type>AuditRule
- set of access rights to be audited
for a user or group
- AuthorizationRuleCollection of
<Type>AccessRule / <Type>AuditRule
- for files, folders, registry keys, cryptographic
keys, Event Wait handles, mutexes, and semaphores.
- <Type>.GetAccessControl
- <Type>.SetAccessControl
- files, folders, registry keys, cryptographic
keys, Event Wait handles, mutexes, and semaphores.
-
Ecrypting/Decrypting
-
Symmetric key encryption
- Classes
- TripleDES
- RijndaelManaged- AES
- recommended to use
- RC2
- replace DES
- Data Encryption Standard - DES
- Props
- BlockSize,FeedbackSize,KeySize
- IV -initialization vector
- both the encryptor and decryptor
must specify the same value
- statically define
- or derive from the Key property
- Key
- can be automatically generated
- can be derived from string(login+password)
- LegalBlockSizes
- LegalKeySizes
- Mode
- Padding
- Methods
- CreateDecryptor/Encryptor
- CryptoStream object
- CryptoStreamMode.Write/Read
- GenerateIV/Key
- ValidKeySize
- Rfc2898DeriveBytes(pswd,salt)
- PasswordDeriveBytes
- requres pswd,salt, iv, number of iterations
used to generate the key
- GetBytes(myAlg.KeySize / 8)
- GetBytes(myAlg.BlockSize / 8)
- Key/BlockSize returns bits
but GetBytes needs length in bytes
- Process
- Create a Stream objects
- Create a SymmetricAlgorithm object
- Specify the algorithm’s key, the IV, or both
- Call SymmetricAlgorithm.CreateEncryptor/Decryptor()
- Create a CryptoStream
- Read from/ write to the CryptoStream
- // Read the unencrypted file into fileData
byte[] fileData = new byte[inFile.Length];
inFile.Read(fileData, 0, (int)inFile.Length);
- Key, IV, Mode - should be the same on Encryptor and Decryptor
-
Asymmetric encryption
- Based on private key - to decrypt and Public key to encrypt
- Used to synchronise private key of symmetric encryption - SSL & HTTPS
- A public key infrastructure PKI is an infrastructure for distributing,
managing, and revoking certificates in an organization
- Keys are big and doen't suit for bug amount of data
- Classes
- RSACryptoServiceProvider
- DSACryptoServiceProvider
- Props
- KeyExchangeAlgorithm
- KeySize,LegalKeySizes
- SignatureAlgorithm
- PersistKeyInCsp
- UseMachineKeyStore
- Methods
- Decrypt/Encrypt
- ExportParameters(boolean)
- returns RSAParameters structure
- To/FromXmlString
- ImportParameters(RSAParameters)
- SignData(byte()/stream,object) As Byte()
- SignHash(byte(),str) As Byte()
- VerifyData/Hash
- RSAParameters structure
- D
- Exponent - e
- Modulus - n
- Export your private key only if you need to reuse it later.
application must protect the privacy of the private key.
- Store Key Pairs for Later Reuse
- New CspParameters()
- CspParameters.KeyContainerName=str
- new RSACryptoServiceProvider(persistantCsp)
- RSACryptoServiceProvider.PersistKeyInCsp=true
- .NET Framework handles creating and retrieving keys automatically
- RSACryptoServiceProvider.Encrypt/Decrypt(byte[],bool)
- Dim messageString As String = "Hello, World!"
Dim myRsa As RSACryptoServiceProvider = New RSACryptoServiceProvider
- Dim messageBytes As Byte() = Encoding.Unicode.GetBytes(messageString)
Dim encryptedMessage As Byte() = myRsa.Encrypt(messageBytes, False)
- Dim decryptedBytes As Byte() = myRsa.Decrypt(encryptedMessage, False)
Console.WriteLine(Encoding.Unicode.GetString(decryptedBytes))
-
Data Hashes
- verify that a file has not been modified
- enable passwords to be verified without storing the password itself
- HashAlgorithm
- MD5CryptoServiceProvider
- The Message Digest algorithm
- RIPEMD160Managed
- SHA1CryptoServiceProvider
- SHA256/384/512Managed
- KeyedHashAlgorithm
- HMACSHA1
- Hash-based Message Authentication Code using SHA1
- MACTripleDES
- Message Authentication Code using TripleDES
- protect against modification of the hash by encrypting
- Process NonKey
- myHash=New MD5CryptoServiceProvider()
- myHash.ComputeHash(byte())
- myHash.Hash as byte()
- Process with Key
- key = New Rfc2898DeriveBytes(str, byte())
- secretKey = key.GetBytes(16)
- myHash=New HMACSHA1(secretKey)
- myHash.ComputeHash(byte())
-
Data Signing
- DSA/RSACryptoServiceProvider
- SignHash/SignData VerifyHash/VerifyData
- Signing
- signer=New DSACryptoServiceProvider()
- signer.SignData(byte())
- publicKey = signer.ToXmlString(False)
- Verifying
- verifier = new DSACryptoServiceProvider()
- verifier.FromXmlString(publicKey)
- verifier.VerifyData(byte(), signature)
- authenticate the identity of a sender
- the strongest defaults available to the run-time environment