Archive for February, 2006

Interesting Win32 Questions

February 18, 2006
  1. Tell the differences between Windows 95 and Windows NT? Lack of Unicode
    implementation for most of the functions of Win95. Different extended error codes. Different number window and menu handles. Windows 95 implements some window management features in 16 bits. Windows 95 uses 16-bit world coordinate system and the coordinates restricted to 32K. Deletion of drawing objects is different. Windows 95 does not implement print monitor DLLs of Windows NT. Differences in registry. Windows 95 does not support multiprocessor computers. NT implementation of scheduler is quite different. Different driver models. Win95 was built with back-compatibility in mind and ill-behaving 16-bit process may easily corrupt the system. Win95 starts from real DOS, while WinNT uses DOS emulation when one needs a DOS. Win95’s FAT is built over 16-bit win3.1 FAT (not FAT32!, actually, Win95’s FAT contains two FATs).
  2. What is the effective way of DIB files management? A: Memory-mapped file is the best choice for device-independent bitmaps. MMF allows to map the file to RAM/SWAP addresses and to let Windows handle all load/unload operations for the file.
  3. What should you be aware of if you design a program that runs days/weeks/months/years? A: When your program should run for a long time, you should be careful about heap allocations, because if you use new/delete intensively in your application, the memory becomes highly fragmented with a time. It is better to allocate all necessary memory in this case that many times small blocks. You should be especially careful about CString class which allocates permanent DLL
  4. What are the advantages of using DLL’s? DLLs are run-time modular. DLL is loaded when the program needs it. Used as a code sharing between executables.
  5. What are the different types of DLL’s? A: Extension, Regular and pure Win32 DLL (without MFC)
  6. What are the differences between a User DLL and an MFC Extension DLL? A: Extension DLL supports a C++ interface, i.e. can export whole C++ classes and the client may construct objects from them. Extension DLL dynamically links to MFC DLLs (those which name starts with MFC??.DLL) and to be synchronous with the version it was developed for. Extension DLL is usually small (simple extension DLL might be around 10K) Regular DLL can be loaded by any Win32 environment (e.g. VB 5) Big restriction is that regular DLL may export only C-style functions. Regular DLLs are generally larger. When you build a regular DLL, you may choose a static link (in this case MFC library code is copied to your DLL) and dynamic (in this case you would need MFC DLLs to be presented on the target machine)
  7. What do you have to do when you inherit from two CObject-based classes? A: First of all, this is a bad idea does not matter what tells you interviewer. Secondly, if you forced to use condemned rhombus structure, read Technical Note 16 in MSDN, which discusses why MFC does not support multiple inheritance and what to do in case you still need it (there are a few problems with CObject class, such as incorrect information, returned by IsKindOf() of CObject for MI, etc.)
  8. What are the additional requirements for inheritance from CWnd-based classes? A: Again, this is the bad idea. Try to find alternative solution. Anyway, if you have to multiply inherit from CWnd-based class, the following are additional requirements to the above conditions (again, this is extremely bad question for interview!!!): There must be only one CWnd-derived base class. The CWnd-derived base class must be the first (or left-most) base class.
  9. What is a “mutex”? A: Mutexes are the mechanism of process synchronization that might be used to synchronize data across multiple processes. Mutex is a waitable object while a critical section is not. Mutexes are significantly slower than critical sections.
  10. What’s the difference between a “mutex” and a “critical section”? Critical section provides synchronization means for one process only, while mutexes allow data synchronization across processes.
  11. What might be wrong with the following pseudo-code:
    INT I=2
    I = I + 1
    END DO
    A:This code is not thread safe. Suppose one thread increments I to 3 and then returns to the beginning of DO statement. Then it increments I to 4 and now context switch happens. Second thread increments I to 5. From this moment the code shown will execute forever until some external force intervention. Solution is obviously using some synchronization object to protect I from being changed by more than one thread.
  12. What is a deadlock ? A: A deadlock, very simply, is a condition in which two or more threads wait for each other to release a shared resource before resuming their execution. Because all threads participating in a deadlock are suspended and cannot, therefore, release the resources they own, no thread can continue, and the entire application (or, worse, more than one application if the resources are shared between threads in multiple applications) appears to hang.
  13. How can we create thread in MFC framework? A: Using AfxBeginThread.
  14. What types of threads are supported by MFC framework? A: Working thread and windows thread. Working thread usually does not have a user interface and easier to use. Windows thread has an user interface and usually used to improve responsiveness of the user input. Message Map
  15. When ON_UPDATE_COMMAND_UI is called? (message may vary) A: When a user of your application pulls down a menu, each menu item needs to know whether it should be displayed as enabled or disabled. The target of a menu command provides this information by implementing an ON_UPDATE_COMMAND_UI handler.
  16. What is a “hook”? A: A point in the Windows message-handling mechanism where an application can install a subroutine to monitor messages. You need hooks to implement your own Windows message filter.
  17. What are the difference between MFC Exception macros and C++ exception keywords? A:Actually, MFC macros may accept exception of only CException class or class, derived from CException, where as C++ exception mechanism accepts exception of ANY type Reusable Control Class
  18. How would you set the background of an edit control to a customized color? A: You have several choices, but the simplest one is subclassing. Kruglinski in his “Inside Visual C++” describes pretty well this process. Generally, you derive the class from none control class, override the messages you want (like WM_CTLCOLOR) and then in init function like OnInitialUpdate of CDialog, subclass the control with SubclassDlgItem().
  19. What is Message Reflection? How could you accomplish the above task using message reflection? A: See Technical Note 62 of MSDN. Usually, message is handled in the parent class that means you have to override message handler for each parent. Sometimes it is nice to handle a message in the control itself, without parent invocation. Such handling mechanism is called message reflection. Control “reflects” message to itself and then processes it. Use ON__REFLECT macro to create a reflected message.
  20. What is the command routing in MFC framework? A: CView => CDocument => CFrameWnd => CWinApp
  21. What’s the purpose of CView class? CDocument class? What are relationships between them? A: The CView class provides the basic functionality for user-defined view classes. A view is attached to a document and acts as an intermediary between the document and the user: the view renders an image of the document on the screen or printer and interprets user input as operations upon the document. The CDocument class provides the basic functionality for user-defined document classes. A document represents the unit of data that the user typically opens with the File Open command and saves with the File Save command. Users interact with a document through the CView object(s) associated with it. A view is a child of a frame window. The relationship between a view class, a frame window class, and a document class is established by a CDocTemplate object. A view can be attached to only one document, but a document can have multiple views attached to it at once.
  22. What class is responsible for document template in MDI application? A: CMultiDocTemplate.
  23. What function must be used to add document template? A: AddDocTemplate.
  24. What the main objects are created for SDI and MDI applications? A: CWinApp – application object. For MDI application with New document implementation CDocTemplate, CDocument, CView, CMainFrame. If your application is SDI, your CMainFrame class is derived from class CFrameWnd. If your application is MDI, CMainFrame is derived from class CMDIFrameWnd. For MDI application CMDIChildWindow is also created.
  25. We have a loop for 800,000. It fails on 756,322. How can we get the information before it fails? A: You could think of several way to debug this: Set the condition in debugger to stop when loop is passed around 756321 times. Throw an exception within a loop (may be not the best idea since exception does not show you the exact location of the fail. Create a log file and to put detailed information within a loop.
  26. Our Debug version works fine, but Release fails. What should be done? A: There are four differences between debug and release builds:
    • heap layout (you may have heap overwrite in release mode – this will cause 90% of all problems),
    • compilation (check conditional compilation statements, assertion functions etc.),
    • pointer support (no padding in release mode which may increase chances of a pointer to point into sky)
    • optimization.

    Check the project settings.


Top Ten of Programming Advice to NOT follow

February 17, 2006

Recently while checking smr’s blog i came across the article which is worth to read oit atleast once.

Copyright (C) 2006 Kristian Dupont Knudsen

The top ten list of programming advice to not follow:

10) Don’t use exceptions

