Chapter: 7

Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application

CurrencyManager

The CurrencyManager class has the ability to keep track of the current position of data within an array, collection or table that is to be bound to a user interface.

WindowsPrincipal

The WindowsPrincipal class allows a user code to check the group membership of a current Windows user. The IsInRole() method of the WindowsPrincipal class is used to manage the role-based security.

Format pattern

The u format pattern represents the UniversalSortableDateTimePattern using the format for universal time display. The U format pattern represents the Full date and time (long date and long time) using universal time.

Parse

Use one of the overloaded Parse methods of the DateTime Structure to convert a string into its equivalent date and time. Use the InvariantCulture of the CultureInfo class to get the CultureInfo that is culture-independent (invariant).

NeutralCultures

NeutralCultures are associated with a language but are not specific to a country/region.

AllowInnerWhite

The AllowInnerWhite member of the DateTimeStyles enumeration is used to ignore the extra white-space characters in the middle of any string during parsing.

Number

The Number member of NumberStyles is used to indicate that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles are used.

AllowThousands

The AllowThousands member of the NumberStyles enumeration is used to indicate that the numeric string can have group separators, for example, separating the hundreds from the thousands.

DigitShapes

The DigitShapes enumeration is used to specify the culture-specific display of digits.

Solar calendar

A solar calendar is a calendar whose dates indicate the position of the earth on its revolution around the sun.

Format pattern

Use the “dddd” format pattern to represent a full name of a day of the week as defined in the current DateTimeFormatInfo.DayNames property.

MonthNames property

Use the “MMMM” format specifier to represent the full name of the month as defined in the current DateTimeFormatInfo.MonthNames property.

Standard format strings

The four standard format strings are as follows:

  • O (or o)
  • R (or r)
  • s
  • u
CultureInfo

The CultureInfo class is used to represent information about a specific culture including the language, the writing system, the calendar used, etc.

InvariantCulture

The InvariantCulture property of the CultureInfo class is culture-independent and is not associated with any specific country or region.

CurrencyPositivePattern

Develops an application for users who live in Australia and format pattern for positive currency values by implementing CurrencyPositivePattern property of the NumberFormatInfo class.

RegionInfo

Gather regional information about customers in a particular country by implementing RegionInfo class.

Culture attribute

The culture attribute of the globalization section is used to specify the default culture for processing incoming requests from an application.

ResourceManager

The ResourceManager class provides access to culture-specific resources at runtime. It looks up culture-specific resources, provides resource fallback when a localized resource does not exist, and supports resource serialization.

CurrentCulture property

Use the System.Threading.Thread.CurrentThread.CurrentCulture property to enable specific users to use the application.

SmallCaptionFont

The SmallCaptionFont property is used to get a font that is used to display text in the title bars of small windows such as tool window.

FontFamily and Font

Use the FontFamily and Font classes to constructs a regular style Arial font with a size of 18 pixels.

Graphics object

To create a Graphics object, you can perform any of the following actions:

  • Receive a reference to a Graphics object as a part of the PaintEventArgs of a control.
  • Call the CreateGraphics method of a control to obtain a reference to a Graphics object.
Graphics object

Create a Graphics object from any object that inherits from the Image class.

Antialiasing

Use the antialiasing with the graphics in an application by using the HighQuality and AntiAlias properties.

Dash property

Use the DashStyle.Dash property to specify a line consisting of dashes.

AccessibleName property

Make application accessible to low vision users by using the AccessibleName property to the accessibility aids (accessibility aids are specialized programs and devices, such as the Braille bar that help the users with disabilities to use computers more effectively).

Rich Text Format

Use the license agreement to store contents in the Rich Text Format (RFT) file and add the file to a setup project and also enhance user interface using the license agreement policy.

Bitmap class

The Bitmap class can be used to change the color of an image.

PaintEventArgs class

Implementing PaintEventArgs class and draw a line on a pictureBox control using the DrawLine() method.

Brushes class

The Brushes class contains static properties that allow a user to get a Brush object of different colors.

Color class

Use the Color class and display a given text with specified brush color on a window.

Icon

The Icon class contains nine constructors.

LineJoin

The LineJoin enumeration is used to specify how to join consecutive lines or curve segments.

FillRectangles

The FillRectangles method of the SolidBrush class is used to fill the interior of a rectangle.

Display statistical date

Display statistical date in graphical format and use a custom graphing control that does not support resizing and ensure that users cannot resize, minimize, or maximize Form.

MinimumSize

The MinimumSize property of the Form class is used to get or set the minimum size up to which a form can be resized. The Size property of the Form class is used to get or set the size of a form.

Character escape

