Sunday, August 28, 2016

Remoting FAQ's


01. What distributed process frameworks outside .NET do you know? Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model  (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).

02. What are possible implementations of distributed applications in .NET?   .NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in  System.Runtime.Remoting and System.Web.Services.

03. When would you use .NET Remoting and when Web services?
Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for     open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.

04. What's a proxy of the server object in .NET Remoting?
 It's a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the  communication between real server object and the client object. This process is also known as marshaling.

05. What are remotable objects in .NET Remoting?
Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where  a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a  reference to an existing object is passed.

06. What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from  one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.

07. What security measures exist for .NET Remoting in System.Runtime.Remoting?
 None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied  at application or server level.

08. What is a formatter?  A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.

09. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs? Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

10. What's SingleCall activation mode used for? If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

11. What's Singleton activation mode? A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by  lifetime lease.

12. How do you define the lease of the object?
By implementing ILease interface when writing the class code.

13. Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.


14. How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.   

15. What are CAO's i.e. Client Activated Objects ?
Client-activated objects are objects whose lifetimes are controlled by the calling application domain, just as they would be if the object were local to the client. With client activation, a round trip to the server occurs when the client tries to create an instance of the server object, and the client proxy is created using an object reference (ObjRef) obtained on return from the creation of the remote object on the server. Each time a client creates an instance of a client-activated type, that instance will service only that particular reference in that particular client until its lease expires and its memory is recycled. If a calling application domain creates two new instances of the remote type, each of the client references will invoke only the particular instance in the server application domain from which the reference was returned.
In COM, clients hold an object in memory by holding a reference to it. When the last client releases its last reference, the object can delete itself. Client activation provides the same client control over the server object's lifetime, but without the complexity of maintaining references or the constant pinging to confirm the continued existence of the server or client. Instead, client-activated objects use lifetime leases to determine how long they should continue to exist. When a client creates a remote object, it can specify a default length of time that the object should exist. If the remote object reaches its default lifetime limit, it contacts the client to ask whether it should continue to exist, and if so, for how much longer. If the client is not currently available, a default time is also specified for how long the server object should wait while trying to contact the client before marking itself for garbage collection. The client might even request an indefinite default lifetime, effectively preventing the remote object from ever being recycled until the server application domain is torn down. The difference between this and a server-activated indefinite lifetime is that an indefinite server-activated object will serve all client requests for that type, whereas the client-activated instances serve only the client and the reference that was responsible for their creation. For more information, see Lifetime Leases.
To create an instance of a client-activated type, clients either configure their application programmatically (or using a configuration file) and call new (New in Visual Basic), or they pass the remote object's configuration in a call to Activator.CreateInstance. The following code example shows such a call, assuming a TcpChannel has been registered to listen on port 8080.

16. How many processes can listen on a single TCP/IP port?
One.

17. What technology enables out-of-proc communication in .NET?
Most usually Remoting;.NET remoting enables client applications to use objects in other processes on the same computer or on any other computer available on its network.While you could implement an out-of-proc component in any number of other ways, someone using the term almost always means Remoting.

18. How can objects in two diff. App Doimains communicate with each other? .Net framework provides various ways to communicate with objects in different app domains. First is XML Web Service on internet, its good method because it is built using HTTP protocol and SOAP formatting.
If the performance is the main concern then go for second option which is .Net remoting because it gives you the option of using binary encoding and the default TcpChannel, which offers the best interprocess communication performance
19. What is the difference between .Net Remoting and Web Services? Although we can develop an application using both technologies, each of them has its distinct advantages. Yes you can look at them in terms of performance but you need to consider your need first. There are many other factors such authentications, authorizing in process that need to be considered.
 Point
 Remoting
 Webservices
 If your application needs interoperability with other platforms or operating systems
 No
 Yes, Choose Web Services because it is more flexible in that they are support SOAP.
 If performance is the main requirement with security
 You should use the TCP channel and the binary formatter
 No
 Complex Programming
 Yes
 No
 State Management
 Supports a range of state management, depending on what object lifetime scheme you choose (single call or singleton call).
 Its stateless service management (does not inherently correlate multiple calls from the same user) 
 Transport Protocol
 It can access through TCP or HTTP channel.
 It can be access only through HTTP channel.


C++ interview question

1. What is virtual constructors/destructors?
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-class destructor. This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. Does c++ support multilevel and multiple inheritance?
Yes.

