C++ What is the namespace? A namespace allows you to resolve conflict of the global identifiers when you use Describe what a SubClassing? Subclassing allows us to reuse code, which saves us time. It’s also a Technique used to intercept Windows messages What is “inline” function ? inline keyword before name of the function allows the compiler to insert a copy of the function body into each place the function is called. Therefore, the size of the code is increasing, but speed of execution is also increasing. No matter how you designate a function as inline, it is a request that the compiler is allowed to ignore. You have to play with it to see what is best so don’t ignore. Also unlike macros, argument types are checked, and necessary conversions are performed correctly inline functions can prevent thrashing: When f() calls g(), the code might be on two distinct pages of memory, but when the compiler procedurally integrates the code of g() into f(), they are often on the same page, so the working set size (number of pages that need to be in memory at once) may go down even if the executable size goes up. When should I use references, and when should I use pointers? Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don't need "reseating"(i.e, Unlike a pointer, once a reference is bound to an object, it can not be "reseated" to another object). This usually means that references are most useful in a class's public interface . 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).
What happens if you return a reference? The function call can appear on the left hand side of an assignment operator.
What's the difference between public:, private:, and protected:? * A member (either data member or member function) declared in a private:section of a class can only be accessed by member functions and friends of that class. Means that base class is sealed-off from subsequent derivations * A member (either data member or member function) declared in a protected:section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes * A member (either data member or member function) declared in a public: section of a class can be accessed by anyone.
Why Do we need Virtual Base Class? 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.
Why Virtual Function? 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
Why should be base class destructor be virtual 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.
Usage of Static Variable? 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
Difference between Static and Global Variable? 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. Can we pass class variables to static functions? Yes. A class variable is nothing but a static variable. So from static function, static variables can be very well accessed 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. Why Friend Function? If we want to give a non-member function unlimited access to the members of a class we would declare such a function as a friend of that class. (ie friend functions are able to access private and protected data members) Friend property is not Inherited, not transitive and acts only in one direction Note: here you have to pass object as parameter in order to access the class data members. What is an object? A region of storage with associated semantics. What's the difference between the keywords struct and class? The members and base classes of a struct are public by default, while in class, they default to private. struct and class are otherwise functionally equivalent.
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. Is the default constructor for Fred always Fred::Fred()? 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. What's the order that local objects are destructed? First constructed, last destructed . Here b's destructor will be executed first, then a's destructor: void userCode() { Fred a; Fred b; // ... }
What's the order that objects in an array are destructed? 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]; // ... }
Should I explicitly call a destructor on a local variable? NO. The destructor will get called again at the close } of the block in which the local was created
What is static binding and dynamic binding? 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 you cannot inherit ? 1)Construtor & Destructor 2) New & = Operators 3)Friend Relationship 4) Private Data member/ member function Can you instantiate an Abstract Class?
No. Because they represent no real objects the only represent Design-objects. These classes are used to store common properties of their subclasses. They will contain pure virtual function. Technically this class is an incomplete class and hence its object cannot be created. Therefore we are forcing derived functions to override that functions. Why we should not return reference or pointer to a local variable? Because with local variable it goes out of scope (since its allocated in the stack) With Pointers, I leads giving raise to a memory leak (since its allocated in the heap). Can you instantiate Cobject? It cannot be instantiated directly since the constructor is the protected member of class.It can only be inherited. It provides support to serialization but does not support RTTI. Why is it important to use reference during "catch" statement? Exception is always thrown by value .If not reference these will invoke copy constructor and copies the exception object unnessarily. Therefore to save space use a references. What are the advantage and disadvantage of using exception handling? Disadvantage: implementing exception-handling mechanism imposes slight overhead. Advantage provides "bullet-proof" program. How procompiled header work in windows? After the header files included in the StdAfx.cpp and StdAfx.h are processesed, the preprocessor saves a snapshot of its internal state as an .PCH file. Since processing all those state headers repeatedly take longs time for compilation, compiler everytime just reloads the prepocessor state from the .PCH file while the compiler complies other .cpp files.
What is a Constructor? -> It’s a non-static member function -> These are the functions which have the same name as that of a class. -> These functions are called by itself while creating an object -> used to initialize the data members of a class. -> It has no return type -> It can be overloaded -> 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 ~ -> It is called by itself when object goes out of scope -> A destructor destroys an object -> used for memory cleanups, file closing and etc...
-> It has no return type -> It cannot be overloaded -> It does not accept any arguments
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. Can I free() pointers allocated with new? ()? ------------No! Can I delete pointers allocated with malloc()? ------------No! What is a DownCast? --------------Moves a pointer down a class hierarchy, from a given class to a class derived from it. What is SizeOf() return?----------Returns the number of bytes occupied by the datatype. 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. Where is Vtable Initialized? ------In Constructor 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.
How to delete Arrays? CMyObject *pobj = new CObject[128]; delete [] pobj; // must Difference Between Copy Constructor and Assignment operator? Copy Constructor creates a new object whereas Assignment operator assigns the values to an existing object of same class.
Difference between Abstract and Interface ? Interface contains no Implementation whereas Abstract may /may-not contains implementation.
How will you handle a constructor that fails? Throw an exception. Constructors don't have a return type, so it's not possible to use error codes. The best way to signal constructor failure is therefore to throw an exception.
Why should I use new instead of trustworthy old malloc()? Constructors/destructors, type safety, overridability. Constructors/destructors: unlike malloc (sizeof (Fred)), new Fred () calls Fred's constructor. Similarly, delete p calls *p's destructor. Type safety: malloc () returns a void* which isn't type safe. new Fred () returns a pointer of the right type (a Fred*). Overridability: new is an operator that can be overridden by a class, while malloc () is not overridable on a per-class basis. 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.
How many ways are there to initialize an int with a constant? int foo = 123; int bar (123); 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. What are templates? Templates are basically used to create generic classes and functions, which operates on diff data types without having to overload the function or create new classes with all the possible datatypes that it is suppose to support. Disadvantage of using Templates? a) Compile/link time increases b) pointer manipulation problems(not freeing memory) c) Efficinecy problem What is MAP in STL? Its an Associative container.(ie map, set, multimap and multiset). It provides the ability for fast retrieval of datas based on keys.
What is an Vector in STL? 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.
What is the difference between erase() and remove() of std::list? Remove() removes elements by value, while erase() uses iterator for the same purpose.
What is the difference between vector and array? Vector is a one-dimensional array. It's also an STL class while array is a data type.
What is the difference between list and vector? The major difference is the way of element access. Vector elements may accessed randomly while list elements must be accessed sequentially Vector uses random access iterator while list support bi-directional iterators Example : Vector<String> v; v.push_back(“hai”); for(vector<string>::const_iterator I= v.begin(); I != v.end(); ++I) cout<< *I << endl; Does MFC containers use STL? They are not. The MFC containers were written before the STL was addedto VC++. And there semantics are quite different
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
Difference between GetMessage & PeekMessage? 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. Explain Messaging in windows? Windows is a message-based OS. It has a central message pump, which processes all the Messages that are posted to it. Every action in windows is considered as a message. All events raised by any application on windows will be posted in the central message Pump as a windows message. There are 2 messages,
Post message: Sends Msg to the windows messaging system and returns the control to the calling thread before the message is actually processed. Send message, which puts the message on the queue and waits for a response (blocking) The message pump calls the appropriate message handler for appropriate action to be taken on it. If no message handler is found for a message the windows default message handler will handle the message 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()”
How will you create exception in your application? 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 are the Exception Classes in MFC? Cexception, CarchiveException, CdaoException, CDBException, CmemoryException, CfileException, CresourceException, ColeDispatchException, CinternetException How to catch any Exception? Catch(…) How will you make objects persistent in MFC? Using Serialization mechanism. Use of Carchive Class? MFC uses an object of the CArchive class as an intermediary between the object to be serialized and the storage medium. This object is always associated with a CFile object, from which it obtains the necessary information for serialization What is the MFC class to check Memory Leak? CmemoryState old, new, diff; old. Checkpoint (); …. new. Checkpoint (); int iLeak = diff. Difference (old, new);
What functions are used when DLL without import lib is used? Load Library (), GetProcAddress () and FreeLibrary(). What are Advanced Type Cast Operators? Reinterpret-cast -> used to cast pointer between non-related classes // B*b= reinterpret _cast
(a)// Static-cast -> used to cast pointer between related and fundamental data type Dynamic-cast -> used to cast pointer between polymorphism classes (Virtual function containing classes) Here a check on the casting is performed at run-time .If fails returns NULL Cont-cast -> used to set/Remove the constant attribute of the passed object 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. How do I write to the console window? Use the fprintf() C print routine and print to a "file" called stderr. Do not use printf() for debugging messages! printf() buffers its messages so there is no syncronization between what you see on the graphics screen and what you see in the text console window. What is a Translate Message()? 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 will you raise memory expection explicity?-------------AfxThrowMemoryException() How will you implement Message loop? Every Windows program has got a message loop The message loop, as you have noticed, consists of three main APIs: GetMessage that pulls messages into our program, TranslateMessage that translates each keystroke messages to a proper character values and places it into the application's private message queue as WM_CHAR message, and DispatchMessage that pushes the retrieved message (msg) into the window procedure for processing (wndProc()) MSG msg; while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } This loop runs continuously until the reception of WM_QUIT message. What is a Device Context ? It’s a Windows Data structure that contains all information about the drawing attribute of a device such as a display or printer. It acts as an link between the application and output device. (CDC-> CpaintDC + CclientDC) +(CgdiObjects->Cbrush,Cfont) How do I create a CDC from a HDC? CDC myDC; cDC.Attach(lpSomeItem->hDC); and cDC.Detach(); Another approach is CDC * pDC = CDC:FromHandle(lpSomeItem->hDC);\ How can I use a custom icon for a window? Use AfxRegisterWndClass() to register a window class with a NULL icon and then Override the PreCreateWindow()
How can get a pointer to a control from a already created dialog? CButton * pButton = (CButton *)pDialog->GetDlgItem(IDC_CHECK1); pButton->SetCheck(m_bShowState); How do I subclass a control using MFC? BOOL CMyDialog::OnInitDialog() { m_MyControl.SubClassDlgItem(ID_MYCONTROL, this) CDialog::OnInitDialog(); Ctl3dSubclassDlg(m_hWnd, CTL3D_ALL);//else it will cause assertions from multiple subclassing }
How can you change the size of a window? -------- MoveWindow(). 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: DWORD WINAPI MyThreadProc(LPVOID lpvThreadParam); The address of the ThreadProc() is passed as a parameter to a CreateThread() function. The thread starts, executes the ThreadProc(), and exits. It is the programmer's responsibility, however, to incorporate a message loop in the ThreadProc() for retrieving and dispatching messages .
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,
For creating worker threads use: CWinThread* AfxBeginThread( AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); For creating user interface threads use: CWinThread* AfxBeginThread( CRuntimeClass* pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); 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 1.Allocate a new CWinThread object on the heap. 2.Call CWinThread::CreateThread() setting it to initially start suspended. 3.Set the thread's priority.
4.Call CWinThread::ResumeThread().
Note: AfxBeginThread has a slight problem. 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. CWinThread* pThread = AfxBeginThread (ThreadFunc, lpVoid, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED); ASSERT (NULL != pThread); pThread->m_bAutoDelete = FALSE; pThread->ResumeThread (); Termination of Threads Normal Thread Termination : For a worker thread, you can call AfxEndThread or a RETURN statement. For a userinterface thread call PostQuitMessage. Premature Thread Termination : 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.
Communication between threads You can post a message to a thread within a process use CwinThread::PostThreadMessage() method. To post a message to a threads in a different processes then it must be registered with the ::RegisterWindowMessage() API function in both processes. The PostThreadMessage() function uses the message map system - use the ON_THREAD_MESSAGE() macro to catch messages sent within a process, or ON_REGISTERED_THREAD_MESSAGE() to catch inter-process messages
Difference between STA and MTA? 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 Explain Synchronizing Threads in MFC? Csemaphore : used to share objects between Threads in a Process (all threads can access simultaneously) CcriticalSection : used to share objects between Threads in a Process (Only one thread can access at a time) Cmutex : used to share objects between Applications in different Process (Only one thread can access at a time) Cevent : to make the application to wait for something to happen
When to Use the Synchronization Classes 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.
Functions used (Client Side / Component Side) [InitializeCriticalSection(), DeleteCriticalSection() / EnterCriticalSection(), LeaveCriticalSection()] [CreateMutext, CloseHandle() / ReleaseMutex()] [CreateSemaphore(), CloseHandle() / ReleaseSemaphore()] [CreateEvent(), CloseHandle() / SetEvent()]
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
Explain the role of windows registry in case of COM. The registry stores all the details of the components that are registered in the system. 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.
Diff between InProc and OutProc server in COM? Inproc : implemented as a DLL and so lives in the same address space as its client(Every client creates a new com intance) OutProc: is an executable running in its own address space on the same m/c (single com instance services many client ) Remote: runs on another m/c
What's the difference between COM and DCOM? DCOM extends COM. DCOM introduced several improvements/optimizations for distributed environment, such as MULTI_QI (multiple QueryInterface()) and security contexts. DCOM demonstrated importance of surrogate process (you cannot run in-proc server on a remote machine. You need a surrogate process to do that.) DCOM introduced a load balancing
DLL Vs COM DisAdv: Dll exposes only functions (non object oriented). Extension DLL export classes but used only from MFC programs. DLL doesn’t support Backward Compatibility(version problem). DLL’s are loaded using File name. If changed mistakenly or different vendors use same name then problem araises. Adv: Loaded Just-In-Time. Dll can share among several application. Allows application to upgrade without need to recompile Diff between Containment and Aggregation? These are the 2 mechanism that COM provides for reuse of code Containment : here the outer object becomes the client to inner object Aggregation: here the outer object exposes inner objects interface directly to the clients as if it’s a part of outer object. (Aggregation works only among in-process component) AUTOMATION Provides a way for objects to make function and data available to other objects. So componentscan drive one another. This is achieved using Idispatch Interface. Automation composed of 3 Parts: 1) Automation Server // Application that expose objects 2) Automation Client // Application that access objects within Automation Server 3) Type Library // Provides information about objects in the Automation Server to clients at runtime 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 Tools to Test ActiveX Controls: 1) Test Container (to check Controls functionality) 2) Control Pad (to develop Controls for web pages) MFC supports class for ActiveX controls: 1) ColeControlModule (Derived from CwinApp) 2) ColeControl (Derived from Cwnd) 3) ColePropertyPage (Derived from CDialog) 4) ColeDispatchDriver Note : the 1,2,3 are used for Creating Controls using MFC and 4 is used for making use of the controls
Diff between ActiveX and DLL? 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. How automation takes place in OLE? By using Typelibrariesw which are imported by the Application and an Object of the Automation component is created and the methods are then called for appropriate action. What is a Type library? 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 Interfaces must be supported for a ActiveX Component?
Idispatch and IDual What is an Idispatch? Its an interface which allows COM to have late-binding, and therefore be used in scripting environments. Methods exposed by Idispatch? GetIDsifName() , Invoke() , GetTypeInfo() and GetTypeInfoCount()
What is a dual interface? 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 is the Advantage of server implementing as Dual Interface? It can be used from both Scripting and non-scripting Environments. Provides Fast Access if Vtables are used. What method gets invoked during OLE Automation Server is called? ------à GetIDsofName() and Invoke()
What is a structured Storage? 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
What is VARIANT? Why and where would you use it? VARIANT is a huge union containing automation type. This allows easy conversion of one automation type to another. The biggest disadvantage of VARIANT is size of the union.
What are the different types of interfaces? 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.
Is there a way to register in-proc server without regsvr32.exe? Yes. Call DllRegisterServer() & DLLUnregisterServer()
What do you mean by Location Transparency? 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 Location transparency offers a number of advantages. It permits Coding Flexibility by allowing us to write code that talks to a component without worrying about where the component is actually present. Provides Distribution Flexibility because objects can reside anywhere. Provides scalability. If a component is overloaded, you can add new ones to form a cluster of components. A referral component can then be built to route clients to appropriate components. It also offers fault tolerance. For example, if a particular component fails the client can be referred to a different component without the client even realizing it.
About Cstring Conversions: Const Char * -> constant pointer == LPCTSTR == CString Char * è non-constant pointer == LPTSTR (LPTSTR lp; lp= str. GetBuffer (0); and call str. ReleaseBuffer (0);) T2OLE (LPCTSTR str) => used to convert Cstring into OLESTRING BSTR bs = str. AllocSysString (); and call::SysFreeString(bs);
What is the size of BSTR? 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 ) ; Explain Security in COM? COM security relies on authentication (the process of verifying a caller's identity) and authorization (the process of determining whether a caller is authorized to do what it is asking to do). There are two main types of security in COM—activation security and call security. Activation security determines whether a client can launch a server at all. Once a server has been launched, you can use call security to control access to a server's objects. What do you mean by object pooling? 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. What are Design Patterns? (RISS) So the goal of design pattern is to isolate changes in your code Patterns is used keep changes from being propagated throughout your code when you modify your code. Design patterns represents solutions to problems that arise when developing software within a particular context. Patterns facilitate reuse of successful software architectures and designs Patterns capture the static and dynamic structure and collaboration among key (Actors) participants in software designs. 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 Explain OMT?(Object Modeling Techniques) OMT Involves analysis and design of a system based on 3 diff Model 1) object 2) dynamic and 3) Functional Object Model: Specify what objects a system contains. It shows the Static Structure and Relationship between them Dynamic Model : Specify when the object changes. It represents the State diagram that interact via events Functional Model: Specify how objects change. Says the result without providing the Internal details using DFD(Dataflow Diagram) Diff Between Association and Link? Association describes the relationship between classes. Link describes the relationship between objects. Explain SOFTWARE LIFE CYCLE? Conceptualization Phase : Define Problem Statement . Generate Requirement Documentation. Identify Usecases holding happy path Analysis Phase : Analysis on Requirements is done. Generates Specification Document. Generates TestCases. Define usescase holding happy and sorrow path. Map requirement to usecase paths and classes
Design Phase Program Structure. Component Packages Implementation Phase Maintenance Phase implementing
: Generates Design Document. Defines Data Structure, Algorithm, and Error Handling Mechanism, Identify : Coding & Testing : Collect Change/ Enhancement request, which is prioritized and grouped for
Types : WATER FALL, V, PHASED, EVOLUTIONARY, SPIRAL WATERFALL -> Problem Defn –Analysis – Design – Coding –Testing –Maintenance Here each phase is considered as discrete phase. Here s/w is developed in sequential phases. There is no overlap and the process is very straight forward. Its very difficult to accommodate changes after the process is underway SPIRAL -> uses prototyping model to ensure the requirements are captured correctly. Each iteration undergoes risk analysis sector and testing sector. 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 Process Models – ISO 9001 (applicable to all industries) CMM ( applicable to software industry alone) 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. Levels of CMM – INITIAL – REPEATABLE – DEFINED – MANAGED – OPTIMIZING 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
Difference between quality Control and Quality Assurance? 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) What does SQA means? SQA S/W Quality Analyst is a person whose role is to take care of QA and QC What does NC means? NC: Non-Conformance are the process that escape from SQA evaluation. Explain Different types of TESTING ? Black Box : This is a FUNCTIONAL TEST. Needs no knowledge of internal design/code. Since tests are based on requirements and functionality. White Box : This is a STRUCTUAL TEST . Needs knowledge of the internal design/code. Since tests are based on coverage of code statements, conditions and paths. Unit : used to test particular function/ module. Done by programmer Incremental Integration : continious testing of an application as new functionality is added. Done by the programmer Integration : testing after combining several parts of an application to determine if they function together correctly. Regression : re-testing after fixes or modifications of the s/w is done. Acceptance : Final testing based on the specification of end-user , over some limited period of time. To detemine whether the s/w is satisfactory to the customer Load : testing an application under usual heavy loads. To find out the maximum sustainable load that the system can handle . Stress : testing an application under unusal heavy loads. ( when running shortage of resource, ram, disk ect) Useablilty : testing the application by a thirdperson to judge the user-friendliness of the application Compatibility : testing how well s/w performs in a particular h/w or s/w or o/s or network ect environments Alpha : testing of an application when development is nearing completion .Done by end-user Beta : testing when development is completed and final bugs and problems need to be found before final release. Done by end-user. 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:
• • • •
Business process modeling with use cases Class and object modeling Component modeling Distribution and deployment modeling
UML is to specify, Visualize and document the artifacts of an object oriented system under development.
UML consists of 1) 2) 3) 4)
modeling elements (Static and Dynamic) (static – classes, attributes, relationship & dynamicobjects, Messages and state) Relationship (Dependency, Association, Generalization and Realization) Extensibility (Stereotype, Tagged value and Constraints) Diagrams (Static View and Dynamic view)
Static View – use case, component, deployment, class and object & Dynamic View– sequence, collaboration, state chart and activity Sequence Diagram -> Time oriented, Collaboration -> Message oriented, State Chart -> Event oriented, ->Activity oriented
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 Provide a SQL statement to SORT the records? ------------à ORDER_BY
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
What is outer join? 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. SELECT * FROM table1 LEFT OUTER JOIN table2 ON table1.name = table2.name/
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.
Explain the Levels Normalization Process? 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 Second Level : Releate tables using Foreign key Third Level : Eliminate fields/columns that do not depend on the 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.
Explain Different KEYS available in DB? 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.
Define Entity Integrity ? It ensures that each row can be uniquely identified by an attribute called the primary key which cannot be NULL.
Define Referential Integrity ?
It ensures that all the values in the foreign key matches with the primary key values is called referential integrity
Define ER Diagram ? It’s a graphical representation of DB Structure. It has 3 things Entity (Table Name); Attribute (Column Name); and RelationShip
Miscellaneous
main() { int x=10,y=15; x=x++; y=++y; printf("%d %d\n",x,y); } Ans: 11 and 16
main() { int x=10,y=15; int z=x++ * ++y; cout<
What is the return value of scanf statement? output of the program? # define infiniteloop while(1) main() { infiniteloop; printf("DONE"); } ans: none expl: infiniteloop in main ends with ";" . so loop will not reach end; and the DONE also will not print. 5 = obj a[i] = i++; ()/=/[] << , >>
à -> -> ->
main() { char *ptr = "Ramco Systems"; (*ptr)++; printf("%s\n",ptr); //runtime error ptr++; printf("%s\n",ptr);//prints "amco Systems" } #include<stdio.h> main() { char *p1; char *p2; p1=(char *) malloc(25); p2=(char *) malloc(25); strcpy(p1,"Ramco"); strcpy(p2,"Systems"); strcat(p1,p2); printf("%s",p1); //prints "Ramco Systems" }
#include<stdio.h> main() { char s1[]="Ramco"; char s2[]="Systems"; s1=s2; // runtime error printf("%s",s1); } output of the program? main() { int a=2, b=3; printf(" %d ", a+++b); } ans:5 expl: here it evaluates as a++ + b.
not possible the subexpression I++ modifies the “i” values which leads to undefined behaviour cannot be friends should be friend function
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); printf("%d %d\n",x,y); swap2(x,y); printf("%d %d\n",x,y);
//swap action takes place //no swap action takes place
} int swap2(int a,int b) { int temp; temp=a; b=a; a=temp; return; } Ans : 10,5,10,5
How do I prevent a the user from starting a second instance of my app? 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 do I display a bitmap on a button? BOOL CMyDialog::OnInitDialog() { HWND hUpCtl; /* The button is control IDC_UP */ hUpCtl = GetDlgItem( hDlg, IDC_UP ); /* The icon is IDI_UP in the resource file */ HICON hU = ::LoadImage( AfxGetResourceHandle(),MAKEINTRESOURCE( IDI_UP ), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR ); ::SendMessage( hUpCtl, BM_SETIMAGE, IMAGE_ICON,(LPARAM) (DWORD) hU ); } How can I make the ENTER key act like the TAB key on a dialog? void CMyDlg:: OnOK() { CWnd *pWnd = GetFocus(); ASSERT (pWnd); if (IDOK == pWnd ->GetDlgCtrlID()) CDialog::OnOK(); else NextDlgCtrl(); } How can I use my VB ActiveX dll from VC++? #import "test.dll" no_namespace named_guids _TestPtr pTest = 0; HRESULT hres = pTest.CreateInstance ( __uuidof(Test) ); pTest->TryItOut(); How can I find the path my application or DLL was loaded from? Use The Win32 API GetModuleFileName(); How can I shutdown the system programmatically? on NT very handy function called InitiateSystemShutdown(). It can basically do the same as ExitWindows(), except it allows you to shutdown remote systems. Remember that to do this, you need to have the SE_REMOTE_SHUTDOWN privilege granted on the remote computer, though. How do I send/post a message to the main thread from another thread? Posting or sending a user-defined message to the main thread is the best way to trigger something in the main thread from other threads. You start by defining the user-defined message itself. WM_APP is a windows constant that is higher than any message used by windows, so define your own windows message like this: #define MY_WM_MESSAGE1 (WM_APP + 1) Your secondary thread will need an hwnd (not a CWnd*) to post to. You can pass the main hwnd when you create the thread, or you can get it with AfxGetMainWnd ()->m_hWnd from within worker threads. Then you are ready to send or post a message from the secondary thread: ::PostMessage(hwnd, MY_WM_MESSAGE1, (WPARAM)0, (LPARAM)0); or ::SendMessage(hwnd, MY_WM_MESSAGE1,(WPARAM)0,(LPARAM)0); The lParam and wParam can be used to pass any parameters you like to the destination.
To receive and process the message in the main thread code, first declare your message handler function in the main window's h file. MFC does not route user-defined messages to views or docs, so the handler must be a member function of the CMainFrame class (or the main dialog class in a dialog-based app). The handler must have exactly this prototype: afx_msg LRESULT OnMyMessage1(UINT wParam, LONG lParam); The next step is to enter your message handler into the message map, typing it in manually instead of using the wizard. Put in an ON_MESSAGE macro like the following after the "//}}AFX_MSG_MAP" line and before the "END_MESSAGE_MAP()" line. //}} AFX_MSG_MAP ON_MESSAGE (MY_WM_MESSAGE1, OnMyMessage1) END_MESSAGE_MAP () LRESULT CMainFrame::OnMyMessage1(UINT wParam, LONG lParam) { ... Do something about the message from secondary thread return 0; // I handled this message } ABOUT MFC COM 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) 3) 4)
COM Interfaces using Interface Maps Automation using Dispatch Maps
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
Ways to add interface to a class 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 Class Cdemo : Public Iunknown { Cdemo1 * m_pDemo1; Cdemo2 * m_pDemo2; Friend Class Cdemo1; Friend Class Cdemo2; }; Nested Classes Class Cdemo : Public Iunknown { Class Xdemo1Cls: Public Idemo1 { }; Class Xdemo2Cls: Public Idemo2 { }; }; In MFC Nested Classes are default and its is achieved by using MFC provided macros BEGIN_INTERFACE_PART() and END_INTERFACE_PART() Similarly, STDMETHOD_() macro is used to define the virtual functions. Similarly to declare interface map to a class use the following macros DECLARE_INTERFACE_MAP() 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) BEGIN_INTERFACE_PART( Demo2Cls, Idemo2) STDMETHOD_ (void, SomeOtherFunction()); BEGIN_INTERFACE_PART(Demo2Cls) DECLARE_INTERFACE_MAP(); // sets up the interface map DECLARE_OLECREATE(Cdemo); // creates a classfactory for the com class }; CDEMO.CPP #include // for guids to get initialized properly IMPLEMENT_DYNCREATE(Cdemo, CcmdTarget) //for dynamic creation IMPLEMENT_OLECREATE(Cdemo, “Demo”, [provide the guid number] ) // implement classfactory //add interface map BEGIN_INTERFACE_MAP(Cdemo, CcmdTarget) INTERFACE_PART(Cdemo, IID_Idemo1, DemoCls1) INTERFACE_PART(Cdemo, IID_Idemo2 DemoCls2) END_INTERFACE_MAP() 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.
Explain COM Threading models? 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. Apartment Threading Model (single threaded apartments) This model was introduced in the first version of COM with Windows NT3.51 and later Windows 95. The apartment model consists of a multithreaded process that contains only one COM object per thread. Single Threaded Apartments (STA)- This also means that each thread can be called an apartment and each apartment is single threaded. All calls are passed through the Win32 message processing system. COM ensures that these calls are synchronized. Each thread has its own apartment or execution context and at any point in time, only one thread can access this apartment. Each thread in an apartment can receive direct calls only from a thread that belongs to that apartment. The call parametes have to be marshalled between apartments. COM handles marshalling between apartments through Windows messaging system.
Free Threading Model (multi threaded apartments) This model was introduced with Windows NT 4.0 and Windows95 with DCOM. The free threaded model allows multiple threads to access a single COM object. Free threaded COM objects have to ensure thread synchronization and they must implement message handlers which are thread aware and thread safe. Calls may not be passed through the Win32 messaging system nor does COM synchronize the calls, since the same method may be called from different processes simultaneously. Free threaded objects should be able to handle calls to their methods from other threads at any time and to handle calls from multiple threads simultaneously. Parameters are passed directly to any thread since all free threads reside in the same apartment. These are also called Multi-Threaded Apartments (MTA) Choosing the Threading Model Choosing the threading model for an object depends on the object's function. An object that does extensive I/O might support free-threading to provide maximum response to clients by allowing interface calls during I/O latency. On the other hand, an object that interacts with the user might support apartment threading to synchronize incoming COM calls with its window operations.
It is easier to support apartment threading in single-threaded apartments because COM provides synchronization on a per-call basis. Supporting free-threading is more difficult because the object must implement synchronization; however, response to clients may be better because synchronization can be implemented for smaller sections of code. APARTMENT THREAD Only one thread found in an apartment
FREE THREAD More than one thread found in an apartment
One one component per thread Owns the component it creates but doesn’t share it
Only one component per thread Owns the component it creates but shared by all threads freely Allows Multiple thread to access Component freely Doesn’t own a message queue
Allows single thread to access Component Owns a message Queue. (External calls are queued) Calls are passes through the message queue system Com synchronizes the calls Parameters are marshaled between apartments Com need not to be thread safe. Com takes care
Calls doesn’t pass through the message queue Com doesn’t synchronizes the calls. Since free thread doesn’t contain message loop Not marshaled since all the free threads resides in the same apartment Com must be thread safe since component must ensure component synchronization itself
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 Why catch by reference? #include using namespace std; class Base {
public: virtual void what() { cout << "Base" << endl; } }; class Derived : public Base { public: void what() { cout << "Derived" << endl; } }; void f() { throw Derived(); } 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 ptr (new int); A(){ A(); } -> compiles successfully but run-time error ~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
Diff between Calloc and Malloc? 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)
Diff between CallbyValue and CallbyReference ? CbV : here values are copied
CbR : here address are copied
Diff between While and Do-While? While -> first tests the codition and if true executes its statement Do-While -> First executes the statement and then tests the condition
What are Enum and TypeDef? 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; ++a -> abc abc::Operator++() { I++; return *this; }
a++ -> abc abc::Operator++( int x) { abc d; d= * this; I++; return d; }
Book: Inside COM by Dale Rogerson All COM Interfaces must inherit from an interface named Iunknown. The purpose of vtable ? The vtable pointer adds extra level of indirection to the process of getting from an abstract base class pointer to a Function. In COM you can access a component only through functions never directly through variables. If we create 2 different instance of CA (comp of A) then we get separate sets of instance data but share the same vtble and same implementation.
All the classes that inherit from an interface can be treated the same way by the client. The Client can use CA and CB interchangeably through an IX pointer. Class CA : public IX {} and Class CB : public IX {} ; Void foo(IX * x) { x->F1(); } 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 overview
1) 2) 3)
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: call AddRef before returning the interface (queryinterface and createinstance does this) call Release when you are done. 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. CoCreateInstance functions inflexibility: 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.
// 3- creates ClassFactory & 6- creates Component //
First the client calls CoCreateInstance which is implemented in the COM Library. CoCreateInstance is implemented using CoGetClassObject which actually looks the component in the registry.If it finds the component it loads the DLL that serves the component. After the DLL loads CoGetClassObject call DllGetClassObject. DllGetClassObject is implemented in the DLL Server. Its job is to create the classfactory and it also queries the class factory for IclassFactory interface which is returned to CoCreateInstance. The CoCreateInstance then uses the IclassFactory interface to call its CreateInstance function. CoCreateInstance releases the classfactory and returns the IX pointer to the client .The client can then use the interface pointer to call a method on the component. COM does not support implementation inheritance because implementation inheritance binds one object tightly to the implementation inheritance of another object. If the implementation of a base object changes the derived objects break and must be changed. What is a smart pointer? A smart pointer is a class that overrides operator ->. The smart pointer class contains pointer to another object. They delegates the call to the object pointed to by the contained pointer. Smart pointer is a smart pointer that contains a pointer to an interface Coolest thing about smart pointer is that we don’t have to remember to call Release. When the smart pointer goes out of scope it automatically calls Release in its destructor. You shouldn’t call Release on the smart pointer. Only you should should assign the pointer to NULL. (spIx = NULL;)
Why do we need to cross the process boundry? 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. Interfaces accessible through vtbl (called from c++ programs)
Interfaces accessible through Invoke() (Called from scripting languages)
COM Threading Models 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
Marshalling takes place
CoUnInitialize
Component
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.
Which type of thread should you use? 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. What does “component support binary compatibility” means? We don’t have to unregistered and register the control every time we compile it again and again. Means the CLSID and IID remains same for new builds of the component each time.
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”.
Explain MTS Context ? 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 ()//
Why we need MTS? 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. Explain the Tx Supported by MTS? Req a new Tx : MTS will start a new Tx each time on Instance is activated Req a Tx : The component will run within an existing Tx if one already exists. If not MTS will create a new one. Supports Tx : The component will run within an existing Tx if one already exists. If not will run without a Tx. Does not support Tx : The component will always run outside any existing Tx
Note: Generally set Req a New Tx to parent Component while setting Req a Tx to child component
Diff between “New”, “CreateObject” and ”CreateInstance”? 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.
Explain ACID property? Atomicity: Consistency:
- If all the actions within a Tx either complete successfully or none be executed at all. - 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.
Explain the Types of database read problems? Lost updates: When a Tx updating a record, another Tx starts updating the same record before the first Tx commits or aborts. Dirty Reads: When a Tx’s updations are visible to second Tx before the first Tx commits. Unrepeatable Reads: Tx reads the same record twice and gets different results because inbetween the reads a Second Tx has updated the record. Phantom Read: A Tx reads the same set of record twice and gets different results because inbetween the reads a second Tx added a new record or removed a record from the same table.
Why MSMQ Series? 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.
When to use what? 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 Used when we want the object to operate on Different types 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-----------------------------------------------------INTERFACE ALONE
- PURE VIRTUAL FUNCTION
IMPLEMENTATION ALONE
– PRIVATE INHERITANCE
INTERFACE + DEFAULT IMPLEMENTATION
- VIRTUAL FUNCTION
INTERFACE + MANDATORY IMPLEMENTATION - NON- VIRTUAL FUNCTION 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 When to use DAO/ ODBC If you are planning to work with JET DB then use DAO else use ODBC. Access ODBC via DAO when you need the speed of JET DB Engine and Extra Functionality of DAO Classes
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 The DLL 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 Header File (dlltest.h): #ifndef _DLLTEST_H_ #define _DLLTEST_H_ #include #include <stdio.h> #include <windows.h> extern "C" __declspec(dllexport) void NumberList(); extern "C" __declspec(dllexport) void LetterList(); #endif Source File (dlltest.cpp): #include "dlltest.h" #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++) { cout << i << " "; } cout << endl << endl; } extern "C" __declspec(dllexport) void LetterList() { GetModuleFileName(NULL, (LPTSTR)module, MAXMODULE); cout << "\n\nThis function was called from "<< module << endl << endl; cout << "LetterList(): "; for(int i=0; i<26; i++) { cout << char(97 + i) << " "; } cout << endl << endl; } The extern "C" __declspec(dllexport) means that we want to allow these functions to be used by our actual program. When you compile this thing, it should create the libraries. Now lets see how we actually use them. Using the DLL (With an Import Library) 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
DLL Test Source File (dllrun01.cpp) - Win32 Console Application: #include #include 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 #include <stdio.h> #include #define MAXMODULE 50 typedef void (WINAPI*cfunc)(); cfunc NumberList; cfunc LetterList; void main() { HINSTANCE hLib=LoadLibrary("DLLTEST.DLL"); if(hLib==NULL) { cout << "Unable to load library!" << endl; getch(); return; } char mod[MAXMODULE]; GetModuleFileName((HMODULE)hLib, (LPTSTR)mod, MAXMODULE); cout << "Library loaded: " << mod << endl; NumberList=(cfunc)GetProcAddress((HMODULE)hLib, "NumberList"); LetterList=(cfunc)GetProcAddress((HMODULE)hLib, "LetterList"); if((NumberList==NULL) || (LetterList==NULL)) { cout << "Unable to load function(s)." << endl; FreeLibrary((HMODULE)hLib); return; } 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 Regular DLL uses 1)
hInstance = ::Loadlibrary( dllpath);
AfxSetResourceHandle(hInstance); FARPROC fproc = ::GetProceAddress( hInstance, “functionName”); (*fproc)(); Extension DLL Class AFX_EXT_CLASS Csample { public : void Fire(){ AfxmessageBox(“Hai Baskar”); } }; Client : #include “sample.h” void view::Firedll() { Csample obj; Obj.Fire(); } //--------------------------------------------------------------------------------------------DLL Linkages Implicit linking & Explicit Linking There are two methods for calling a function in a DLL:
•
•
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.
Diff between Extension DLL and Regular DLL Linked Dynamically alone Both client & dll programs must use same version of MFC Dlls Support C++ interfaces. It exports whole classes to client where clients can construct object of those classes.
Linked both Dynamically and statically No version problem Doesn’t support c++ interface supports only C++ style function
Mydll.cpp
Compiler Linker
Myclient.cpp Mydll.def
makefile
Compiler
Mydll.exp
Mydll.dll
Library Manager
Mydll.lib Linker
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) DisAdv: m emory capacity increases , multiple copies exists in memory Adv : no need to provide re-distributable file while delivery. Because all the dependencies are bundled in one file 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) There are two types of linking 1) Implicit and 2) Explicit 1) Implicit : has to provide the .lib , .h in the project setting and copy the dll in the executable directory or system path. 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 #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 (LPVOID); // In short, Return value *must* be DWORD WINAPI And the parameter must be LPVOID DWORD WINAPI genericThreadFunc1(LPVOID); DWORD WINAPI printString(LPVOID); DWORD WINAPI printNumber(LPVOID); // We need an array of Handles to threads HANDLE hThreads[MAX_THREADS]; // ...an array of thread id's DWORD id[MAX_THREADS]; // And a waiter (which I'll explain later) DWORD waiter; // Here are the three functions that are defined. // They do trivial things and should be mostly self explanatory. DWORD WINAPI genericThreadFunc1(LPVOID n) { cout << "Thread started (genericThreadFunc1)..." << endl; for(int i = 0; i < 100; i++) { cout << "threadFunc1 says: " << i << endl; } cout << "...(genericThreadFunc1) Thread terminating." << endl; return (DWORD)n; } DWORD WINAPI printString(LPVOID n) { cout << "Thread started (printString)..." << endl; // 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). char* str = (char*)n; for(int i = 0; i < 50; i++) { cout << "printString says: " << str << endl; } cout << "...(printString) Thread terminating." << endl; return (DWORD)n; } DWORD WINAPI printNumber(LPVOID n) { cout << "Thread started (printNumber)..." << endl; int num = (int)n; for(int i = num; i < (num + 100); i++) { cout << "printNumber says: " << i << endl; } cout << "...(printHello) Thread terminating." << endl; return (DWORD)n;
} // 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. // Here's some basics: // Parameter 0: Lookup // Parameter 1: Stack size (0 is default which means 1MB) // Parameter 2: The function to run with this thread // Parameter 3: Any parameter that you want to pass to the thread function // Parameter 4: Lookup // Parameter 5: Once thread is created, an id is put in this variable passed in 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) for(int i = 0; i < MAX_THREADS; i++) { CloseHandle(hThreads[i]); } 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 #include <windows.h> #define FULL 1 #define EMPTY 0 int SharedBuffer; int BufferState; HANDLE hMutex; HANDLE hNotFullEvent, hNotEmptyEvent; void Producer(); void Consumer(); int main(int argc, char* argv[]) { HANDLE hThreadVector[2]; DWORD ThreadID; BufferState hMutex
= EMPTY; = CreateMutex(NULL,FALSE,NULL);
// create manual event objects hNotFullEvent = CreateEvent(NULL,TRUE,FALSE,NULL); hNotEmptyEvent = CreateEvent(NULL,TRUE,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); // process ends here return 0; } void Producer() { int i; for (i=5; i>=0; i--) { while(1) { if (WaitForSingleObject(hMutex,INFINITE) == WAIT_FAILED) { cerr << "ERROR: Producer()" << endl; ExitThread(0); } if (BufferState == FULL) { ReleaseMutex(hMutex); // wait until buffer is not full WaitForSingleObject(hNotFullEvent,INFINITE); continue; // back to loop to test BufferState again } // got mutex and buffer is not FULL, break out of while loop break;
} // got Mutex, buffer is not full, producing data cout << "Produce: " << i << endl; SharedBuffer = i; BufferState = FULL; ReleaseMutex(hMutex); // end critical section PulseEvent(hNotEmptyEvent); // wake up consumer thread } } 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, Lowercase 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”); Generic MFC Data Type _TCHAR
Map to ASCII
Map to UNICODE
Char
wchar_t
_T or _TEXT
char constant strings
LPTSTR
char*, LPSTR(Win32)
wchar_t*
const char*, LPCSTR(Win32)
const wchar_t*
LPCTSTR
wchar_t constant strings
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 is a smaller version of SGML. XML is a meta-language.( A meta-language is a language that's used to define other languages.) XML is about defining data.
XML: What it can do With XML you can : _ Define data structures _ Make these structures platform independent _ Process XML defined data automatically _ Define your own tags With XML you cannot _ Define how your data is shown. To show data, you need other techniques. XSL (eXtensible Stylesheet Language) is created for this purpose. But the presentation can also be defined with CSS (Cascading Style Sheets).
XML declaration is done by using a Tag Structure of XML
<element> <sub-element>content <sub-element>content
Elements in XML can use attributes. The syntax is: <element attribute-name = "attribute-value"> content volvo 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 To be valid an XML document needs to apply to the following rules: _ The document must be well formed. (More on well formed in the previous page). _ The document must apply to the rules as defined in a Document Type Definition (DTD), 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 subelements.
This means that the element car has two subtypes: brand and type. Each subtype can contain characters. the number of possible occurrences the following indications can be used: _ + must occur at least one time but may occur more often _ * may occur more often but may also be omitted _ ? may occur once or not at all '|' you define a choice between two sub elements. A DTD can be an external document that's referred to. A DTD can also be included in the XML document itself. 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 2) What is a well formed XML ? A XML document that has correct XML syntax. 3)What is a valid XML document ? A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules of a Document Type Definition (DTD): 4) What is the purpose of DTD ? The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements. 6) Can we use a CSS file to format XML document ? YES 7) what does the tag <xml> do in HTML , what is the relevance XML data can be embedded directly in an HTML page Or can be attached as separate XML file Data Islands can be bound to HTML elements in this manner. 8)What is the usage of XML parser ? To create, read and update - an XML document, we need XML parser. 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. 12) When to use DOM ? 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. 13) Which parser is the best fit ? 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. Advanced XML Questions 1) how to resolve duplication of names when 2 or more xml documents are used in an application? Namespaces, elaborate on (URI, URN) 2) What is a CDATA section? Anything within CDATA section is ignored by the parser.
A CDATA section cannot contain another CDATA section. Also make sure there are no spaces or line breaks in the strings it holds
3) Why XML Encoding is required ? XML documents can contain foreign characters. To let the XML parser understand these characters, you should save your XML documents as Unicode. 4) Name 2 HTML tags that are used to display XML data? <span datasrc="#xmldso" datafld="TITLE"> DTD & XML Schema 1) What is the purpose of DTD ? The purpose of a Document Type Definition is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements. A DTD can be declared inline in your XML document, or as an external reference. DTD doesn’t support inheritence. 2) why use a DTD ? 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. 3) What is an XML Schema? The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a DTD. An XML Schema:
• • • • • • • •
defines elements that can appear in a document defines which elements are child elements defines the number of child elements defines the order of child elements defines whether an element is empty or can include text defines attributes that can appear in a document defines data types for elements and attributes defines default and fixed values for elements and attributes
4) advantage of schemas over DTD ?
• •
XML Schemas are extensible to future additions XML Schemas support data types
•
XML Schemas support namespaces
5) DTD elements ? Declaring only one occurrence of the same element The example declaration above declares that the child element message can only occur one time inside the "note" element. Declaring minimum one occurrence of the same element The + sign in the example above declares that the child element message must occur one or more times inside the "note" element. Declaring zero or more occurrences of the same element The * sign in the example above declares that the child element message can occur zero or more times inside the "note" element. Declaring zero or one occurrences of the same element The ? sign in the example above declares that the child element message can occur zero or one times inside the "note" element. Declaring either/or content The example above declares that the "note" element must contain a "to" element, a "from" element, a "header" element, and either a "message" or a "body" element. Declaring mixed content 6) what is the root element of every schema ? <schema> 7) how to refer a schema in a XML ? <note xmlns=http://www.microsoft.com xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.microsoft.com note.xsd"> sree baskar message meet me during lunch
8) How to define simple elements in XSD ? <xs:element name="firstname" type="xs:string"/> <xs:element name="age" type="xs:integer"/> <xs:element name="dateofbirth" type="xs:date"/> 9) What are the available common types in XSD ?
xs:string xs:decimal xs:integer xs:boolean xs:date xs:time
10) how to assign default values to these common types in XSD ? <xs:element name="color" type="xs:string" default="red"/>
11) how to assign constant values that can not be changed ? <xs:element name="color" type="xs:string" fixed="red"/> 12) How to specify attributes that are mandatory ./ non-mandtory ? what is the key word used ? <xs:attribute name="lang" type="xs:string" use="optional"/> To make an attribute required: <xs:attribute name="lang" type="xs:string" use="required"/> USE is the key word for specifying an attibute 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"/> 14) advantage of schemas over DTD ? I . XML Schema has Support for Data Types
One of the greatest strength of XML Schemas is the support for data types. With the support for data types:
It is easier to describe permissible document content It is easier to validate the correctness of data It is easier to work with data from a database It is easier to define data facets (restrictions on data) It is easier to define data patterns (data formats) It is easier to convert data between different data types
II. XML Schemas use XML Syntax Another great strength about XML Schemas is that they are written in XML. Because XML Schemas are written in XML:
You don't have to learn another language You can use your XML editor to edit your Schema files You can use your XML parser to parse your Schema files You can manipulate your Schema with the XML DOM You can transform your Schema with XSLT
III XML Schemas are Extensible XML Schemas are extensible, just like XML, because they are written in XML. With an extensible Schema definition you can:
Reuse your Schema in other Schemas Create your own data types derived from standard types Reference multiple schemas from the same document Restrictions on XML elements are called facets.
15) How to make Restrictions on a Set of Values 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"/> The "car" element is a simple type with a restriction. The acceptable values are: Audi, Golf, BMW.
16) how to set restrictions on a series of values ? 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]"/> The "letter" element is a simple type with a restriction. The only acceptable value is ONE of the LOWERCASE letters from a to z. 17) How to enforce restrictions on whitespace characters ? To specify how white space characters should be handled, we would use the whiteSpace constraint. 18) What are the restrictions available on length ? To limit the length of a value in an element, we would use the length, maxLength, and minLength constraints. 19) differentiate between (maxExclusive,maxInclusive) also between(minExclusive,minInclusive) 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) 20) can a empty complex element contain attributes? -------------------------------> Yes 21)what is the restriction ? That should not have any content between the opening and closing tags. 23) what is the usage of element in XSD The 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? XSLT is a language for transforming the structure of XML documents. The XSL Transformations (XSLT) vocabulary provides a rule-based framework for selecting and processing document content, and transforming it into new documents. 2)How does XSLT work?
During the transformation process, XSLT uses XPath to define parts of the source document that match one or more predefined templates. When a match is found, XSLT will transform the matching part of the source document into the result document. The parts of the source document that do not match a template will end up unmodified in the result document. 3)what is the root element in a XSL stylesheet The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or <xsl:transform>. 4) what is the use of “match” attribute ? 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). 5) Why do I need to use a different XSLT namespace with Internet Explorer? Actually, you don't! You should use the standard xmlns:xsl="http://www.w3.org/1999/XSL/Transform". 7) What's XPath got to do with XSLT? XSLT uses Xpath path expressions to filter through a node-tree. An XSLT style sheet contains "template rules" that define which parts of a document's content should be selected and how they should be processed to create the desired result. There are two parts to a template rule: a pattern and a template. A template rule uses XPath syntax to express a "pattern" which is then "matched" against elements in the source tree to select the nodes to be processed by the template 8) How to connect an XML source document to an XSLT style sheet? An XML style sheet declaration is used to connect an XML document to its style sheet. The style sheet declaration is placed after the XML version declaration and before the root element. Here's what one looks like: 9) What is XPath (XML Path Language)? The XPath Recommendation defines a path language and expression syntax used by XSLT, XPointer, and XLink. XPath syntax operates on the abstract, logical structure of an XML document, rather than its physical "surface syntax." 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 10) What is an XPath node tree? A "node tree" is what is constructed by an XPath processor after parsing. XPath operates on an XML document as a tree of "nodes." A node tree built by an XPath processor can be used to provide a document hierarchy represented as an inverted ìtreeî with the "root node" at the top and the ìbranchesî and ìtrunkî below. 11) What is an XPath expression? XPath's primary syntactic construct is the "expression." Two examples of XPath expressions are "location paths" and "function calls." 12) What is the relationship between XSLT and XPath? XSLT uses XPath expressions to select nodes for processing
DCOM
How COM Is Different
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.
•
COM methods can be called across a network.
•
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.
Here is a typical interaction between a COM client and server: Client Request Requests access to a specific COM interface, specifying the COM class and interface (by GUID)
Calls a method of the interface. Release the interface
Server Response •
Starts the server (if required). If it is an In-Process server, the DLL will be loaded. Executable servers will be run by the SCM.
•
Creates the requested COM object.
•
Creates an interface to the COM object.
•
Increments the reference count of active interfaces.
•
Returns the interface to the client.
Executes the method on a COM object. •
Decrements the interfaces reference count.
•
If the reference count is zero, it may delete the COM object.
•
If there are no more active connections, shut down the server. Some servers do not shut themselves down.
•
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. Most COM functions return an error code called an HRESULT. The CoInitialize() function initializes the COM library. You need to call this function before you do anything else. Call CoUninitialize() when you're completely finished with COM. This function de-allocates the COM library. The function that gives us an interface pointer is CoCreateInstance().We can then use the interface pointer to call methods on the server. If you create an interface with CoCreateInstance, you'll need to call Release(). 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. The four basic steps to create a server: 1. Use the ATL Wizard to create the shell for your COM server. You choose whether you want the server to be a DLL, an EXE or a service. 2. Create a new COM object inside the server shell. You will choose the threading model. This creates the interface into which you can install your methods. 3. Add the methods to your object and declare their parameters. 4. Write the code for your methods. 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 singlethreaded, 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. when a COM client tries to start a COM server. Some of the more common problems include: • The client could not start COM • The client could not locate the requested server • The client could locate the requested server but it did not start properly • The client could not find the requested interface • The client could not find the requested method • The client could find the requested method but it failed when called • The client could not clean up properly In order to track these potenital problems, you have to check things every step of the way by looking at HRESULT values. The files created by the MIDL include: m BeepServer.RGS - Registration script for the server. m BeepServer.h - This file contains definitions for the COM components. m BeepServer_i.c - GUID structures for the COM components. m Proxy/Stub files - This includes "C" source code, DLL definitions, and makefile (.mk) for the Proxy and Stub. RGS scripts are similar, but use a complete different syntax and are only used by ATL for object registration. These scripts are invoked by the ATLRegistry Component (Registrar). This was defined with a macro in the object header: DECLARE_REGISTRY_RESOURCEID(IDR_BEEPOBJ) Basically, this script is used to load registry settings when the server calls CComModule::RegisterServer(), and to remove them when CComModule::UnregisterServer() is called. All COM registry keys are located in HKEY_CLASSES_ROOT. There are several sub-keys under the CLISD: • ProgID - The programmatic identifier. • VersionIndependentProgID - Associates a ProgID with a CLSID. • InprocServer32 - Defines a server type (as a DLL). This will vary depending on whether this is an In-Process, Local, or Remote server. • ThreadingModel - The COM threading model of the object. • TypeLib - The GUID of the server's type library. 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.
Sample Client Source Code 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. #include "stdafx.h" // added _WIN32_DCOM #include // get "cout" #include // get _com_error #include // get time_t // extract definitions from server project #include "..\RemoteServer\RemoteServer.h" #include "..\RemoteServer\RemoteServer_i.c" // forward reference for status display method void ShowStatus( HRESULT hr ); int main(int argc, char* argv[]) { HRESULT hr; // COM error code IGetInfo *pI; // pointer to interface // Get the server name from user char name[32]; cout << "Enter Server Name:" << endl; gets( name ); _bstr_t Server = name; // remote server info COSERVERINFO cs; // Init structures to zero memset(&cs, 0, sizeof(cs)); // Allocate the server name in the COSERVERINFO struct cs.pwszName = Server; // structure for CoCreateInstanceEx MULTI_QI qi[1]; memset(qi, 0, sizeof(qi)); // initialize COM hr = CoInitialize(0); ShowStatus( hr ); // macro to check for success if (SUCCEEDED(hr)) { // set a low level of security hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); // init security ShowStatus( hr ); } if (SUCCEEDED(hr)) { // Fill the qi with a valid interface qi[0].pIID = &IID_IGetInfo; // get the interface pointer hr = CoCreateInstanceEx(
CLSID_GetInfo, // clsid NULL, // outer unknown CLSCTX_SERVER, // server context &cs, // server info 1, // size of qi qi ); // MULTI_QI array ShowStatus( hr ); } if (SUCCEEDED(hr)) { BSTR bsName; // Basic style string // Extract the interface from the MULTI_QI strucure pI = (IGetInfo*)qi[0].pItf; // Call a method on the remote server hr = pI->GetComputerName( &bsName ); ShowStatus( hr ); // Convert name to a printable string _bstr_t bst( bsName ); cout << "Server Name :" << bst << endl; // get time from remote computer time_t tt; hr = pI->GetTimeT(&tt ); ShowStatus( hr ); // display time_t as a string cout << "Server Time :" << ctime( &tt ) << endl; // Release the interface pI->Release(); } // Close COM CoUninitialize(); // Prompt user to continue cout << "Press ENTER to continue" << endl; getchar(); return 0; } // main ends // Display detailed status information void ShowStatus( HRESULT hr ) { if (SUCCEEDED(hr)) { cout << "OK" << endl; } else { // construct a _com_error using the HRESULT _com_error e(hr); char temp[32]; // convert to hexidecimal string and display sprintf( temp, "0x%x", hr ); cout << "Error : " << temp << endl; // The hr as a decimal number cout << "Decimal : " << hr << endl; // show the 1st 16 bits (SCODE) cout << "SCODE : " << HRESULT_CODE( hr ) << endl; // Show facility code as a decimal number cout << "Facility: " << HRESULT_FACILITY( hr ) << endl; // Show the severity bit cout << "Severity: " << HRESULT_SEVERITY( hr ) << endl; // Use the _com_error object to format a message string. This is // Much easier then using ::FormatMessage
cout << "Message : " << e.ErrorMessage() << endl; } }
Things to do while working with DCOM Get it working locally 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. Don't forget to register the proxy/stub DLL or type library 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.) Try to get around name resolution problems 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 fullblown 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. Try DCOMCNFG and OLEVIEW 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. Ask a network administrator An administrator may be able to help you resolve tough security and name resolution problems. MSXML Example Msxml.tlh and msxml.tli files are to be copied
---------------------------------------------------------------------------------------------------------------------------------------------------------. h file #import <msxml.dll> #include MSXML::IXMLDOMDocumentPtr dptr; MSXML::IXMLDOMNodeListPtr nlptr; MSXML::IXMLDOMNodePtr nptr; ---------------------------------------------------------------------------------------------------------------------------------------------------------. cpp file #include <msxml.h> ::CoInitialize(0); MSXML::IXMLDOMDocumentPtr dptr =0; HRESULT hr = CoCreateInstance(CLSID_DOMDocument,0,CLSCTX_INPROCE_SERVER, IID_IXMLDomDocument, (Void**) &dptr); dptr-> Load (xmlfilename); ::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. This can be avoided by using the foll technique: 1)unlock the most recently locked objects first 2) ensure that threads lock shared objects in the same order 3) ensure that a thread which is causing another to wait does not use ::sendmessage() to send a message to the waiting thread , since sendmessage() would never return. 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. How do you Estimate Cost? There are 2 types 1) Top Down : here the cost is derived from the analysis of the major project component 2) Bottom Up : here the cost is derived by accumulating estimates from the people who are responsible for various project components. COCOMO model (Constructive Cost Model) gives the relationship between Effort Vs Size . Cost does not scale linearly with size General Testing terms: +ve Testing : determine whether the product meets the client req. - ve Testing : testing with the intend to find errors Activities of testing are => TestPlan -> test req -> testcase -> test data -> defect log -> feedback ---à TestPlan Adv of Construct init instead of Assigning inside the constructor? It makes more sense when handling with constant variables Struct P { const int size; P(int sz):size(sz) //only way { } }; How will you minimize interface dependencies between A and B files? Its very important not to include A.h inside B.h , instead include A.h inside B.cpp and provide A class forward declaration in B.h 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
Explain Types of Patterns? 1)Singleton pattern : provides only one instance of an object. To do this you have to declare all constructors as private. Next you can create objects either statically or on demand. In any case objects must stored privately. Provide public methods to access the object. 2) Factory pattern: here it ensures that the creation on objects happens in factory class rather than creation code be spread throughout the system. Advantage is if you add new objects in future only you have to change the code in the classfactory alone. 3) Visitor pattern: 4) Observer Pattern: Used if a group of objects needs to update themselves when someother object changes its state.(Doc-View arch) What is the role of Software Architecture? He is concerned not only with structure and behaviour but also with usage , functionality, performance, resilience, reuse, economic and technology constraints. An architecture mitigates the technical risks associated with a system.To lead the architect must be a good written and oral communicator. Diff between Architect and senior Developer=> The designer is concerned with what happens when a user presses a button and the architecture is concerned with what happens when 10000 users presses a button. The architecture you create must address the following services -> performance, scalability, reliability, availability, extensibility, maintainability, manageability and security. What are the types of scalability? Horizontal scaling involves adding more machines to the environment thus increasing the overall system capacity. Vertical scaling involves adding additional processors, memory or disks to the current machine. 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.
What is the difference between instance method and class method?
Instance method has a “this” reference whereas class method does not . What is the difference between instance variable and class variable?
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. Can you instantiate an interface?
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. 2. Who created UML? UML was created at Rational Software by methodologists Grady Booch, Ivar Jacobson, and Jim Rumbaugh with input from other leading methodologists, many software vendors, as well as end-users. Its aim is to unify the various existing systems into a best-of-breed modeling language. 3. Is UML a standard? Yes. UML was adopted by the Object Management Group (www.omg.org) as a standard in November, 1997. 4. What can I use UML for? UML was designed with these primary purposes in mind: 1) Business process modeling with use cases 2) Class and object modeling 3) Component modeing 4)
Distribution and deployment modeling
5. Do I really need UML? Can't I just describe how my application is designed using regular words? Instead of describing interrelated processes and code architecture in words, many people prefer to use a diagram to visualize the relationship of elements to one another. UML is a standard way to create these diagrams. As a result, it makes it easier for programmers and software architects to communicate. 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. 8. Are there UML-based tools that I can use today? Yes. Many UML tools are starting to appear. The most popular visual modeling tool is Rational Rose from Rational Sofware (www.rational.com/products/rose), the originators of UML. 9. What is a process? Defines Who is doing What, When to do it, and How to reach a certain goal. 10. What is an artifact? It’s a piece of information that is produced, modified, or used by a process 11. Define the workflow available in UML?
Requirement(usecase model), Analysis(Analysis model), Design(Design and Deployment model), Implementation (Impl. Model) and Test (Test model) Note: Usecases bind these workflows together. Explain the diff between DBMS and RDBMS?
DBMS : a computer program that manages a permanent , self-descriptive repository of data 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. #import "..\server\server.tlb" no_namespace named_guids int main( int argc, char *argv[] ) { ... IMathPtr ptrMath; // Create an instance of the server try { HRESULT hr; hr = ptrMath.CreateInstance( CLSID_Math ); if ( FAILED( hr )) _com_issue_error( hr ); } catch( _com_error& e ) { cout << "Error creating instance" << endl; cout << "HRESULT message is " << e.ErrorMessage() << endl; cout << e.Description() << endl; return -1; } The #import keyword is most useful when developing COM client applications. By using the wrapper classes you don't have to write nearly as much client-side code. Should I use ATL's CComBSTR class or the native _bstr_t type? _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. Why should I use ATL instead of MFC when developing components?
• • •
ATL provides dual interface support as part of its basic implementation. MFC requires a lot of additional work to add dual support. ATL provides support for all of COM's threading models, in particular the free threading model. MFC does not and probably will never support the free threading model because MFC is thread safe only at the class level. ATL does not require MFC's 1 meg runtime (MFC40.DLL). This isn't necessarily an issue because it is present on most systems, however it definitely increases load times for your component.
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 RAD Model = Prototype Model + Waterfall Model Like prototype model, the customer is kept in the loop continuously so that changes are reflected timely and accurately , Like waterfall model, it impose some structure in quality assurance and req capturing. But RAD is faster and responsiveness. Disadvantage : For development it requires modeling tools and CASE tools, Continuous Customer involvement Advantage : Component re-use and Building blocks approach 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. Debugging Visual C++ windows Author: Keith Bugg 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.
C++ Handlerstry, throw and catch 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 */ my_array = new int[array_size][10];
// use my_array release the memory when you're done with it: delete []my_array; How can I handle a destructor that fails? Write a message to a log-file. But do not throw an exception! . Reason: The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception. (i.e., all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding. ). During stack unwinding, all the local objects in all those stack frames are destructed. Note: Never throw an exception from a destructor. How should I handle resources if my constructors may throw exceptions? 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." Why would I use a const variable / const identifier as opposed to #define? const identifiers are often better than #define because:
•
they obey the language's scoping rules
•
you can see them in the debugger
•
you can take their address if you need to
•
you can pass them by const-reference if you need to
•
they don't create new "keywords" in your program.
There are cases where #define is needed, but you should generally avoid it when you have the choice Why is my executable so large? 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 library is quite large, and consists of numerous classes and virtual functions. Using any part of it might pull in nearly all of the 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 How do I display text in the status bar using MFC? CString s = "Text"; CStatusBar* p = (CStatusBar*)AfxGetApp()->m_pMainWnd-
>GetDescendantWindow(AFX_IDW_STATUS_BAR); p->SetPaneText(1, s); What's the difference between C++ and Visual C++? C++ is the language itself Visual C++ is a compiler that tries to implement the language. How do I convert a value (a number, for example) to a std::string? The library allows you to convert pretty much anything to a std::string using the following syntax // File: convert.h #include #include <sstream> #include <string> #include <stdexcept> class BadConversion : public std::runtime_error { public: BadConversion(const std::string& s) : std::runtime_error(s) {} }; inline std::string stringify(double x) { std::ostringstream o; if (!(o << x)) throw BadConversion("stringify(double)"); return o.str(); } #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. How do I convert a std::string to a number? The library allows you to convert a std::string to pretty much anything using the following syntax // File: convert.h #include #include <sstream> #include <string> #include <stdexcept> class BadConversion : public std::runtime_error { public: BadConversion(const std::string& s) : std::runtime_error(s)
{} }; inline double convertToDouble(const std::string& s) { std::istringstream i(s); double x; if (!(i >> x)) throw BadConversion("convertToDouble(\"" + s + "\")"); return x; } #include "convert.h" void myCode() { std::string s = ...a string representation of a number...; ... double x = convertToDouble(s); ... } Why can't the compiler find my header file in #include "c:\test.hpp" ? #include "/version/next/alpha/beta/test.hpp"
// RIGHT! (use forward slashes ("/") rather than backslashes
("\") in your #include filenames) #include "\version\next\alpha\beta\test.hpp"
// WRONG!
What's the deal with operator Overloading?
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
Can I use realloc() on pointers allocated via new ? No
Do I need to check for NULL after p = new Fred ()?
No. In C++, if the runtime system cannot allocate sizeof(Fred) bytes of memory during p = new Fred(), a std::bad_alloc exception will be thrown. Unlike malloc(), new never return NULL Do I need to check for NULL before delete p?
No. The C++ language guarantees that delete p will do nothing if p is equal to NULL In p = new Fred(), does the Fred memory "leak" if the Fred constructor throws an exception?
No. If an exception occurs during the Fred constructor of p = new Fred(), the C++ language guarantees that the memory sizeof(Fred) bytes that were allocated will automagically be released back to the heap. What if I forget the [] when deleteing array allocated via new T[n]?
Leads to Heap corruption is a likely result. Or worse. Your program will probably die Is it legal (and moral) for a member function to say delete this?
As long as you're careful, it's OK for an object to commit suicide (delete this). What does "const Fred& x" mean? It means x aliases a Fred object, but x can't be used to change that Fred object. Does "Fred& const x" make any sense? No, it is nonsense. But that is redundant, since references are always const. You can't reseat a reference. What does "Fred const& x" mean?
Fred const& x is functionally equivalent to const Fred& x.
What is a "const member function"? A member function that inspects (rather than mutates) its object.
What does "const int* p" means ? Because "const int* p" means "p promises not to change the *p When should my destructor be virtual? When someone will delete a derived-class object via a base-class pointer
How do I separate interface from implementation in C++?
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. What is a "pure virtual" member function? A member function declaration that turns a normal class into an abstract class How can I set up my member function so it won't be overridden in a derived class? Simply add a comment next to the method and rely on code reviews or random maintenance activities to find violators How can I tell if an integer is a power of two without looping? inline bool isPowerOf2(int i)
{ return i > 0 && (i & (i - 1)) == 0; }
Is the type of "pointer-to-member-function" different from "pointer-to-function"? YES. Consider this example int f(char a, float b);
•
Its type is "int (*)(char,float)" if an ordinary function
•
Its type is "int (Fred::*)(char,float)" if a non-static member function of class Fred
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)". What is a "parameterized type"?
Another way to say, "class templates."
Explain the types of Marshalling and Define them ? 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 : it support only variant types to support scripting client
A good Example to explain 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. 2.
Pass it as a parameter in a method call on a COM interface (i.e. the normal way!) 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 Standard Marshaller. 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.