The \u0020 character escape is used to match a Unicode character using hexadecimal numbers.

Wildcard character

The * wildcard character is used to match the preceding character or sub expression zero or more times. For example, “te*” matches “te” and “test”. The “*” character is equivalent to “{0,}”.

Wildcard character

The . wildcard character is used to match any single character except “\n”. To match any character including the “\n”, use a pattern such as “[\s\S]“.

Character

The \G character is used to specify that the match must occur at the point where the previous match ended.

StringBuilder

Create a StringBuilder object and initialize it with a given string and set capacity to 75. Use the AppendFormat method of the StringBuilder class to append a formatted string at the end of the StringBuilder object.

Traditional

The Traditional member of the StringDigitSubstitute enumeration is used to specify substitution digits that correspond with the user’s native script or language.

Regular expressions

Regular expressions are the most effective way to verify the format of the data that matches a phone number.

Carrot

The carrot (^) character is used to specify that the match must begin at either the first character of a string or the last character of a line.

Character

The \b character is used to specify that the match must occur on a boundary between \w (alphanumeric) and \W (nonalphanumeric) characters.

Unicode

The UTF8Encoding, UnicodeEncoding, and UTF32Encoding classes are better suited for global applications. The ASCIIEncoding class supports only the Unicode character values between U+0000 and U+007F.

AppendLine

The AppendLine method is used to append the default line terminator or a specified string to the end of the StringBuilder object.

Match

The Match method is used to search an input string for an occurrence of a regular expression and it will return the results as a single Match object.

StringBuilder

The StringBuilder class represents dynamic or mutable strings of characters, it represents a string-like object whose value is changeable.

Graphics object

The four objects that can be used with a Graphics object are as follows:

  • Pen
  • Color
  • Brush
  • Font
Substring

The Substring() method of the String class retrieves substring from a given string.

Share
Tagged with:
 
Chapter: 6

Implementing interoperability, reflection, and mailing functionality in a .NET Framework application

Component Services tool

The Component Services tool creates, configures, and maintains a COM+ application. This tool can be used to view the system events, manage the system services and the distributed transactions. This tool performs the four tasks.

COM+ transaction attributes

The COM+ transaction attributes are as follows:

  • Required
  • RequiresNew
  • Disabled
  • Supported
  • Not Supported
Platform Invocation and COM Interop Service

Use the Platform Invocation Service and COM Interop Service to provide interoperability with the unmanaged code.

SingleCall object

In a SingleCall object, a new object is created whenever a message arrives. The new object then processes the message and returns an optional reply. Finally, the object created is discarded.

Regasm.exe

Assembly Registration (Regasm.exe) tool is used to read the metadata within an assembly. It also adds the necessary entries to the registry allowing a COM client to create .NET Framework classes. Once a class is registered using Regasm.exe, a COM client can use it as a COM component.

COM components

COM components can be used in applications by adding a reference to a type library.

Strong name

Strong name is a name consisting of an assembly’s identity, public key, and digital signature. It includes the assembly’s name, version number, and other related information (if any).

Tlbimp.exe tool

Use the Visual Studio 2005 IDE and Tlbimp.exe tool to import a COM type library to the Microsoft .NET Framework.

Assembly Registration Tool

Deploying an assembly on COM application to a client computer using the Assembly Registration Tool (Regasm.exe) and register the file on the client computer.

COM Type Libraries

Deploy a Client and a component to a single folder on multiple client computer by using COM Type Libraries.

Satellite assemblies

The assemblies that contain culture-neutral resources are referred to as satellite assemblies. These assemblies are used to deploy language-specific resources for an application.

Caspol.exe

Caspol.exe can be used to examine and modify Machine-level, User-level, and Enterprise-level code access security policies.

MarshalByRefObject

The MarshalByRefObject class allows access to objects across application domain boundaries in applications that support remoting.

Dumpbin.exe

The dumpbin.exe utility is a command-line tool used for viewing imports and exports. It allows users to view various details for a given unmanaged code.

Type Library Importer

The Type Library Importer (Tlbimp.exe) tool is used to convert the type definitions from a COM type library into equivalent definitions in a common language runtime assembly.

IsCallerInRole

The IsCallerInRole method of the ContextUtil class determines whether the client is having the specific role or not.

Web references

Web references refer to XML Web services that are published on either a local intranet or the Internet.

Regsvr32.exe

The Regsvr32.exe tool is used to register or un-register dynamic-link libraries (DLLs) and ActiveX controls (OCX) in the Windows Registry.

Sn.exe

The Strong Name (Sn.exe) tool is used to sign assemblies with strong names. It also provides signature generation, signature verification, and key management.