2. Why Garbage collection?
Since C++ does not provide automatic garbage collection like some other languages, smart pointers can be used for that purpose. The simplest garbage collection scheme is reference counting or reference linking, but it is quite possible to implement more sophisticated garbage collection schemes with smart pointers.

3. How to write a swap( ) function which swaps the values of the variables using bitwise operators.?
Ans: Here is the swap( ) function.
swap ( int *x, int *y )
{
*x ^= *y ;
*y ^= *x ;
*x ^= *y ;
}
The swap( ) function uses the bitwise XOR operator and does not require any temporary variable for swapping.

4. What are the advantages of inheritance?
• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged high-quality software, thus reducing problem
after a system becomes functional.

5. What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j>=0; j--) //function body
cout<<”*”; cout< function_declaration; template
function_declaration;
The only difference between both prototypes is the use of keyword class or typename, its use is
indistinct since both expressions have exactly the same meaning and behave exactly the same way.

6. What do you mean by inline function?
The idea behind inline functions is to insert the code of a called function at the point where the
function is called. If done carefully, this can improve the application's
performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.

7. What is virtual class and friend class?
Friend classes are used when two or more classes are designed to work together and need access
to each other's implementation in ways that the rest of the world
shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has.

8. What is function overloading and operator overloading?
Student Resources Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call.
Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.
Operator overloading allows existing C++ operators to be redefined so that they work on objects
of user-defined classes. Overloaded operators are syntactic sugar for
equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce
maintenance costs).

9. Difference between realloc() and free()?
The free subroutine frees a block of memory previously allocated by the malloc subroutine.
Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer

10. What do you mean by binding of data and functions?
Encapsulation.

11. What is abstraction?
Abstraction is of the process of hiding unwanted details from the user.
12. What is encapsulation?
Packaging an object’s variables within its methods is called encapsulation.
13. What is the difference between an object and a class?
Classes and objects are separate but related concepts. Every object belongs to a class and every
class contains one or more related objects.
Ø A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.
Ø The class to which an object belongs is also (usually) static. If a particular object belongs to a
certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.

Ø An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

14. What is polymorphism? Explain with an example?
"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or
reference) to assume (be replaced by) or become many different forms of
object.
Example: function overloading, function overriding, virtual functions. Another example can be a plus ‘+’ sign, used for adding two integers or for using it to concatenate two strings.

15. What do you mean by inheritance?
Inheritance is the process of creating new classes, called derived classes, from existing classes or
base classes. The derived class inherits all the capabilities of the base class, but can add
embellishments and refinements of its own.
16. What is a scope resolution operator?
A scope resolution operator (::), can be used to define the member functions of a class outside the class.
17. What are virtual functions?
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever
the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

18. What is friend function?
As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of
the class. But it must be listed in the class definition.

19. What is the difference between class and structure?
Structure: Initially (in C) a structure was used to bundle different type of data types together to
perform a particular functionality. But C++ extended the structure to contain functions also. The
major difference is that all declarations inside a structure are by default public.
Class: Class is a successor of Structure. By default all the members inside the class are private.

20. What is public, protected, private?
Ø Public, protected and private are three access specifiers in C++.
Ø Public data members and member functions are accessible outside the class.
Ø Protected data members and member functions are only available to derived classes.
Ø Private data members and member functions can’t be accessed outside the class.
However there is an exception can be using friend classes.

21. What is an object?
Object is a software bundle of variables and related methods. Objects have state and behavior.
22. What is a class?
Class is a user-defined data type in C++. It can be created to solve a particular kind of problem.
After creation the user need not know the specifics of the working of a class.


Q. When linking C or Assembly language modules with C++ modules I get undefined symbol errors at link time. It appears that none of the C or Assembly public symbols can be found.

A. C++ is a strongly typed language. In order to support the language to its fullest, Turbo C++ must attach information to the symbols generated for function names and variables. When this is done, the symbol will no longer match the standard C style function name. In order to link correctly, the compiler must be notified that the symbol is declared in an external module without type information tacked on to the symbol. This is done by prototyping the function as type extern "C". Here is a quick example: extern "C" int normal_c_func( float, int, char ); // name not altered void cplusplus_function( int ); // name altered See related comments under Linker Errors and in the Paradox Engine question in this section.

