reflection and ado

Upload: kartik-kashyap

Post on 09-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Reflection and Ado

    1/38

    Reflection and ADO. Net

    Karthik Eetur

  • 8/8/2019 Reflection and Ado

    2/38

    REFLECTION

    Reflection is a way of getting information about anyspecific class or assembly at runtime. You can alsosay its RTTI (Runtime Type Information).

    With the help of reflection you can get the all the

    properties and methods with arguments/parameters.You can also get the list of classes, interfaces,structures and enumeration in an assembly by usingreflection.

    You can dynamically create an instance of an objectat runtime and invoke methods dynamically.

    examples of reflection: Object browser and VisualStudio .NET IDE (Integrated DevelopmentEnvironment)

  • 8/8/2019 Reflection and Ado

    3/38

    Namespace: System. Reflection

    The Reflection namespace contains

    classes and interfaces that provide a

    managed view of loaded types,

    methods, and fields, with the ability to

    dynamically create and invoke types.

  • 8/8/2019 Reflection and Ado

    4/38

    Classes in Reflection

    class AmbiguousMatchException The exception that is thrown when

    binding to a method results in more

    than one method matching the binding

    criteria.

    class Assembly Defines anAssembly, which is a

    reusable, versionable, and self-

    describing building block of a common

    language runtime application.

    class AssemblyAlgorithmIdAttribute Specifies an algorithm to hash all filesin an assembly. This class cannot be

    inherited.

    class AssemblyCompanyAttribute Defines a company name custom

    attribute for an assembly manifest.

  • 8/8/2019 Reflection and Ado

    5/38

    class AssemblyConfigurationAttribute Defines an assembly configuration

    custom attribute (such as retail or debug)

    for an assembly manifest.

    class AssemblyCopyrightAttribute Defines a copyright custom attribute for

    an assembly manifest.

    class AssemblyCultureAttribute Specifies which culture the assemblysupports.

    class AssemblyDefaultAliasAttribute Defines a friendly default alias for an

    assembly manifest.

    class AssemblyDelaySignAttribute Specifies that the assembly is not fullysigned when created.

    class AssemblyDescriptionAttribute Defines an assembly description custom

    attribute for an assembly manifest.

  • 8/8/2019 Reflection and Ado

    6/38

    class AssemblyFlagsAttribute Specifies whether an assembly

    supports side-by-side execution on the

    same machine, in the same process, orin the same application domain. This

    class cannot be inherited.

    class AssemblyInformationalVersionAttr

    ibute

    Defines an assembly informational

    version custom attribute for an

    assembly manifest.

    class AssemblyKeyFileAttribute Specifies the name of a file containing

    the key pair used to generate a shared

    name.

    class AssemblyName Fully describes an assembly's unique

    identity.

    class AssemblyNameProxy Provides a remotable version of the .

    class AssemblyProductAttribute Defines a product name custom

    attribute for an assembly manifest.

  • 8/8/2019 Reflection and Ado

    7/38

    class ConstructorInfo Discovers the attributes of a class

    constructor and provides access to

    constructor metadata.

    class CustomAttributeFormatException The exception that is thrown when the

    binary format of a custom attribute is

    invalid.

    class DefaultMemberAttribute Defines the member of a type that is

    the default member used by

    Type.InvokeMember. The default

    member is a name given to a type.

    class EventInfo Discovers the attributes of an eventand provides access to event

    metadata.

    class FieldInfo Discovers the attributes of a field and

    provides access to field metadata.

  • 8/8/2019 Reflection and Ado

    8/38

    class ManifestResourceInfo Contains manifest resource topology

    information.

    class MemberInfo Discovers the attributes of a member

    and provides access to member

    metadata.

    class MethodBase Provides information about methods

    and constructors.

    class MethodInfo Discovers the attributes of a method

    and provides access to method

    metadata.

    class Missing Represents a missing Object. This

    class cannot be inherited.

    class Module Performs reflection on a module.

  • 8/8/2019 Reflection and Ado

    9/38

    class ParameterInfo Discovers the attributes of a parameter

    and provides access to parametermetadata.

    class Pointer Provides a wrapper class for pointers.

    class PropertyInfo Discovers the attributes of a property

    and provides access to property

    metadata.class ReflectionTypeLoadException The exception that is thrown by the

    Module.GetTypes method if any of the

    classes in a module cannot be loaded.

    This class cannot be inherited.

    class StrongNameKeyPair Encapsulates access to a public orprivate key pair used to sign strong

    name assemblies.

    class TargetException Represents the exception that is

    thrown when an attempt is made to

    invoke an invalid target.

  • 8/8/2019 Reflection and Ado

    10/38

    Interfaces & Structures in

    Reflectioninterface ICustomAttributeProvider Provides custom attributes for reflection

    objects that support them.

    interface IReflect Allows objects to return MemberInfo

    objects that represent an object.

    structure InterfaceMapping Retrieves the mapping of an interface

    into the actual methods on a class that

    implements that interface.

    structure ParameterModifier Attaches a modifier to parameters so

    that binding can work with parameter

    signatures in which the types have

    been modified.

    (refer document)

  • 8/8/2019 Reflection and Ado

    11/38

    Loading Metadata of an Assembly

    In the Entity Data Model (EDM), item collections areresponsible for loading metadata from persistentresources, such as XML files or common languageruntime (CLR) assemblies, and are in an instance ofthe MetadataWorkspace class

    ADO.NET provides an ItemCollection class as a coreAPI for loading and holding in-memory metadata.

    The ItemCollection has several derived classes,such as ObjectItemCollection, EdmItemCollection,StoreItemCollection, andStorageMappingItemCollection.

    Each of these collection classes is specialized for adifferent type of metadata. The following sectionsexplain how these collection classes interact withdifferent types of metadata.

  • 8/8/2019 Reflection and Ado

    12/38

    ObjectItemCollection:

    The ObjectItemCollection class is responsible forloading metadata about the object model. The objectmodel represents the CLR classes that can be used as aprogrammatic realization of the conceptual model.

    EdmItemCollection:

    An EdmItemCollection class is responsible for loadingmetadata about the conceptual model. TheEdmItemCollection class loads its metadata from aconceptual schema definition language (CSDL) file that

    is an XML representation of the conceptual model.

  • 8/8/2019 Reflection and Ado

    13/38

    StoreItemCollection:

    An StoreItemCollection class is responsible for loadingthe metadata about the storage (database) model. TheStoreItemCollection class loads its metadata from astore schema definition language (SSDL) file that is anXML representation of the storage model.

    StorageMappingItemCollection :

    A StorageMappingItemCollection class is responsiblefor loading metadata that represents the mappingbetween the conceptual model and the storage(database) model.

    The StorageMappingItemCollection class loads itsmetadata from a mapping specification language (MSL)file that is an XML representation of the mapping betweenthe conceptual model and the storage model.

  • 8/8/2019 Reflection and Ado

    14/38

    ADO.NET

    ADO.NET is a set of classes that expose dataaccess services for .NET Framework programmers.

    ADO.NET provides a rich set of components forcreating distributed, data-sharing applications.

    It is an integral part of the .NET Framework,providing access to relational, XML, and applicationdata.

    ADO.NET supports a variety of development needs,including the creation of front-end database clientsand middle-tier business objects used by

    applications, tools, languages, or Internet browsers.

  • 8/8/2019 Reflection and Ado

    15/38

    ADO.NET OVERVIEW ADO.NET provides consistent access to data sources such

    as SQL Server and XML, and to data sources exposedthrough OLE DB and ODBC. Data-sharing consumerapplications can use ADO.NET to connect to these datasources and retrieve, handle, and update the data that theycontain.

    ADO.NET separates data access from data manipulation intodiscrete components that can be used separately or intandem.

    ADO.NET includes .NET Framework data providers forconnecting to a database, executing commands, andretrieving results. Those results are either processed directly,

    placed in an ADO.NET Dataset object in order to be exposedto the user in an ad hoc manner, combined with data frommultiple sources, or passed between tiers.

    The Dataset object can also be used independently of a .NETFramework data provider to manage data local to theapplication or sourced from XML.

  • 8/8/2019 Reflection and Ado

    16/38

    ADO.NET ARCHITECTURE

  • 8/8/2019 Reflection and Ado

    17/38

    Advantages of ADO. Net :

    ADO. Net works on disconnected architecture.

    data can be cached in datasets.

    data is persisted as XML.

    Performance : Extremely Fast.

    Disadvantages of ADO. Net: Providing a comprehensive disconnected data-

    access model, which is crucial to the Webenvironment

    Providing tight integration with XML, and Providing seamless integration with the .NET

    Framework (e.g., compatibility with the baseclass library's type system).

  • 8/8/2019 Reflection and Ado

    18/38

    DAO & RDO in ADO

    Data Access Objects (DAO) can be used either with theMicrosoft Jet database engine or, using the ODBCDirect option,without it.

    This chapter discusses design and implementation issues thatarise when using the Data Access Objects (DAO) to access

    remote databases. Remote Data Objects (RDO) implement a set of objects to deal

    with the special requirements of remote data access.

    RDO implements a thin code layer over the ODBC API anddriver manager that establishes connections, creates result setsand cursors, and executes complex procedures using minimal

    workstation resources. Although RDO is also accessed by DAO when your code

    creates an ODBCDirect Workspace object, documentation forthis implementation can be found by searching for specific

    ODBCDirect topics.

  • 8/8/2019 Reflection and Ado

    19/38

    Features of Remote Data Objects With RDO and the RemoteData control, your applications can access

    ODBC data sources without using a local query processor

    By using RDO, you can:

    Create simple cursorless result sets, or more complex cursors.

    Run queries and process any number of result sets.

    Execute stored procedures that return result sets with or without outputparameters and return values.

    Execute action queries that perform data manipulation or data definitionoperations.

  • 8/8/2019 Reflection and Ado

    20/38

    Data Providers

  • 8/8/2019 Reflection and Ado

    21/38

    .NET Framework data provider Description

    .NET Framework Data Provider for

    SQLServer

    For Microsoft SQL Server version

    7.0 or later.

    .NET Framework Data Provider forOLE DB

    For data sources exposed using OLEDB.

    .NET Framework Data Provider for

    ODBC

    For data sources exposed using ODBC.

    Note The .NET Framework Data

    Provider for ODBC is not included in the

    .NET Framework version 1.0. If yourequire the .NET Framework Data

    Provider for ODBC and are using the

    .NET Framework version 1.0, you can

    download the .NET Framework Data

    Provider for ODBC at

    http://msdn.microsoft.com/downloads.The namespace for the downloaded

    .NET Framework Data Provider for

    ODBC is Microsoft.Data.Odbc.

  • 8/8/2019 Reflection and Ado

    22/38

    .NET Framework Data Provider for

    Oracle

    For Oracle data sources. The .NET

    Framework Data Provider for Oracle

    supports Oracle client software version

    8.1.7 and later. Note The .NET

    Framework Data Provider for Oracle is

    not included in the .NET Frameworkversion 1.0. If you require the .NET

    Framework Data Provider for Oracle

    and are using the .NET Framework

    version 1.0, you can download the .NET

    Framework Data Provider for Oracle at

    http://msdn.microsoft.com/downloads.

  • 8/8/2019 Reflection and Ado

    23/38

    core elements of the .NET

    Framework data provider model

    Object Description

    Connection Establishes a connection to a specific

    data source.

    Command Executes a command against a data

    source.

    DataReader Reads a forward-only, read-only

    stream of data from a data source.

    DataAdapter Populates a DataSet and resolves

    updates with the data source.

  • 8/8/2019 Reflection and Ado

    24/38

    Connection Class

    SqlConnection con = new

    SqlConnection(@"Data Source=JLC-

    A10ADD7FFE4\SQLEXPRESS;Initial

    Catalog=srinivas;IntegratedSecurity=True");

    Here con is the connection class object

    Using connection class con we areconnecting to database using

    connection string

  • 8/8/2019 Reflection and Ado

    25/38

    Connection Strings

    A connection string contains initializationinformation that is passed as a parameter froma data provider to a data source.

    The syntax depends on the data provider, and

    the connection string is parsed during theattempt to open a connection.

    Syntax errors generate a run-time exception,but other errors occur only after the datasource receives connection information.

    Once validated, the data source applies theoptions specified in the connection string andopens the connection.

  • 8/8/2019 Reflection and Ado

    26/38

    Command class Initialization of object:

    SqlCommand cmd;

    Methods of SqlCommand class:

    ExecuteNonQuery()used for INSERT,UPDATE,DELETE

    ExecuteScalar()

    used to perform changes to single column

    ExecuteReader()

    used for select statement

  • 8/8/2019 Reflection and Ado

    27/38

    Using Commands to Modify Data

    (ADO.NET) Using a .NET Framework data provider, you can execute

    stored procedures or data definition language statements(for example, CREATE TABLE and ALTER COLUMN) toperform schema manipulation on a database or catalog.These commands do not return rows as a query would, so

    the Command object provides an ExecuteNonQuery toprocess them.

    In addition to using ExecuteNonQuery to modify schema,you can also use this method to process SQL statementsthat modify data but that do not return rows, such asINSERT, UPDATE, and DELETE.

    Although rows are not returned by the ExecuteNonQuerymethod, input and output parameters and return values canbe passed and returned via the Parameters collection ofthe Command object.

  • 8/8/2019 Reflection and Ado

    28/38

    Data Reader and Data Adapters

    You can use the ADO.NET DataReaderto retrieve a read-only, forward-only stream of data from a database. Resultsare returned as the query executes, and are stored in thenetwork buffer on the client until you request them usingthe Read method of the DataReader. Using theDataReadercan increase application performance both by

    retrieving data as soon as it is available, and (by default)storing only one row at a time in memory, reducing systemoverhead.

    A DataAdapteris used to retrieve data from a data sourceand populate tables within a DataSet. The DataAdapteralso resolves changes made to the DataSet back to the

    data source. The DataAdapter uses the Connection objectof the .NET Framework data provider to connect to a datasource, and it uses Command objects to retrieve data fromand resolve changes to the data source.

  • 8/8/2019 Reflection and Ado

    29/38

    Classes in .NET Data provider

    Object Description

    Transaction Enables you to enlist commands in

    transactions at the data source.

    CommandBuilder A helper object that will automatically

    generate command properties of aDataAdapteror will derive parameter

    information from a stored procedure

    and populate the Parameters

    collection of a Command object.

    Parameter Defines input, output, and return value

    parameters for commands and stored

    procedures.

  • 8/8/2019 Reflection and Ado

    30/38

    Exception Returned when an error is

    encountered at the data source. For

    an error encountered at the client,

    .NET Framework data providers throw

    a .NET Framework exception.

    Error Exposes the information from a

    warning or error returned by a data

    source.

    ClientPermission Provided for .NET Framework data

    provider code access security

    attributes.

  • 8/8/2019 Reflection and Ado

    31/38

    Transaction handling

    Begin Transaction

    Some code to update records

    Some code to select some records

    Retrieve some data from the selected records

    Update some value depending upon selected

    records

    Commit Transaction

  • 8/8/2019 Reflection and Ado

    32/38

    App.config file Windows applications in VS.NET use the

    name app.configby default for theconfiguration file.

    This will not be automatically created when

    you create a Windows application. If you needa configuration file for your application, openyour project in VS.NET, go to the 'SolutionExplorer' and right click on the project name.ChooseAdd>Addnewitem from the menu

    and select 'Application Configuration file' fromthe list of choices. This will create anapp.config file for you in the application root.

    By default, the app.config file will have thefollowing content:

  • 8/8/2019 Reflection and Ado

    33/38

    Store values in config file

    To store values in the configuration file,

    you can create XML elements in the

    format:

  • 8/8/2019 Reflection and Ado

    34/38

    See the sample config entries below:

  • 8/8/2019 Reflection and Ado

    35/38

    Read values from config file

    To read from this config file, just use the

    following code in your application:

    string dbPath =

    System.Configuration.ConfigurationSetti

    ngs.AppSettings["DatabasePath"];

    string email =

    System.Configuration.ConfigurationSettings.AppSettings["SupportEmail"];

  • 8/8/2019 Reflection and Ado

    36/38

    ConfigurationSettings is the class used toaccess the contents of the configuration

    file using System.Configuration;

    If you have the above directive on top offile, we can use

    string dbPath =ConfigurationSettings.AppSettings["DatabasePath"];

    string email =ConfigurationSettings.AppSettings["SupportEmail"];

  • 8/8/2019 Reflection and Ado

    37/38

    In VB.NET, you have to use "( ... )"

    instead of the "[ ... ]", as shown below:

    Dim dbPath as String =

    ConfigurationSettings.AppSettings("Data

    basePath")

    Dim email as String =ConfigurationSettings.AppSettings("Sup

    portEmail")

  • 8/8/2019 Reflection and Ado

    38/38

    Thank you.