Codebase

The Common Language Runtime finds the assembly through the codebase setting. If no match is found in the location as specified in the codebase element in the application configuration file, the binding request fails. Then the CLR finds the assembly through probing.

Assembly manifest

The following are the different approaches on how the correct version of an assembly is specified in the assembly manifest:

  1. Include the AssemblyVersion() attribute in an application’s source code.
  2. Update the AssemblyVersion() attribute in the AssemblyInfo file of an application.
  3. Include the System.Reflection namespace in the project when the AssemblyVersion() attribute is included in the application’s source code.
Sn.exe

The Sn.exe tool is used to sign a portable executable file for a component or an assembly with an Authenticode digital signature.

Assembly class

Use a method in an application code and the method of the Assembly class to load and examine many assemblies having the same identity but located in different paths.

Email

Use the following classes to construct email messages:

  • Attachment
  • MailAddress
  • MailMessage
WebResponse

The WebResponse class derived from the System.Net namespace is used to provide a response from a Uniform Resource Identifier (URI).

WebRequest

The WebRequest class derived from the System.Net namespace is used to make a request to a Uniform Resource Identifier (URI).

MailAddress

The MailAddress class specifies the source and destination email address in two different objects.

Share
Tagged with:
 
Chapter: 5

Improving the security of the .NET Framework applications by using the .NET Framework 2.0 security features

Declarative security check

Declarative security check is a security check performed on the declarative information in metadata. It uses attributes to place security information into the metadata of application code.

Imperative security check

Imperative security check is a security check that occurs on calling a security method within the code being protected. It works by instantiating security classes and using them directly. It can be isolated within an object or method.

Utilities for verification

The utilities for the verification of the security policy for a deployed application are Caspol.exe, Preverify.exe, and Permview.exe.

PublisherPolicy

Deploy an application to the client computers on a company’s intranet. Later, modify the assembly, any application that uses version 1.0 must now use version 2.0 by using PublisherPolicy.

Permission request

Create an assembly that is consumed by other application and permission not granted to an assembly without minimum permission request.

Caspol.exe

Use the Code Access Security Policy tool (Caspol.exe) to enable users and administrators to modify the security policy for the machine policy level, the user policy level, and the enterprise policy level.

Digital certificate

The Digital certificate is used to verify the identity of a potential customer.

Standard Internet e-mail

Standard Internet e-mail is usually sent as plaintext over networks. This is not secure, as intruders can monitor mail servers and network traffic to obtain sensitive information.

IPSec

L2TP with IPSec needs a certificate authority server (CA server) to generate certificates as well as to check their validity for providing secure communication.

Biometrics

Biometrics is a method of authentication that uses physical characteristics, such as fingerprints, scars, retinal patterns, and other forms of biophysical qualities to identify a user.

Passport authentication provider

The Passport authentication provider is used for user authentication. It uses an encrypted mechanism to indicate authenticated users.

Permissions

Use the following permissions to obtain minimum permissions to execute an application properly:

  • Code Access Permissions
  • Identity Permissions
  • Role-Based Permissions
ApplicationAccessControl

The ApplicationAccessControl attribute allows access checking at the component level in order to support component, interface, or method level role checks. The scope of the ApplicationAccessControl attribute is assembly.

element

The username and password attributes are specified in the element of the Web.config file for every request on a page.

FullTrust permission

The FullTrust permission set provides the best performance to set the permission sets. Use the authentication methods, which are provided by Internet Information Services (IIS) in an application.

Custom authentication

Use the in the Web.config file to enable Custom authentication.

Single Sign-On

The Single Sign-On (SSO) is a system capability that enables users to access a number of applications without having to log on and/or provide a password to each application.

SecurityAction.RequestMinimum value

The SecurityAction.RequestMinimum value is used to request for the minimum permissions required for code to run.

SecurityAction enumeration

The SecurityAction enumeration is used to specify the security actions that can be performed using declarative security.

Declarative security

Declarative security check is a security check performed on the declarative information in metadata.

Packet Privacy authentication level

In the Packet Privacy authentication level, authentication and encryption of data are performed. This level includes data integrity and the identity and signature of a user.

Authentication element

The authentication element in the Web.config file is added to identify users to view an application.

SslStream.IsMutuallyAuthenticated

The SslStream.IsMutuallyAuthenticated property is used to get a boolean value that indicates whether both the server and client have been authenticated.

Cryptosystem

A Cryptosystem is a computer system that implements cryptography. It is used to secure email, digital signature, hash function, and key management.

TripleDESCryptoServiceProvider

The TripleDESCryptoServiceProvider class is used to encrypt data in a file as well as in the memory.