Q. Classes with static data members are getting linker errors ("undefined").

A. This code is built into Turbo C++ 1.0 but not in version 3.0. In the 1.0 compiler, static members without definitions were given a default value of 0. This default definition will no longer be made in the compiler. The programmer must now give an explicit definition for each static member. Here is a quick example:
class A
{
static int i;
};
A linker error saying that A::i is not defined will result unless the source also contains a line such as:
int A::i = 1;

Q. What potential problems can arise from typecasting a base class pointer into a derived class pointer so that the derived class's member functions can be called?

A. Syntactically this is allowable. There is always the possibility of a base pointer actually pointing to a base class. If this is typecast to a derived type, the method being called may not exist in the base class. Therefore, you would be grabbing the address of a function that does not exist.

Q: What's the difference between the keywords STRUCT and CLASS?

A: The members of a STRUCT are PUBLIC by default, while in CLASS, they default to PRIVATE. They are otherwise functionally equivalent.

Q: I have declared a derived class from a base class, but I can't access any of the base class members with the derived class function.

A: Derived classes DO NOT get access to private members of a base class. In order to access members of a base class, the base class members must be declared as either public or protected. If they are public, then any portion of the program can access them. If they are protected, they are accessible by the class members, friends, and any derived classes.

Q: How can I use the Paradox Engine 1.0 with C++?,
A: Because the Paradox Engine functions are all compiled as C functions, you will have to assure that the names of the functions do not get "mangled" by the C++ compiler. To do this you need to prototype the Engine functions as extern "C". In the pxengine.h header file insert the following code at the lines indicated.

/* inserted at line # 268 */
#ifdef __cplusplus
extern "C" {
#endif

/* inserted at line # 732, just before the final #endif */
#ifdef __cplusplus
}
#endif

Paradox Engine version 2.0 is "aware" of C++ and thus does not require any modifications to its header file.

Q: I have a class that is derived from three base classes. Can I insure that one base class constructor will be called before all other constructors?
A: If you declare the base class as a virtual base class, its constructor will be called before any non-virtual base class constructors. Otherwise the constructors are called in left-to-right order on the declaration line for the class.

Q: Are the standard library I/O functions still available for use with the C++ iostreams library?
A: Yes, using

#include

functions such as printf() and scanf() will continue to be available. However, using them in conjunction with stream oriented functions can lead to unpredictable behaviour.

Q. In C++, given two variables of the same name, one local and one global, how do I access the global instance within the local scope?
A. Use the scope (::) operator.

int x = 10;
for(int x=0; x < ::x; x++)
{
cout << "Loop # " << x << "\n"; // This will loop 10 times
}

Q. Will the following two functions be overloaded by the compiler, or will the compiler flag it as an error? Why?
void test( int x, double y); & int test( int a, double b);
A. The compiler will flag this as a redeclaration error because neither return types nor argument names are considered when determining unique signatures for overloading functions. Only number and type of arguments are considered.

Q. If I pass a character to a function which only accepts an int, what will the compiler do? Will it flag it as an error?
A. No. The compiler will promote the char to an int and use the integer representation in the function instead of the character itself.

