- Code Access Security (CAS) may be used by .NET applications to put restriction on code regarding certain actions.
- An Application is called partially trusted when some kind of CAS is applied on it, others are called fully trusted.
- Evidence is something that proves as an identity and describes an individual as deserving a certain level of trust.
- Permissions determine which applications are trusted to what extent.
- There are 19 pre-defined Permissions in NET 2.0 (pertaining to different areas such as Web Access, Registry Access, File IO Access, etc.)
- Permission Sets combine a set of Permissions to represent particular level of security e.g. FullTrust, Internet, LocalIntranet, etc.
- Applications are brought under CAS using Code Groups which define a set of Permissions (and their respective settings/levels).
- Each Code Group requires an Evidence object. The assemblies that provide a particular Evidence become eligible to Permissions defined by the code group.
- Code Groups may be nested within one another and therefore may require more than one Evidence. (e.g My_Computer_Zone is a Code Group that requires a Zone:My Computer type of Evidence and grants FullTrust Permissions to assemblies bearing that Evidence.)
- Nesting one code group into another would result in a Union Code Group with all the Permissions set by both of them.
- There are four configurable Security Policies (Unions of Code Groups) built-in for .NET applications; Enterprise, Machine, User and Application Domain.
- However, if an Assembly falls under more than one Security Policy, the CLR uses the most restrictive one.
Tuesday, July 28, 2009
Chapter 11-Lesson 1
Labels:
AppDomain,
CAS,
Code Groups,
Evidence,
Full Trust,
Partial Trust,
Permissions
Sunday, July 26, 2009
Chapter 10-Lesson 4
- System.Management provides tools to check system resources using WMI (Windows Management Instrumentation)
- ManagementObjectSearcher class is used to apply queries onto a system and retrieve useful information.
- This object uses ManagementScope to determine the system name and Login information, and ObjectQuery to determine the SQL-like query to be used.
- The Get( ) method invokes the query on the scope object and returns a ManaementObjectCollection.
- Usually the query is of the form like Select * from Win32_LogicalDisk or Select * from Win32_Service WHERE Started = FALSE
- ManagementEventWatcher class may be used to track and respond to events in the WMI context. (refer to Lab for specific example)
Chapter 10-Lesson 3
- An isolated task performed by Operating System is called a Process.
- An application may be using 1 or more processes.
- 32-bit processors can allocate a maximum of 4GB memory.
- Within the memory, a Virtual Memory Manager keeps setting in the form of 4KB memory pages (chunks) that it assigns to processes as and when required.
- Process class in System.Diagnostics namespace is used to handle processes through .NET
- GetProcessById( ) static method takes ID of a process as argument and throws an ArgumentException if one is not found.
- Performace for applications running on Windows can be measured using PerformanceCounter class, since it uses Registry to store values retrieved from code.
- CounterCreationData may be used to specify Name, Type and other information related to a PerformanceCounter.
- PerformanceCounterCategory class is used to manage and manipulate PerformanceCounter objects.
- The Start( ) method of the Process class may be used to invoke an outside process.
- If we use the overload of Start( ) method that takes Username and Password, then the UseShellExecute property must be set to false.
- ProcessStartInfo object may also be passed to Start( ) method to specify process name and any Command-line arguments.
- The StackTrace object represents the CLR Stack trace for a given application.
- StackTrace is composed of StackFrames which represent individual method calls.
Chapter 10-Lesson 2
- Debug and Debugger classes are used to programatically control the debugging of code.
- .NET Runtime considers these classes only when program is built in Debug mode.
- Debugger.Log( ) static method logs a given message to a target. For that, we need to confirgure the Listeners collection of the Trace object. (overloads define the target which could be a File, Output Window, etc)
- Debugger class provides only two useful methods, namely Break( ) and Log( )
- To have more control over debugging, we may use Debug class.
- Debug.Assert( ) evaluates a given condition and if it is false breaks into the debugger and displays a given message.
- The following methods send messages to the output window with difference only in either formatting or in use of conditions: Write( ), WriteLine( ), WriteIf( ), WriteLineIf( ).
- The Print( ) method, however, sends message only to any attached Trace Listeners.
- DebuggerBrowsable attribute over any member of class would determine its visibility in the Debug window whenever a breakpoint is set. (It is supported only in C#.NET)
- DebuggerDisplay attribute determines how particular members of a class will be shown when an object is displayed in the Debug window. This method is used to decorate a class.
- DebuggerHidden attribute tells the debgger to ignore the lines of code that it decorates.
- DebuggerStepThrough attribute tells the debugger to Step Over the code it decorates. (This will save time for code that we are sure won't cause problems)
- DebuggerVisualizer attribute is new in .NET 2.0
- Trace class is implemented both in Debug and Release builds.
- DefaultTraceListener is attached to the output window.
- TextWriterTraceListener can redirect trace messages to a text file or Stream. (which is mentioned in the constructor)
- XmlWriterTraceListener directs Trace or Debug information to a TextWriter or Stream object. However, the file will contain XML as ouput rather than plain text as in the above listener. (XML indeed contains more information than plain text)
- XmlWriterTraceListener is new in .NET 2.0. If no filename is specified in constructor, CLR uses a GUID to create a filename.
- EventLogTraceListener directs messages to an EventLog specified in the constructor.
- DelimitedListTraceListener works the same as the above two but can use a delimiter to seperate entries.
- All of the above listeners may be configured either by using code or the configuration file.
Labels:
Breakpoints,
Debug,
Debug.Assert( ),
Debugger,
Debugging,
Instrumentation,
Listeners,
Trace
Chapter 10-Lesson 1
- Event Log is available in Windows 2000 and above.
- Event Logs should be avoided in partial trust environments.
- System.Disgnostics nampespace is required to use objects such as EventLog.
- WriteEntry( ) method of the EventLog class is used to actually create an entry.
- The Entries property of the EventLog class is a collection containing objects of type EventLogEntries.
- We may use any of the existing logs or we may choose to create our own by specifying its name in the EventLog constructor.
Tuesday, July 21, 2009
Chapter 9-Lesson 2
- Installer class allows for creation of Setup files to help deploy our Assemblies.
- Adding a class to the project that inherits from Installer class and overriding Install( ), Commit( ), Rollback( ) and Uninstall( ) methods will make an Application installable. Additionally we add a RunInstaller Attribute and set it to true.
- To initiate an Installer programmatically, we use AssemblyInstaller or ComponentInstaller classes.
Chapter 9-Lesson 1
- To put Application settings without using Windows Registry or database, we use configuration files in .NET
- System.Configuration namespace is required to use classes that serve to read/write configuration information for .NET applications.
- ConfigurationManager class provides properties and methods that return Configuration objects related to a particular Assembly.
- CodeBase section of the configuration file tells the CLR which .NET Framework version to use.
- ConfigurationSettings class is obsolete in .NET 2.0. Instead use ConfigurationManager.AppSettings
- ConfigurationManager.AppSettings is a NameValueCollection containing strings
- ConnectionString settings can be accessed as ConnectionStringSettingsCollection. It is exposed as ConfigurationManager.ConnetionStrings property.
- It is better to use WebConfigurationManager in ASP.NET applications rather than ConfigurationManager.
- We may create settings file by hand or we may add a SettingsFile to our project in order to visually create settings.
- Configuration Settings are case-sensitive and white-space sensitive.
- System.Runtime.Remoting section may be used to define settings for remote applications.
Saturday, July 18, 2009
Chapter 8-Lesson 3
- Windows Services are processes that run in their own user-session without any UI.
- Windows Services inherit from ServicesBase class.
- The Main( ) method in a service contains code to call Run( ) method responsible for starting/executing the service.
- The OnStart( ) method method should NOT stick into an infinte loop not should it get blocked. If we wish to create polling mechanism, use System.Timers.Timer object.
- To override OnPause( ), OnContinue( ) and OnShutDown( ) methods, first set ServiceBase.CanPauseAndContinue or ServiceBase.CanShutdown to true.
- Remember to always set the ServiceName property in the property pane.
- System.ServiceProcess.ServiceController class is required to interact with a service from .NET Assembly.
- To install the service, we need ServiceInstaller and ServiceProcessInstaller objects (automatically created in Visual Studio when we right click Service Design View and choose Add Installer)
- LocalService is the least previliged Account and LocalSystem is the most previliged Account property for ServiceProcessInstaller.
- While creating MSI installer for Service, add Project Output from Service Project as Primary Output and then add a Custom Action. (refer to page 462-463)
- To record Exceptions for a Service use EventLog.
Labels:
Custom Action,
Project Output,
ServiceInstaller,
Services,
Timer,
Windows Services
Chapter 8-Lesson 2
- In-depth security means we are able to prevent damage caused due to a vulnerability in a (third-party) Assembly that we are not aware of, cannot prevent and cannot fix.
- We may run Assemblies within an AppDomain with certain previliges by specifying an Evidence object to the Assembly. An Evidence is an object that behaves as an ID card displaying role/status of an entity. The authorities may then use this object to determine what kind of previliges an object (an Assembly in this case) recieves.
- The Evidence object takes an object array in its constructor. We may store anything in that array or we may use any of the predefined enumerations to define a specific type of previlige-level. The Evidence object will then be passed when ExecuteAssembly( ) method is run on an AppDomain.
- We may also pass such an Evidence object to CreateDomain( ) method to limit previliges for the entire AppDomain.
- Certain properties of an AppDomain are configurable via the AppDomainSetup class, which may be passed along with the Evidence object while creating new AppDomains.
Chapter 8-Lesson 1
- Operating System manages processes, while .NET Runtime manages Application Domains.
- If we consider an Assembly as class, then its instances could be called Application Domains.
- If an Application uses more than one assembly, it is possible to create a seperate process for each of them. The problem would be the performance hit ad resource usage caused between context shifts from one process to another. Therefore it is better to use one Assembly that acts as a host for other Assemblies. Then we may share resources (data) among Assemblies within an Application Domain. (e.g. ASP.NET Application object is an Application Domain)
- Points-to-Ponder: (See page 439)
- AppDomain class allows for creating Application Domains within .NET
- AppDomain.CreateDomain( ) static method is used to create a new Application Domain with a friendly name, and RunAssembly( ) instance-level method is used to load an Assembly within a domain.
Wednesday, July 15, 2009
Chapter 7-Lesson 3
- Asynchronous Programming Model allows us increase performance of our application by running certain piece of code onto a seperate thread while the main thread is blocked for some reason.
- .NET supports APM by supplying BeginXXX and EndXXX methods built-in to various library classes. (e.g. BeginRead( ) and EndRead( ) methods in Stream class)
- Rendezvous Models allow for three styles of using APM, Wait-Until-Done, Polling and Callback.
- Use null while calling an APM supportive method for Callback and state arguments to use Wait-Until-Done. If we use this, EndXXX will block current thread until Asynchronous call is completed.
- The Completed property of the IAsyncResult object returned by the BeginXXX method may be used to check (poll) whether the Asynchronous work has been completed. If not, we may keep on working on current thread.
- If BeginXXX is called by one method and EndXXX needs to be called by another method, we would need Callback Model.
- Callback model allows us to specify a method (using AsyncCallback delegate) in the BeginXXX method. This method would be called in order to complete the Asynchronous call (EndXXX).
- We may optionally supply an object (as a state object) that might be needed to call EndXXX. (Refer to page 417)
- If an Exception occurs during Asynchronous method calls, it is thrown when EndXXX is called. Reason: Since it occurred on the other thread, we cannot catch it on the main thread.
- However, in Windows Forms Applications, the Application object is notified whenever an exception occurs (either on main thread and worker threads). Therefore, we can attach a method to Application.ThreadException to handle an exceptional situation.
- Creating threads on our own is not recommended. Instead use ThreadPool class to create/reuse threads for our methods. (Don't buy threads, lease 'em)
- ThreadPool has a number of available slots to be used as threads. These slots are maintained by ThreadPool class and it keeps processor busy by continuously assigning to it slots that have pending work in them. These reusable slots may be called pre-built threads.
- We make a request to acquire a slot (whenever one becomes available) by calling ThreadPool.QueueUserWorkItem( ) static method and pass it a WaitCallback delegate representing the name of the method we wish to run as thread.
- If the Application uses a large number of Threads through ThreadPool, Threads may start to starve. In such a situation we may set the SetMaxThreads property of ThreadPool class to incease number of pre-built threads (slots).
- If faster Startup time is required, we may set the minimum number of threads in ThreadPool using SetMinThreads property.
- Typically ThreadPool class limits minimum number of threads in the pool to be 2 per second.
Labels:
APM,
Asynchronous,
Blocked,
Polling,
Rendezvous,
Starvation,
ThreadPool
Tuesday, July 14, 2009
Chapter 7-Lesson 2
- There are three operations usually involved with arithmetic operations on variables, i.e. Load Variable value into Register, Change value in Register, Write Back the new value to variable.
- In threaded code, all the above steps/operations are treated as atomic operations.
- Therefore, it might happen that two threads read/load the same variable into the register, change its value equally and write it back, all at the same time. (Valid in multi-core or multi-processor scenario)
- Interlocked class may be used to accertain that a certain variable is accessed by only one thread in a multi-threaded application.
- Interlocked class has static methods which can be used when performing arithmetic operations on variables.
- However, interlocked class has some limitations. It cannot be used for a wide variety of types and cannot be used to make pieces of code thread-safe. (Refer to Page 392)
- To declare a piece of code as thread-safe, use lock keyword to create thread-safe block. Lock keyword requires and object reference passed to it (usually this).
- This creation of lock block is called Synchronization Locks.
- Synchronization Locks may also be created using Monitor class static methods.
- To avoid deadlocks, we may use Monitor.TryEnter( ) method. Otherwise use Timeout.Infinite static property to tell the thread to wait as long as it takes.
- If we wish to deal (synchronize) reading and writing operations seperately, we may use ReaderWriterLock class to lock certain data only for reading or writing.
- LockCookie type object would be required to downgrade a WriterLock to a ReaderLock. (This implies that a WriterLock is downgradable only if it was previously upgraded from a ReaderLock)
- Three OS kernel level objects are represented in .NET by classes named Mutex, Semaphore, AutoResetEvent and ManualResetEvent. All of these derive from WaitHandle class.
- Mutex is almost same as Monitor class with the fact that it allows synchronization across AppDomain and process boundaries.
Labels:
Interlocking,
Lock,
Synchronization,
Thread,
Thread Safety
Chapter 7-Lesson 1
- Thread class is used to create and start a thread.
- ManagedThreadId property may not be the same as operating system thread ID.
- Abort( ) methods actually raises the ThreadAbortException to kill the thread.
- Resume( ) and Suspend( ) methods have been deprecated.
- In order to notify the thread host about the critical region of a thread, use static methods BeginCriticalRegion( ) and EndCriticalRegion( ) of Thread class. Use these methods inside a method that would be used as a thread.
- The static Sleep( ) method blocks the current thread for a certain amount of time during which other threads may run.
- SpinWait( ) does the same but does not allow other thread to run during that time.
- Join( ) method of Thread class asks the host thread to wait until the child/worker thread has finished executing.
- ParameterizedThreadStart delegate is used to represent threads that require parameters/arguments for calling.
- Page 383*
Friday, July 10, 2009
Chapter 6-Lesson 3
- Font class along with Graphics.DrawString( ) method may be used to draw text on forms, Bitmaps and Images.
- StringAlignment.Near actually aligns text to Left.
- Font class has 13 constructor overloads.
- LineAlignment flag determines vertical alignment of text.
Thursday, July 9, 2009
Chapter 6-Lesson 2
- Image is an abstract class.
- Image class uses static methods to create objects to/from image files.
- Bitmap class inherits from Image class and is used for still images.
- MetaFile class also inherits from Image class and is used for Animated images.
- Graphics class is still more complex than Bitmap class. We can always use Graphics.FromImage( ) method to represent a Bitmap as a Graphics object and use Graphics methods over it.
- To save images to a file, use Bitmap.Save( ) method.
- ImageFormat enum specifies supported image formats (BMP, GIF, JPEG, TIFF, etc) for saving images.
- SystemIcons class exposes standard windows icons (of size 40 x 40) as properties.
Sunday, July 5, 2009
Chapter 6-Lesson 1
- Brush is an abstract class. Brushes is a sealed class.
- ColorConverter and ColorTranslator are used to convert colour value from one format to another.
- Graphics is a sealed class.
- Pen (and related) classes are used to draw shapes and Brush (and related classes) are used to fill regions with colours.
- All classes suffixed with Converter are accessed through TypeDescriptor.
- Color, Rectangle, Point and Size are structures and not classes.
- Color names in Color structure are actually properties inside the structure.
- DrawString( ) method of the Graphics class may be used to draw a string using a specified Brush and Font objects.
- By default Pen class draws solid lines
- Usually System.Drawing.Drawing2D namespace is required for Graphics programming.
- LineCap enumeration defines possible values to set edges of a line.
- Draw methods usuallu require a Pen type object and Fill methods usually require a Brush type object.
- Brush is an abstract class. Use one the childrens instead.
Subscribe to:
Posts (Atom)