Optimal Asymmetric Encryption Padding

In cryptography, Optimal Asymmetric Encryption Padding (OAEP) is a padding scheme, which is often used with RSA encryption.

RijndaelManaged

The RijndaelManaged class, which is a symmetric cryptography is used to encrypt assembly data.

Cipher Block Chaining

CBC is the default mode for all encryption classes that uses Cipher Block Chaining (CBC) as the cipher mode.

HashAlgorithmType

The HashAlgorithmType enumeration is used to specify that the algorithm is used for generating Message Authentication Code (MAC) in Secure Sockets Layer (SSL) communications.

Certificate-based authentication

Certificate-based authentication is the most secure method of authentication. It provides a stronger key for encryption as compared to Digest authentication and sends encrypted passwords across the network. This prevents unauthorized users from intercepting passwords.

Secure Sockets Layer

Secure Sockets Layer (SSL) is a protocol developed by Netscape for transmitting private documents via the Internet. Secure Sockets Layer (SSL) uses a combination of public key and symmetric encryption to provide communication privacy, authentication, and message integrity.

IsSubSetOf method

The IsSubSetOf method of the PrincipalPermission class is used to determine whether or not the current permission object is a subset of the specified permission object.

PrincipalPermissionAttribute

The PrincipalPermissionAttribute attribute applies to a class or method in order to declaratively demand for those users who belong to a specified role or have been authenticated.

Union

The Union method of the PrincipalPermission class is used to create a permission object that is the union of the current permission object and a target parameter permission object.

PrincipalPermission

Use the PrincipalPermission class to imperatively demand that the current user is a member of the local Users group.

System.Environment.UserName property or System.Environment.GetEnvironmentVariable() method

Use either the System.Environment.UserName property or System.Environment.GetEnvironmentVariable() method to identify a username of a security context in which the current assembly is running.

PermitOnly method

The PermitOnly method of the FileIOPermission class is used to prevent callers higher in the call stack from using the code that calls a method to access resources that are not specified by the current instance.

Security policy levels

The security policy levels in hierarchical order are Enterprise policy, Machine policy, User policy, and Application domain policy.

Reset method

The Reset method of the PolicyLevel class is used to set the current policy level to the default state.

Publisher policy configuration file

A publisher policy configuration file contains compatibility information issued by the publisher of a shared component.

ZoneMembershipCondition

Use the ZoneMembershipCondition class to test whether or not an assembly was located on the intranet.

ApplicationDirectoryMembershipCondition

Use the ApplicationDirectoryMembershipCondition to test whether the assembly was located in a specific folder.

Generic role-based security

The generic role-based security is used to secure data from unauthorized users.

Role-based authorization

Role-based authorization uses the GenericPrincipal class to represent the roles of the current user.

Session object

The Session object is used to create a variable that will be available as long as the session is active.

Share
Tagged with:
 
Chapter: 4

Implementing serialization and input/output functionality in a .NET Framework application

Formatter class

The Formatter class is used to provide base functionality for the common language runtime serialization formatters.

Serialize

By default, a property or a field that returns an object or array of objects is automatically serialized.

SerializableAttribute

The SerializableAttribute attribute specifies whether or not a class can be serialized. The Marshal-by-value objects are remotable objects that implement the ISerializable interface.

Namespace property

The Namespace property of the DataSet class is used to specify the namespace of a DataSet object.

WriteXml method

The WriteXml method of the DataSet class is used to write XML schema and data from a DataSet object in XML format.

Load method

The Load method of the XmlDocument class is used to load the XML document in the memory stream.

ImportNode method

The ImportNode method of the XmlDocument class is used to import the node from another XML document.

SoapFormatter

SoapFormatter is a simple, modular, extensible, and XML-based protocol. It is used to exchange messages between remoting applications.

RPC-Based Body Formatting

RPC-Based Body Formatting is used to refer to the section 7 of the SOAP specification. In this formatting, all the parameters are contained within the single element in a SOAP message body.

BinaryFormatter and SoapFormatter class

The BinaryFormatter and SoapFormatter classes implement the IRemotingFormatter interface to support remote procedure calls (RPCs), and the IFormatter interface to support serialization of a graph of objects.

CDRom

CDRom is used to specify that a drive is an optical disc device, such as a CD or DVD-ROM. Removable is used to specify that a drive is a removable storage device, such as a floppy drive or a USB flash drive.

FileInfo class

The FileInfo class contains methods to create, delete, copy, and move files and properties related to a file.

FileStream, MemoryStream, and StreamReader classes

Use the FileStream, MemoryStream, and StreamReader classes to perform the following operations:

  • Read data from the byte stream
  • Read data from the memory stream
  • Read data from the file stream