Q. I was trying to allocate an array of function pointers using the new operator but I keep getting declaration syntax errors using the following
syntax: new int(*[10])(); What's wrong?
A. The new operator is a unary operator and binds first to the int keyword producing the following: (new int) (*[10])();
You need to put parentheses around the expression to produce the expected results: new (int (*[10]());

Q. What are inline functions? What are their advantages? How are they declared?
A. An inline function is a function which gets textually inserted by the compiler, much like macros. The advantage is that execution time is shortened because linker overhead is minimized. They are declared by using the inline keyword when the function is declared:

inline void func(void) { cout << "printing inline function \n"; }

or by including the function declaration and code body within a class:

class test
{
tv public:
void func(void) { cout << "inline function within a class.\n"}
};

Q. If I don't specify either public or private sections in a class, what is the default?
A. In a class, all members are private by default if neither public nor private sections are declared.

Q. What does the _seg modifier do?
A. Using _seg causes a pointer to become a storage place for a segment value, rather than an offset ( or a segment/offset ). For instance, if "int _seg *x" contains the value 0x40, then when you use "*x", the value pointed to will be at segment 0x40, offset 0. If you add a value to the pointer, the value is multiplied by the size of the pointer type. That new value is used as an offset, and is combined with the segment value contained in the pointer. For instance,

int _seg *x;
int value;

x = (int _seg *)0x40;
value = *(x + 20);

value is assigned the value of the integer at 0x40:0x28
(Remember, 20 * sizeof(int) = 40 = 0x28).


Q. Can I statically allocate more than 64K of data in a single module?
A. Yes. Far data items are now supported:

...
char far array1[60000L];
char far array2[60000L];
...

For arrays larger than 64k use:
char huge array3[100000L];

Q. What is a friend member function?
A. Declaring a friend gives non-members of a class access to the non-public members of a class.

Q. Why do I get a "Type name expected" error on my definition of a friend class in my new class?
A You need to let the compiler know that the label you use for your friend class is another class. If you do not want to define your entire class, you can simply have "class xxx", where xxx is your label.

Q: How can I output hex values in upper case using the iostream libraries?
A: You need to set the state of the stream using setf(). For example,

#include

int main(void)
{
cout << hex;
cout << "\nNot upper-case : " << 255;
cout.setf(ios::upper-case);
cout << "\nUppercase : " << 255;
return 0;
}

Q. What is the "this" pointer?
A. "this" is a local variable in the body of a non-static member function. It is a pointer to the object for which the function was invoked. It cannot be used outside of a class member function body.

Q. Why does a binary member function only accept a single argument?
A. The first argument is defined implicitly.

Q. Looking through the class libraries there are definitions in classes which look like:
class test {
int funct( void ) const;
};
What is the const keyword doing here?
A. There is a pointer to the object for which a function is called known as the 'this' pointer. By default the type of 'this' is X *const ( a constant pointer). The const keyword changes the type to const X *const ( a constant pointer to constant data ).

Q: I want to use _new_handler and set_new_handler.
A: Turbo C++ supports _new_handler and set_new_handler. The type of _new_handler is as follows.
typedef void (*vfp)(void);
vfp _new_handler;
vfp set_new_handler( vfp );

Q: I would like to use C++ fstreams on a file opened in binary mode, how is this done?
A: Use ios::binary as the open mode for the file:
#include
ifstream binfile;
binfile.open("myfile.bin", ios::binary);

Q: How can I get at the DOS file handle associated with my iostream?
A: Using a combination of member functions fd() and rdbuf() you can get at the file handle.
#include
#define fstrno(s) (((s).rdbuf())->fd())
ifstream test("test.txt");
cout << "handle is " << fstrno(test) << '\n';

C Interview Questions



Q. What is a pragma?
      The #pragma preprocessor directive allows each compiler to implement compiler-specific features that can be turned on and off with the #pragma statement. For instance, your compiler might support a feature called loop optimization. This feature can be invoked as a command-line option or as a #pragma directive.

To implement this option using the #pragma directive, you would put the following line into your code:

#pragma loop_opt(on)

Conversely, you can turn off loop optimization by inserting the following line into your code:

#pragma loop_opt(off)

Q. What is the difference between far and near?
Some compilers for PC compatibles use two types of pointers. Near pointers are 16 bits long and can address a 64KB range. Far pointers are 32 bits long and can address a 1MB range.

Near pointers operate within a 64KB segment. There’s one segment for function addresses and one segment for data. Far pointers have a 16-bit base (the segment address) and a 16-bit offset. The base is multiplied by 16, so a far pointer is effectively 20 bits long. Before you compile your code, you must tell the compiler which memory model to use. If you use a small code memory model, near pointers are used by default for function addresses.

That means that all the functions need to fit in one 64KB segment. With a large-code model, the default is to use far function addresses. You’ll get near pointers with a small data model, and far pointers with a large data model. These are just the defaults; you can declare variables and functions as explicitly near or far.

Far pointers are a little slower. Whenever one is used, the code or data segment register needs to be swapped out. Far pointers also have odd semantics for arithmetic and comparison. For example, the two far pointers in the preceding example point to the same address, but
they would compare as different! If your program fits in a small-data, small-code memory model, your life will be easier.

Q. When would you use a pointer to a function?
      Pointers to functions are interesting when you pass them to other functions. A function that takes function pointers says, in effect, “Part of what I do can be customized. Give me a pointer to a function, and I’ll call it when that part of the job needs to be done. That function can do its part for me.” This is known as a “callback.” It’s used a lot in graphical user interface libraries, in which the style of a display is built into the library but the contents of the display are part of the application.

As a simpler example, say you have an array of character pointers (char*s), and you want to sort it by the value of the strings the character pointers point to. The standard qsort() function uses function pointers to perform that task. qsort() takes four arguments,

Ø a pointer to the beginning of the array,

Ø the number of elements in the array,

Ø the size of each array element, and

Ø a comparison function, and returns an int.

Q. How are pointer variables initialized?
      Pointer variable are initialized by one of the following two ways

Ø Static memory allocation

Ø Dynamic memory allocation
.

Q. How can you avoid including a header more than once?
      One easy technique to avoid multiple inclusions of the same header is to use the #ifndef and #define
preprocessor directives. When you create a header for your program, you can #define a symbolic name that is unique to that header. You can use the conditional preprocessor directive named #ifndef to check whether that symbolic name has already been assigned. If it is assigned, you should not include the header, because it has already been preprocessed. If it is not defined, you should define it to avoid any further inclusions of the header. The following header illustrates this technique.

#ifndef _FILENAME_H
#define _FILENAME_H
#define VER_NUM “1.00.00”
#define REL_DATE “08/01/94”
#if _ _WINDOWS_ _
#define OS_VER “WINDOWS”
#else
#define OS_VER “DOS”
#endif
#endif

When the preprocessor encounters this header, it first checks to see whether _FILENAME_H has been defined. If it hasn’t been defined, the header has not been included yet, and the _FILENAME_H symbolic name is defined. Then, the rest of the header is parsed until the last #endif is encountered, signaling the end of the conditional #ifndef _FILENAME_H statement. Substitute the actual name of the header file for “FILENAME” in the preceding example to make it applicable for your programs.

Q. Difference between arrays and pointers?
      Ø Pointers are used to manipulate data using the address. Pointers use * operator to access the data pointed to by them

Ø Arrays use subscripted variables to access and manipulate data. Array variables can be equivalently written using pointer expression.

Q. What are the advantages of the functions?
      Ø Debugging is easier

Ø It is easier to understand the logic involved in the program

Ø Testing is easier

Ø Recursive call is possible

Ø Irrelevant details in the user point of view are hidden in functions

Ø Functions are helpful in generalizing the program.

Q. Is NULL always defined as 0?
      NULL is defined as either 0 or (void*)0. These values are almost identical; either a literal zero or a void pointer is converted automatically to any kind of pointer, as necessary, whenever a pointer is needed (although the compiler can’t always tell when a pointer is needed).

Q. What is the difference between NULL and NUL?
      NULL is a macro defined in <stddef.h> for the null pointer.

NUL is the name of the first character in the ASCII character set. It corresponds to a zero value. There’s no standard macro NUL in C, but some people like to define it.

The digit 0 corresponds to a value of 80, decimal. Don’t confuse the digit 0 with the value of ‘’ (NUL)!
NULL can be defined as ((void*)0), NUL as ‘’.

Q. Can the sizeof operator be used to tell the size of an array passed to a function?
      No. There’s no way to tell, at runtime, how many elements are in an array parameter just by looking at the array parameter itself. Remember, passing an array to a function is exactly the same as passing a pointer to the first element.

Q. Is using exit() the same as using return?
      No. The exit() function is used to exit your program and return control to the operating system. The return statement is used to return from a function and return control to the calling function. If you issue a return from the main() function, you are essentially returning control to the calling function, which is the operating system. In this case, the return statement and exit() function are similar.

Q. How many levels of pointers can you have?
      The answer depends on what you mean by “levels of pointers.” If you mean “How many levels of indirection can you have in a single declaration?” the answer is “At least 12.”

int i = 0;
int *ip01 = & i;
int **ip02 = & ip01;
int ***ip03 = & ip02;
int ****ip04 = & ip03;
int *****ip05 = & ip04;
int ******ip06 = & ip05;
int *******ip07 = & ip06;
int ********ip08 = & ip07;
int *********ip09 = & ip08;
int **********ip10 = & ip09;
int ***********ip11 = & ip10;
int ************ip12 = & ip11;
************ip12 = 1; /* i = 1 */

The ANSI C standard says all compilers must handle at least 12 levels. Your compiler might support more.

Q. What is the purpose of realloc( )?
      The function realloc(ptr,n) uses two arguments. The first argument ptr is a pointer to a block of memory for which the size is to be altered. The second argument n specifies the new size. The size may be increased or decreased. If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( ) may create a new region and all the old data are moved to the new region.

Q. Is it better to use a macro or a function?
      The answer depends on the situation you are writing code for. Macros have the distinct advantage of being more efficient (and faster) than functions, because their corresponding code is inserted directly into your source code at the point where the macro is called. There is no overhead involved in using a macro like there is in placing a call to a function. However, macros are generally small and cannot handle large, complex coding constructs. A function is more suited for this type of situation.

Additionally, macros are expanded inline, which means that the code is replicated for each occurrence of a macro. Your code therefore could be somewhat larger when you use macros than if you were to use functions.

Thus, the choice between using a macro and using a function is one of deciding between the tradeoff of faster program speed versus smaller program size. Generally, you should use macros to replace small, repeatable code sections, and you should use functions for larger coding tasks that might require several lines of code.

Q. What are the standard predefined macros?
      The ANSI C standard defines six predefined macros for use in the C language:

Macro Name Purpose

_ _LINE_ _ Inserts the current source code line number in your code.

_ _FILE_ _ Inserts the current source code filename in your code.

_ _DATE_ _ Inserts the current date of compilation in your code.

_ _TIME_ _ Inserts the current time of compilation in your code.

_ _STDC_ _ Is set to 1 if you are enforcing strict ANSI C conformity.

_ _cplusplus Is defined if you are compiling a C++ program.

Q. What is a const pointer?
      The access modifier keyword const is a promise the programmer makes to the compiler that the value of a variable will not be changed after it is initialized. The compiler will enforce that promise as best it can by not enabling the programmer to write code which modifies a variable that has been declared const.

A “const pointer,” or more correctly, a “pointer to const,” is a pointer which points to data that is const(constant, or unchanging). A pointer to const is declared by putting the word const at the beginning of the pointer declaration. This declares a pointer which points to data that can’t be modified. The pointer itself can be modified. The following example illustrates some legal and illegal uses of a const pointer:

const char *str = “hello”;
char c = *str /* legal */
str++; /* legal */
*str = ‘a’; /* illegal */
str[1] = ‘b’; /* illegal */

Q. why n++ executes faster than n+1?
      The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas; n+1 requires more instructions to carry out this operation.

Q. What is the difference between text and binary modes?
      Streams can be classified into two types: text streams and binary streams. Text streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the new line n character and vice versa. Binary streams are uninterrupted and are treated one byte at a time with no translation of characters. Typically, a text stream would be used for reading and writing standard text files, printing output to the screen or printer, or receiving input from the keyboard.

A binary text stream would typically be used for reading and writing binary files such as graphics or word processing documents, reading mouse input, or reading and writing to the modem.

Q. How do you determine whether to use a stream function or a low-level function?
      Stream functions such as fread() and fwrite() are buffered and are more efficient when reading and writing text or binary data to files. You generally gain better performance by using stream functions rather than their unbuffered low-level counterparts such as read() and write().

In multi-user environments, however, when files are typically shared and portions of files are continuously being locked, read from, written to, and unlocked, the stream functions do not perform as well as the low-level functions. This is because it is hard to buffer a shared file whose contents are constantly changing. Generally, you should always use buffered stream functions when accessing nonshared files and you should always use the low-level functions when accessing shared files.
Q. What is static memory allocation and dynamic memory allocation?
      Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time.

Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.

Q. When should a far pointer be used?
      Sometimes you can get away with using a small memory model in most of a given program. There might be just a few things that don’t fit in your small data and code segments. When that happens, you can use explicit far pointers and functions declarations to get at the rest of memory. A far function can be outside the 64KB segment most functions are shoehorned into for a small-code model. (Often, libraries are declared explicitly far, so they’ll work no matter what code model the program uses.)

A far pointer can refer to information outside the 64KB data segment. Typically, such pointers are used with farmalloc() and such, to manage a heap separate from where all the rest of the data lives. If you use a small-data, large-code model, you should explicitly make your function pointers far.

Q. What is the benefit of using const for declaring constants?
      The benefit of using the const keyword is that the compiler might be able to make optimizations based on the knowledge that the value of the variable will not change. In addition, the compiler will try to ensure that the values won’t be changed inadvertently.

Of course, the same benefits apply to #defined constants. The reason to use const rather than #define to define a constant is that a const variable can be of any type (such as a struct, which can’t be represented by a #defined constant). Also, because a const variable is a real variable, it has an address that can be used, if needed, and it resides in only one place in memory.

Q. What is the easiest sorting method to use?
      The answer is the standard library function qsort(). It’s the easiest sort by far for several reasons:

It is already written.
It is already debugged.
It has been optimized as much as possible (usually).
Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2));

