Escolar Documentos
Profissional Documentos
Cultura Documentos
Is there another way to tell the compiler to make a member function inline other than using inline
keyword?
Yep: define the member function in the class body itself:
What is a reference?
A reference is a quantity that holds the address of an object but behaves syntactically like that object. A
reference cannot exist without object and must be initialized. The reference is the referent, so changing the
reference changes the state of the referent.
A Reference is an "lvalue" (something that can appear on the left hand side of an assignment operator).
The function call can appear on the left hand side of an assignment operator.
InOrder to save space and Avoid Ambiguities in case of multiple inheritence i.e, virtual base class if
inherited more than once via different path then only one copy of data member presents which is
shared by all the derived classes that use it as a virtual base.
Is to have derived classes inherit a function interface as well as a default implementation. But its not mandatory to
redefine in its derived class. A virtual function allows derived classes to replace the implementation provided by the base
class
If you destroy an object through a pointer or reference to a base class and the base class destructor is not
virtual then the derived class destructor are not executed and the destruction might not be complete. If not it
leads to memory leaks.
Only one copy is created and shared by all the objects of the class. Defined outside the class, initialized to Zero .Life time
will be the entire program. static variables exist without creating an object
Static Function: Can access or refer to only static data members of a class, Accessable through a class name instead of
an object. If your function is static, it cannot access non static functions
Static Variable: is accessible only to all functions defined in the same file
Global Variable: is accessible by all functions defined even from different files.
Explain on Const?
Any function of a class which does not modify the data member of class within it should add a const at the
end of a function ( it even cannot call any member function that are not constant). It makes the function
read-only
Note: Keyword Mutable can change the value of data inside a const member function
To define a const statement: Const int MAX=100; const distance d3(10,6); //the values 10 and 6 cannot be changed
Note: the const members must be initialized in the constructors’ member initializer lists
Why we should implement copy constructor?
To perform Deep Copy. It allows you to make copies of all fields and makes copies of dynamically allocated
memory pointed to by the fields. (Ex. userdefined copy constructor and overloaded Assignment operator)
Note: copy constructor will always take a reference to an object of its own class as its argument.If not it will
result in calling the copy constructor recursively. And you cannot return a value from it. It is called during
a) initialization of one object with another object of same class b) passing an object by value c) returing an
object by value.
What is an object?
A region of storage with associated semantics.
Define Encapsualtion?
Encapsulation puts a firewall around the chunk, which prevents other chunks from accessing it.
Designing a clean interface and separating that interface from its implementation merely allows users to use
the interface. But encapsulating (putting "in a capsule") the implementation forces users to use the interface.
Encapsulation doesn’t provide security, Encapsulation prevents mistakes, not espionage
Can one constructor of a class call another constructor of the same class to initialize the this
object?
No.
A "default constructor" is a constructor that can be called with no arguments. One example of this is a
constructor that takes no parameters:
class Fred
{
public:
Fred(); // Default constructor: can be called with no args
// ...
};
Another example of a "default constructor" is one that can take arguments, provided they are given default
values:
class Fred
{
public:
Fred(int i=3, int j=5); // Default constructor: can be called with no args
// ...
};
Should you use the this pointer in the constructor?
Some people feel you should not use the this pointer in a constructor because the object is not fully formed
yet. However you can use this in the constructor, but be carefull .
Here is something that always works: the {body} of a constructor (or a function called from the constructor)
can reliably access the data members declared in a base class and/or the data members declared in the
constructor's own class. This is because all those data members are guaranteed to have been fully
constructed by the time the constructor's {body} starts executing
Here is something that never works: the {body} of a constructor (or a function called from the constructor)
cannot get down to a derived class by calling a virtual member function that is overridden in the derived
class. If your goal was to get to the overridden function in the derived class, you won't get what you want
Can you initialize static member data in the constructor's initialization list?
No. Because you must always explicitly define your class's static data members.
First constructed, last destructed . Here b's destructor will be executed first, then a's destructor:
void userCode()
{
Fred a;
Fred b;
// ...
}
First constructed, last destructed. Here in the example the order for destructors will be a[9], a[8], ..., a[1],
a[0]:
void userCode()
{
Fred a[10];
// ...
}
NO. The destructor will get called again at the close } of the block in which the local was created
SB:refers to an entity existing in different physical form simultaneously. Binding takes place at compile time
based on the type of object.
DB:refers to an entity existing changing its form depending on the circumstances. Binding takes place at
runtime based on the context of the object.
What is a Constructor?
-> These are the functions which have the same name as that of a class.
-> a constructor function is not provided in a class, then C++ compiler provides a default constructor
What is a Destrutor?
-> This function has the same name as that of a class but starts with ~
Example on Throw:
Int Foo() throw() -> means no exception is thrown from this function
Int Foo() throw(x,y) -> means this function will only throw exceptions x & y and exception derived from them.
No other exceptions are handled.
Int Foo() -> means that this function can throw any exception.
What does mean int **p? ----------Its an - Pointer to pointer to int OR Pointer to array of int
Why to use Void Pointer? ----------Used to cast into and back again without any loss of information.
What is a member Function? —Its an ordinary Function- has its own name, a return type and invoked
using dot operator.
What is a Polymorphic Class? ----Polymorphic class in any class containing a virtual function is a
polymorphic
What is a conditional Compilation? ---------are the Directives to control what does and does not get
compiled.
Use of Scope Resolution Operator? ---------used to access the base-class version from the derived
What is a “This” pointer? ---------special pointer available within a class alone. It’s used to refer the current
object from within the class.
Throw an exception. Constructors don't have a return type, so it's not possible to use error codes.
What's the difference between "const Fred* p", "Fred* const p" and "const Fred* const p"?
You have to read pointer declarations right-to-left.
* const Fred* p means "p points to a Fred that is const" -- that is, the Fred object can't be changed
* Fred* const p means "p is a const pointer to a Fred" -- that is, you can change Fred object but you can't
change pointer p itself.
STL
Advantage of STL?
A library of container templates approved by the ANSI committee for inclusion in the standard C++
specification. Provides containers and algorithms that have already been written and are available in what is
usually called the Standard Template Library (STL). STL provides implementation of Dynamic arrays. STL
provides a set of Template classes used to make C++ programming faster and simpler. The components of
STL area) Algorithm b) Container c)Iterator d)Function Object d)Adaptor.
Its an Sequencial Container(ie, vector, deque, list) which organizes a finite set of objects all of same type-in
a linear arrangement.
What is an Iterator
Pointers themselves are iterators . It decouples algorithm from Container.
Remove() removes elements by value, while erase() uses iterator for the same purpose.
Vector is a one-dimensional array. It's also an STL class while array is a data type.
MFC
Explain Document-view architecture
It’s a part of MFC framework that provides a logical seperation between application’s data and
representation of data. A document objects acts as an container for application data and a view is a window
object usually associating with client area of Screen window through which the user interacts with the data
contained in the document.
Components of Doc-View arch:
a) the Document -> contains data, supports Serialization and Handle Messages(only
WM_COMMAND msgs)
b) the View -> handle commands and Responsible for displaying data
c) Views FrameWindow ->Supports splitter window, hosts views and other controls
d) Document Template -> defines relationship among doc, view, FrameWindow
e) Document Template Res ID -> supports Icon, Menu and String resources
Both check the message queue for a message that matches the filter criteria and then copy the message to
an MSG structure. The Main Difference between 2 function is that GetMessage does not return until a
message matching the filter criteria is placed in the queue whereas Peek Message returns immediately
regardless of whether a message is in the queue.
Exceptions in C++?
An Expection is any unusal event either erroneous or not, detectable by either H/W or S/W, that may require
special processing. The special processing that may be required after the detection of an exception is called
exception handling.
Try, catch and throw. If no exception is caught by “Catch” then “Terminate()” is called which in turn calls
“Abort()”
Using Throw statement. When Throw is executed the “Try” block finalizes right away and every object
created within the TRY block is destroyed. After that the control is passed to the corresponding “Catch”
block. Next, program continues right after the catch block.
What functions are used when DLL without import lib is used?
What happens when you add variable or add new function in debug session? Can you continue?
No. Warning “New Datatype or Function are not supported by Edit&Continue. Build Required” with YES and
NO buttons.
If YES then the Debug session is lost.
Translate the virtual key message into character message and places it back into the Application Message
Queue
What MFC classes that doesn’t support Message Mapping ? ---------Cobject and CGDIObject
How to work with RichEdit control?----------------- call AfxInitRichEdit() from your InitInstance()
Threads
A “thread” is a path of execution within a process. It is a unit of code that o/s can execute
Multithreading is the ability of an program to split itself into separate threads of execution that also seems
to run concurrently.
All threads require a thread procedure (referred to below as ThreadProc()) that subscribes to the following
function signature:
MFC supports two types of threads: a user interface thread and a worker thread. A user interface thread
contains a Windows message loop. Unlike a user interface thread, a worker thread doesn't contain a
Windows message loop, therefore no Windows-based objects can exist within it. This type of thread is
typically used to perform auxiliary tasks such as querying a database.
MFC provides the CwinThread class that wraps the functionality of a user interface thread. CwinApp is
derived from CWinThread,
In order to create a user-interface thread, you must perform the following basic steps:
1. Create a new class, derived from CWinThread
2. Implement and use the DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE macros in the new
class.
3. Over ride the InitInstance in the new class.
4. Call AfxBeginThread with the RUNTIME_CLASS of your new class.
CWinApp is an example of a user-interface thread object, as it derives from CWinThread and handles
events and messages generated by the user.
A brief description of what AfxBeginThread does. Essentially AfxBeginThread is a helper function that
handles setting up and starting a CWinThread object for us. To do this it goes through (broadly speaking)
four steps
By default, as soon as the thread has completed it is deleted and so if our thread doesn't take much time to
complete, by the time that AfxBeginThread returns, our CWinThread pointer may already have been
deleted and so dereferencing this pointer to get at the thread handle for a WaitForSingleObject() call will
cause our application to crash.
Fortunately CWinThread provides a simple answer to this by way of the m_bAutoDelete member variable.
As described above, this is TRUE by default. However, if we set it to FALSE, then the thread will not delete
itself when it completes.
Termination of Threads
For a worker thread, you can call AfxEndThread or a RETURN statement. For a user-
interface thread call PostQuitMessage.
Call AfxEndThread from within the thread Passing the desired exit code as the only
parameter. To Retriev the Exit Code of a Thread call the GetExitCodeThread function. If
the thread is still active, GetExitCodeThread will place STILL_ACTIVE.
STA: can have only one thread executing per apartment. It relies on Message Loop.
MTA: can have more than one thread executing per apartment. It doesn’t rely on Message Loop
The six multithreaded classes with two categories: synchronization objects ( CsyncObject,
Csemaphore, Cmutex, CCriticalSection, and CEvent) and synchronization access objects
( CmultiLock and CSingleLock). CSyncObject is the base class for other four synchronization
classes.
COM
What is COM?
Its an Technology. Its an Protocol used to establish communication between 2 s/w junks. It’s a
Reusable code, which can be easily plugged and used in any language. The main benefits of COM
are language independence and location transparency
It stores the physical path as to where the Component dll is stored in the system, so that when it is
instantiated the appropriate dll is called. It stores the DispID, CLSID, ProgID etc. necessary for a component
instantiation.
ActiveX Controls
Originallyin 1994 OCX controls were available. Later it provided initial design for OLE control. For OLE
control to work properly on the internet ActiveX controls got resulted. ActiveX controls are reusable
components supporting a variety of OLE functionality. They are used for speed and efficiency. An ActiveX
Control can be thought of as an Automation Server. It can be used in Scripting Languages.
ActiveX controls provides User Interface. Its Self-Registering, Optimized for download and Execute
ActiveX : Encapsulate whole aspect of object , Difficult to implement and use , used in different platforms
DLL: Encapsulate only functional aspect of object, Easy to implement and use, used in Win32 platform.
What is Marshalling?
Involves packaging of data from the client into proxy and then unpacking it in the stub for forwarding to the
server.
Contains information about all the objects the server contains along with the interfaces and their
functions supported by each object. It can be read by VC++ or VB displaying the object Information
to the user. Typelib are constructed from the IDL file. (VC++5.0 ODL file was used). IDL is compiled
using MIDL compiler.
What is an Idispatch?
Its an interface which allows COM to have late-binding, and therefore be used in scripting environments.
A dual inteface are simply COM interfaces that derive from Idispatch. Dual interface is one that
supports both - IDispatch interface and vtbl-based interface. Therefore, it might be used in scripting
environment like VBScript and yet to use power and speed of vtbl-based interface for non-scripting
environment.
What method gets invoked during OLE Automation Server is called? ------à GetIDsofName() and
Invoke()
Structured Storage allows you to create files and organize information easily.
Blocks of data can be placed in hierarchical form, just as files are placed in directories. Uses IStorage and IStream
Interfaces
VARIANT is a huge union containing automation type. This allows easy conversion of one
automation type to another.
Standard interfaces
This represents the collection of Microsoft developed interfaces which are publicly documented. Standard
interfaces are also called as OLE interfaces. Ex: IShellLink, IMoniker, IPersist, IConnectionPoint, IDispatch,
etc.
Custom interfaces
A custom interface is a user-defined interface that uses VTABLE binding(Iunknown Interface). Since a
client from a different machine may use this component, we must provide a proxy/stub DLL and the
interface identifier (IID), which must be registered before a client can communicate with our COM object.
Custom interfaces do not support dynamic invocation.
Automation interfaces
An Automation interface is a user-defined interface that supports dynamic invocation and late binding
via the IDispatch interface. The advantage scripting clients can use it. Also, we don’t have to create
proxy/stub DLLs because Microsoft provided generic marshaling code in the Automation marshaler
(oleaut32.dll). Instead of using proxy/stub DLLs, the Automation marshaler uses a type library, which stores
detailed type information regarding objects and their supported interfaces. The only disadvantage of an
automation interface is that it supports only Automation compatible data types.
Dual interfaces
A dual interface is the one which supports the IDispatch as well as VTABLE binding. IDispatch permits
dynamic invocation thereby letting even the scripting clients use your component, whereas, VTABLE permits
faster access to the interface methods.
One drawback of this technique is that we have to use Automation compatible types, such as BSTR and
VARIANT and also all interface methods must return a HRESULT
What is an HRESULT?
COM component methods use HRESULTs to report error/success conditions to their users. Note that
S_FALSE is defined as 1 and S_OK is defined a 0. By convention successful return codes begin with an S_,
while failure codes begin with an E_.
If you have an object with two interfaces, can you custom marshal one of them?
No! The decision is all-or-nothing; an object has to custom marshal all its interfaces or none of
them.
The component can be anywhere in cyberspace. For a client it doesn’t matter where the component is
physically residing. This is the idea behind Location Transparency.
Location transparency is achieved using a concept called marshalling. RPC supports location transparency.
COM, which is built on top of RPC supports this. To carry out communication between the client and the
server COM uses an interface to define a set of related functions defined in IDL file. Using this IDL file, MIDL
compiler will generate the marshalling code. This marshalling code is known as proxy/stub code. When a
remote method invocation is made this proxy/stub code gets into action. In reality, the proxy code will
intercept the call. The job of this code is to marshal the intelligent data into raw buffer and unmarshalls the
buffer into a data back
BSTR are length-prefixed, Null terminated OLECHAR strings.( note: olechar is a type-def to wchar_t type
which represents 16bit Unicode characters).
Ex: BSTR bs=”hi” takes 10bytes (prefix length (4)+ h(2) + i(2)+ \0(2) )
What does in, out and retval signify when adding a method to an IDL file?
Ex: HRESULT Calculate ([in] int n1, [in] int n2, [out] int *n3, [out] int *n4, [out, retval] int * z)
A method can have any number of [in] values.
A method can have any number of [out] values.
The [in] parameters may or may not be pointers.
The [out] parameters must always be pointers.
A method can have only one retval.
A method may not have a retval at all.
The retval must be the right most parameter in a method.
Which are the different ways in which we can access the methods of a component through an MFC
VC++ client?
Method 1:
CoInitialize( NULL ) ;
hr = CLSIDFromProgID ( OLESTR ("AtlServer.Math" ), &clsid) ;
hr = CoCreateInstance ( clsid, NULL, CLSCTX_ALL, __uuidof ( IMath ), ( void **)
&math ) ;
Method II: Using Smart Pointer
IMathPtr p ;
hr = p.CreateInstance (__uuidof ( Math ) ) ;
Method III: Using Smart Pointer
IMathPtr p (__uuidof ( Math ) ;
Object pooling is kind of recycling of objects. When a client releases an object that supports object
pooling, instead of destroying, COM+ recycles it. When another client requests same object, COM+
gives an instance from recycle. Since these set of component instances
loaded in memory so that they are immediately available for use by client applications.
OOPS
Define ROSE ?
Rational Object Oriented Software Engineering, provides the software developer with a complete set of
visual modeling tools for development of robust, efficient solutions to real business needs
Why OOPS getting popular?
OOPs is used to create larger programs with easier and with better quality. Used to Group related data and
functions together
Explain OO concepts.
Polymorphism: ability of a function or operator to act in different ways on different data types is called
polymorphism.
Inheritance: Process by which objects of one class acquire properties of objects of another class.
Encapsulation: wrapping up of data and functions into a single unit is known as encapsulation
Abstraction: means the act of representing the essential features of something without knowing its internal
details fully.
Pattern types:
Creational Patterns -> concerns with object creation ( abstract factory, singleton)
Structrual patterns -> concerned with how objects are composed off(adaptor, Bridge, Composite,
Decorator, Façade, Flyweight)
Behaviour Pattern -> concerned with Algorithms and responsibility between objects (Iterator,
Mediator, Observer)
What is MVC?
Model (holds Business logic –Beans ) View(holds GUI logic –jsp) Controller (hold basic logic to process
user events – servlets)
Explain Each:
Scalable : A system is said to be scalable- if as the load increases the system should still responds within
the acceptable time.
Performance: Usually measured in terms of response time for a given Screen per User
Maintainablitly: Ability to correct flaws in the existing functionality without impacting other components of
the system
Define Lifecycle - describes the steps followed by the project team to produce a tangible software product
Define Process - is a documented way that contribute one/more steps in producing a product
Define CMM ?
CMM stands for Capability Maturity Model. Software Engg Institute developed CMM for software industry.
(Version 1.0 was released in 1992 and now Ver 1.1 currently available)
CMM establishes a framework for performing software process Assesment and software capability
Evaluation.
Software process Assesment : focus on identifying improvements within company software processes
Software capability Evaluation : focus on identifying risks associated with a particular project.
Note: Evaluation may be performed on existing projects to monitor their process performances with the
intent of identifying potential improvement with software process of the project.
CMM provides a conceptual structure for improving the management and development of S/W products in a
disciplined and consistent way. It does not guarantee that software products will be successfully build or that
all problems in a software process will be resolved.
CMM identifies practices for a mature software processes. Note : Matured organization addresses all the
issues essential to a successful project including –People, Technology and Processes.
Maturity of an organization’s software process helps to project a project’s ability to meet its goal.
LEVEL 1 : Organization has no process. (Customer Req. are uncontrolled and no project management
practices followed)
LEVEL 2 : tracks the processes that fetches performance and quality (Management reacts to problems
only when they occurs. Establishes a basic project management processes)
LEVEL 3 : Organization defines the processes for execution of its day-to-day function.(Everyone and
management knows their roles and responsibilities. Management prepares risk management plan)
LEVEL 4 : Organization defines the framework to capture and analyses the metrics. Using Metrics S/W
quality is laid. Here we quantify the quality level and processes (Management measure the progress and
problems and predict the outcome precisely)
LEVEL 5 : Here the processes are continually fine-tuned to achieve still more better results as they go
along. Here inefficient activities are identified which are then replaced or revised. Here productivity and
quality are improved in a controlled manner.
(here we follow change management process and Technology change management processes)
Define Metrics ?
Measuring your progress in order to know where you are and what mid-course correction you need to take
to achieve goals.
Metrics are of 2 types (1) in-process metrics and (2) end-result metrics
Road Map to Metrics are PLAN -> DO -> CHECK -> ACT ->>>> PLANà>>>
During metrics we track Time-Bound Targets and Result Oriented Targets should be measured and We
Define the UCL and LCL and Mean-Value of a metric
Quality Control refers to testing a product after a given phase to find out if it has any defects and in case it
does have defects to employee corrective measures to remedy the same. Quality Control is done after the
product is build. It Oriented towards defect detection rather than defect prevention. (Ex: Testing, Test cases,
Tractability matrix)
Quality Assurance if focuses on the prevention of defect from the very start. . Its defect prevention
oriented rather than defect deduction oriented. (Ex: Inspection / Review and Audits)
Define UML?
UML: The Unified Modeling Language (UML) is considered the de facto standard object modeling language
in the industry. The UML is the evolution of early approaches to object-oriented analysis and design. Based
on the seminal works by Grady Booch, Ivar Jacobson, and Jim Rumbaugh in the Booch, OOSE, and
methods, these three Rational experts have provided the basis for the next generation of visual software
modeling. The UML details the application modeling language for:
UML is to specify, Visualize and document the artifacts of an object oriented system under development.
UML consists of
1) modeling elements (Static and Dynamic) (static – classes, attributes, relationship & dynamic-
objects, Messages and state)
2) Relationship (Dependency, Association, Generalization and Realization)
3) Extensibility (Stereotype, Tagged value and Constraints)
4) Diagrams (Static View and Dynamic view)
Static View – use case, component, deployment, class and object &
Dynamic View– sequence, collaboration, state chart and activity
DATABASE
How do you run SQL statements from VC++?
By using CDatabase class and using the method ExecuteSQL () you can run SQL Statements directly from
VC++
What is a Trigger?
Trigger defines an action the database should take when some database-related events
(insert/update/delete) occurs. The code within Trigger called the trigger-body is made up of PL/SQL blocks.
Triggers are executed by Database.
Note: When enforcing business rules first relay on declarartive referential integrity Only Use Triggers to
enforce those rules that cannot be coded through referential integrity.
Types of Triggers is classified based on type of triggering transaction and based on level at which triggers
are executed. They are 1) Row level Triggers (triggers executed once for each row in a Tx)2) Statement
level Triggers (triggers executed once for each Tx) 3) Before and After Triggers(inserts/updates/deletes) 4)
Instead-of Triggers (redirection takes place) 5) Schema Triggers (events during create/alter/drop tables) 6)
DB level Triggers (events when errors, logon, logoff, startup and shutdown). Rather can calling large block
of code within a trigger body you can save the code as a stored procedure and call the procedure from
within the trigger by using a call command
To enable trigger use -> alter trigger abc enable;
To enable all triggers of a table -> alter table abc enable all triggers;
To disable triggers -> alter trigger abc disable /alter table abc disable all triggers
To drop triggers -> drop trigger abc;
In short -Its an PL/SQL block that fires with DML command. It is not called explicitly. It is executed
automatically when the associated DML is issued. 2Types -> Row Level and Statement level Triggers
Example:
CREATE or REPLACE TRIGGER my_customer_audit BEFORE UPDATE On my_customer FOR EACH
ROW
BEGIN
INSERT INTO update_check Values('Updating a row', sysdate);
END;
Explain each:
DDL -> Create , Alter, Drop, Truncate
DML -> Insert, Delete, Select, Update ( all have implicit cursors)
DCL (Data Control Language) -> Commit, Rollback and SavePoint
View ->its an logical table (not a physical table). You can only insert / Delete but you cannot
update.
What class you in MFC use to connect to Database? And Connect to Tables? ---------àCDatabase and
CRecordSet
DataBase Arch
ODBC: provides ODBC driver managers and ODBC drivers. It’s an low-level API used to interact
with DB.
DAO: provides object model for DB programming. Provides Automation Interfaces, Uses JET
/Access DB Engine
RDO: developed for VB programmers. Call ODBC API’s directly
ADO: Provides Automation Interface therefore used from scripting languages, Provides Object
Model for DB programming. Here like DAO no hierarchy of objects exists.
OLEDB: provides Com Interface alone. It doesn’t provide Automation Interface. Used to access
both Relational and Non-Relational databases
MFCODBC: acts as an wrapper to OBDC API’s. It’s considered as high-level DB interface.
What is Normalization?
To eliminate data redundancy, to eleminate inconsistent dependency , actually to speedup your application,
to incorporate the flexibility in the design so as to easily adopt to new changes
Outer Joins are almost similar to Inner Joins, but in Outer Joins all the records in one table are combined
with records in the other table even if there is no corresponding common value.
What is a Cursor?
When a SQL statement is executed oracle opens a private workspace area in the system called Cursor.
There are 2 types
Implict Cursor(all DML statement uses) Explicit Cursor (only used by the SELECT statement when
returning multiple records)
What is the Diff between Procedure and Function?
Both are PL/SQL named blocks used to perform a specific task . Only difference is a Procedure may or may
not return a value whereas Function must return a value. Note: Procedures:-Sophisticated Business logic
and application logic can be stored as procedures within oracle. Unlike procedures, functions can return a
value to the caller.
What is an Index table?
Its based on a sorted ordering of the values. Index table provide fast access time when searching.
First Level : Eliminate repeating of groups of data in each table by creating separate tables for
each group of related data. Identify each set of related data with a primary key
Fourth Level: in many-to- many relationship independent entites cannot be stored in the same
table (most developers ignore this rule)
Fifth Level : the Original Table must be reconstructed from the tables into which it has been
broken down. Its only useful when dealing with large data schema
Zero Form : If a DB which does not complains to any of the Normalization forms. This type is
usefull only for data ware housing.
CANDIDATE KEY - an attribute that uniquely identifying a row. There can be more than one
candidate key in a table
PRIMARY KEY - a Candidate key that you choose to identify rows uniquely is called primary key.
There is only one PK for a given table.
ALTERNATE KEY -the Candidate keys that was not choosen as primary key.
COMPOSITE KEY : when a key is made of more than one candidate keys
FOREIGN KEY : used to relate 2 tables using a common attribute. When a primary key in one
table is available as an attribute in another related table is called FK.
It ensures that each row can be uniquely identified by an attribute called the primary key which
cannot be NULL.
Define ER Diagram ?
It’s a graphical representation of DB Structure. It has 3 things Entity (Table Name); Attribute
(Column Name); and RelationShip
Miscellaneous
Which of the following is the correct declaration for the function main() ?
ans: main( int , char *[])
if ptr is defined as int *ptr[][100]; which of the following correctly allocates memory for ptr?
ans: ptr = (int *)(malloc(100* sizeof(int));
Swapping Problem:
#define swap1(a,b) a=a+b;b=a-b;a=a-b;
main()
{
int x=5,y=10;
swap1(x,y); //swap action takes place
printf("%d %d\n",x,y);
swap2(x,y); //no swap action takes place
printf("%d %d\n",x,y);
}
int swap2(int a,int b)
{
int temp;
temp=a;
b=a;
a=temp;
return;
}
Ans : 10,5,10,5
The safest way is to use a named Mutex. You can do it like this:
BOOL CMyApp::IsAppRunning ( )
{
HANDLE hMutex = NULL;
hMutex = CreateMutex ( NULL, TRUE, _T("MySpecialMutexNameHERE") );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
{
CloseHandle ( hMutex );
return TRUE;
}
return FALSE;
}
Make sure you change the Mutex name to something unique for your app. Now, all you have to do from your
InitInstance() is :
if ( IsAppRunning () ) return FALSE;
The only problem with this function is that you leak the mutex handle when it does get created. It's not much
of a problem because it will get closed by Windows when the app exits (which is what we want, anyway), but
it's consider bad programming practice. For those of you more strict, here's another approach, provided by
Aaron J. Margosis, that uses a simple class. All you have to do is create an instance of the class when your
program starts and where it won't go out of scope until it exits (a member of your CWinApp-derived class will
be just fine):
// Uses named mutex to guarantee a single instance with the same name on this machine. If another
process has already created an instance
// with the same name, "First()" will return FALSE. The object must not be destroyed until the process exits.
class OnlyOne
{
public:
OnlyOne( LPCSTR mutexName )
: m_mutex( CreateMutex(NULL, TRUE, mutexName ) ),
m_error(GetLastError() )
{}
~OnlyOne()
{
if ( m_mutex)
{
CloseHandle( m_mutex );
}
}
BOOL First() const
{ return ( m_error == 0 ); }
private:
// These MUST be declared in this order:
HANDLE m_mutex ;
DWORD m_error ;
private:
// Not implemented:
OnlyOne( const OnlyOne & );
OnlyOne & operator = ( const OnlyOne & ) ;
};
Once again, pick a unique name for the mutex for each app you use any of the above methods in. One way
to virtually guarantee that the name will be unique is to use the textual representation of a GUID generated
for each app, which you can use using guidgen.exe or similar tool
How can I find the path my application or DLL was loaded from?
Use The Win32 API GetModuleFileName();
The main COM enabling MFC class is CcmdTarget. CcmdTarget is derived from Cobject class.CcmdTarget
implements Iunknown Interface.
CcmdTarget handles
1) Windows messages using Message Maps
2) COM Interfaces using Interface Maps
3) Automation using Dispatch Maps
4) ActiveX controls using Event Maps
Fundamentally all these maps work the same way. A map consists of key-value pair.
Incase of Windows, message ID and pointer to message handling function
Incase of Interfaces, Interface ID and pointer to Vtable for those interfaces
Lets see how CcmdTarget actually work
1) Multiple Inheritance
2) Interface Implementation
3) Nested Classes
Note: MFC uses the Nested Classes by default
Multiple Inheritance
Class Cdemo: Public Iunknown, Public Idemo1, Public Idemo2
{};
Interface Implementation
Nested Classes
BEGIN_INTERFACE_MAP()
INTERFACE_PART()
END_INTERFACE_MAP()
Ex: CDEMO.H
Class Cdemo: Pulbic Iunknown
{
BEGIN_INTERFACE_PART( Demo1Cls, Idemo1)
STDMETHOD_ (void, SomeFunction());
BEGIN_INTERFACE_PART(Demo1Cls)
Cdemo:: Cdemo()
{
AfxOleLockApp();
}
Cdemo:: ~Cdemo()
{
AfxOleUnLockApp();
}
STDMETHODIMP Cdemo:: Xdemo1Cls:: Square(Int n, LPLONG lpResult)
{
METHOD_PROLOGUE(Cdemo, Demo1Cls)
lpResult = n * n;
return NOERROR;
}
Creating CM Objects
COM Object is identified by CLSID.The com runtime will interrogate the registry to find the server and load it
if it is not already loaded . The server will then create a classfactory object whose job is to create the actual
object that implements the interface. When the object has been created, a pointer to its Vtable gets returned.
MFC Implements the Iclassfactory interface in the ColeObjectFactory class.
COM terminology to threads is slightly different. There are three types of threading models in COM. They
are apartment threading, free threading and rental threading ( introduced for MTS ) The closest analogy to
Win32 is that UI threads are analogically similar to the Apartment threading model and worker threads are
analogically similar to the Free threading model.
Sockets
A Socket has 3 primary components
the interface to which it is bound (ip address)
the port no: ( to which it will be sending/receiving data)
the type of socket (either STREAM/ DATAGRAM)
Socket : is an object through which window socket application Send/Receive packets of data across the
network
Port : identifies a unique process for which a service can be provided .Certain ports are reserved for
common services like FTP, HTTP, etc.
Sockets Types:
1) STREAM Socket ->(Sync) – Bidirectional, Sequenced and Unduplicated (Ex. Telephone call)
2) 2) DATAGRAM Socket ->(Async)–Bidirectional,Non-Sequenced and Duplicated (BroadCasting)
Syn – waits for response // GetMessage() //Blocking
Async - Doesn’t wait for response // PostMessage //Non-Blocking
Syn –
1) TCP/IP protocol
2) each packet has a header and footer and a sequence No: in which it has to be transferred
3) each packet has to be acknowledged by the receiver. If not then the packets will be retransmitted
4) its slow
5) its reliable
6) sequence
Async -
1) UDP packets
2) encapsulate window socket API’s at low level
3) used to handle Socket API directly and Dealing with N/W notification events
4) here you have to handle
a) blocking scenerios
b) byte order diff betwn sending and receving m/c’s
c) converting between Unicode and multibyte character set strings
5) used for broadcast
6)non reliable and non Sequence
7) but Fast
int main()
{
try
{
f();
}
catch(Base b)
{
b.what();
}
try
{
f();
}
catch(Base& b)
{
b.what();
}
} ///:~
The output is
Base
Derived
Auto-ptr : is defined in <memory> . It holds a pointer and deletes the object pointed to at the end of the
scope. Its an very light weight class. Its not a reference counted pointer. It can hold pointer to individual
element alone and not a pointer to an array.
auto-ptr<int> ptr (new int);
~A() { A(); } -> compiles successfully and displays the output until the stack gets overflow
main()
{
A();
~A(); -> Error. You cannot call the destructor directly from
outside.
}
Note :
• If a function is going to “return by reference” then the returning value should not be local
to the function
• For( ; 7>8 ;) -> do not create infinite loop.
• For(; ; ) and while(1) and while (!0); and for(int I=0; I<1; I) -> creates infinite loop
• Comments cannot be nested (/* /* … */ */ )
• Char a[] is not same as Char* a;
• Char a[5]; a= “hello”; is an Error. Only you have to use strcpy(a, “hello”);
• #pragma once -> is used to avoid multiple definations of “# include” files
• Do not redefine non-virtual functions down the hierarchy
Malloc -> Takes one parameter / single block of memory is allocated / holds garbage / needs
typecasting
Calloc -> Takes two parameter / multiple blocks of memory is allocated / holds zero / needs
typecasting
Int* p = (int*)malloc(n*2) / int p =( int*)calloc(n,2)
CbV : here values are copied CbR : here address are copied
While -> first tests the codition and if true executes its statement
Do-While -> First executes the statement and then tests the condition
Enum is an user-defined data type that is limited to a fixed list of integer values alone. Internally compiler
treats enumerated variables as integers alone. TypeDef allows to rename a datatype(both defined and user
defined datatypes)
Enum A { one, two, three }; enum A a; a = one;
Typedef unsigned long tl; tl var1;
int main()
{
CA * pa = new CA;
CB * pb = new CB;
IX * x = pa;
Foo(x);
X= pb;
Foo(x);
}
here CA and CB have separate and different instance data, vtbls and implementations.
As long as the interface don’t change the client or the component can change without breaking the entire
system. This allows new components to replace older components without breaking the entire
system.
Reference counting is a simple and fast method for enabling components to delete themselves. A
COM component maintains a number called reference count. When this reference count goes to 0
the component deletes itself from memory. Ton use reference counting you have to know only 3
simple rules:
1) call AddRef before returning the interface (queryinterface and createinstance does this)
2) call Release when you are done.
3) Call AddRef whenever you assign an interface pointer to another interface pointer.
COM Library has to be initialized only once per process by calling CoInitialize. If it has been called for a
process already then it will return S_FALSE instead of S_OK. Since it has to initialized only once per
process and COM Library is used to create components in-proc components don’t need to initialize the
library. The general convention is to handle COM initialization in EXE’s and not in DLL’s. A Coinitialize has to
paired with counintialize.
OLE is build on top on COM. OLE Library contains extra support . Ole is called by using oleinitialize and
oleunintialize. The ole* function calls internally Co* functions. However using ole* instead of Co* wastes
resources and time . In DCOM use CoInitializeEx to mark a component as Free-Threaded.
Objects must be created before they can be used. If objects creation is different for every object it becomes
harder to use different objects polymorphically. Therefore we want object creation to be as flexible as
possible so that all components can be created in a similar manner. When cocreateinstance method call is
finished the component is already created which is too late to put conditions on its creation. The solution to
this is to make explicit use of another component whose sole purpose is to create component we want. Now
here comes the classfactory concept.
Behind the scences cocreateinstance creates a component called classfactory which then creates desired
components. The client uses IclassFactory for controlling how the classfactory creates each component.
Cocreateinstance takes a CLSID and returns a pointer to an interface in a component
Classfactory takes a CLSID and returns a pointer to an interface in the class factory.
To this we use CoGetClassObject which returns the requested pointer to the class factory while
cocreateinstance returns pointer to the component itself. CoCreateInstance takes an Iunknown pointer while
CoGetClassObject takes a COSERVERINFO pointer(which is used by DCOM to control remote
components)
Note: There is another interface IclassFactory2 which adds licensing or permissions to IclassFactory. Using
this classfactory can ensure that client is authorized to use the component.
CoCreateInstance is actually implemented using CoGetClassObject.
CocreateInstance(…, void** ppv)
{
IclassFactory * pFactory = NULL;
CoGetClassObject(…,(void **)&pFactory);
pFactory ->CreateInstance(…,ppv);
}
There are 2 cases in which CoGetClassObject should be used instead of CoCreateInstance.
1) whenever you want to use IclassFactory2
2) whenever you want to create a bunch of components all at one time
Using Classfactories is much more confusing than letting CoCreateInstance do the work for you
Note : CoGetClassObject calls the function DllGetClassObject which actually creates class factory.
If your application is already an EXE then you have to implement components as EXE’s instead
of DLL’s. Every EXE runs in a different process.The logical address in one process access a different
physical memory location.
If a component is in a DLL your client can easily access the memory because the component and the client
are in the same address space. But if the client and component are in different address spaces the client
can’t access the memory in the components process. If client can’t access then our interfaces would be
pretty useless. There are many options for communicating between processes including DDX, named pipes
and shared memory. However COM uses LPC. LPC’s are a means of communication between different
processes on the same machine. LPC’s are implemented by the operating system and it knowns how to
handle it. IF both the processes are on the same machine marshalling is fairly straight forward. The data in
one process needs to be copied to the address space of another process. If the processes are on different
machines the data has to be put into to a standard format fro the differences between machines.
To marshal a component implement an interface named Imarshal. The main reason for this is to improve
performance.
If the client to communicate with in-proc,local and remote components worry about LPC’s then the goal of
local transperancy is lost. COM achieves this by using Proxy/Stub dlls. The MIDL compiler takes IDL file and
generates
C-Code for the proxy and stub DLL.
FOO.H -> contains declarations of all the interfaces described by IDL file (Interface
declaration)
FOO_I.C -> defines all the GUIDs used in the IDL file. (Interface
GUIDs)
FOO_P.C -> implements the proxy and stub code for the interfaces in the IDL file(Proxy/ Stub Dlls)
DLLDATA.C -> implements the DLL that contains the proxy and stub code. ( Dll Code)
Idispatch
Automation focuses on run-time type checking and compile-time type checking. An automation
server is a cOM component that implements Idispatch interface. An Automation controller doesn’t directly
call the functions implemented by the automation server.Instead it uses the member functions in the
Idispatch interface to indirectly call functions in the automation server.
A DISPID is not a GUID but just a long integer . The DISPID identifies a function. Automation controller
passes DISPID to invoke member function. The invoke function can use DISPID as an index in an array of
function pointers.
A set of functions implemented by an Idispatch::Invoke() implementation is called a dispatch interface or
Dispinterface for a short. Dispinterface contains an array of function names and an array of function
pointers indexed by DISPID’s.
It’s a COM interface that implements Idispatch::Invoke inherit from Idispatch instead of
Iunknown. A Dual interface is a dispinterface that makes all the functions that are available through Invoke
also available directly through the Vtbl . Dual Interfaces allow C++ programmers to make their calls via the
Vtbl ; such calls not only are easier for C++ programmers to implement but executes faster. Instead of
calling through the vtble scripting languages can call via the invoke method. A VB program can either
connect to dispinterface part or vtbl part of a dual interface.
TypeLibrary
The compiler ensures at compile time that the correct argument types are passed to each
function using the header file. But, We have not provided VB with an equivalent to the C++ header file. Only
the VARIANT structure make this possible. You can resolve this by replacing C++ header file with
Typelibrary. VB doesn’t require a header file it uses VARIANT which allows us to almost completely remove
static type checking in favour of having the component check types at runtime but its very time consuming
and also lead to program errors. Therefore we need a language equivalent of C++ header files . The solution
in COM is typelibraries, which provide type information about components , interfaces, methods, properties,
arguments and structures. The content of a typelibrary is the same as that of a C++ header file. A
typelibrary can be accessed programmatically. Its an Binary file. Without typelibrary VB is limited to
communicating to components through DispInterfaces. If a typelibrary is available VB can access
component through Vtbl part of its dual interface. Access through Vtbl is typesafe and faster.
To create type library use automation library function CreateTypeLib which returns IcreateTypeLib interface
which is used to fill the type library information. IDL and MIDL compilers are used to build type libraries.
To use type library use LoadRegTypeLib which attempts to load type library from the windows registry . If
you use LoadTypeLib is loads from disk.
Typically Win32 application has 2 kinds of threads : 1) UserInterface thread and 2) Worker
Thread
User-Interface threads are associated with one or more windows. These threads have message loops that
keep the windows alive and responsive to the users input. Worker thread are used for background
processing and are not associated with a window. Worker thread usually don’t have message loops. A single
process can have multiple user-interface threads and multiple worker threads.
The thread that owns a window is the thread that created the window. So the window procedure is always
executed on the same thread regardless of the thread that sent the message it is processing.The end result
is that all messages are synchronized. Windows are guranteed to get messages in the proper order. Writing
thread-safe code is very time consuming.
COM instead of calling user-interface thread uses the term apartment thread. The term free thread is
used instead of worker thread. An apartment is a conceptual entity consisting of a user-interface style
thread and a message loop.
Note : In-proc components don’t have their own message loops but instead share the message loop of
their client EXE.
The Out-of-proc server for the component provides it with a message loop.
Apartments are similar to Single threaded processes in all the foll aspects:
A process has its own message loop. An apartment has its own message loop. Function calls within a
process and function calls within an apartment are not marshaled. Synchronization of function calls across
processes or across apartment boundaries is performed through the message loop. As a final detail, each
process must initialize the COM library. Likewise each apartment must initialize the COM library
Process Boundary
CoInitialize CoInitialize
Client Component
Component
Marshalling takes place
CoUnInitialize
CoUnInitialize
Apartment Boundaries
An Apartment thread is one and only thread found in an apartment. An apartment thread owns the
component component it creates. A component in an apartment will be called only by the apartment thread.
If the thread send a message to a window owned by a different thread, windows places the message into
the message queue for the window. If another thread calls a method on our component which is in an
apartment the COM places the call into the queue for the apartment. The message loop pulls the call off and
calls the method on the apartment thread.
Free Threaded
COM Synchronizes calls to components on apartment threads. COM doesn’t synchronize calls to
components created by FreeThreads. If a component is created by a free thread it can be called by any
thread and at any time. The developer of the component must ensure that the component synchronizes
access to itself.The component must be thread safe. Free threading moves the burden of synchronization
from COM to the component.Since COM doesn’t synchronizes calls to component, free threads don’t need
message loops. A component created by a free thread is considered as a free thread component. The
component is owned by the thread that created it but is sharing among all threads can be accessed freely be
all threads.
Note: A apartment thread is similar to win32 process in that both have a single thread and a message loop.
A single process can have any number of apartment threads and free threads. Only the thread that created it
must call a Component created in an apartment thread.
User-interface code must use apartment threads. If you need only to perform a simple operation in
background use free threads. They are much easier to implement. Moreover all calls to an apartment thread
must be marshaled .This can be a significant performance hit.Calls between free threads in the same
process are not marshaled and can be much faster, depending on how the component implement their
synchronization code.
DNA: - Ideal to design and implement robust distributed application Providing Client Transparency and Fault
Tolerance. It takes care of plumbing work to connect separate parts to work together. It provides full Tx
processing support
Fault Tolerance - no N/W is guaranteed to give continuous and fast performance. Therefore it provides a
way to cope with N/W delays and S/W failures while protecting the data integrity.
MTS: - It’s a service available to the client in the background providing support to Manage both
Component and Tx. It also provides service to applications that don’t use Tx. As a service it
allocates, activates, deactivates instance of component that are used by your application. This can
improve response time and resource availability. As a Tx Processor allows to build a reliable and
robust data management application much simpler, especially in distributed application where the
data resides on different / remote servers.
MTS can be managed using “ Tx Server Explorer” and in NT we call MMG (Microsoft Management
Console)
In WinNT add reference to “MTS Type Library” to VB Project whereas in Win2k use “COM+ service type
library”.
Component Creation and Destruction problem is solved by providing a pool of component instances like
connection pooling. MTS can provide a component to an application on demand and allow other application
to use the same component when the first one is just hanging on to the component instance. It does this by
fooling the application into thinking still it holds a reference to the component when infact MTS has stealed it
away while application was not looking and given it to someone else. If the first application suddenly want to
use the component then MTS rushes around the pool and steals one and handle it back to the application.
If it doesn’t find none in the pool it will immediately create one and handle it back to client. MTS achieves
this by using a context object to the application where the application thinks this as a real component. But
what MTS has given is just an empty shell.
Tx Server
MTS provides a context for each application wherein the client don’t realize that the object they are referring
are being shuffled around behind the scenes. Every Context object exposes a COM Interface IobjectContext
using which a Tx can be Committed/Aborted/Disabled/Enabled/ Check Security Issues.
Similarly IobjectControl is used to activate and deactivate the component. //Even it exposes CanBePooled
()//
We often need to carryout Tx operation that spans different Databases, which may be on different servers
and even at different locations. MTS can do this for us automatically. MTS internally uses DTC (Distributed
Tx Coordinator) and RM (Resource Manager) to achieve this.
In VB New and CreateObject are used to create instance of a component. MTS adds another
method to it called CreateInstance ().
New: -. MTS creates a private instance of an object after which MTS will provide no support and
the object have to look after itself. Should not be used to create MTS objects
CreateObject: - MTS creates a new separate instance, which will run outside the current Tx. MTS will
provide a new context object to it.
CreateInstance: - MTS creates a new instance, which will run inside the current Tx.
All the Tx information will be copied to this instance. MTS will provide a new context
object to it.
Atomicity: - If all the actions within a Tx either complete successfully or none be executed at all.
Consistency: - If all the actions within a Tx doesn’t break any rules laid for that environment. Meaning
Data Integrity is absorbed.
Isolation: - If all actions within a Tx gives the same result when running these actions one at a time serially
(one after another). If results are different then Tx is not isolated
Durable: - If all the actions within the Tx stores their result in a permanent device before they report
success.
Provides one of the simplest solutions for communication between distributed system in diff environment
and guarantee the delivery of messages even if the system shut downs.
What is DOM?
DOM is Document Object Model API’s designed to allow programmers to access their information without
having to write a parser in their programming language of choice. Thus by using either DOM or SAX API’s
your program is free to use whatever parser it wishes. These APIs are available in all languages (java.
C++. Etc). The Textual information in your XML document gets turned into a bunch of Tree nodes wherein
you can access your information only by interacting with this tree of nodes. DOM preserves the sequence of
elements that it reads from XML document because for DOM it really matters because DOM by default
creates an object model for you.
What is SAX?
SAX is Simple API for XML. SAX API’s designed to allow programmers to access their information without
having to write a parser in their programming language of choice. These APIs are available in all languages
(java. C++.etc). The Textual information in your XML document doesn’t get turned into a bunch of Tree
nodes, but as a sequence of Events. SAX is faster then DOM. SAX doesn’t provide object model for you,
therefore here we have to create our own custom object model and write a Event handler class that listens
to SAX Events and does element to object mapping. It can fire events for every open and close tag, for
#PCDATA and CDATA sections and also fires events for DTD’s, comments and Instructions.
If you XML document contains document data then DOM is the perfect solution.
If you XML document contains structured data/ machine readable (sql and Xql queries, resultset) then SAX
is the perfect solution.
Explain about Lex, Yacc , Flex and Bison?
In general the Compiler or Interpreter for a programming language is often decomposed into 2 parts:
1) Read the source program and discover its structure
2) Process this structure
Lex and Yacc can generate program fragments that solve the first task.
The task of discovering the source structure again is decomposed into subtasks:
1)Split the source file into tokens (Lex)
3) Find the hierarchical structure of the program (Yacc).
Lex is a program generator designed for processing character input streams.
Yacc is a general tool for describing the input to a computer program. It specifies a structure and control of
flow.
Flex is a tool that reads the given input file for generating scanners (an exe file)
Bison is a general purpose Parser generator that converts a grammar description into a C program to parse
that grammar.
Bison is upward compatible with Yacc. Yacc grammars will work with bison with no changes
InGeneral:
Overloading : Different Signature, Same Scope , Same Name and Virtual Not Required
Overridding : Same Signature, Different Scope , Same Name and Virtual Required
Used when the existing implementation has to be replaced / modified in the subclass
NEW OPERATOR : allocates memory , initialize the object , returns the correct pointer type and it can be
overloaded
PASS BY REFERENCE - > 1) Memory consumption 2) Avoids Slicing Problem (context of the object is
used instead of object type when invoking functions) .
Pass By Reference means the passing the address itself rather than passing the value. Passby Value
means passing a copy of the value to be passed.
//-----------------------------THUMB RULE------------------------------------------------------
Adv of DAO
Better performance , Compatibility with ODBC, ability to specify relationship between tables , provide access
to validation rules , support DDL and DML
Note:
DAO works with 32 bit whereas ODBC works with both 32and 16 bits
DAO does heterogeneous joints for you, whereas ODBC forces you to do it
DAO snapshots are read only while ODBC is updatable.
ADO
If you are developing an application that access data from datasource ranging from mainframe to desktop or
if you are building a web application designed to provide user the datasources then ADO is selected.
DDX : used to initialize the controls entered by user
DDV : used to validate the data entered by user
RFX: used to exchange data between database table and recordset variables
DLL
Introduction
DLLs (Dynamic Link Libraries) are very useful when you're writing of programs that all use common
functions. In such a case, you can create a library that they all call functions from. Another interesting use
would be to create plug-ins for your application.
When application loads dll it allocates memory from its private heap area for dll to reside. If more than one
application loads the same dll then win32 uses memory mapping system which loads the dll only once into
the global heap and then maps this dll’s address into the address space of each application that needs to
load this dll.
Dll will have only one instance whereas exe can have multiple instances. Two running instance of an
application share code but each has its own data segment. But incase of Dll’s they share both code and
data segment.
Creating a dll is nothing too far out. Basically, you write your functions then compile them. create a new
project and set the target as a Win32 Dynamic-Link Library and compile which should produce a dll, an
import library (.lib), and an export library (.exp). Here is a sample DLL
#include <iostream.h>
#include <stdio.h>
#include <windows.h>
#endif
#define MAXMODULE 50
char module[MAXMODULE];
extern "C" __declspec(dllexport) void NumberList()
{
GetModuleFileName(NULL, (LPTSTR)module, MAXMODULE);
cout << "\n\nThis function was called from " << module << endl << endl;
cout << "NumberList(): ";
for(int i=0; i<10; i++)
{
First lets look at how to use our DLL using the import library (dlltest.lib) that was one of the resulting files
from compiling the DLL above. This method is the easiest because all you really have to do is include
the header file, then include the import library when you're linking your objects. That's it. Here's an
example
void main()
{
NumberList();
LetterList();
getch();
}
The code above will work fine if you have your dlltest.h header file in your compiler's header path, and the
dlltest.lib import library in the lib path. You also need to link your import library with your other modules when
linking. Be warned though, when you run the resulting executable, the DLL must be in the path or in the
same directory as the executable otherwise it will have an error. That's the whole point. But if you had 10
programs that use the same DLL, you can put one copy of the DLL in a common directory.
dllrun01.exe Output:
This function was called from C:\DLLTEST\DLLRUN01.EXE
NumberList(): 0 1 2 3 4 5 6 7 8 9
This function was called from C:\DLLTEST\DLLRUN01.EXE
LetterList(): a b c d e f g h i j k l m n o p q r s t u v w x y z
Now we'll look at how to load the DLL on the fly. This is useful for things such as if you don't know what the
dll is called before-hand (for example the plug-in system I mentioned earlier). Here's the example code:
DLL Test Source File (dllrun02.cpp) - Win32 Console Application:
#include <windows.h>
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#define MAXMODULE 50
cfunc NumberList;
cfunc LetterList;
void main() {
HINSTANCE hLib=LoadLibrary("DLLTEST.DLL");
if(hLib==NULL) {
NumberList=(cfunc)GetProcAddress((HMODULE)hLib, "NumberList");
LetterList=(cfunc)GetProcAddress((HMODULE)hLib, "LetterList");
if((NumberList==NULL) || (LetterList==NULL))
{
NumberList();
LetterList();
FreeLibrary((HMODULE)hLib);
getch();
}
The code should load our library (assuming its in the path), then get the addresses of the two functions that
we want to call. I'd recommend that you be careful when calling functions from dlls without import libraries.
There's a lot more code to write (loading each function/library), and a lot more room for errors if your dll isn't
correct. So if you don't need to do it this way, I wouldn't. That's up to you.
dllrun02.exe Output:
Library loaded: C:\DLLTEST\DLLTEST.DLL
This function was called from C:\DLLTEST\DLLRUN02.EXE
NumberList(): 0 1 2 3 4 5 6 7 8 9
This function was called from C:\DLLTEST\DLLRUN02.EXE
LetterList(): a b c d e f g h i j k l m n o p q r s t u v w x y z
(*fproc)();
Extension DLL
};
Client :
#include “sample.h”
void view::Firedll()
Csample obj;
Obj.Fire();
//---------------------------------------------------------------------------------------------
• In load-time dynamic linking, a module makes explicit calls to exported DLL functions. This requires
you to link the module with the import library for the DLL. An import library supplies the system with
the information needed to load the DLL and locate the exported DLL functions when the application
is loaded. For more information, see Load-Time Dynamic Linking.
• In run-time dynamic linking, a module uses the LoadLibrary or LoadLibraryEx function to load the
DLL at run time. After the DLL is loaded, the module calls the GetProcAddress function to get the
addresses of the exported DLL functions. The module calls the exported DLL functions using the
function pointers returned by GetProcAddress. This eliminates the need for an import library. For
more information, see Using Run-Time Dynamic Linking.
Mydll.def
makefile
Compiler
Compiler
Mydll.exp Library Mydll.lib
Linker Manager
Linker
Mydll.dll
MyClient.exe
In Short
If a DLL is compiled it generates .lib, .obj, .dll (.def files are created by VC++ tool)
makefile compiles and creates the dll. It creates the .obj file
.lib – contains only function ordinals. Its used by the compiler
.obj – contains function code in binary format
.dll – contains total function code in binary format ( can be made up of many .obj files)
.def – contains what all the functions that are exported to or imported from external agencies
and describes about library manager
Static Linking
You include a lib code as part of your code itself.
Requries .lib and .h file for compilation and No Dll required at run-time, since
the lib file will contain the code within it in this process (if the project is
Win32 Static library type)
Rebuilding of system is required if any updations (if any function signature or code changes) are
made to library.
Dynamic Linking
At runtime the application picks up the dlls. (if the project is Win32 Dynamic-Link
Library type)
2) Explicit : we use LoadLibrary() and GetProcAddress() . Here no need of .lib and .h files. Requires
dll location alone.
Rebuilding of system is required if any updations (any function signature changes alone and not
to bother about code change)are made to library.
Threads
This is a simple application that creates 3 threads and runs them simultaneously. The work of the threads
(i.e. what they actually do is explained inside the code).
First, always include <windows.h> for all the Win32 specific thread information
#include <windows.h>
#include <iostream.h>
#define MAX_THREADS 3
// Prototypes are good and handy, but not necessary in this example. These three functions are run by each
of our three //threads Please note how the functions are declared: In Win32, thread functions MUST be
declared like this:
// DWORD WINAPI <name>(LPVOID);
// In short, Return value *must* be DWORD WINAPI And the parameter must be LPVOID
// NOTE: In the next line, we make a pointer and cast what was passed in.
// This is how you use the LPVOID parameters passed into the CreateThread call (below).
// Get ready, because here's where all the *REAL* magic happens
int main(int argc, char* argv[])
{
int CONSTANT = 2000;
char myString[20];
strcpy(myString,"Threads are Easy!");
// Here is where we call the CreateThread Win32 API Function that actually creates and
// Begins execution of a thread. Please read your help files for what each parameter
// Does on your Operating system.
hThreads[0] = CreateThread(NULL,0,genericThreadFunc1,(LPVOID)0,NULL,&id[0]);
hThreads[1] = CreateThread(NULL,0,printString,(LPVOID)myString,NULL,&id[1]);
hThreads[2] = CreateThread(NULL,0,printNumber,(LPVOID)CONSTANT,NULL,&id[2]);
// Now that all three threads are created and running, we need to stop the primary thread
// (which is this program itself - Remember that once "main" returns, our program exits)
// So that our threads have time to finish. To do this, we do what is called "Blocking".
// We're going to make main just stop and wait until all three threads are done.
// This is done easily with the next line of code. Please read the help file about
// the specific API call "WaitForMultipleObjects".
waiter = WaitForMultipleObjects(MAX_THREADS,hThreads,TRUE,INFINITE);
// After all three threads have finished their task, "main" resumes and we're now ready
// to close the handles of the threads. This is just a bit of clean up work.
// Use the CloseHandle (API) function to do this. (Look it up in the help files as well)
return 0;
}
MULTI THREADING
When working with Multithreading Mutual exclusion alone is not sufficient to solve the wrong
accessing of shared resources. We need both Mutual exclusion and Synchronization among threads to
access the shared resource sequentially.
In order to achieve synchronization we need a way for each thread to communicate with the others.
When a thread A produces a new value for the shared variable it must inform the thread B of this event.
Similarly when B thread reads the data value It must trigger an event to notify thread A about the empty
buffer. For this to implement introduce two event objects called hNotEmptyEvent and hNotFullEvent to
synchronize the thread A & B . Its important that the Thread A&B each wait for the event objects outside their
critical section; otherwise the program can deadlock where each thread is waiting for the other to make
progress. If we don’t release the mutex before waiting for the event object then this will lead to DeadLock.
#include "stdafx.h"
#include <iostream.h>
#include <windows.h>
#define FULL 1
#define EMPTY 0
int SharedBuffer;
int BufferState;
HANDLE hMutex;
HANDLE hNotFullEvent, hNotEmptyEvent;
void Producer();
void Consumer();
BufferState = EMPTY;
hMutex = CreateMutex(NULL,FALSE,NULL);
hThreadVector[0]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Producer,NULL, 0,
(LPDWORD)&ThreadID);
hThreadVector[1]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Consumer,NULL, 0,
(LPDWORD)&ThreadID);
WaitForMultipleObjects(2,hThreadVector,TRUE,INFINITE);
void Producer()
{
int i;
void Consumer()
{
int result;
while (1)
{
if (WaitForSingleObject(hMutex,INFINITE) == WAIT_FAILED)
{
cerr << "ERROR: Producer()" << endl;
ExitThread(0);
}
if (BufferState == EMPTY)
{
// nothing to consume
ReleaseMutex(hMutex); // release lock to wait
// wait until buffer is not empty
WaitForSingleObject(hNotEmptyEvent,INFINITE);
continue; // return to while loop to contend for Mutex again
}
if (SharedBuffer == 0)
{
// test for end of data token
cout << "Consumed " << SharedBuffer << ": end of data" << endl;
ReleaseMutex(hMutex); // end critical section
ExitThread(0);
}
else
{
// got Mutex, data in buffer, start consuming
result = SharedBuffer;
cout << "Consumed: " << result << endl;
BufferState = EMPTY;
ReleaseMutex(hMutex); // end critical section
PulseEvent(hNotFullEvent); // wake up producer thread
}
}
}
Answer:
Produce :5
Consumed : 5
Produce : 4
Consumed : 4
Produce : 3
Consumed : 3
Produce :2
Consumed : 2
Produce :1
Consumed : 1
Produce :0
Consumed :0 end of data
Press any key to continue
UNICODE
ASCII character set is limited to 256 characters. This is fine for Latin based languages. (Upper-case, Lower-
case and Special Characters). But Asian and Eastern Languages contain more than 256 characters.
Unicode is a solution to solve 256 character ASCII limit problem. ASCII character is stored in one byte of
memory. To store larger character sets UNICODE increased to two bytes which provide a range of 65535
characters. Unfortunately doubling the byte size also causes compatibility problems. When programs in
windows program compiled for UNICODE they break. Therefore before developing decide whether your
program is to run Internationally or remain local to ASCII complaint markets.
VC++ provides some built-in support for UNICODE and MFC provides Macros that convert generic text to
UNICODE data type. To activate the UNICODE standard in VC++, select Build | Setting from file menu and
select C/C++ tab and append the _UNICODE value to the “Preprocessor definitions” field.
VC++ provides several MFC specific data types for making an application tolerant to international character
sets [to make the application fully portable to UNICODE, ASCII, DBCS (double byte character string) and
MBCS]
The developer only needs to change a few coding habits to write UNICODE friendly applications.
In your code replace char with TCHAR and string constant with TEXT macro
Ex: char str [100] è wchar_t str [100]
Void strcpy (char * out , char* in) è void wcscpy ( wchar_t * out, wchar_t * in)
TEXT (“hello boss”);
However, it is important to note that the above Generic Types are Microsoft extensions; they are not
ANSI compatible
XML FUNDAMENTALS
XML is a good replacement for EDI. EDI is expensive, it uses a dedicated communication infrastructure.
By using XML everybody knows that the same interpretation of the data is used.
It uses the Internet for the data exchange. And it's very flexible. XML makes communication easy. It's a great
tool for transactions between businesses.
<?xml version="1.0"?>
Structure of XML
<?xml version="1.0"?>
<root>
<element>
<sub-element>content</sub-element>
<sub-element>content</sub-element>
</element>
</root>
Try to avoid attributes. Software that checks XML-documents can do a better job with tags than with
attributes.
Well formed XML document means that the XML document applies to the syntax rules for XML. The Basic
Rules are (There are more rules pertaining to Entities)
_ it contains a root element
_ all other elements are children of the root element
_ all elements are correctly paired
_ the element name in a start-tag and an end-tag are exactly the same
_ attribute names are used only once within the same element
Companies that exchange XML-documents can check them with the same DTD.
DTD defines rules for a particular type of XML document. A DTD describes elements, Data. ( PCDATA
stands for parsed character data and CDATA will not be parsed or shown.) . An element can contain sub-
elements.
<!ELEMENT car (brand, type) >
<!ELEMENT brand (#PCDATA) >
<!ELEMENT type (#PCDATA) >
This means that the element car has two subtypes: brand and type. Each subtype can
contain characters.
XSL can convert XML documents into HTML. XSLT is used to describe how an
XML source document is transformed into another XML document that uses the XSL
1)Usage of XML ?
• XML can Separate Data from HTML (html is responsible for rendering data and xml is responsible
to hold data)
• XML can be used to Store Data
• XML can be used to Share Data
A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules of a
Document Type Definition (DTD):
9) Differentiate between SAX(Simple API for XML) and DOM (Document Object Model) ?
Here the textual information in the XML document gets turned into a bunch of tree nodes.
DOM gives access to the information stored in XML document as a hierarchical object model.
DOM creates a tree of nodes and we can access the information by interacting with this tree of nodes.
SAX chooses to give you access to the information in the XML document, not as a tree of nodes, but as a
sequence of events!
SAX doesnt create a default object model on top of the XML document (like DOM does).
This makes SAX faster, and also necessitates the following things to do:
• creation of your own custom object model which "holds” all the information in the XML document .
• creation of a document handler class that listens to SAX events and makes sense of these events
to create objects in the custom object model.
All SAX requires is that the parser should read in the XML document, and fire a bunch of events depending
on what tags it encounters in the XML document. The developer is responsible for interpreting these events
by writing an XML document handler class, which is responsible for making sense of all the tag events and
creating objects in your own object model.
SAX is faster than DOM, because it bypasses the creation of a tree based object model of information.
On the other hand, you have to write a SAX document handler to interpret all the SAX events (which can be
a lot of work).
11) What kinds of SAX events are fired by the SAX parser?
SAX will fire an event for every open and close tag, it also fires events for #PCDATA and CDATA sections.
Document handler has to interpret these events in some meaningful way and create own custom object
model based on them. SAX also fires events for processing instructions, DTDs, comments, etc.
If the XML documents contain document data then DOM is a completely natural fit. An example of this is
the Datachannel RIO product, which can index and organize information that comes from all kinds of
document sources (like Word and Excel files). In this case, DOM is well suited to allow programs access to
information stored in these documents.
However, when dealing with structured data DOM is not the best choice. SAX might be a better fit in this
scenario.
If your information is structured in a way that makes it easy to create this element to object mapping then
you should use the SAX API. On the other hand, if your data is much better represented as a tree then you
should use DOM.
1) how to resolve duplication of names when 2 or more xml documents are used in an application?
XML documents can contain foreign characters. To let the XML parser understand these characters, you
should save your XML documents as Unicode.
The purpose of a Document Type Definition is to define the legal building blocks of an XML document.
With DTD, your XML files can carry a description of its own format with it.
With a DTD, independent groups of people can agree to use a common DTD for interchanging data.
Your application can use a standard DTD to verify that the data you receive from the outside world is valid.
You can also use a DTD to verify your own data.
The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a
DTD.
An XML Schema:
5) DTD elements ?
<schema>
<?xml version="1.0"?>
<note xmlns=http://www.microsoft.com xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.microsoft.com note.xsd">
<to>sree</to>
<from>baskar</from>
<heading>message</heading>
<body>meet me during lunch </body>
</note>
8) How to define simple elements in XSD ?
xs:string
xs:decimal
xs:integer
xs:boolean
xs:date
xs:time
12) How to specify attributes that are mandatory ./ non-mandtory ? what is the key word used ?
13) How to set restricted/ acceptable values for XML elements or attibutes? What is the exact
terminology for this?
This part of code defines an element called "age" with a restriction. The value of age can NOT be lower than
18 or greater than 60:
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="18"/>
<xs:maxInclusive value="60"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Another great strength about XML Schemas is that they are written in XML.
Because XML Schemas are written in XML:
XML Schemas are extensible, just like XML, because they are written in XML.
With an extensible Schema definition you can:
To limit the content of an XML element to a set of acceptable values, we would use the enumeration
constraint.
This example defines an element called "car":
<xs:element name="car">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
The "car" element is a simple type with a restriction. The acceptable values are: Audi, Golf, BMW.
To limit the content of an XML element to define a series of numbers or letters that can be used, we would
use the pattern constraint.
This example defines an element called "letter":
<xs:element name="letter">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
The "letter" element is a simple type with a restriction. The only acceptable value is ONE of the
LOWERCASE letters from a to z.
To specify how white space characters should be handled, we would use the whiteSpace constraint.
To limit the length of a value in an element, we would use the length, maxLength, and minLength
constraints.
maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value)
maxInclusive Specifies the upper bounds for numeric values (the value must be less than or equal to this
value)
minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value)
minInclusive Specifies the lower bounds for numeric values (the value must be greater than or equal to this
value)
That should not have any content between the opening and closing tags.
The <any> element enables us to extend the XML document with elements not specified by the schema!
XSLT
XSL (eXtensible Stylesheet Language) is a language for expressing style sheets. It consists of three parts:
XSLT, XPath, and XSL Formatting Objects.
1) What is XSLT?
The XSL Transformations (XSLT) vocabulary provides a rule-based framework for selecting and processing
document content, and transforming it into new documents.
The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or
<xsl:transform>.
The match attribute is used to associate the template with an XML element. The match attribute can also be
used to define a template for a whole branch of the XML document (i.e. match="/" defines the whole
document).
XML Path Language (XPath) can be used as a general purpose query notation for addressing and filtering
the elements and text of XML documents. XPath is supported in the Microsoft® XML Parser (MSXML) within
XSL Transformations (XSLT), and through the Document Object Model (DOM) extensions selectNodes and
selectSingleNode
COM is not C++, and for good reason. COM objects are somewhat more complicated then their C++
brethren. Most of this complication is necessary because of network considerations. There are four basic
factors dictating the design of COM:
• C++ objects always run in the same process space. COM objects can run across processes or
across computers.
• C++ method names must be unique in a given process space. COM object names must be
unique throughout the world.
• COM servers may be written in a variety of different languages and on entirely different operating
systems, while C++ objects are always written in C++.
Note :When we write COM code we don’t use new and delete.
An Interface is a sort of Abstarct class but not exactly. An interface is nothing but a named collection of
functions. In C++ , a class can have only on interface. Whereas COM allows CoClass to have multiple
interfaces, each interface having its own collection of functions.
Public subset of a class is the interface to the outside world. Interface hides the guts of the class (private
section) from the consumer. Consumer sees only the public section. The interface is like a window into the
COM object. All COM interactions go through interfaces, and they shape that interaction.
Requests access to a specific COM • Starts the server (if required). If it is an In-Process
interface, specifying the COM class and server, the DLL will be loaded.
interface (by GUID) Executable servers will be run by the SCM.
A COM client is a program that uses COM to call methods on COM server. Four Steps to Client Connectivity
1. Initialize the COM subsystem and close it when finished.
2. Query COM for a specific interfaces on a server.
3. Execute methods on the interface.
4. Release the interface.
The MFC OLE classes provide most of COMs features. Perhaps the biggest problem with the MFC/OLE
approach to COM components is the complexity. OLE programming is difficult, and most programmers
never get very far with it. Because of the pain associated with OLE development, Microsoft created a new
tool called ATL (Active Template Library). For COM programming, ATL is definitely the most practical tool to
use at the present. In fact, using the ATL wizard makes writing COM servers quite easy if you don't have any
interest in looking under the hood.
A COM server is really a collaboration between several disparate components:
• Your application
• The COM subsystem
• ATL template classes
• "IDL" code and MIDL Generated "C" headers and programs
• The system registry
You won't find a single main() function that manages and controls the server.
An In-Process server is a COM library that gets loaded into your program at run-time. In other words, it's a
COM object in a Dynamic Link Library (DLL). Normally a DLL is loaded when LoadLibrary() is called. In
COM, you never explicitly call LoadLibrary(). Everything starts automatically when the client program calls
CoCreateInstance().Once loaded, the DLL has a class factory to create the COM object.
CoCreateInstance() returns a pointer to the COM object. You don't have to know anything about DLL's to
use COM. All you have to do is call CoCreateInstance(). One of the advatages of COM is that it hides these
details so you don't have to worry about this type of issue. Our main reason for selecting an In-process
server is somewhat more prosaic: It makes the example simpler. We won't have to worry about starting
remote servers (EXE or service) because our server is automatically loaded when needed. We also avoid
building a proxy/stub DLL todo the marshalling. Unfortunately, because the In-Process server is so tightly
bound to our client. A DLL server shares memory with it's client, whereas a distributed server would be much
more removed from the client. The process of passing data between a distributed client and server is called
marshaling. Marshaling imposes important limitations on COM's capabilities that we won't have to worry
about with an in-proc server.
NOTE: (Important)
One frequently asked question concerned threading models.
The easiest way to understand the difference is to think of apartment-threaded COM objects as single-
threaded, while thinking of free-threaded COM objects as multi-threaded.
In apartment threading, method calls from multiple clients are serialized in the COM object on the server.
That is, each individual method call completes its execution before the next method call can begin.
Apartment-threaded COM objects are therefore inherently thread safe.
Freethreaded COM objects can have multiple method calls executing in the COM object at the same time.
Each method call from each client runs on
a different thread. In a free-threaded COM object you therefore have to pay attention to multi-threading
issues such as synchronization.
Initially you will want to use apartment threading because it makes your life easier, but over time the move to
free threading may offer you more advantages.
The client and server program can be written identically, regardless of where the programs are running. This
concept is known as Local/Remote Transparency. This makes your job as a programmer much more
consistent. Connecting to a remote computer requires a whole new layer of objects and network traffic.
Like all COM communication, everything starts when the client requests an interface from a server. In
DCOM, the client calls CoCreateInstanceEx(), passing in a description of the server computer and
requesting a class identifier (CLSID) and Interface. This requestis handled by the Service Control Manager
(SCM), which is a part of Windows. The SCM is responsible for the creation and activation of the COM
object on the server computer. In the case of DCOM, the SCM will attempt to launch the server on the
remote computer.
Once the remote COM server has been created, all calls will be marshaled through the proxy and stub
objects. The proxy and stub communicate using RPCs (Remote Procedure Calls), which handle all the
network interaction. On the server side, the stub object takes care of marshaling. On the client, the proxy
does the work. The transmittal of data across the network is taken care of by RPC. Actually, DCOM uses an
extended type of RPC called an Object RPC, or ORPC. RPCs can run on a number of protocols, including
TCP/IP, UDP, NetBEUI, NetBIOS, and named pipes. The standard RPC protocol is UDP (User Datagram
Protocol). UDP is a connectionless protocol, which seems like a bad fit for a connection-oriented system like
DCOM. This isn't a
problem however; DCOM automatically takes care of connections. As you can see, distributed COM is
accomplished through a complex interaction of different hardware, operating system, and software
components. You should realize two important things from this: a) COM does a lot of work behind the
scenes, and b) there are a lot of things that can go wrong. At the time of writing, only the TCP/IP protocol is
available for DCOM data transfer on Windows 95/98 systems. This can be an annoying limitation, requiring
you to install TCP/IP on all Windows 95 systems, even when other network protocols are available.
Actually, you can make a server program run remotely just by changing registry settings. There are two
Microsoft tools to do this: OLEVIEW and DCOMCNFG. Both tools set the registry so that DCOM tries to find
the server on a remote computer. You can type in the remote computer name under the Activation tab of
OLEVIEW, and it will be started on that computer.
To activate our DCOM server we take the basic COM client shell and add some additional methods to make
it DCOM-ready. One obvious change is that we specify the name of the server computer. Here are the other
things we must add to the client:
• A way to specify the server computer name. This will load into the COSERVERINFO structure.
• Call CoCreateInstanceEx() instead of CoCreateInstance(). This also involves some different
parameters and a structure called MULTI_QI.
• The first thing you do in any COM program is call CoInitialize. We'll use the default-threading
model, which is apartment threading.
Calling CoCreateInstanceEx will populate the MULTI_QI array. Like most COM API functions,
CoCreateInstanceEx returns an HRESULT.This function typically returns any of three HRESULTs.
• S_OK. All interfaces were returned.
• CO_S_NOTALLINTERFACES. At least one of the interfaces was returned, but some others failed.
• E_NOINTERFACE. None of the interfaces could be returned.
The registration for DCOM is identical to standard COM. The server program will typically register itself
when
you run it with the -REGSERVER switch.
C:\> remoteServer -regserver
To use a proxy/stub DLL, you need to register it.
C:\> REGSVR32 remoteserverps.dll
This registers the proxy/stub DLL on the client so DCOM can automatically activate it. If you're using an
IDispatch (or dual) based automation client, you won't have a proxy/stub DLL. In this case, you'll use a type
library to register.
Security is a really important issue, especially for network applications. Eventually, you will have to ensure
that your DCOM application is secure. Once you understand the concepts and get the server working, then
you can add security to your application. My advice is to get things working before you introduce any
security.
Security varies between Win95/98 environments and Windows NT. Windows 95/98 offers some limited
security features. You can go wild with security on Windows NT. You can manipulate security settings for
both the client and sever in your program. This is done with the CoInitializeSecurity API call. You can use
this call to either add security or turn security off. You call this method immediately after calling CoInitialize.
Following is a listing of the client program. We will describe all the important parts of this code in the
following sections.
// RemoteClient.cpp : Defines the entry point for the console application.
} // main ends
By getting the system to work locally, you've eliminated most of the common programming and registration
errors. There are still a few things, like security and remote activation, that you can only test across the
network. Specify your local computer in the COSERVERINFO structure, which will exercise much of the
network-related code.
Be sure you can connect
Perhaps the most useful tool is PING.
Be sure you registered the COM server on the server computer. Be sure you registered the proxy/stub DLL
on both the client and server computer. If you're using an automation or dual interface, be sure the type
library is registered on both systems. (To register a proxy/stub DLL, use the REGSVR32 command.)
A common work-around is to refer to the server by its TCP/IP address. This will eliminate many name
resolution problems. You can easily put a TCP/IP address instead of a standard computer name into the
COSERVERINFO structure.
launch the server
If you're working with Windows 95/98, COM won't automatically launch a server. This limitation is
necessary because of the lack of security on these operating systems. Because Windows NT provides full-
blown security, it can automatically launch servers. The work-around for this problem with Windows 95/98
clients is simple. Manually start the server before the client connects. Once the server is launched, it will
connect normally.
My favorite solution is to run a simple "watchdog" program on the server computer. This simple application
always maintains a COM connection to the server. Because this program runs from the server computer, it
launches the server automatically when it starts. As long as the watchdog program is running, the server will
stay alive. If desired, you can start the watchdog program from the Startup group to bring the server up
when the machine boots.
DCOMCONF and OLEVIEW are two Microsoft utilities that show you registration information about your
COM servers. Both of these products show you registry information in a more structured format.
DCOMCNFG is a fairly crude tool. It shows a lot of information, but many people have trouble using it
effectively.
Re-Register the server and proxy/stub (or Typelib)
Sometimes re-registering the server and proxy/stub DLL can do wonders. If you're using Automation (or
dual) interfaces, re-register the type library.
An administrator may be able to help you resolve tough security and name resolution problems.
MSXML Example
MSXML::IXMLDOMDocumentPtr dptr;
MSXML::IXMLDOMNodeListPtr nlptr;
MSXML::IXMLDOMNodePtr nptr;
-----------------------------------------------------------------------------------------------------------------------------------------------
------------
. cpp file
#include <msxml.h>
::CoInitialize(0);
HRESULT hr = CoCreateInstance(CLSID_DOMDocument,0,CLSCTX_INPROCE_SERVER,
IID_IXMLDomDocument, (Void**) &dptr);
::CoInInitialize();
-----------------------------------------------------------------------------------------------------------------------------------------------
------------
Explain Polymorphism?
Its an OOPS feature known by the phrase “One Interface – Multiple Methods”.
Objects reacting to serve message differently.
Define Assert?
To identify error during the development of program
Define Trace?
To identify value of the variable during the execution of the program.
DeadLock : Its an Execution state for some set of threads. When each thread in the set is blocked waiting
for some action by one of the other threads in the set , now each is waiting on the others and none will ever
become ready again which causes in a DeadLock.
So a deadlock is one where 2 threads waiting for each other to release.
What is SOAP?
Simple Object Access Protocol
Corba uses IIOP (internet inter ORB protocol ) and DCOM uses ORPC (Object RPC) . Now to establish a
communication between these two protocol SOAP is the best solution.
Explain Usecase?
Captures the requirement of the system.
It’s a set of possible interactions in a system as its actor proceed towards a single defined goal.
Its used to generate Testcases.
Components of Usecase :
Name, Description, Outcome, Dependencies, Roles, Pre-condition , Post-Condition, Business rules ,
Requirements and Workflow.
What is N0-adhoc-Testcase?
Where no document exists. It just test the product blindly without any testcases.
COCOMO model (Constructive Cost Model) gives the relationship between Effort Vs Size .
Cost does not scale linearly with size
Activities of testing are => TestPlan -> test req -> testcase -> test data -> defect log -> feedback ---à
TestPlan
Struct P
{
const int size;
P(int sz):size(sz) //only way
{
}
};
What you will avoid doing when using with new operator?
Int count =0;
X * ptrx = new X(++count);
During this cases better to check whether new has successfully allocated memory or not before proceeding
further.
Arch of MTS
The architecture you create must address the following services -> performance, scalability, reliability,
availability, extensibility, maintainability, manageability and security.
Explain reliability?
As load increases the system handles the Tx as accurately as it did before the load increases.
Explain Availability?
Refers to the constant service been provided even if any individual component fails by making use of
redundancy component
Explain Extensibility?
Abiltity to correct flaws in the existing functionality without impacting other components of the system.
Instance variable represents a separate data item for each instance of a class, whereas class variable
represents a single data item shared by the class and all its instances.
You can’t. you must instantiate a class that implements the interface.
UML
1. What is UML?
The Unified Modeling Language (UML) is the industry-standard language for specifying, visualizing,
constructing, and documenting the artifacts of software systems. Using UML, programmers and application
architects can make a blueprint of a project, which, in turn, makes the actual software development process
easier.
3. Is UML a standard?
Yes. UML was adopted by the Object Management Group (www.omg.org) as a standard in November, 1997.
6. I already use project management software to plan my software development projects. Why
should I use UML?
Unlike project management software, which is designed to coordinate the various parts of a project in
relation to a timeline, UML-based diagrams can be used to show the interrelationships within a project from
an architectural perspective.
9. What is a process?
Defines Who is doing What, When to do it, and How to reach a certain goal.
RDBMS : a computer program that provides an abstraction of relational tables to the user. It provides 3
kinds of functionality 1) present data in the form of table 2) provide operators for manipulating the tables
and 3) support integrity rules on tables.
What does the new #import keyword do and why would I use it?
The #import keyword reads in a COM type library and produces a wrapper classe for the component's
interfaces. #import produces two files in the Debug or Release directory during this process. The
typelibraryname.tli and .tlh files contain simple wrapper classes that use the new Visual C++ native COM
support types. This types make accessing COM objects a bit easier. For example, here's some code that
imports a type library and uses the created smart pointer classes.
_bstr_t is part of Microsoft's compiler implementation, using CComBSTR may be a better approach if you
expect to target/compile your COM projects for other platforms such as Unix.
Should I use ATL's smart pointers CComPtr or the native _com_ptr_ type?
The primary difference is that _com_ptr_ supports exception handling and CComPtr does not. Also, the
comments above mentioned, if you want to use ATL on non-Visual C++ platforms, you should stick with
CComPtr because _com_ptr_ is only provided as part of Microsoft's C++ implementation.
Software Models
Waterfall Model
1)This model is simple to use 2) by dividing the project into different phases the lining up of skill set required
for the requirement become possible 3)only disadvantage is only very few projects can be divided into such
water-tight phases. 4) this model is based on reactive error correction rather than proactive error prevention.
This reactive mechanism is more expensive that proactive approach 5) In projects where requirements are
changing rapidly then this model is useless. Since lot of reworking and chances of propagated errors
increases significantly.
Spiral Model
1) Here the project software life cycle is visualized in terms of phases and sectors. 2) Each iteration starts
from a particulat sector and returns to that sector at a higher level than its starting point 3) It strikes a good
balance mechanism for early problem identification and correction while not missing out proactive problem
prevention. 4) Each iteration has a risk analysis sector that evaluates alternatives for proactive problem
avoidance. Also each iteration has a testing / Customer acceptance sector that takes care of error correction
at that level. 5)this model more suits to general purpose or system software development.
RAD
Disadvantage : For development it requires modeling tools and CASE tools, Continuous Customer
involvement
BASELINE
Is a process by which a given set of items formally become publicly available in a standard location to the
people who are authorized to use it. Activites of Baselining involves a) Freezing current version b) Allocating
a Configuration ID c) Allocating version No: d) storing approval authority information e) finally broadcasting
the above information to the concerned people.
Assert: basically it's a way of testing a piece of code is valid. This is accomplished using the ASSERT
macro. This macro is valid only when you are running a debug version of your program; it's ignored
completely under release.
Example : CWnd* pWnd = GetParent(); ASSERT(pWnd != NULL);
If you ran this, and for some reason pWnd was indeed NULL, you'd get a dialog box The assertion message
box contains the name of the source file and the line number at which the assertion failed. The main causes
of assertion failures are memory corruption and invalid parameters being passed to a class member or
Window API function.
The ASSERT macro is generally used to check function parameters and return values
Verify This routine is similar to ASSERT, except that it test the condition in both the debug and release
environments. The main difference is that VERIFY prints and exits (if necessary) only under debug. In
release mode, the expression is executed but not checked for validity.
Debugging Environment As you know, there are two kinds of executables you can create with Visual C++:
a debug version and a release version. Each of these versions uses different DLLs, and only the release
version can be distributed, owing to licensing restrictions on the debug DLLs.
Debug Vs Release you may have had the unsettling experience of discovering that your program works
just fine in debug, but fails in release. This problem is generally caused by access violations and can
generally be traced to one of the following factors.
• The Heap
• Compilation
• Pointers
• Optimizations
Heap: In the debug version, memory is allocated differently from the release version. The debug memory
allocator places guard bytes around allocated memory. These guard bytes serve to protect the allocated
memory from an overwrite (access violation), which is not available under the release version.To determine
if the guard bytes have been changed use two ASSERT( AfxCheckMemory() ); macros and move the first
ASSERT closer to the second one until you find the problem. (note the 2nd assert will be place at the last
line of the code under test)
Compilation: the ASSERT macro is commented out in release, so if you've put some important code (like a
call to allocate memory) inside an ASSERT block, you'll get a failure. Also, a different memory allocator is
used in debug than in release.
Pointers : When you build a release version of your application, the guard bytes are removed. Pointers that
have not been properly initialized are more likely to point to uninitialized memory than the debug information
that was added in the debug version
Optimization : By default, a release build is optimized for speed and size, and this can cause the compiler to
generate unexpected code. While optimization is generally the least cause of a release-build problem, it
does happen.
Dump The CObject::Dump() function is a debugging aid that lets you display the internal state of an object
in the debugger's output window. When running in debug mode, MFC will automatically call Dump() for any
CObject-derived object that is not properly destroyed when the program terminates
For example.
void CMyDate::Dump(CDumpContext &dc) const
{
CObject::Dump(dc);
dc << "Month = " << m_Month;
}
CMyDate myDate = new CMyDate;
myDate ->m_Month = 2;
myDate ->m_Day = 14;
myDate ->m_Year = 1999;
// now dump the contents
#ifdef _DEBUG
afxDump << "Dumping myDate:\n";
myDate ->Dump(afxDump);
afxDump << "\n";
#endif
Exception An exception is some abnormal, unexpected event that changes the normal flow of control and
signals the operating system to intervene. Exceptions are raised (or thrown) as a result of some
undetectable hardware or software event beyond the control of your program. Exceptions come in two
flavors: hardware and software. An example of a hardware exception is divide-by-zero. Passing a bad
parameter to a function, and not having sufficient memory to complete and operation, are examples of
software exceptions. Exception handling allows you to respond to exceptions.
throw statement without an operand rethrows the exception up the ladder. Object that is rethrown
is the original exception object, and not a copy.
Win32 Structured Exception Handling _ _try / _finally
MFC Exception Handling TRY, CATCH, THROW
MFC Exception Classes CException, CdaoException, CDBException, CmemoryException and
CfileException, CuserException, ColeException and
ColeDispatchException
CmemoryState
MFC includes the class CMemoryState for assisting in detecting memory leaks. It works only for finding
leaks that use the new allocator (that is, memory allocated but never freed with the delete command). One
of the class members is Checkpoint (). This is a way of taking "snapshots" of memory at different places in
your code stream. Another class member, Difference(), tell you if the state of the memory between the
checkpoints has changed.
DumpAllObjectsSince () -> dumps a summary of all allocated objects from a previous checkpoint.
DumpStatistics () -> displays memory allocation statistics for a CMemoryState object
Define FireWall
As many of you know, a firewall is a combination of hosts, routers, and associated software that partitions
your intranet from the rest of the Internet. The router component of the firewall implements packet filtering
and the host component implements application-level filtering.
Use packet filters to block traffic to and from the internal hosts that must have the highest level of security. It
is extremely important to configure routers to drop "spoofing" packets that claim to originate inside the
network but arrive on an external interface.
Application-level filtering takes place on a firewall host that is running service proxies. These proxies act as
an intermediate access control layer and hide internal network addresses from the outside.
If you want your site to be internal only, at minimum make sure your firewall blocks all traffic to port 80 on
your server. Then configure the web server to reject requests from Internet protocol numbers outside of your
domain.
If there is a link to a page on your site from another site that a search engine has indexed, your private
intranet site will eventually be indexed also. To solve this problem, password protect access to your site so
unauthorized remote users can't hit it.
How can I establish a dynamic two-dimension array with the new operator?
int (*my_array)[10];
int array_size;
/* assign a value to 'array_size' when you know the dimension you want */
delete []my_array;
If a constructor throws an exception, the object's destructor is not run. If your object has already done
something that needs to be undone (such as allocating some memory, opening a file, or locking a
semaphore), this "stuff that needs to be undone" must be remembered by a data member inside the object.
For example, rather than allocating memory into a raw Fred* data member, put the allocated memory into a
"smart pointer" member object, and the destructor of this smart pointer will delete the Fred object when the
smart pointer dies. The template std::auto_ptr is an example of such as "smart pointer."
There are cases where #define is needed, but you should generally avoid it when you have the choice
One reason executables can be large is that portions of the C++ runtime library might get statically linked
with your program. How much gets linked in depends on compiler options regarding whether to statically or
dynamically link the standard libraries, on how much of it you are using, and on how the implementer split up
the library into pieces. For example, the <iostream> library is quite large, and consists of numerous classes
and virtual functions. Using any part of it might pull in nearly all of the <iostream> code as a result of the
interdependencies (however there might be a compiler option to dynamically link these classes, in which
case your program might be small).
Another reason executables can be large is if you have turned on debugging (again via a compiler option).
In at least one well known compiler, this option can increase the executable size by up to a factor of 10
CString s = "Text";
CStatusBar* p = (CStatusBar*)AfxGetApp()->m_pMainWnd-
>GetDescendantWindow(AFX_IDW_STATUS_BAR);
p->SetPaneText(1, s);
C++ is the language itself Visual C++ is a compiler that tries to implement the language.
The <iostream> library allows you to convert pretty much anything to a std::string using the
following syntax // File: convert.h
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
#include "convert.h"
void myCode()
{
double x = ...;
...
std::string s = "the value is " + stringify(x);
...
}
Note: The expression o.str() returns the std::string that contains whatever has been inserted into stream o, in
this case the string value of x.
The <iostream> library allows you to convert a std::string to pretty much anything using the following
syntax
// File: convert.h
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
#include "convert.h"
void myCode()
{
std::string s = ...a string representation of a number...;
...
double x = convertToDouble(s);
...
}
overloading
allows C/C++ operators to have user-defined meanings
Can I overload operator== so it lets me compare two char[] using a string comparison?
NO.
Should I design my classes from the outside (interfaces first) or from the inside (data first)?
Outside first
In p = new Fred(), does the Fred memory "leak" if the Fred constructor throws an exception?
What if I forget the [] when deleteing array allocated via new T[n]?
No, it is nonsense. But that is redundant, since references are always const. You can't reseat a
reference.
Use an abstract base class. At the programming language level, an ABC is a class that has one or
more pure virtual member functions. You cannot make an object (instance) of an ABC.
Note: if it's a static member function of class Fred, its type is the same as if it was an ordinary function: "int
(*)(char,float)".
1)Standard Marshalling :
Marshalling takes place using proxies and stubs, which does the plumbing work for data to transfer
across boundaries. Proxies reside at Client end and stub resides at Server end. Each request from
server has to communicate with the proxy in the another end where it needs to cross the boundaries.
2)Custom Marshalling :
Custom marhsed component implements an interface called Imarshal to provide the code to make
sure the data transfer to happen across the n/w. This doesn’t provide proxies and stubs. Which means
you are transferring the entire COM object across the boundary.(to the client machine ) . Thereby you
avoid n/w traffic delay.
3)Typelibrary Marshalling :
If a AddressBook Server happened to be in Frankfurt (and the client is in Chicago), then each time I get
or set the property, it results in a costly round-trip over the network This is because my "Entry" exists on
the server in Frankfurt. When the Client in Chicago calls "AddEntry", the method call is remoted to the
Frankfurt server, which creates an internal IEntry implementation. It then "marshals" this interface and
returns this to the client in Chicago
COM, behind the scenes, creates a "Stub" on the machine in Frankfurt, which converts RPC method
calls into local method calls on my IEntry implementation. The Unmarshalled interface on the client in
Chicago results in COM creating a "Proxy" that implements "IEntry", by converting calls made by the
client into RPC method calls that connect back to the Stub in Frankfurt. In COM, this is called "COM
Standard Marshalling", because it's what you get by default when you pass an Interface between
apartments.
Each time I set a property on the client, it goes through the COM supplied "Proxy" which converts it into
an RPC call. This RPC call goes over the network and is invoked on the Stub in Frankfurt, which
converts it back into a method call that is made on the server IEntry implementation. Needless to say,
this is extremely inefficient, especially if we have a lot of properties to set. Each "getting" or "setting" of a
property results in a round trip over the network!
What is needed here is a more efficient interface. We need an IEntry interface that allows the client to
group together all of the required property changes into a single method call that results in only one
round trip
Fortunately, with Custom marshalling, COM gives us a way to have our cake and eat it too. Ideally, what
we want is the following to happen:
When the IEntry implemention on the Server is passed back to the client, a local "inproc" version of
IEntry is constructed in the client's apartment that has a copy of the properties contained in the server.
Then, when the client gets or sets properties, its local version of the IEntry interface just remembers the
changes, but doesn't actually communicate back to the server. Then, when the client calls "Commit()",
its local IEntry implementation connects back to the Server's "IEntryStream" interface and calls
"Update", once. Furthermore, if the Server is actually INPROC with the client, we don't want to bother
with any of this at all - we just return the actual IEntry interface directly to the client.
COM Custom marshalling allows us to implement this solution, in a way that is completely invisible to
the client. The client has no idea that this is how we are performing its changes, except that it will be
much faster!
The way that we indicate to COM that we wish to use Custom marshalling is by making our instance of
whatever object we want to marshal implement the "IMarshal" interface.
Basically, in COM, references to interfaces can always be "serialized" into a stream of bytes that can be
sent almost anywhere, or even saved to a file (but only for about 6 minutes before DCOM will garbage
collect it away). Another word for "Serializing"is "Marshalling" which is the term used by COM
Whenever you have a COM interface that you want to be able to use somewhere else, you have two
choices:
1. Pass it as a parameter in a method call on a COM interface (i.e. the normal way!)
2. Serialize it using "CoMarshalInterface" into a stream of bytes. Send the stream of bytes where you
want it. Then call CoUnmarshalInterface on the other end.
Method 2 is exactly what your MIDL generated proxy stub code does when you use method 1. The
ProxyStub marshalling code generated by MIDL (and the oleautomation marshaler etc.) simply
generates calls to CoMarshalInterface/CoUnmarshalInterface on the stub and proxy respectively.
The main problem with supporting IMarshal for an interface is that all interfaces exposed by that object
through QI must be supported. Once we've said we know how to custom marshal an object, we have to
support marshalling all interface pointers that that object implements. Calling for these cases
CoMarshalInterface is not good enough because, as I said before, it simply QI's us again for IMarshal
and would end up in an infinite recursive loop.
However, what we can do is get an instance of the COM standard marshaller (which generates a
normal proxy and stub between the client and server) by calling a COM API function called
CoGetStandardMarshal. This resultant interface does not call back on us.
Whenever we therefore end up having to support IMarshal for an interface that we don't support, we
can simply forward to the IMarshal supplied by CoGetStandardMarshal. In the case of IEntryStream,
that's what I end up doing.