FileStream class

The FileStream class is used to specify write, read, and other file-related operations either in synchronous or asynchronous manner.

NegotiateStream class

The NegotiateStream class of the System.Net.Security namespace is used to provide a stream that uses the Negotiate security protocol for a client authentication and use the SslStream class of the System.Net.Security namespace to provide a stream that uses the Secure Socket Layer (SSL) security protocol to authenticate the server and optionally a client.

Marshal class

Use the Marshal class to allocate unmanaged memory, copy unmanaged memory blocks, and convert from managed to unmanaged types.

StreamReader and StreamWriter classes

The StreamReader class is used to read characters from a byte stream. The StreamWriter class is used to write characters to a stream.

Path class

Use the Path class to get the file extension using the GetExtention() method and to change the file extension using the ChangeExtention() method.

Trace class

Implement the Trace class to log any errors thrown by an application and direct the Trace output to a local log file.

StreamReader class

The StreamReader class implements a TextReader that reads characters from a byte stream in a particular encoding. The System.IO.File.OpenText method creates a StreamReader that reads from an existing text file having the specified path.

GZipStream class

When you inherit from the GZipStream class, you must override the three properties: CanSeek, CanWrite, and CanRead.

Isolated storage

Use the following to perform the isolated storage tasks:

  • The IsolatedStorageFile class
  • The IsolatedStorageFileStream class
  • The IsolatedStorageScope enumeration
GZipStream class

The GZipStream class is used to provide methods and properties used to compress and decompress streams. It represents the GZip data format. This data format uses the same algorithm as the DeflateStream class, but can be extended to use other compression formats also.

Share
Tagged with:
 
Chapter: 3

Embedding configuration, diagnostic, management, and installation features into a .NET Framework application

ApplicationScopedSettingAttribute class

The ApplicationScopedSettingAttribute class is used to specify that an application settings property has a common value for all users of an application. It cannot be inherited.

ConfigurationManager class

The ConfigurationManager class is used to provide access to configuration files for client applications.

Building blocks of .NET Framework

There are three building blocks of .NET Framework, which are as follows:

  1. Common Language Runtime (CLR)
  2. Common Type System (CTS)
  3. Common Language Specification(CLS)
Process.Start

The Process.Start method is used to start a Windows application and is registered in the system registry on a computer.

Demand

The Demand method is used to decide at runtime whether all callers in the call stack have been granted the permission specified by a current permission object by implementing class library.

Application configuration file

An application configuration file is used to install it on a client computer along with an application and ensure that the settings in the application configuration file are applied.

Account property

The Account property is used to specify the security context of the Windows service application. In the Properties window of the Visual Studio .NET Component Designer, you can set the Account property to LocalService, LocalSystem, NetworkService, or User value.

Settings for services

Use the following properties to specify the individual settings for each service in a service database:

  • DisplayName
  • ServiceName
  • ServicesDependOn
  • StartType
Publisher policy configuration file

The Publisher policy configuration file contains compatibility information issued by the publisher of a shared component. It ensures that the latest version of the shared component is used by all applications using the component.

Gacutil.exe

The Global Assembly Cache (Gacutil.exe) tool is used to view and manipulate the contents of the global assembly cache. Microsoft Management Console (MMC) is a Windows utility designed to manage servers and services through a common user interface.

Publisher policy files

Publisher policy files contain compatibility information issued by the publisher of a shared component. These files ensure that the latest version of the shared component is used by all applications using the component.

TypeLoadException

The TypeLoadException exception is thrown when the common language runtime (CLR) is unable to find an assembly or the type within the assembly, or cannot load the type.

Sn.exe

The Strong Name (Sn.exe) tool is used to sign assemblies with strong names. It also provides signature generation, signature verification, and key management.

Binding policy

For deploying shared assemblies, the binding policy that is a set of rules determines the place to search for the assembly and version to bind to the application. The searching process of the CLR involves the following three stages of the binding policy resolution:

  1. Application policy resolution
  2. Publisher policy resolution
  3. Administrator policy resolution
Correct version of an assembly

The following are the steps that determine the correct version of an assembly:

  1. The CLR examines the application configuration file.
  2. It examines the publisher policy file.
  3. It examines the machine configuration file.
Dispose method

Use components that provide services and resources and release the resources explicitly by the components using the Dispose method.

EventLog.Source

The Source property of the EventLog class is used to specify the source name to register and use when writing to the event log.

CreateEventSource

The CreateEventSource method of the EventLog class establishes an application as a valid event source for writing event information to a particular event log on a computer.

Event log