Q. What is Preprocessor?
      The preprocessor is used to modify your program according to the preprocessor directives in your source code. Preprocessor directives (such as #define) give the preprocessor specific instructions on how to modify your source code. The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code. This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.

The preprocessor contains many features that are powerful to use, such as creating macros, performing conditional compilation, inserting predefined environment variables into your code, and turning compiler features on and off. For the professional programmer, in-depth knowledge of the features of the preprocessor can be one of the keys to creating fast, efficient programs.

Q. What is the heap?
      The heap is where malloc(), calloc(), and realloc() get memory.

Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isn’t deallocated automatically; you have to call free().

Recursive data structures are almost always implemented with memory from the heap. Strings often come from there too, especially strings that could be very long at runtime. If you can keep data in a local variable (and allocate it from the stack), your code will run faster than if you put the data on the heap. Sometimes you can use a better algorithm if you use the heap—faster, or more robust, or more flexible. It’s a tradeoff.

If memory is allocated from the heap, it’s available until the program ends. That’s great if you remember to deallocate it when you’re done. If you forget, it’s a problem. A “memory leak” is some allocated memory that’s no longer needed but isn’t deallocated. If you have a memory leak inside a loop, you can use up all the memory on the heap and not be able to get any more. (When that happens, the allocation functions return a null pointer.) In some environments, if a program doesn’t deallocate everything it allocated, memory stays unavailable even after the program ends
.

Q. What will the preprocessor do for a program?
      The C preprocessor is used to modify your program according to the preprocessor directives in your source code. A preprocessor directive is a statement (such as #define) that gives the preprocessor specific instructions on how to modify your source code. The preprocessor is invoked as the first part of your compiler program’s compilation step. It is usually hidden from the programmer because it is run automatically by the compiler.

The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code. This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.


Q. How do you use a pointer to a function?
      The hardest part about using a pointer-to-function is declaring it.

Consider an example. You want to create a pointer, pf, that points to the strcmp() function.

The strcmp() function is declared in this way:

int strcmp(const char *, const char * )

To set up pf to point to the strcmp() function, you want a declaration that looks just like the strcmp() function’s declaration, but that has *pf rather than strcmp:

int (*pf)( const char *, const char * );

After you’ve gotten the declaration of pf, you can #include <string.h> and assign the address of strcmp() to pf: pf = strcmp;


Q. What is the purpose of main( ) function?
      The function main( ) invokes other functions within it.It is the first function to be called when the program starts execution.

Ø It is the starting function

Ø It returns an int value to the environment that called the program

Ø Recursive call is allowed for main( ) also.

Ø It is a user-defined function

Ø Program execution ends when the closing brace of the function main( ) is reached.

Ø It has two arguments 1) argument count and 2) argument vector (represents strings passed).