Okay, I just had to throw in this particular one because it keeps showing up over at Joel’s. 🙂
Joel feels strongly about this and since he is read by many, I think he is considered somewhat of an authority in the area. However, exceptions are in my opinion superior to error return codes for many reasons.
This discussion relates to programming language discussions which tend to be dead ends, so I’ll step carefully. I think the number one reason why I like exceptions is that it makes it easier to convince myself that my invariants are enforced. Joel says: “Every time you call a function that can raise an exception and don’t catch it on the spot, you create opportunities for surprise bugs caused by functions that terminated abruptly, leaving data in an inconsistent state, or other code paths that you didn’t think about.” I would argue the exact opposite: everytime you call a function that merely returns an error code, you risk such surprises, simply because you may not react to this error code. Throwing exceptions is a way to ensure that code is not executed with a broken precondition. Error codes rely on the programmer to remember. In C++, Java and C#, constructors are the most obvious example. If something goes wrong during the construction of an object, throwing an exception is the only way to back out, unless you want to leave behind a zombie object. Granted, throwing an exception will cause your entire program to explode if you don’t catch it but at least, you will have valuable information about where things went wrong. Zombie objects on the other hand, are bombs with a timer set to go off in maybe a second or so, when code that relies on that particular object fails. Now, a second may not be a lot to you and me but to the computer, this is millions of instructions away from the erroneous code. Tracking that is a lot harder.