Develop an application to log important information of the application while it is executing and to write message text to the event log.

Debug class

Perform an integration testing for an application and ensure that when the Write() method of the Debug class or the Trace class is called, each time only one entry is added to the event log.

SystemException

The SystemException class throws an exception when an error occurs in an application using the Common Language Runtime (CLR).

Process class

The Process class can be used to print a word document with the help of the Print attribute.

ProcessModule and the ProcessModuleCollection class

The ProcessModule and ProcessModuleCollection classes can be used to get the complete information about modules used in a given application.

Breakpoint

The Breakpoint is used to analyze variables, data records, and other settings in an application.

Data Breakpoint

The Data Breakpoint is used during the execution of an application to change the value of the variables defined in the application.

Cordbg.exe

The Runtime Debugger (Cordbg.exe) is a tool that provides command-line debugging services.

Locals window

The Locals window is a debugging window and its contents change to reflect only the variables applicable to the current procedure. Global variables and variables in other projects are not accessible from the Locals window.

Write method

The Write method of the Debug class displays messages and writes variable values to the Output window, when an application is either stopped or paused.

Immediate mode

The Immediate mode of the Command window is used for debugging .NET applications. This mode evaluates expressions, executes command statements, and prints values of variables defined in the application code.

Print method

The Print method of the Debug class can be used to display a message with a line terminator in the trace listeners collection.

Trace switch

Trace switch is an object that exists in the application code that allows filtering information. It allows enabling, disabling, and filtering of output in an application.

Output debugging window

The Output debugging window is used to display status messages at runtime. Its content is cleared each time the application is compiled or run.

Call Stack debugging window

The Call Stack debugging window displays a list of currently active procedure calls during break mode.

Client-activated .NET Remoting object

A client-activated .NET Remoting object is created to ensure that an object logs error and warning messages to a log file and Windows application log.

Watch window

The Watch window is used to see the values of variables within different scopes, i.e., module level, procedure level, and global variables.

Assert

The Assert method of the Trace class is used to check for a condition and displays a message if the condition is false.

Cordbg.exe

The Cordbg.exe tool is used to debug the application from a command prompt. It provides command-line debugging services. It also helps to find and fix bugs in programs that target the .NET Framework common language runtime.

Call Stack debugging window

The Call Stack debugging window is used for viewing the list of currently active procedure calls.

Log method

The Log method of the Debugger class writes tracing and debugging messages that are displayed in the output window of the IDE.

TraceSwitch class

Use the TraceSwitch class within a code and whenever the code uses Trace logging, it consults with the TraceSwitch level to verify whether or not to log information.

Query property

The Query property of the ManagementEventWatcher class is used to get or set the criteria to apply to events.

Management class

The Management class is used to represent a Common Information Model (CIM) management class. It is a WMI class such as Win32_LogicalDisk and Win32_Process.

AuthenticationLevel enumeration

Use the Unchanged member of the AuthenticationLevel enumeration to specify that the authentication level should remain the same as before.

base

The base keyword can be used when a subclass needs to refer to its immediate baseclass.

Share
Tagged with:
 
Chapter: 2

Implementing service processes, threading, and application domains in a .NET Framework application

Event log

Write an event to the event log to allow a service to interact with users. The service does not require a logged-in user in order to execute and run under the context of any user including the system.

Service

A service does not have a user interface or any visual output. Therefore, it can be easily run in the background to monitor an operating system without any user logging.

Installutil tool

The Installutil tool is used to install a Windows application. The .NET class library provides some predefined installer classes that helps in application installation.

ClickOnce technology

ClickOnce technology eliminates the difficulties in updating Windows-based applications, dependence of multiple application programs on shared components, and allowing permissions only to administrative users for application installations.

OnCustomCommand

If a class derives from the ServiceBase class, the OnCustomCommand method is executed when the Service Control Manager (SCM) passes a custom command to the service.

CanHandlePowerEvent property

When the CanHandlePowerEvent property is set to true, the power event command is passed to the service and then the OnPowerEvent method is called.

ThreadPriority enumeration

The ThreadPriority enumeration contains five priority members, which are a follows:

  1. Lowest
  2. BelowNormal
  3. Normal
  4. Highest
  5. AboveNormal
Join

The Join method is used to block the calling thread until a thread terminates.

WaitSleepJoin

The WaitSleepJoin state is used to specify that a thread is blocked.

WaitCallBack delegate

Implement multiple threads using WaitCallBack delegate in an application.

Try/Catch block

Handle the DivideByZeroException using the try/catch block.

Thread class

The Thread class of the System.Threading namespace is used to create a thread and execute it.

Thread.IsBackground