Ø Any user-defined name can also be used as parameters for main( ) instead of argc and argv

Q. How can you restore a redirected standard stream?
      The preceding example showed how you can redirect a standard stream from within your program. But what if later in your program you wanted to restore the standard stream to its original state? By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state.

The dup() function duplicates a file handle. You can use the dup() function to save the file handle
corresponding to the stdout standard stream. The fdopen() function opens a stream that has been
duplicated with the dup() function.

Q. What is #line used for?
      The #line preprocessor directive is used to reset the values of the _ _LINE_ _ and _ _FILE_ _ symbols,
respectively. This directive is commonly used in fourth-generation languages that generate C language source files.
Q. What is the difference between the memmove() and memcpy() function?
      memmove() offers guaranteed behavior if the source and destination arguments overlap. memcpy() makes no such guarantee, and may therefore be more efficient to implement. It's always safer to use memmove().

Tuesday, April 15, 2014

Best practice for "Get FOLDER Path in C#"

private static void ImagePath()
        {
            string binpath = AppDomain.CurrentDomain.BaseDirectory;
            string appPath = binpath.Replace("bin\\Debug\\", string.Empty);
            ImageFolderPath = Path.Combine(appPath, @"PrintImage\PrintPage.bmp");
            //if (!Directory.Exists(fullpath)) return "";
            //else
            //return ImageFolderPath;          
        }