9) Use unsigned integers for values that can only be positive

I’m a bit nervous about this one because it is used in the STL and if there is one thing that I have learned it is that those guys thought things through. STL is an example of strikingly good design. However, in STL, size types – *::size_type are unsigned integers just like the old C size_t was. Why that is I simply don’t understand. Unsigned integer types seem nice at first because they feel safer. They have a constraint that says “this variable will never become negative” which makes perfect sense for a number of variables, such as sizes. Problem is, this constraint is enforced by wrapping rather than bounds checking (at least in C and C++ – in C# you can turn on overflow checking and as far as I know, Java doesn’t have unsigned integer types). Hence, you simply end up having no way to tell whether it has been violated or not – the bit which could be used for error indication is now used to gain size. But we’re talking one bit here, people. If you’re stretching your code so far as to require the size gained by that one bit, you are probably in the danger zone of introducing errors of more serious kinds.

8) Design classes parallel to their physical counterparts

I believe that one of the reasons why OO is so popular is that it is so easy to grasp. Inheritance and specialization really does seem to occur in real life and the concept of classes fits nicely into real life phenomena. A Ford is a car is a vehicle. Only this does not map very well to software. You’re not implementing a car. You’re probably implementing a record of a car which can carry a number of stock items from one city to another, with a certain mileage and speed. This is not a car, it is a virtual reference to a certain car. Thinking of it as a car will lead your design in the wrong direction. Even if you’re designing a model of a new prototype of car for Ford, which will be rendered in 3D with physical modelling and all, you’re _still_ not implementing a car. People who think in such parallels are likely to find themselves confused if they run into the “a square is a rectangle” problem. In math, squares may well be subclasses of rectangles but making square inherit from rectangle is plainly wrong.
But while I’m on the topic, I want to bring in a favourite nit of mine, namely that inheritance is overrated. It used to be the case with C++, though it seems most of the deep hierarchy people have moved to Java and C#, leaving the C++ community to evolve in a direction that I think is more promising. Danny Kalev puts this rather precisely.

7) Make sure your team shares a common coding standard

Not quite going to tell you to not do this, simply that I think it is much less important than people make it. Programmers can see through indentation and naming conventions, really. But alas, some don’t want to (I didn’t for a long time – I would actually spend a lot of time reformatting source code to fit my liking if I had to use it. Sigh).

Consider these two versions of the same function:

public string FormatAsHeadline(string sourceText)
string resultCode = "

" + sourceText + "

"; HeaderCount++; return resultCode; } public string format_as_headline (string source_text) { string result_code="


"; headerCount++; return result_code; }

Now tell me, is there one of the versions of the code above you could not immediately decipher? Of course not. The two pieces are semantically identical but they look different. But not so different that they would fool a programmer. Now, if you’re going to tell me that style is important, at least have the guts to admit that they only really are because of your aesthetical nit picking desires.

6) Write lots of comments

Make sure you comment your code. Otherwise, it will be impossible for anyone to understand – including yourself in a year or so. I have heard that many many times and thought that it was probably right. It makes sense after all, and I have often found use of comments when trying to find meaning in somebody elses code. Particularly, I have struggled with comment-less code and sworn that I would never make that mistake. However, this is mostly the case when the code is not self explanatory. Which it should be. If you feel the need to write comments in your code, I suggest you try to refactor instead, so comments won’t be needed. Renaming some variables or introducing a function call will probably do the trick. Context is better documented using assertions. In fact, a context that cannot be described using assertions is probably a bad sign!
There are times when comments serve a pupose though. Algorithmics can be hard to grasp and yet impossible to simplify through further abstractions. In such cases, you can explain yourself with comments. I think my colleague Lars Thorup pointed out a very good test for comments: they should contain the word “beacuse”. This way, you know that you are answering a why rather than a what.
Oh, and my favourite specialization of the comments advice: keep a history of changes and author info etc. in the top of each file.
I’ve never actually heard anyone say that you should do this but I have seen it so many times that there must be people out there recommending it. Why on earth you would clutter the code with information that so obviously belongs in the version control system is just beyond me.

5) Use accessors or properties rather than public fields

We’ve all learned this. Public fields are no good. Which is true, they’re not, because they break encapsulation. However, supplying accessors gives you but a tiny bit more encapsulation. What you need to do is determine why somebody from the outside needs to manipulate the inner workings of your class. Often, you will find that there should really be a method or set of methods that do the manipulation. Otherwise, your class might be the victim of what Martin Fowler calls “feature envy”, which means that other classes seem to wish they had the fields that your class does. Maybe they should, then?