The Thread.IsBackground property is used to run a process in background. A thread is either a background thread or a foreground thread.

Timer class

The System.Threading namespace is used to work with the Timer class and other classes related to the Timer class.

Semaphore class

The Semaphore class is used to create a semaphore that can satisfy up to three concurrent requests.

Mutex class

The Mutex class is used to synchronize access to a protected resource.

Sleep method

The Sleep method is a static method and always acts on the currently running thread.

Regsvcs.exe

The Regsvcs.exe tool is used to load and register assemblies as well as generate, register, and install a type library into a COM application.

Launch Condition

The Launch Condition tab in the Project Properties dialog box is used to specify conditions for installation. These conditions can be used in conjunction with a file, registry, or component search.

File System editor

The File System editor can be used to add project outputs to a deployment project. It can be used to specify the location on the target computer where files are to be installed, and to create shortcuts on the target computer.

Custom Actions editor

The Custom Actions editor is used to define custom actions that can execute code at the end of an installation process to perform actions, such as the installation of location-specific files, which cannot be handled during installation.

User Interface editor

The User Interface editor allows a developer to change the visual screen that the a user sees while installing an application.

Share
Tagged with:
 
Chapter: 1

Developing applications that use system types and collections

Type casting

Type casting is the process of converting the value of a specific data type into another data type. There are two types of casting in .NET, i.e., implicit and explicit.

Array

An array of data is declared by using a value data type with square braces and a variable name in which the array of data is to be stored.

params

The params keyword provides the facility to specify a method parameter that takes a variable number of arguments.

Boxing

Boxing is an implicit conversion of a value type to a reference type. Unboxing is the inverse of boxing.

static

Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole.

Value type

A value type is a variable that contains data values, which are stored in a memory storage area known as the stack.

+ operator

The + operator concatenates two strings, and as a result, produces a new String object. It may also be used to concatenate a string with other data types.

ToString(), GetType(), and Equals()

The ToString(), GetType(), and Equals() methods are available in all the classes of .NET Framework.

Short datatype

The Short datatype is stored as a signed 16-bit (2-byte) integer ranging in value from -32,768 to 32,767. It is also stored as an unsigned 16-bit (2-byte) integer ranging value from 0 to 65,535.

Enumeration

Enumeration is used to provide symbols to a fixed set of related data values. Therefore, developers can use red, green, or blue, etc. instead of values such as 1, 2, or 3, etc.

Finally

A finally block is used to execute a certain portion of code that must be executed, irrespective of whether or not an exception is caught.

unsafe

The unsafe keyword is used in case of pointers in C#. The unsafe keyword denotes an unsafe code or block, which is required for any operation involving pointers.

Property

Each class is made up of properties, methods, and events. Property is a named attribute of an object. Properties define the characteristics of an object, such as name.

Constructor

A constructor is used to create an object that is an instance of a class. It has the same name as the class in which it resides.

Destructor

A destructor is a special type of method used to destroy instances of a class when they are no longer used by an application. A destructor has the same name as the class in which it resides, preceded by a tilde (~) symbol.

Runtime environment

The .NET Framework provides the development and runtime environment for .NET applications. It is composed of several components that are required to build and run .NET-based applications.

Logical errors

Logical errors are those errors that appear in an application once it is in use. An application with logical errors compiles and executes correctly. However, it does not produce the desired result.

Array in C#

When declaring an array in Visual C# .NET, only the upper bound of the array is defined. Arrays in Visual C# .NET are always zero-based, i.e., the lower bound is always zero.

Exception

The common language runtime throws an exception when an error occurs during program execution resulting from a failed runtime check. This error is usually nonfatal and is recoverable by user programs.

Class

A class is a reference type, and its object is created on the heap. On the other hand, a structure is a value type, and its object is created on the stack.

Pre and Postfix

Use Pre and Post fix operators such as –, ++, etc to change the values of variables.

Method

A user defined class that inherits abstract class and method.

Abstract

An abstract method only has a semicolon after the method name and parenthetical argument list. The subclasses provide the body of the abstract method.

Inheritance

Use inheritance feature of .NET in an application and define an abstract class that contains a declaration of an abstract method.

Button click event

Use the button click event to change the back color of the form according to the choice of a user without exception handling.

StartPosition

The StartPosition property of the form is used to display it at the center of the screen.

Random class

The Random class is used to change the back color of the form in random order whenever you click the button.

Dock property

The Dock property is used to cover the complete form.

ContextMenu

Add a ContextMenu control in an application and use the Show() method of the ContextMenu to display in the application.

Try

A try block must be followed by a catch block or a finally block.