Tuesday, February 18, 2014

Export to CSV ,EXCEL ,PDF in WPF (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Collections;
using System.Windows.Controls.Primitives;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.Data;

namespace Binnovitec.GSMController.Dashboard.Helper
{
   public static class Export
    {      

       public static void ExportToPdf(DataGrid grid, string pathOfPdfWithFileName)
        {
            PdfPTable table = new PdfPTable(grid.Columns.Count);
            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            PdfWriter writer = PdfWriter.GetInstance(doc, new System.IO.FileStream(pathOfPdfWithFileName, System.IO.FileMode.Create));
            doc.Open();
            for (int j = 0; j < grid.Columns.Count; j++)
            {
                table.AddCell(new Phrase(grid.Columns[j].Header.ToString()));
            }
            table.HeaderRows = 1;
            IEnumerable itemsSource = grid.ItemsSource as IEnumerable;
            if (itemsSource != null)
            {
                foreach (var item in itemsSource)
                {
                    DataGridRow row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                    if (row != null)
                    {
                        DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(row);
                        for (int i = 0; i < grid.Columns.Count; ++i)
                        {
                            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(i);
                            TextBlock txt = cell.Content as TextBlock;
                            if (txt != null)
                            {
                                table.AddCell(new Phrase(txt.Text));
                            }
                        }
                    }
                }


                doc.Add(table);
                doc.Close();
            }
        }

       public static void ExportToCsv(DataGrid dgDisplay, string pathOfCSVWithFileName)
        {
            int h = 0;
            h = dgDisplay.Items.Count;
            dgDisplay.SelectAllCells();
            dgDisplay.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
            ApplicationCommands.Copy.Execute(null, dgDisplay);
            String resultat = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
            String result = (string)Clipboard.GetData(DataFormats.Text);
            dgDisplay.UnselectAllCells();
            System.IO.StreamWriter file = new System.IO.StreamWriter(pathOfCSVWithFileName);
            file.WriteLine(resultat);
            file.Close();
            // file1.Close();          

            MessageBox.Show("Excel file created.xls");
        }


        public static  void ExportToExcel(DataGrid dgDisplay, string pathOfExcelWithFileName) //Microsoft.Office.Interop.Excel.Application
        {
            int i = 0;
            int k = 1, h = 1;
            GetDataGridRows(dgDisplay);
            var rows = GetDataGridRows(dgDisplay);
            Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel._Workbook ExcelBook;
            Microsoft.Office.Interop.Excel._Worksheet ExcelSheet;
            ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1);
            ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet;
            for (i = 1; i <= dgDisplay.Columns.Count; i++)
            {
                ExcelSheet.Cells[1, i] = dgDisplay.Columns[i - 1].Header.ToString();
            }
            foreach (DataGridRow r in rows)
            {
                DataRowView rv = (DataRowView)r.Item;
                foreach (DataGridColumn column in dgDisplay.Columns)
                {
                    if (column.GetCellContent(r) is TextBlock)
                    {
                        TextBlock cellContent = column.GetCellContent(r) as TextBlock;
                        ExcelSheet.Cells[h + 1, k] = cellContent.Text.Trim();
                        k++;
                    }

                }
                k = 1;
                h++;
            }
            //ExcelApp.Visible = true;
            //ExcelApp.DisplayAlerts = false;
            ExcelBook.SaveAs(pathOfExcelWithFileName, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
    Excel.XlSaveConflictResolution.xlUserResolution, true,
    Missing.Value, Missing.Value, Missing.Value);
            ExcelBook.Close(pathOfExcelWithFileName, Missing.Value, Missing.Value);
            ExcelSheet = null;
            ExcelBook = null;
            ExcelApp = null;

            // return ExcelApp;

        }

        private static IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
        {
            var itemsSource = grid.ItemsSource as IEnumerable;
            if (null == itemsSource) yield return null;
            foreach (var item in itemsSource)
            {
                var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (null != row) yield return row;
            }
        }


        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T)
                    return (T)child;
                else
                {
                    T childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
    }
}