4) Use the singleton pattern for variables that you KNOW you should have only one instance of

Global variables are evil. And just because you put a such into a class which in turn is put into a design pattern from nothing less than the GoF book, it is no less so. Variables should live in the innermost scope possible, since this makes every scope more deterministic. A method that relies only on local variables is easier to analyze than one that also relies on members of the class. Because instead of having to look around the method for places where manipulation takes place, you now have to look around the entire class. And guess what happens if you pull the variable even further out? That’s right – if global variables are used, you have to look around the entire program for manipulation.
On a more philosophical level, what is “global”? The date could be said to be a global variable, if one doesn’t consider timezones and such, but that is hardly what you mean. Neither is it what you get. “Global” in programming terms means per process. Which is sometimes fine but it is actually a rather arbitrary resolution given the distribution of many software systems. A software system can consist of many processes running on many machines – and each process may internally run many threads. In this perspective, process-level variables are really somewhat of an odd size.
I should note that this goes for mutable variables only. I think. Global, immutable variables – constants – are okay. For the simple reason that since they do not vary, determinism is maintained and, they can safely be accessed by all threads as well as multiple processes.

3) Be tolerant with input and strict with output

Yet another piece of advice that seems intuitive. My program or function should be able to accept almost anything but produce a very deterministic and streamlined set of results. This seems like really diplomatic behaviour, however, it easily conflicts with a principle that is of greater importance: fail fast. A function that accepts a vast variety of input formats is harder to test and harder to validate. Also, it allows for problems to propagate down the system – if a calling function supplied invalid data, this is less likely detected. This brings us back to the exceptions point. You will want to fail as soon as you realize something is wrong – and fail as effectively as possible. Not pleasant to the user, perhaps, but much easier to find and debug.
If you want to allow for various formats, for instance if you input is entered by the user, you should split your function into two: a normalization function and a processing function.

2) Code all the corner cases immediately, cause otherwise you’ll never go back and fix things

Why do we programmers feel guilty when not finishing a function? We’re simply keeping focus! First of all, the “you’ll never go back and fix it” argument is just silly. If you don’t then it’s obviously because it’s not necessary! But this point is part of an entirely different discussion about whether you focus on aesthetics or economics, which I will not bring up here.
Known hacks and incomplete code can be documented, preferably with a failing test. But you can write a todo-item in your taks list for all I care. Getting the broader picture together first is important because it shows you whether your solution is on the right track or not. When you are certain, focus on the details, but not before that. Which brings us to my number one piece of advice not to follow:

1) Design first, then code

Okay, things are going political now, but even though you will find many many people who disagree, I still feel that this is the single most valuable lesson that I have learned. Designing first and then coding simply doesn’t work. The problem is that this is so counter intuitive that you more or less have to find it out for yourself.
I think every programmer has experienced a project with no planning turning into a mess. Changing such code can only be done with hacks and patches to everyones great frustration. It is at that time that you realize that the only decent way to code is by designing things right from the start. Only now the frustration is even greater when you realize that your beautiful design isn’t prepared for exactly this new feature that you are to implement now. What to do then?
You should think before you code. Go ahead, but think for hours, not days. Don’t kid yourself into believing you can sketch an entire design document with UML diagrams and everything without making mistakes. At least, don’t think you can do so any faster than you could have simply written the code.
Now, if you’re not familiar with agile methodologies such as eXtreme Programming, the whole concept of evolving design sounds like the very problem programmers are trying to solve with all their clever ways of abstracting things out. And indeed, evolving design only works well if you follow a number of practices. Short iterations, automated testing and frequent refactoring being the most important.
I suggest you read Martin Fowler’s excellent article Is Design Dead? which explains it all a lot better that I am capable of.


February 11, 2006

 This is an abstract taken from here. I hope this will be enough to clear all the doubts regarding MFC /.Net Technologies for the starters.

1. What are the future plans for MFC, ATL in the .NET world? Are MFC and ATL’s days numbered?

This is a very popular question. I’m sure you’re aware that there are literally millions of Visual C++ developers who use, extend, and incorporate both MFC and ATL into their applications. In fact, as many as 75% of all Visual C++ developers use MFC. Microsoft considers these libraries to be extremely robust and mature – they’ve been around for a long time, have been used as the infrastructure for hundreds of thousands of applications, and have grown over the years with countless updates and extensions. They have been very successful. Our focus is starting to shift to .NET, but MFC and ATL will each be continually updated in order to maintain sync with operating system features, and will be maintained into the foreseeable future. Backwards compatibility is always an issue with libraries like these, and as computing environments and requirements change it becomes more and more difficult to extend an older technology and still retain robustness. The time has come for us to introduce a newer technology with a renewed lifespan, and the C++ team is committed to making the transition as easy and comfortable as possible for MFC developers. With Visual C++ .NET you can continue to use MFC and ATL where it makes sense, and begin the transition to the .NET Framework at a pace you set.