Default constructors and explicit constructors
Create and use default constructors and explicit constructors in an application.
ICollection interface
The ICollection interface is implemented by all collections to provide the CopyTo() method as well as the Count, IsSynchronized, and SyncRoot properties. It is used to define size, enumerators, and synchronization methods for all non-generic collections.
SortedList and BitArray collections

The SortedList and BitArray collections are accessed by an index.

IComparer and IComparable interfaces

The IComparer and IComparable interfaces are used to sort a collection using the Array.Sort method.

System.Collections and System.Collections.Generic namespaces

The following collections are available in both the System.Collections namespace and System.Collections.Generic namespace:

  • Comparer
  • SortedList
  • Stack
DictionaryEntry object

The DictionaryEntry object is used to store entries in a Hashtable collection.

IEnumerable and IDictionaryEnumerator interfaces

The IEnumerable and IDictionaryEnumerator interfaces are used to create a new collection type that must be iterated using a for each loop.

IClassFactory interface

The IClassFactory interface deals with two issues: locality and language independence. It provides a language-neutral way to create a COM object by a client.

AddRange

The AddRange method of the Control.ControlCollection class is used to add an array of controls to a collection. It is also used to add a single control to a collection.

ArrayList

The ArrayList class of the System.Collections namespace implements the IList interface by using an array of data.

SortedList object

It adds names to a SortedList object and retrieves the index number of a name.

Hashtable object

It retrieves values to their corresponding keys stored in a Hashtable object.

Dequeue

The Dequeue method of the Queue class is used to retrieve as well as remove an item at the beginning of a queue.

IsValid

The IsValid property of the CustomValidator control is used to indicate whether or not an input control passes validation.

LinkedList class

The LinkedList class is a doubly linked list. It is created dynamically as per the requirements. It comprises a sequence of nodes; each node in the LinkedList Generic class contains a data field and one or two references pointing to the next and/or the previous node.

LinkedList.Enumerator

The LinkedList.Enumerator is used to read all the data of a generic LinkedList. The LinkedList Generic class is a doubly linked list. It is created dynamically as per the requirements. It comprises a sequence of nodes, each node in the LinkedList Generic class contains a data field and one or two references pointing to the next and/or the previous node.

Ngen.exe

If an application calls a large number of methods or large shared libraries at startup, using pre-compilation is the best technique to optimize the performance of the application during startup. Pre-compiling the application with Native Image Generator (Ngen.exe) reduces its startup time.

CompareTo

The CompareTo method of the IComparable generic interface returns a 32-bit signed integer value that indicates the relative order of the objects that is to be compared.

StringDictionary

The StringDictionary class is used to store key and value pairs. When you create an instance of the specialized StringDictionary class, you can use only string indexes and set only values that are strings.

BitVector32 structure

The BitVector32 structure is used to provide a simple structure that stores boolean values and small integers in a 32-bit of memory size.

“= =” and Equals()

If two strings are equivalent, the “==” returns true, also the “Equals()” method returns true. When you use “==” operator with the string class it compares value rather than the identity.

Hybrid Dictionary

It manages collections and selects a class that is optimized for key-based item retrieval from both small and large collections using Hybrid Dictionary.

String concatenation

It is used to gather data from multiple email messages and format the data for display on the page and ensure that the page displays the data as quickly as possible.

Interface

An interface describes a group of related behaviors that can belong to a class or a struct.

Array.Sort and IComparer

Create a new collection type that must be sorted by using the Array.Sort and IComparer interface.

IConvertable interface

It converts the value of an object of an implementing type into a Common Language Runtime (CLR) type that has an equivalent value by using IConvertable interface.

EventArgs class

Create a class that inherits from the EventArgs class to pass specialized information to an event handler apart from the source and event handler objects.

Multiple events can share the same delegate

Multiple events can share the same delegate type. Once a delegate type is declared for an event, the event is declared as a delegate type field.

StackTrace

The StackTrace property is used to trace a stack at runtime. It is an ordered collection of one or more stack frames.

Event

A custom event can invoke a delegate.

PrintPageEventArgs

The PrintPageEventArgs class is used to provide data for the PrintPage event and it occurs when the output for the current page is needed.

EditCommand event

The EditCommand event of the DataGrid control occurs when users click the Edit button for a DataGrid item. The EditItemIndex property of the DataGrid control specifies the index of an item in the DataGrid control to edit.

TextBox event

The TextBox event handler is used to execute when the TextChanged event of the TextBox is raised. The TextChanged event of the TextBox control occurs when the Text property value is changed.

TextChanged event

When the TextChanged event of a TextBox control is fired, the text typed in one TextBox control will also appear in another TextBox control.

Share
Tagged with: