Wednesday, June 27, 2007
Threads in .NET
A common use of threads is for all kinds of periodical updates.
.NET offers three different ways:
Windows timers with the
System.WinForms.Timer class
Periodical delegate calling with
System.Threading.Timer class
Exact timing with the
System.Timers.Timer class
System.WinForms.Timer class :
For inexact timing we use the window timer. Events raised from the window timer go through the message pump (together with all mouse events and UI update messages) so they are never exact. The simplest way for creating a WinForms.Timer is by adding a Timer control onto a form and creating an event handler using the control's properties. We use the Interval property for setting the number of milliseconds between timer ticks and the Start method to start ticking and Stop to stop ticking.
System.Threading.Timer
class :
The System.Threading.Timer class is a new waiting thread in the thread pool that periodically calls supplied delegates. To use it you must perform several steps:
Create state object which will carry information to the delegate
Create TimerCallback delegate with a method to be called. You can use static or instance methods.
Create a Timer object with time to wait before first call and periods between successive calls (as names of this two parameters suggests, first parameter should be lifetime of this timer object, but it just don't work that way)
Change the Timer object settings with the Change method (same remark on parameters apply)
Kill the Timer object with the Dispose method
System.Timers.Timer
class :
The final timing options come from the System.Timers.Timer class. It represents server-based timer ticks for maximum accuracy. Ticks are generated outside of our process and can be used for watch-dog control. In the same System.Timers namespace you can find the Schedule class which gives you the ability to schedule timer events fired at longer time intervals.
System.Timers.Timer class is the most complete solution for all time fired events. It gives you the most precise control and timing and is surprisingly simple to use.
Create the Timer object. You can a use constructor with interval setting.
Add your event handler (delegate) to the Tick event
Set the Interval property to the desired number of milliseconds (default value is 100 ms)
Set the AutoReset property to false if you want the event to be raised only once (default is true – repetitive raising)
Start the ticking with a call to the Start() method, or by setting Enabled property to true.
Stop the ticking with call to the Stop() method or by setting the Enabled property to false.
Tuesday, June 26, 2007
Difference between finalize and dispose
For eg:
Difference between Bitmap and meta files
------------------------------------------------------------
1.Bitmaps are often used for very complex images originating in the real world, such as digitized photographs or video captures.
2.Metafiles are more suitable for human-generated or machine-generated images, such as architectural drawings.
The difference between bitmaps and metafiles is the difference between raster graphics and vector graphics.
1.Raster graphics treats output devices in terms of discrete pixels; ( Bitmap)
vector graphics treats the output device as a Cartesian coordinate system upon which lines and filled objects can be drawn.( Meta
file)
Bitmaps have two major drawbacks.
1.device dependence. For Example : The most obvious device dependency is color. Displaying a color bitmap on a monochrome
device is often unsatisfactory.
2.bitmap often implies a particular resolution and aspect ratio of an image. Although bitmaps can be stretched or compressed, this
process generally involves duplicating or dropping rows or columns of pixels, and this can lead to distortion in the scaled image. A metafile can
be scaled to almost any size without distortion.
3.bitmaps require a large amount of storage space.
Example :bitmap representation of an entire 640-by-480-pixel, 16-color Video Graphics Array (VGA) screen requires more than 150 KB; a
1024-by-768 image with 24 bits per pixel requires more than 2 MB.
Metafiles usually require much less storage space than bitmaps.
One advantage of bitmaps over metafiles, however, is speed.
Copying a bitmap to a video display is usually much faster than rendering a metafile. In recent years, compression techniques have allowed the
shrinking of bitmaps to a size where they can be effectively transmitted over telephone lines and used extensively in World Wide Web pages on
the Internet.
Mastering VC++
http://www.codeproject.com/useritems/OpenSource_VC_MFC.asp
http://win32assembly.online.fr/tutorials.html
VC++ Win32 Dialog box
-------------------------------------------
Dialog Box :
1.A dialog box generally takes the form of a popup window containing various child window controls.
2.The size and placement of these controls are specified in a "dialog box template" in the program's resource script file. (.rc)
3.window procedure for processing the dialog box messages is referred as the "dialog Procedure."
4.Dialog procedures generally do not process WM_PAINT messages.
5.dialog box can be considered as an input/output "black box" meaning that you don't have to know how a dialog box works internally in order to be able to use it, you only have to know how to interact with it.That's a principle of object oriented programming (OOP) called information hiding.
6.A dialog box is defined as a resource much the same way as a menu. You write a dialog box template describing the characteristics of the dialog box and its controls and then compile the resource script with a resource editor.
7.all resources are put together in the same resource script file.
two main types of dialog box:
1.modal
2.modeless.
Modeless dialog box :
A modeless dialog box lets you change input focus to other window. The example is the Find dialog of MS Word.
Modal dialog box :
two subtypes of modal dialog box:
1.application modal
2.system modal
An application modal dialog box doesn't let you change input focus to other window in the same application but you can change the input focus to the window of OTHER application.
A system modal dialog box doesn't allow you to change input focus to any other window until you respond to it first.
A modeless dialog box is created by calling CreateDialogParam API function.
A modal dialog box is created by calling DialogBoxParam API function.
The only distinction between an application modal dialog box and a system modal one is the DS_SYSMODAL style. If you include DS_SYSMODAL style in a dialog box template, that dialog box will be a system modal one.
Thursday, June 21, 2007
Difference between Panel and GroupBox classes?
1.Panel is scrollable and the captions can't be displayed in it
S.No Panel GroupBox
1 Can have scroll bars. Can't have scroll bars.
(Scrollable) (Unscrollable)
2. can't have captions can have captions
Wednesday, June 20, 2007
Marshalling Problem Practically applied
Simple DLL Developement :
1. open the simple Win32 DLL project ( TestDll) , it will creates the stdafx.h, stdafx.cpp and TestDll.cpp
2.Add the new header file (TestDll.h)
within the TestDll.h file I added the following code >..
#ifdef DLLDIR_EX
#define DLLDIR __declspec(dllexport) // export DLL information
#else
#define DLLDIR __declspec(dllimport) // import DLL information
#endif
extern "C"
{
bool DLLDIR GetStatusKeyword();
BOOL DLLDIR GetStatusTypedef();
}
within the TestDll.cpp file, I added the following :
#include "TestDll.h"
bool DLLDIR GetStatusKeyword()
{
return false;
}
BOOL DLLDIR GetStatusTypedef()
{
return false;
}
Select menu items as follows ...
Project ->Settings ->C++ -> General option
Add the DLLDIR_EX macro in the "Preprocessor Definitions " text box.
and then compile it
they will show the EXPORTS keyword in a text box and compile the DLL project.
I got the TestDll.dll and TestDll.lib output files .
Develope the C# client application :
Create the C# Console application and add the namespace "System.Runtime.InteropServices" to it
and add the code as follows :
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace TestDLLClient
{
class Win32API
{
[DllImport("TestDLL.dll")]
public static extern bool GetStatusTypedef();
[DllImport("TestDLL.dll")]
public static extern bool GetStatusKeyword();
}
class Program
{
static void Main(string[] args)
{
if (Win32API.GetStatusKeyword())
{
Console.WriteLine("\n GetStatusKeyword() fn succeeded ");
}
else
{
Console.WriteLine("\n GetStatusKeyword() fn failed ");
}
if (Win32API.GetStatusTypedef())
{
Console.WriteLine("\n GetStatusTypedef() fn Succeeded");
}
else
{
Console.WriteLine("\n GetStatusTypedef() fn failed");
}
Console.Read();
}
}
}
Next Copy the Testdll.dll and Testdll.lib to the "debug" folder of the C# client application.
then compile and run the C# application.
we got the output of the C# application is as follows:
GetStatusKeyword() fn succeeded
GetStatusTypedef() fn failed
Guys the problem is not over,
Next I modified the dll code as follows :
bool DLLDIR GetStatusKeyword()
{
OutputDebugString(" \n GetStatusKeyword() fn ..."); // This will writes the string in debug view...
return false;
}
BOOL DLLDIR GetStatusTypedef()
{
return false;
}
Next Compile the DLL project and copy the TestDll.dll and TestDll.lib to the C# client application's "Debug" folder.
Now Compile the C# application and see the result, u may wonder about the things...
The output is as follows :
GetStatusKeyword() fn failed
GetStatusTypedef() fn failed
It is a funny thing...
Note :
TestDLL application is developed in Visual studio 6.
C# client application is developed in .NET 2005...
Any guys got this problem before or try these things ....
Marshalling Problem :(funny )
if we are accessing the fn in a VC++ DLL from C# application :
Note the following thing :
1.Within the VC++ DLL fn always make the return type as BOOL instead of bool keyword.
Note :
Try the problem with a simple VC++ DLL contains BOOL as a return type and another fn returns bool data type.
Call it from C# application.
Problems I faced :
bool DLLDIR GetStatus()
{
return false;
}
if I accessed this fn from C# application I got the return value as true.
So try it ...
if it gives the true value then add the OutputDebugString() fn to the GetStatus() fn...
and see what will happen ...( Result : it returns false...)
It is the proposed standard to use BOOL instead of bool , if we access it using interoperability mechanism.
Address Increment with the help of sizeof() operator
x++; //it will increments the pointer by 2 bytes
char* y = new char[10];
x++; // it will increments the pointer by 1 byte
How pointers are moved during address addition or address subtraction operation ?
they will use sizeof() operator to find the size of it and added it.
For Example
int * x = new int[10];
++x;
can't invoke a non-const member function on a const object
Example :
class CTest
{
public:
CTest() { }
~CTest() { }
void Exam() { }
void Exam2() const { }
};
void f( const CTest testObj)
{
testObj.Exam() ; // Will cause an Error , we are invoking a non-const member function in a const object
}
Invoking a non-const member function on a const object.
Possible solutions
Remove the const from the object declaration.
Add const to the member function.
Example
// C2662.cpp
class C
{
public:
void func1();
void func2() const;
} const c;
int main()
{
c.func1(); // C2662
c.func2(); // no error
}
two input surfaces are same size for (2 In 1Out) DirectX transform filter
2 In 1 Out ( 2 Inputs and 1 Output )
accepts two inputs and gives one output.
Both the inputs must be the same size ?....
For 2 input directx transform filter,
Both the input surfaces must be the same size.
I tested it with XTL file with XTLTest sample application.
I have given two input video file.
One video file's resolution is 720 * 480 and another one video file's resolution is 320 * 240.
I used my two input directx transform filter.
video filenames and directx transform filter is specified in XTL file.
I run this .XTL file and generated the graph edit file (.grf). I learnt one thing from that Graphedit file.
if the video which is having large size is resized ( using resize filter ) to the another video file's size.
Then both video resolution is same size and then it is passed to the Transition DirectX transform filter (Wipe, DyadicArithmetic)
Tuesday, June 19, 2007
Lvalues and RValues
----------------------------------
An object is a contiguous region of storage. An lvalue is an expression that refers to such an object. The original
definition of lvalue referred to an object that can appear on the left-hand side of an assignment. However, const
objects are lvalues that cannot be used in the left-hand side of an assignment. Similarly, an expression that can appear
in the right-hand side of an expression (but not in the left-hand side of an expression) is an rvalue. For example
#include
using namespace std;
int& f();
void func()
{
int n;
char buf[3];
n = 5; // n is an lvalue; 5 is an rvalue
buf[0] = 'a'; // buf[0] is an lvalue, 'a' is an rvalue
string s1 = "a", s2 = "b", s3 = "c"; // "a", "b", "c" are rvalues
s1 = // lvalue
s2 +s3; //s2 and s3 are lvalues that are implicitly converted to rvalues
s1 = //lvalue
string("z"); //temporaries are rvalues
int * p = new int; //p is an lvalue; 'new int' is an rvalue
f() = 0; //a function call that returns a reference is an lvalue
s1.size(); //otherwise, a function call is an rvalue expression
}
An lvalue can appear in a context that requires an rvalue; in this case, the lvalue is implicitly converted to an rvalue.
An rvalue cannot be converted to an lvalue. Therefore, it is possible to use every lvalue expression in the example as an rvalue, but not vice versa.
Sunday, June 17, 2007
I implemented the StrConcat() fn in a VC++(unmanaged) DLL..
VC++ DLL code contains :
void StrConcat( char *pszSource, char* pszDest )
{
strcat(pszDest, pszSource); //copy the string
}
here is my new code ...we think it looks silly programming...
ok ...
pszSource and pszDest are arguments to the StrConcat( ) fn( Great Invention).
Important Points :
1.pszSource acts as a input parameter to StrConcat() fn.
2.pszDest acts as both input and output parameter to StrConcat() fn.
I need to call this method from C# application. we can make use of the .NET's platform invocation services to call the DLL fn in C#.
Platform Invocation Services :
-------------------------------------
1.Platform Invocation Services (PInvoke) allows managed code to call unmanaged functions that are implemented in a DLL.
Unmanaged code called in managed code through marshalling.
Calling a DLL Export Directly from C#
To declare a method as having an implementation from a DLL export, do the following:
1.Declare the method with the static and extern C# keywords
2.Attach the DllImport attribute to the method. The DllImport attribute allows you to specify the name of the DLL that contains the method. The common practice is to name the C# method the same as the exported method, but you can also use a different name for the C# method.
3.Optionally, specify custom marshaling information for the method's parameters and return value, which will override the .NET Framework default marshaling.
C# application :
class PlatformInvokeTest
{
[DllImport("CustomDLL.dll")]
public static extern void StrConcat(string source, string dest); // this is the C++ function //exposed by the dll
}
Did u think the above will concatenate the string ... I am sure we will not get the concatenated string in dest.
The reason is as follows :
I already told the Unmanaged code DLL is called through the marshalling mechanism.
for Marshalling, we have to specify whether In or Out parameter passed to the fn. if we are not specifying anything in dest string. we have to declare it as
follows :
[DllImport("CustomDLL.dll")]
public static extern void StrConcat(string source, ref string dest); // this is the C++ function exposed by the dll
we can specify the input parameter using In attribute.
we can specify the output parameter usign Out attribute.
if the parameter is both in and out parameter, At that time we have to use ref keyword to indicate the pass by reference.
Instead of it, we can use
[DllImport("CustomDLL.dll")]
public static extern void StrConcat(string source, StringBuilder dest); // this is the C++ function exposed by the dll
//StringBuilder class has both In and out attribute by default .
two types of Marshalling :
1.Default Marshalling
2.Custom marshalling
Default Marshaling and Specifying Custom Marshaling for Parameters to Unmanaged Methods
When calling an unmanaged function from C# code, the common language runtime must marshal the parameters and return values.
For every .NET Framework type there is a default unmanaged type, which the common language runtime will use to marshal data across a managed to unmanaged function call. For example, the default marshaling for C# string values is to the type LPTSTR (pointer to TCHAR char buffer). You can override the default marshaling using the MarshalAs attribute in the C# declaration of the unmanaged function.
About Example :
Next we have to call the VC++ function puts() from msvcrt.dll. this will displays the characters on screen .
Example for custom marshalling :
// Marshal.cs
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
[DllImport("msvcrt.dll")]
public static extern int puts(
[MarshalAs(UnmanagedType.LPStr)]
string m);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
public static void Main()
{
puts("Hello World!");
_flushall();
}
}
string is marshalled as LPSTR data type in VC++. // [MarshalAs(UnmanagedType.LPStr)]
Specifying Custom Marshaling for User-Defined Structs
You can specify custom marshaling attributes for fields of structs and classes passed to or from unmanaged functions. You do this by adding MarshalAs attributes to the fields of the struct or class. or we can use the StructLayout Attribute.
[StructLayout(LayoutKind.Sequential)]
public class LOGFONT
{
public const int LF_FACESIZE = 32;
public int lfHeight;
}
Callback function in VC++ DLL is converted as delegate in C# :
if the VC++ DLL have the Call back fn in a DLL as follows :
typedef void (__stdcall *PFN_MYCALLBACK)();
int __stdcall MyFunction(PFN_ MYCALLBACK callback);
we can call it through the delegate keyword.
How can we call the above fn in C# ?
To call MyFunction from managed code, declare the delegate, attach DllImport to the function declaration, and optionally marshal any parameters or the return value:
public delegate void MyCallback();
[DllImport("MYDLL.DLL")]
public static extern void MyFunction(MyCallback callback);
Summary :
1.we can call the Unmanaged DLL fn using DllImport attribute.
2.For every .NET Framework type there is a default unmanaged type, which the common language runtime will use to marshal data across a managed to unmanaged function call.
3.the default marshaling for C# string values is to the type LPTSTR (pointer to TCHAR char buffer). You can override the default marshaling using the MarshalAs attribute in the C# declaration of the unmanaged function.
4.we can do Custom Marshaling for User-Defined Structs using MarshalAs or StructLayout attribute.
5. Callback fn in unmanaged code(VC++ DLL) called with delegate in C#.( Managed code )
Saturday, June 16, 2007
DirectX transform is also a BHO ( Browser helper Object)
Browser Helper Object (BHO) is a DLL module designed as a plugin for Microsoft's Internet Explorer web browser to provide added functionality. BHOs were introduced in October 1997 with the release of version 4 of Internet Explorer. Most BHOs are loaded once by each new instance of Internet Explorer. However, in the case of the Windows File Explorer, a new instance is launched for each window.
Some modules enable the display of different file formats not ordinarily interpretable by the browser. The Adobe Acrobat plugin that allows Internet Explorer users to read PDF files within their browser is a BHO.
Other modules add toolbars to Internet Explorer, such as the Alexa Toolbar that provides a list of web sites related to the one you are currently browsing, or the Google Toolbar that adds a toolbar with a Google search box to the browser user interface.
Browser Helper Objects
HKLM\SOFTWARE\Microsoft\Windows \CurrentVersion\Explorer\Browser Helper Objects
If this key exists and there are CLSIDs listed under it, Internet Explorer will use CoCreateInstance() to try to create an instance of each object listed as a subkey under this key. Note that the CLSID of the object you create must be listed as a subkey and not a named value.
For example, imagine that the following entry exists in the registry, HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects\{CE7C3CF0-4B15-11D1-ABED-709549C10000}. Internet Explorer will try to create an instance of the object pointed to by the CLSID {CE7C3CF0-4B15- 11D1-ABED-709549C10000} each time Internet Explorer starts.
These registry keys can be created manually or through the self registration portion of your COM application.
There are some requirements when creating a Browser Helper Object
• The application that you create must be an in-proc server (that is, DLL).
• This DLL must implement IObjectWithSite.
• The IObjectWithSite::SetSite() method must be implemented. It is through this method that your application receives a pointer to Internet Explorer's IUnknown. (Internet Explorer actually passes a pointer to IWebBrowser2 but the implementation of SetSite() receives a pointer to IUnknown.) You can use this IUnknown pointer to automate Internet Explorer or to sink events from Internet Explorer.
• It must be registered as a Browser Helper Object as described above.
WARNING: Internet Explorer will create an instance of each Browser Helper Object listed in the registry every time a new instance of Internet Explorer is started. This means that if you have Active Desktop installed, the Browser Helper Objects will be loaded every time you open a new folder as well as when the browser itself is started.
Thursday, June 14, 2007
mutable keyword
-----------------------
Class member functions may be declared as const, which causes this to be treated as a
const pointer. Thus, that function cannot modify the object that invokes it. Also, a const
object may not invoke a non-const member function. However, a const member
function can be called by either const or non-const objects.
within const member fns we can' change the value. In C++ we can change the value using mutable keyword.
class X
{
int i;
public:
int f1() const; // const member function
};
int X::f1() const
{
i = 10; // This will gives error because we are trying to modify the value in a const member function
return i;
}
we can modify the values if we use the mutable keyword. Following code will works...
This is the concept of mutable in C++.
class X
{
mutable int i;
public:
int f1() const; // const member function
};
int X::f1() const
{
i = 10; // This will gives error because we are trying to modify the value in a const member function
return i;
}
Tuesday, June 12, 2007
Real use of BitFields
C/C++ has a built-in feature called a bit-field
that allows you to access a single bit. Bit-fields can be useful for a number of reasons,
such as:
1. If storage is limited, you can store several Boolean (true/false) variables in
one byte.
2. Certain devices transmit status information encoded into one or more bits
within a byte.
3.Certain encryption routines need to access the bits within a byte.
To access individual bits, C/C++ uses a method based on the structure.
The general form of a bit-field definition is
struct struct-type-name {
type name1 : length;
type name2 : length;
..
.
type nameN : length;
} variable_list;
Here, type is the type of the bit-field and length is the number of bits in the field.
A bit-field must be declared as an integral or enumeration type. Bit-fields of length
1 should be declared as unsigned, because a single bit cannot have a sign.
Bit-fields are frequently used when analyzing input from a hardware device.
For example, the status port of a serial communications adapter might return a
status byte organized like this:
Bit Meaning When Set
0 Change in clear-to-send line
1 Change in data-set-ready
2 Trailing edge detected
3 Change in receive line
4 Clear-to-send
5 Data-set-ready
6 Telephone ringing
7 Received signal
You can represent the information in a status byte using the following bit-field:
struct status_type {
unsigned delta_cts: 1;
unsigned delta_dsr: 1;
unsigned tr_edge: 1;
unsigned delta_rec: 1;
unsigned cts: 1;
unsigned dsr: 1;
unsigned ring: 1;
unsigned rec_line: 1;
} status;
You might use a routine similar to that shown here to enable a program to determine
when it can send or receive data.
status = get_port_status();
if(status.cts) printf("clear to send");
if(status.dsr) printf("data ready");
To assign a value to a bit-field, simply use the form you would use for any other type
of structure element. For example, this code fragment clears the ring field:
status.ring = 0;
How to call Unmanaged DLL from C# application ?
I develeoped the win32 DLL.
I added the code in the DLL header file as follows :
#ifdef DLLDIR_EX
#define DLLDIR __declspec(dllexport) // export DLL information
#else
#define DLLDIR __declspec(dllimport) // import DLL information
#endif
extern "C"
{
bool DLLDIR GetSysInfo(char* pszSystemName);
};
DLL implementation file I added its defn
How I accessed the DLL in C# ?
VC++ DLL is an Unmanaged code.
This is following way How I accessed that file...
I just copied the .DLL and .LIB files from my DLL project.
and copied it to the debug folder of the C# application
Within C# application
using System.Runtime.InteropServices; // For Interoperability
[DllImport("RemoteSystemDLL.dll")]
public static extern bool GetSysInfo(StringBuilder buf);
and called this GetSysInfo() fn in my application.
// this is the C++ function exposed by the dll
Monday, June 11, 2007
Operator Keywords
C++ suggested to use the following key words for any operation.
operator operator Keywords Description
&& and logical AND
|| or logical OR
! not logical NOT
!= not_eq Inequality
& bitand bitwise and
| bitor bitwise or
^ xor bitwise xor
~ compl complement operator
&= and_eq bitwise AND assignement
|= or_eq bitwise OR assignement
^= xor_eq bitwise XOR assignement
Example program :
=================
The following example program is compiled in microsoft visual C++
win32 console application.
#include
int main(int argc, char* argv[])
{
int i = 0;
int j = 20;
printf("Hello World! : %d", i and j);
return 0;
}
Note the program, I used the "and" operator keyword. In that way we can access the
operators listed above.