2. Where do these libraries fit into the .NET vision?

Today MFC and ATL fill roles that aren’t yet fully realized in .NET. .NET, with all of its thousands of classes in the framework library, doesn’t provide application framework functionality similar to that provided by MFC. Developers need to be aware of their options – both managed and unmanaged, and choose carefully the technology most suited for the task. Visual C++ developers are typically very advanced, and have for years been accustomed to choosing appropriate technologies for their applications — so this should be nothing new. With .NET, VC++ developers have the distinct advantage of being able to seamlessly integrate existing unmanaged code with newer managed code and data without the headaches of losing backwards compatibility or learning a new language. Managed extensions for C++ make sense for progressing applications forward, and they’re easy to use.

3. How long will these libraries be supported?

We have no plans to stop supporting any library shipping with Visual C++. All of the VC++ libraries have extremely high usage in real-world code, and Microsoft isn’t about to ignore this fact. We’ll continue to refine existing libraries, and have plans to introduce new libraries as technology evolves.

4. What are the new version numbers and DLL names for MFC and ATL?

MFC version 7.0 – MFC70.DLL
ATL version 7.0 – ATL70.DLL

Note the changes from the DLL names in 6.0 – we broke binary compatibility in order to make some key refinements to the libraries themselves. But your code will recompile against the new versions just fine.

5. Once .NET becomes established on every PC running Windows, will there be any reason at all to write C++ or MFC apps?

Assuming feature parity between .NET and MFC, a developer might choose MFC if there were a compelling need to write purely unmanaged code. Developers may choose to use C++ to target .NET because of the powerful C++ language features not found elsewhere, like templates, and the quality of code generated by the compiler. Visual C++ .NET is the only .NET compiler that generates highly optimized MSIL, and it is the only compiler that can generate an assembly image containing both managed and unmanaged code. Developers should choose C++ when they need unbounded flexibility and control.

6. Why would a developer wish to use MFC instead of Windows Forms, and why Windows Forms instead of MFC?

Windows Forms are a technology that do not yet provide the command-routing and document-view infrastructure found in MFC. Today, choosing Windows Forms is similar to choosing Visual Basic 6.0 in place of MFC. Each offer distinct advantages – the developer or architect must determine what priorities are relevant. The really sweet thing about C++ is that you can choose MFC and at the same time incorporate .NET technology where it makes sense. One reason we did this was so it would be dead-simple to extend existing applications without requiring them to be rewritten. A second reason is to enable the C++ developer to self-pace their adoption of .NET technology. We knew the C++ developer wouldn’t be interested in a technology that forced abandonment of their existing skills or code.

7. Will MS be writing any of their apps in MFC or will they start moving to C# and Windows Forms?

A majority of Microsoft applications are already incorporating .NET technology, using not only C#, but also C++ and Visual Basic .NET. There may well be less MFC development done at Microsoft going forward, but because MFC is integral to so many existing applications – our own and 3rd party — it will continue to be a viable and supported framework for some time to come.

8. What is the future of WTL? Will it be made an official framework?

We don’t have specific plans for WTL. However, we are rather stunned by its growing popularity and are keeping a close watch. It is not a topic we’re ignoring internally.

9. MFC and ATL had some changes under the hood, but no major facelift and only a handful of new classes. What were the reasons for this?

As I’ve said, these are mature libraries that accomplish their objectives well. Our intention is to enhance them to keep pace with operating system features, to refine them where it makes sense, and maintain backwards compatibility. The updates we made for Visual C++ .NET reflect this positioning, and comprise a slew of refinements that make these libraries easier and safer to use, while adding support for Windows 2000 and XP.

10. Can you give us a brief rundown of the new features in Visual C++?

The list is actually quite long – a full enumeration of new features exists in the product documentation under “What’s New in Visual C++ .NET”. I have several favorites that I’ve been using in my own code. For the first time, it is now easy to use both MFC and ATL in a single application – the compiler will no longer complain about conflicting header definitions. Both libraries now share CString, and have in common several of the other non CObject derived classes. This feature alone factors out a lot of potential for duplicated effort in code, and can lead to a much more elegant implementation. It’s about time we did this, and it just makes sense. The STL library has been entirely overhauled – with more readable source code, a faster and standards-compliant implementation, fixes to all known major issues like threading and cross-DLL usage, and, at long last, all new documentation. And of course, the compiler itself has loads of new options and features, including whole-program optimization, code security features including support for runtime buffer-overrun checking, and managed-code generation.

11. Can we expect MFC and ATL/WTL to be extended in the near future to cover new features and controls in W2K, XP and CE 2002? Will MFC try to emulate some of the new components in .NET?

Yes, MFC and ATL will continue to enable developers to target the newest features of Windows. If you want to include new .NET features in your MFC application you can do this directly – there’s no need for MFC emulation of the feature.

12. Are there any tools to help developers move from MFC/ATL to .NET?

Beyond the /CLR switch of the C++ compiler, no. Should there be? What would you like them to do? How should they work? We’re very interested in this and are keen to have feedback about the importance of such a tool.

13. Can I still use MFC and my old MFC components in .NET?

Yes. It is easy to wrap or extend existing C++ components so they are callable from .NET – by any language. This is much simpler than it used to be with COM and ActiveX. Simply add a keyword to mark an object as a .NET reference-type, and compile with /CLR. No IDL, no reference counting, no registration code. Code it and use it – very simple.

14. Will MFC and ATL be extended to cover XML Web Services?

MFC and ATL already have the capability to consume and expose XML Web Services in Visual C++ .NET, both with managed and unmanaged code.

15. The various wizards had some annoyances, such as not handling derived classes very well, or being too restrictive. How have Microsoft addressed this in Visual Studio .NET?

One way we’ve addressed this in Visual Studio .NET is by exposing, for the first time, an extremely extensive automation interface enabling developers and third-parties to create their own add-in applications. If a wizard or feature doesn’t do what you want it to, you can write your own. With VS.NET automation, you can plug into the IDE at the same level of integration as any of Microsoft’s features. If you’re a member of the VSIP program you can even integrate new languages and compilers with the IDE.

16. Will MFC be ported to managed code to allow it to be used in Managed C++

We won’t likely port MFC to be a fully managed library. But it is entirely feasible to extend your own MFC applications with managed code – without leaving C++.

17. Will there be a MFC-like framework for .NET?

The .NET framework will continue to evolve and will likely add capabilities that are found in MFC. The C++ team is driving for this internally – we want .NET to be a compelling and comfortable place for C++ developers. We’ll achieve this is in a couple of ways. First, we’ll continue to make it easy to use the .NET Framework in C++ code. Secondly, we’ll ensure that there are compelling reasons to continue using C++ – by enabling C++ to achieve a level of flexibility and control on .NET not found in other languages.

18. What compelling reasons are there to upgrade to Visual Studio .NET if I have no intention of writing managed code?

Every aspect of the product has updates – the IDE, the debugger, the compiler, the libraries. As I mentioned before, the compiler alone offers the several new optimization and code-security features that increase the robustness of your applications. Across the board we’ve overhauled features like Intellisense, debugging scenarios, even the warning and error messages you get building code.

Bottom line: building existing code with Visual Studio .NET will result in faster, more robust software with lots of new potential to expand the capabilities of your application with emerging technology.

19. Can I use Visual C++ .NET to develop traditional MFC apps?

Of course! No one is forcing VC++ developers to swallow .NET whole – in fact, managed-extensions aside, the majority of features we’ve added this iteration are geared at unmanaged code development. MFC development is better than ever with refined IDE integration, compile-time type-checking for message maps, ATL support, and new classes to access new OS features.

20. What’s your favorite Website? You guys rock.

Redistribution of mfc70.dll files

Is there anyone who knows which mfc70.dll files I need
to redistribute with my program? ( I don´t want to link
statically ) And is it safe to overwrite clients mfc70.dll if
the case is that is allready installed on their computer?

The following might be more than you are asking for…but it might be helpful…

You can link the MFC dll statically as suggested but I do not like this thing very much since it blows up your application file etc. Usually I suggest building a custom-based installation file (you can use InstallShield for example) which installs your application and all necessary dll’s on the target system even with version checking…

Updating system dll’s is always a tricky thing to do. But nevertheless sometimes your software requires changing some of the system dll’s.

In this context it is important to install a newer version of a file and not an older one. For example, you will want to install a newer version of a system DLL on top of an older version, but not an older version on top of a newer version. Typically, version checking is the responsibility of the setup program. If you write your own custom setup program, you must manually check the version when installing redistributable files.

First of all you need to find out which dll’s needs to be redistributed to make sure that your application will run independent of the installed dll’s on the target system. For an overview of the dependicies of your application you have two possibilities:

1. Use the ‘Dependency Walker’ (depends.exe)

2. Use ‘Dumpbin’ (dumpbin.exe) with the parameter /DEPENDENTS

Both methods will show you a list of dll’s that are linked to your application – either statically or dynamically. To find out which dll’s are dynamically loaded you need to use the profiling feature of the ‘Dependeny Walker’.

Be always aware that a dll might have dependicies to other dll’s or even a version of a specific dll. If you have installed your application on a target system and it won’t run you can again use the ‘Dependency Walker’. Run it on the target machine and it will report which dll’s are either missing or present with an incorrect version. Dll’s should always overwrite the existing dll’s to avoid multiple instances of the dll on the system.

If your application needs MFC support and you don’t want to link it statically to your application (which I normally not recommend) you need to distribute it as well. MFC dll’s are shared components therefore they will be placed within the system directory. You can get the system directory by a call to the API function



UINT GetSystemDirectory(LPTSTR lpBuffer, UINT uSize)

Again, installations within the system directory needs to be done carefully. NEVER overwrite a newer dll since other applications may rely on the specific version. To check the version of a dll Windows provides several API functions (Version API).

Your setup application needs to place needed files in the correct locations and prompt the user if the setup application notice some significantly difference like different language version or you try to overwrite a newer file with the older one. Therefore you will need some information on those files like name and location of the source and destination file and much more important the sharing status of the file (only used by one application or shared between multiple applications).

Regarding the location and the sharing status you can use the function



DWORD VerFindFile(DWORD  dwFlags,

                  LPTSTR szFileName,

                  LPTSTR szWinDir,

                  LPTSTR szAppDir,

                  LPTSTR szCurDir,

                  PUINT  lpuCurDirLen,

                  LPTSTR szDestDir,

                  PUINT  lpuDestDirLen)

This function will return several error codes whether the file is currently used by the system etc. Depending on the error code your setup program must react in a proper way.

To install the source file you should use the function



DWORD VerInstallFile(DWORD  uFlags,

                     LPTSTR szSrcFileName,

                     LPTSTR szDestFileName,

                     LPTSTR szSrcDir,

                     LPTSTR szDestDir,

                     LPTSTR szCurDir,

                     LPTSTR szTmpFile,

                     PUINT  lpuTmpFileLen)

since it will do some work for you. It copies the source file to a temporary file within the destination directory – if necessary it will expand a compressed file. After that an automatic comparison of the version information of the temporary and the destination file will be done. Again, your setup program should react to the returned error codes in a proper way. This function can be called multiple times with different flags. For example, if the first call returned an error indicating a version conflict you can force the installation disregarding the conflict by calling this function again with the ‘VIFF_FORCEINSTALL’ flag. On the other side your setup program needs to take care of the created temporary file by deleting them properly.

To retrieve the version information your setup program can use the following functions…



DWORD GetFileVersionInfoSize(LPTSTR lptstrFilename, LPDWORD lpdwHandle)


BOOL GetFileVersionInfo(LPTSTR lptstrFilename,

                        DWORD  dwHandle,

                        DWORD  dwLen,

                        LPVOID lpData)


BOOL VerQueryValue(const LPVOID pBlock,

                   LPTSTR       lpSubBlock,

                   LPVOID       *lplpBuffer,

                   PUINT        puLen)


DWORD VerLanguageName(DWORD wLang, LPTSTR szLang, DWORD nSize)

‘GetFileVersionInfoSize()’ returns the size of the version information. ‘GetFileVersionInfo()’ uses information retrieved by ‘GetFileVersionInfoSize()’ to retrieve a structure that contains the version information. ‘VerQueryValue()’ retrieves a specific member from that structure. Your setup program needs to call those function depending on the error code returned by e.g. ‘VerInstallFile()’.

C++ Coding Standards

February 11, 2006

Recently while surfing I came across UMBC(University of Maryland) website which had the C++ Coding standards to be followed for the submission of some assignment. Though for a short term programmers i can’t say but for genuine C++ lovers i think the standards are really worth it. Many a times we forget some small small points that can make your code more legible and believe me when it comes to documentation about half of the programmers feel that it is really not necessary to document the code. But when you look at the same code say about after 4-5 month you may have to struggle hard to understand YOUR code itself. So it is always a good practice to document your own code so that it can be reused at any point of time.
Though there are more stringent rules when it comes to coding standards but for the starters here’s the link.

Managed Code vs Unmanaged one

February 10, 2006

With the release of Visual Studio .NET many developers are now willing to consider using the new technology known as managed code. But especially for C++ developers, it can be a bit confusing. That’s because C++, as I pointed out in my first column here, is special.

What Is Managed Code?

Managed Code is what Visual Basic .NET and C# compilers create. It compiles to Intermediate Language (IL), not to machine code that could run directly on your computer. The IL is kept in a file called an assembly, along with metadata that describes the classes, methods, and attributes (such as security requirements) of the code you’ve created. This assembly is the one-stop-shopping unit of deployment in the .NET world. You copy it to another server to deploy the assembly there—and often that copying is the only step required in the deployment.

Managed code runs in the Common Language Runtime. The runtime offers a wide variety of services to your running code. In the usual course of events, it first loads and verifies the assembly to make sure the IL is okay. Then, just in time, as methods are called, the runtime arranges for them to be compiled to machine code suitable for the machine the assembly is running on, and caches this machine code to be used the next time the method is called. (This is called Just In Time, or JIT compiling, or often just Jitting.)

As the assembly runs, the runtime continues to provide services such as security, memory management, threading, and the like. The application is managed by the runtime.

Visual Basic .NET and C# can produce only managed code. If you’re working with those applications, you are making managed code. Visual C++ .NET can produce managed code if you like: When you create a project, select one of the application types whose name starts with .Managed., such as .Managed C++ application..

What Is Unmanaged Code?

Unmanaged code is what you use to make before Visual Studio .NET 2002 was released. Visual Basic 6, Visual C++ 6, heck, even that 15-year old C compiler you may still have kicking around on your hard drive all produced unmanaged code. It compiled directly to machine code that ran on the machine where you compiled it—and on other machines as long as they had the same chip, or nearly the same. It didn’t get services such as security or memory management from an invisible runtime; it got them from the operating system. And importantly, it got them from the operating system explicitly, by asking for them, usually by calling an API provided in the Windows SDK. More recent unmanaged applications got operating system services through COM calls.

Unlike the other Microsoft languages in Visual Studio, Visual C++ can create unmanaged applications. When you create a project and select an application type whose name starts with MFC, ATL, or Win32, you’re creating an unmanaged application.

This can lead to some confusion: When you create a .Managed C++ application., the build product is an assembly of IL with an .exe extension. When you create an MFC application, the build product is a Windows executable file of native code, also with an .exe extension. The internal layout of the two files is utterly different. You can use the Intermediate Language Disassembler, ildasm, to look inside an assembly and see the metadata and IL. Try pointing ildasm at an unmanaged exe and you’ll be told it has no valid CLR (Common Language Runtime) header and can’t be disassembled—Same extension, completely different files.

What about Native Code?

The phrase native code is used in two contexts. Many people use it as a synonym for unmanaged code: code built with an older tool, or deliberately chosen in Visual C++, that does not run in the runtime, but instead runs natively on the machine. This might be a complete application, or it might be a COM component or DLL that is being called from managed code using COM Interop or PInvoke, two powerful tools that make sure you can use your old code when you move to the new world. I prefer to say .unmanaged code. for this meaning, because it emphasizes that the code does not get the services of the runtime. For example, Code Access Security in managed code prevents code loaded from another server from performing certain destructive actions. If your application calls out to unmanaged code loaded from another server, you won’t get that protection.

The other use of the phrase native code is to describe the output of the JIT compiler, the machine code that actually runs in the runtime. It’s managed, but it’s not IL, it’s machine code. As a result, don’t just assume that native = unmanaged.

Does Managed Code Mean Managed Data?

Again with Visual Basic and C#, life is simple because you get no choice. When you declare a class in those languages, instances of it are created on the managed heap, and the garbage collector takes care of lifetime issues. But in Visual C++, you get a choice. Even when you’re creating a managed application, you decide class by class whether it’s a managed type or an unmanaged type. This is an unmanaged type:

class Foo
int x;
Foo(): x(0){}
Foo(int xx): x(xx) {}

This is a managed type:

__gc class Bar
int x;
Bar(): x(0){}
Bar(int xx): x(xx) {}

The only difference is the __gc keyword on the definition of Bar. But it makes a huge difference.

Managed types are garbage collected. They must be created with new, never on the stack. So this line is fine:

Foo f;

But this line is not allowed:

Bar b;

If I do create an instance of Foo on the heap, I must remember to clean it up:

Foo* pf = new Foo(2);
// . . .
delete pf;

The C++ compiler actually uses two heaps, a managed an unmanaged one, and uses operator overloading on new to decide where to allocate memory when you create an instance with new.

If I create an instance of Bar on the heap, I can ignore it. The garbage collector will clean it up some after it becomes clear that no one is using it (no more pointers to it are in scope).

There are restrictions on managed types: They can’t use multiple inheritance or inherit from unmanaged types, they can’t allow private access with the friend keyword, and they can’t implement a copy constructor, to name a few. So, you might not want your classes to be managed classes. But that doesn’t mean you don’t want your code to be managed code. In Visual C++, you get the choice.

Reference :