Thursday, September 27, 2007

ListView header problem in C#

private void CreateMyListView()
{
// Create a new ListView control.
ListView listView1 = new ListView();
listView1.Bounds = new Rectangle(new Point(10, 10), new Size(300, 200));

// Set the view to show details.
listView1.View = View.Details;
// Allow the user to edit item text.
listView1.LabelEdit = true;
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Display check boxes.
listView1.CheckBoxes = true;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = true;
// Display grid lines.
listView1.GridLines = true;
// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;

// Create three items and three sets of subitems for each item.
ListViewItem item1 = new ListViewItem("item1", 0);
// Place a check mark next to the item.
item1.Checked = true;
item1.SubItems.Add("1");
item1.SubItems.Add("2");
item1.SubItems.Add("3");
ListViewItem item2 = new ListViewItem("item2", 1);
item2.SubItems.Add("4");
item2.SubItems.Add("5");
item2.SubItems.Add("6");
ListViewItem item3 = new ListViewItem("item3", 0);
// Place a check mark next to the item.
item3.Checked = true;
item3.SubItems.Add("7");
item3.SubItems.Add("8");
item3.SubItems.Add("9");

// Create columns for the items and subitems.
listView1.Columns.Add("Item Column", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Column 3", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Column 4", -2, HorizontalAlignment.Center);

//Add the items to the ListView.
listView1.Items.AddRange(new ListViewItem[] { item1, item2, item3 });
/*
// Create two ImageList objects.
ImageList imageListSmall = new ImageList();
ImageList imageListLarge = new ImageList();

// Initialize the ImageList objects with bitmaps.
imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage1.bmp"));
imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage2.bmp"));
imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage1.bmp"));
imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage2.bmp"));

//Assign the ImageList objects to the ListView.
listView1.LargeImageList = imageListLarge;
listView1.SmallImageList = imageListSmall;
*/
// Add the ListView to the control collection.
this.Controls.Add(listView1);
}

Labels:

Wednesday, September 26, 2007

DllMain in a DLL

DllMain Called with Flags

There are several conditions where DllMain is called with the DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, DLL_THREAD_ATTACH, or DLL_THREAD_DETACH flags.

The DLL_PROCESS_ATTACH flag is sent when a DLL is loaded into the address space of a process. This occurs in both situations where the DLL is loaded with LoadLibrary, or implicitly during application load. When the DLL is implicitly loaded, DllMain is executed with DLL_PROCESS_ATTACH before the processes enter WinMain. When the DLL is explicitly loaded, DllMain is executed with DLL_PROCESS_ATTACH before LoadLibrary returns.

The DLL_PROCESS_DETACH flag is sent when a process cleanly unloads the DLL from its address space. This occurs during a call to FreeLibrary, or if the DLL is implicitly loaded, a clean process exit. When a DLL is detaching from a process, the individual threads of the process do not call the DLL_THREAD_DETACH flag.

The DLL_THREAD_ATTACH flag is sent when a new thread is being created in a process already attached to the DLL. Threads in existence before the process attached to a DLL will not send the DLL_THREAD_ATTACH flag. The first thread to attach to the DLL does not send the DLL_THREAD_ATTACH flag; it sends the DLL_PROCESS_ATTACH flag instead.

The DLL_THREAD_DETACH flag is sent when a thread is exiting cleanly. There is a situation when DllMain may be called when the thread did not first send the DLL_THREAD_ATTACH flag. This can happen if there are other threads still running and the original thread exits cleanly. The thread originally called DllMain with the DLL_PROCESS_ATTACH flag and later calls DllMain with the DLL_THREAD_DETACH flag. You may also have DllMain being called with DLL_THREAD_DETACH if a thread exits but was running in the process before the call to LoadLibrary.

 

Situations Where DllMain is Not Called or Is Bypassed

DllMain may not be called at all in dire situations where a thread or process was killed by a call to TerminateThread or TerminateProcess. These functions bypass calling DllMain. They are recommended only as a last resort. Data owned by the thread or process is at risk of loss because the process or thread could not shut itself down properly.

DllMain may be bypassed intentionally by a process if it calls DisableThreadLibraryCalls. This function (available with Windows 95 and Windows NT versions 3.5 and later) disables all DLL_THREAD_ATTACH and DLL_THREAD_DETACH notifications for a DLL. This enables a process to reduce its code size and working set. For more information on this function, see the SDK documentation on DisableThreadLibraryCalls.

C# Tips

I am working in C# 2005

1.Modal Dialog and Modeless Dialog in C#
2.C# MDI forms
3.Opening the Chm file
4.CheckOnClick property in a menuitem
 set the Checked property as true or false

Modal Dialog and Modeless Dialog in C# :
-------------------------------------------------------------
if we are having Two Forms in our Project,  From the  Form1, we will display the Form2 as Modal and Modeless dialog.

Class Form2
{

}

class  Form1
{
     void btnShowForm2_Click()
     {
 Form2 frm = new Form2();

 frm.Show() ;// For Modeless Dialog
 frm.ShowDialog() ;//  This is for Modal dialog
 
     }
}

2.C# MDI forms
----------------------
     From Main Form, we will create the another Form means
this can be made as MDI forms.

 Wecan display more than one forms at a time in MDI forms.

For the parent Form, we have to enable the IsMdiContainer property as true.

and then drill down in to the coding as follows :

 class ChildForm
 {
 }
 class ParentForm
 {
  
  //this.IsMdiContainer = true;

  private void mnuShowChildForm_Click()
  {
   ChildForm frm = new ChildForm();
   frm.MdiParent = this;
   frm.Show();
  }
 }


Only MdiParent property of the child form is set to the Parent form's Object.

 
3. Sometimes we faced the problem in opening chm files content display problem.

while opening the chm file, sometimes it displays the dialog with "always ask before opening this file"  check box.

if this check box is not selected by us then it will not display the chm contents. So To display the chm file contents, we must enable

"always ask before opening this file"  check box.

4.CheckOnClick property in a menu item  Sometimes we may need Checked property in a menuitem. For Instance, if the user selects the menuitem then it will show the Checked mark in a menuitem and if we select once again, the checkbox will
not be shown. this selection process takes place continously like Toggle on or off.

 
 For Doing this one, the menu item is having the property CheckOnClick .

if we enable this property, then we can display the check mark and we can change the execution behavior also based on the check mark.

 CheckedState property is set to true or false based on whether the check  mark is currently displayed in a menuitem or not.

This feature can be aptly used in the following Scenario.

 if we have MDI parent form, based on the checked selection of the menuitem we have to display the MDI child form.


if the menuitem is selected for the first time, we have to display the child form. if the menuitem is selected once again, then the child form must be

hided...

 By default set the menuitem's CheckOnClick property as true and Checked property as false.

  For doing this one , add the menu event handler as follows :

 void mnuShowChildForm_Click()
 {
  if( mnuShowChildForm.Checked == true)
  {
   childFormObject.Show();
  }
  else
  {
   childFormObject.Hide();
  }
 }
 

 

 

Tuesday, September 18, 2007

MFC message maps

MFC Message Maps:
MFC provides an alternative to the switch statement used in traditional Windows programs to handle messages sent to a window. A mapping from messages to member-functions may be defined so that when a message is to be handled by a window, the appropriate member function is called automatically.

This message-map facility is designed to be similar to virtual functions but has additional benefits not possible with C++ virtual functions.


Defining a Message Map:

1.The DECLARE_MESSAGE_MAP macro declares three members for a class.

A private array of AFX_MSGMAP_ENTRY entries called _messageEntries,


A protected AFX_MSGMAP structure called messageMap that points to the _messageEntries array


A protected virtual function called GetMessageMap that returns the address of messageMap.
This macro should be placed in the declaration of any class using message maps. By convention, it is at the end of the class declaration. For example:

class CMyWnd : public CMyParentWndClass
{
// my stuff...

protected:
//{{AFX_MSG(CMyWnd)
afx_msg void OnPaint();
//}}AFX_MSG

DECLARE_MESSAGE_MAP()
};


The message map's table is defined with a set of macros that expand to message map
entries. A table begins with a BEGIN_MESSAGE_MAP macro call, which defines the class that is handled by this message map and the parent class to which unhandled messages are passed. The
table ends with the END_MESSAGE_MAP macro call.

Between these two macro calls is an entry for each message to be handled by this message map. Every standard Windows message has a macro of the form ON_WM_xxx (where xxx is the name of the message) that generates an entry for that message.

Labels:

CObject services

CObject Services :
Cobject provides basic services needed for all the classes.

1.Supports serialization
2.run-time class information
3.Dynamic Object Creation
4.Object diagnostic output (Debugging)
5.Compatibility with collection classes

The first-level macros, DECLARE_DYNAMIC and IMPLEMENT_DYNAMIC, permit run-time access to the class name
and its position in the hierarchy. This, in turn, allows meaningful diagnostic dumping and dynamic Object creation.

The second-level macros, DECLARE_SERIAL and IMPLEMENT_SERIAL, include all the functionality of the first-level macros,
and they enable an object to be “serialized” to and from an “archive.”

MFC collection classes are derived from CObject So we can store any class( derived from CObject) into the collection class.



Serialization Example :
----------------------------------

class CMyObject : public CObject
{
// ...Member functions
public:
CMyObject() { }
virtual void Serialize( CArchive& ar ) { }

// Implementation
protected:
DECLARE_SERIAL( CMyObject )
};


class COtherObject : public CObject
{
// ...Member functions
public:
COtherObject() { }
virtual void Serialize( CArchive& ar ) { }

// Implementation
protected:
DECLARE_SERIAL( COtherObject )
};


class CCompoundObject : public CObject
{
// ...Member functions
public:
CCompoundObject();
virtual void Serialize( CArchive& ar );

// Implementation
protected:
CMyObject m_myob; // Embedded object
COtherObject* m_pOther; // Object allocated in constructor
CObject* m_pObDyn; // Dynamically allocated object
//..Other member data and implementation

DECLARE_SERIAL( CCompoundObject )
};

IMPLEMENT_SERIAL(CMyObject,CObject,1)
IMPLEMENT_SERIAL(COtherObject,CObject,1)
IMPLEMENT_SERIAL(CCompoundObject,CObject,1)


CCompoundObject::CCompoundObject()
{
m_pOther = new COtherObject; // Exact type known and object already
//allocated.
m_pObDyn = NULL; // Will be allocated in another member function
// if needed, could be a derived class object.
}

void CCompoundObject::Serialize( CArchive& ar )
{
CObject::Serialize( ar ); // Always call base class Serialize.
m_myob.Serialize( ar ); // Call Serialize on embedded member.
m_pOther->Serialize( ar ); // Call Serialize on objects of known exact type.

// Serialize dynamic members and other raw data
if ( ar.IsStoring() )
{
ar << m_pObDyn;
// Store other members
}
else
{
ar >> m_pObDyn; // Polymorphic reconstruction of persistent
// object
//load other members
}
}





RunTimeClass Information Support Example :
====================================


// in .H file
class CPerson : public CObject
{
DECLARE_DYNAMIC( CPerson )
public:
CPerson(){};

// other declaration
};


// in .CPP file
IMPLEMENT_DYNAMIC( CPerson, CObject )


void SomeFunction(void)
{
CObject* pMyObject = new CPerson;

if(pMyObject->IsKindOf( RUNTIME_CLASS( CPerson ) ) )
{
//if IsKindOf is true, then cast is all right
CPerson* pmyPerson = (CPerson*) pMyObject ;
...
delete pmyPerson;
}
...
delete [MyObject];
}


Dynamic Object Creation :
-----------------------------------


To dynamically create an object given its run-time class

Use the following code to dynamically create an object by using the CreateObject function of the CRuntimeClass.
Note that on failure, CreateObject returns NULL instead of raising an exception:

CRuntimeClass* pRuntimeClass = RUNTIME_CLASS( CMyClass );
CObject* pObject = pRuntimeClass->CreateObject();
ASSERT( pObject->IsKindOf( RUNTIME_CLASS( CMyClass ) ) );


Object diagnostic output :
------------------------------------

Dumping Object Contents :

This topic explains how to get a diagnostic dump of the contents ofour objects.

When deriving a class from CObject, we have the option to override the Dump member function and write a textual representation of the object’s member variables to a dump context which is similar to an I/O stream. Like an I/O stream, you can use the insertion (<<) operator to send data to a CDumpContext.

we do not have to override Dump when you derive a class from CObject. However, if we use other diagnostic features for debugging, providing the capability for dumping an object and viewing its contents is very helpful and highly recommended.

Note Before we can dump objects, we must enable diagnostic tracing so we can see the results of our dump in the debugger.


To override the Dump member function

Call the base class version of Dump to dump the contents of a base class object.


Write a textual description and value for each member variable of your derived class.
The declaration of the Dump function in the class declaration looks like:

class CPerson : public CObject
{
public:
#ifdef _DEBUG
virtual void Dump( CDumpContext& dc ) const;
#endif

CString m_firstName;
CString m_lastName;
// etc. ...
};

Note Since object dumping only makes sense when you are debugging your program, the declaration of the Dump function is bracketed with an #ifdef _DEBUG / #endif block.

In the following example from an implementation file for the class CPerson, the Dump function’s first statement calls the Dump member function for its base class. It then writes a short description of each member variable along with the member’s value to the diagnostic stream.

#ifdef _DEBUG
void CPerson::Dump( CDumpContext& dc ) const
{
// call base class function first
CObject::Dump( dc );

// now do the stuff for our specific class
dc << "last name: " << m_lastName << "\n"
<< "first name: " << m_firstName << "\n";
}
#endif

Note Again, notice that the definition of the Dump function is bracketed by #ifdef _DEBUG / #endif directives. If you refer to afxDump in a program linked with the nondebug libraries, you will get unresolved externals errors at link time.

To send Dump output to afxDump

You must supply a CDumpContext argument to specify where the dump output will go when you call the Dump function for an object.
MFC supplies a predefined CDumpContext object named afxDump that you will normally use for routine object dumping.
The following example shows how to use afxDump:

CPerson* pMyPerson = new CPerson;
// set some fields of the CPerson object...
//...
// now dump the contents
#ifdef _DEBUG
pMyPerson->Dump( afxDump );
#endif

In Windows NT, afxDump output is sent to the debugger, if present. Otherwise, you won’t get any afxDump output.

Note afxDump is defined only in the debug version of MFC.

Labels:

Tuesday, September 11, 2007

Interoperability Tips

Interoperability :

 [DllImport("MAPI32.DLL", CharSet = CharSet.Ansi)]
        public static extern UInt32 MAPISendMail(IntPtr lhSession, IntPtr ulUIParam,
         MapiMessage lpMessage, UInt32 flFlags, UInt32 ulReserved);

 

if we want to rename the MAPISendMail fn  as SendMail within C# , How can we do it ?

we can do the following.

 

    [DllImport("MAPI32.DLL", EntryPoint = "MAPISendMail", CharSet = CharSet.Ansi)]
        public static extern UInt32 SendMail(IntPtr lhSession, IntPtr ulUIParam,
         MapiMessage lpMessage, UInt32 flFlags, UInt32 ulReserved);

 

 EntryPoint = "MAPISendMail"  // specified function address is obtained from the DLL


So In our C# application we can simply call

 SendMail( ...)
 
 
Literally what will happen is the address of the MAPISendMail() fn is assigned to the SendMail() fn.
 
So if we call the SendMail() fn from C#, it will in turn calls the MAPISendMail() functionality from MAPI32.dll
 
 

MAPISendMail in C# application

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MAPIConsole
{
/*
[StructLayout(LayoutKind.Sequential)]
public struct MapiRecipDesc
{
public long Reserved;
public long RecipClass;
public string Name;
public string Address;
public long EIDSize;
public object EntryID;
}

[StructLayout(LayoutKind.Sequential)]
public struct MapiMessage
{
public long Reserved;
public string Subject;
public string NoteText;
public string MessageType;
public string DateReceived;
public string ConversationID;
public long Flags;
public object Originator;
public long RecipCount;
public MapiRecipDesc Recips;
public long FileCount;
public object Files;
}
*/


///
/// A MapiFileDesc structure contains information about a file containing a message attachment
/// stored as a temporary file.
///
/// The file can contain a static OLE object, an embedded OLE object, an embedded message,
/// and other types of files.
///

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiFileDesc
{
///
/// Reserved; must be zero.
///

public uint ulReserved = 0;

///
/// Bitmask of attachment flags. Flags are MAPI_OLE and MAPI_OLE_STATIC.
///
/// If neither flag is set, the attachment is treated as a data file.
///

public uint flFlags = 0;

///
/// An integer used to indicate where in the message text to render the attachment.
///
/// Attachments replace the character found at a certain position in the message text.
/// That is, attachments replace the character in the MapiMessage structure field
/// lpszNoteText[nPosition]. A value of – 1 (0xFFFFFFFF) means the attachment position is
/// not indicated; the client application will have to provide a way for the user to
/// access the attachment.
///

public uint nPosition = 0xffffffff;

///
/// Pointer to the fully qualified path of the attached file.
///
/// This path should include the disk drive letter and directory name.
///

public string lpszPathName = string.Empty;

///
/// Pointer to the attachment filename seen by the recipient, which may differ from the filename in
/// the lpszPathName member if temporary files are being used.
///
/// If the lpszFileName member is empty or NULL, the filename from lpszPathName is used.
///

public string lpszFileName = string.Empty;

///
/// Pointer to the attachment file type, which can be represented with a MapiFileTagExt
/// structure.
///
/// A value of NULL indicates an unknown file type or a file type determined by the operating system.
///

public IntPtr lpFileType = IntPtr.Zero;
}

///
/// MapiFileTagExt structure specifies a message attachment's type at its creation
/// and its current form of encoding so that it can be restored to its original type at its destination.
///
/// A MapiFileTagExt structure defines the type of an attached file for purposes such as encoding and
/// decoding the file, choosing the correct application to launch when opening it, or any use that
/// requires full information regarding the file type.
///
/// Client applications can use information in the lpTag and lpEncoding
/// members of this structure to determine what to do with an attachment.
///

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiFileTagExt
{
///
/// Reserved; must be zero.
///

public uint ulReserved = 0;

///
/// The size, in bytes, of the value defined by the lpTag member.
///

public uint cbTag = 0;

///
/// Pointer to an X.400 object identifier indicating the type of the attachment in its original form,
/// for example "Microsoft Excel worksheet".
///

public IntPtr lpTag = IntPtr.Zero;

///
/// The size, in bytes, of the value defined by the lpEncoding member.
///

public uint cbEncoding = 0;

///
/// Pointer to an X.400 object identifier indicating the form in which the attachment is currently
/// encoded, for example MacBinary, UUENCODE, or binary.
///

public IntPtr lpEncoding = IntPtr.Zero;
}

///
/// A MapiMessage structure contains information about a message.
///

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiMessage
{
///
/// Reserved; must be zero.
///

public uint ulReserved = 0;

///
/// Pointer to the text string describing the message subject,
/// typically limited to 256 characters or less.
///
/// If this member is empty or NULL, the user has not entered subject text.
///

public string lpszSubject = string.Empty;

///
/// Pointer to a string containing the message text.
///
/// If this member is empty or NULL, there is no message text.
///

public string lpszNoteText = string.Empty;

///
/// Pointer to a string indicating a non-IPM type of message.
///
/// Client applications can select message types for their non-IPM messages.
///
/// Clients that only support IPM messages can ignore the lpszMessageType member
/// when reading messages and set it to empty or NULL when sending messages.
///

public string lpszMessageType = null;

///
/// Pointer to a string indicating the date when the message was received.
///
/// The format is YYYY/MM/DD HH:MM, using a 24-hour clock.
///

public string lpszDateReceived = DateTime.Now.ToString("yyyy/MM/dd hh:mm");

///
/// Pointer to a string identifying the conversation thread to which the message belongs.
///
/// Some messaging systems can ignore and not return this member.
///

public string lpszConversationID = string.Empty;

///
/// Bitmask of message status flags.
///
/// The flags are MAPI_RECEIPT_REQUESTED , MAPI_SENT,
/// and MAPI_UNREAD.
///

public uint flFlags = 0;

///
/// Pointer to a MapiRecipDesc structure containing information about the
/// sender of the message.
///

public IntPtr lpOriginator = IntPtr.Zero;

///
/// The number of message recipient structures in the array pointed to by the
/// lpRecips member.
///
/// A value of zero indicates no recipients are included.
///

public uint nRecipCount = 0;

///
/// Pointer to an array of MapiRecipDesc structures, each containing
/// information about a message recipient.
///

public IntPtr lpRecips = IntPtr.Zero;

///
/// The number of structures describing file attachments in the array pointed to by the
/// lpFiles member.
///
/// A value of zero indicates no file attachments are included.
///

public uint nFileCount = 0;

///
/// Pointer to an array of MapiFileDesc structures, each containing
/// information about a file attachment.
///

public IntPtr lpFiles = IntPtr.Zero;
}

///
/// A MapiRecipDesc structure contains information about a message sender or recipient.
///

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiRecipDesc
{
///
/// Reserved; must be zero.
///

public uint ulReserved= 0;

///
/// Contains a numeric value that indicates the type of recipient.
///
/// Possible values are:
///
/// Value Constant Meaning
///
/// 0 MAPI_ORIG Indicates the original sender of the message.
/// 1 MAPI_TO Indicates a primary message recipient.
/// 2 MAPI_CC Indicates a recipient of a message copy.
/// 3 MAPI_BCC Indicates a recipient of a blind copy.
///
///

public uint ulRecipClass= MAPI.MAPI_TO;

///
/// Pointer to the display name of the message recipient or sender.
///

public string lpszName = string.Empty;

///
/// Optional pointer to the recipient or sender's address; this address is provider-specific message
/// delivery data. Generally, the messaging system provides such addresses for inbound messages.
///
/// For outbound messages, the lpszAddress member can point to an address entered by the user for
/// a recipient not in an address book (that is, a custom recipient).
///
/// The format of an address pointed to by the lpszAddress member is [address type][e-mail address].
/// Examples of valid addresses are FAX:206-555-1212 and SMTP:M@X.COM.
///

public string lpszAddress = string.Empty;

///
/// The size, in bytes, of the entry identifier pointed to by the lpEntryID member.
///

public uint ulEIDSize = 0;

///
/// Pointer to an opaque entry identifier used by a messaging system service provider to identify the
/// message recipient. Entry identifiers have meaning only for the service provider;
/// client applications will not be able to decipher them. The messaging system uses this member
/// to return valid entry identifiers for all recipients or senders listed in the address book.
///

public IntPtr lpEntryID = IntPtr.Zero;
}



public class MAPI
{

[DllImport("MAPI32.DLL",EntryPoint = "MAPILogon", CharSet = CharSet.Ansi)]
public static extern UInt32 Logon(IntPtr ulUIParam, string lpszProfileName, string lpszPassword,
UInt32 flFlags, UInt32 ulReserved, ref IntPtr lplhSession);



[DllImport("MAPI32.DLL", EntryPoint = "MAPISendMail", CharSet = CharSet.Ansi)]
public static extern UInt32 SendMail(IntPtr lhSession, IntPtr ulUIParam,
MapiMessage lpMessage, UInt32 flFlags, UInt32 ulReserved);


[DllImport("MAPI32.DLL", EntryPoint = "MAPILogoff", CharSet = CharSet.Ansi)]
public static extern uint Logoff(IntPtr lhSession, IntPtr ulUIParam, uint flFlags, uint ulReserved);



public const int SUCCESS_SUCCESS = 0;
public const int MAPI_USER_ABORT = 1;
public const int MAPI_E_USER_ABORT = MAPI_USER_ABORT;
public const int MAPI_E_FAILURE = 2;
public const int MAPI_E_LOGIN_FAILURE = 3;
public const int MAPI_E_LOGON_FAILURE = MAPI_E_LOGIN_FAILURE;
public const int MAPI_E_DISK_FULL = 4;
public const int MAPI_E_INSUFFICIENT_MEMORY = 5;
public const int MAPI_E_BLK_TOO_SMALL = 6;
public const int MAPI_E_TOO_MANY_SESSIONS = 8;
public const int MAPI_E_TOO_MANY_FILES = 9;
public const int MAPI_E_TOO_MANY_RECIPIENTS = 10;
public const int MAPI_E_ATTACHMENT_NOT_FOUND = 11;
public const int MAPI_E_ATTACHMENT_OPEN_FAILURE = 12;
public const int MAPI_E_ATTACHMENT_WRITE_FAILURE = 13;
public const int MAPI_E_UNKNOWN_RECIPIENT = 14;
public const int MAPI_E_BAD_RECIPTYPE = 15;
public const int MAPI_E_NO_MESSAGES = 16;
public const int MAPI_E_INVALID_MESSAGE = 17;
public const int MAPI_E_TEXT_TOO_LARGE = 18;
public const int MAPI_E_INVALID_SESSION = 19;
public const int MAPI_E_TYPE_NOT_SUPPORTED = 20;
public const int MAPI_E_AMBIGUOUS_RECIPIENT = 21;
public const int MAPI_E_AMBIG_RECIP = MAPI_E_AMBIGUOUS_RECIPIENT;
public const int MAPI_E_MESSAGE_IN_USE = 22;
public const int MAPI_E_NETWORK_FAILURE = 23;
public const int MAPI_E_INVALID_EDITFIELDS = 24;
public const int MAPI_E_INVALID_RECIPS = 25;
public const int MAPI_E_NOT_SUPPORTED = 26;
public const int MAPI_ORIG = 0;
public const int MAPI_TO = 1;
public const int MAPI_CC = 2;
public const int MAPI_BCC = 3;
//***********************
// FLAG Declarations
//***********************
//* MAPILogon() flags *
public const int MAPI_LOGON_UI = 0x1;
public const int MAPI_NEW_SESSION = 0x2;
public const int MAPI_FORCE_DOWNLOAD = 0x1000;
//* MAPILogoff() flags *
public const int MAPI_LOGOFF_SHARED = 0x1;
public const int MAPI_LOGOFF_UI = 0x2;
//* MAPISendMail() flags *
public const int MAPI_DIALOG = 0x8;
//* MAPIFindNext() flags *
public const int MAPI_UNREAD_ONLY = 0x20;
public const int MAPI_GUARANTEE_FIFO = 0x100;
//* MAPIReadMail() flags *
public const int MAPI_ENVELOPE_ONLY = 0x40;
public const int MAPI_PEEK = 0x80;
public const int MAPI_BODY_AS_FILE = 0x200;
public const int MAPI_SUPPRESS_ATTACH = 0x800;
//* MAPIDetails() flags *
public const int MAPI_AB_NOMODIFY = 0x400;
//* Attachment flags *
public const int MAPI_OLE = 0x1;
public const int MAPI_OLE_STATIC = 0x2;
//* MapiMessage flags *
public const int MAPI_UNREAD = 0x1;
public const int MAPI_RECEIPT_REQUESTED = 0x2;
public const int MAPI_SENT = 0x4;

}


class Program
{
/*
public void SendMail()
{
uint ulResult = 0;
IntPtr hSession = IntPtr.Zero;
uint ulFlags = MAPI.MAPI_LOGON_UI | MAPI.MAPI_NEW_SESSION;

ulResult = MAPI.Logon(IntPtr.Zero, null, null, ulFlags, 0, ref hSession);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine(" MAPILogon() fn failed...");
return;
}



MapiRecipDesc recipient = new MapiRecipDesc();
recipient.Reserved = 0;
recipient.RecipClass = MAPI.MAPI_TO;
recipient.Name = null;
recipient.Address = "sundararajan_svks@yahoo.com";
recipient.EIDSize = 0;
recipient.EntryID = null;

MapiMessage message = new MapiMessage();
message.Reserved = 0;
message.Subject = "Greetings From C#";
message.NoteText = "Hello Mr...Sundara rajan";
message.MessageType = null;
message.DateReceived = null;
message.ConversationID = null;
message.Flags = 0;
message.Originator = null;
message.RecipCount = 1;
message.Recips = recipient;
message.FileCount = 0;
message.Files = null;


ulResult = MAPI.SendMail(hSession, IntPtr.Zero, ref message, MAPI.MAPI_NEW_SESSION, 0);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine("SendMail() fn failed...");
return;
}

ulResult = MAPI.Logoff(hSession, IntPtr.Zero, 0, 0);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine("Logoff() fn failed...");
return;
}
}
*/

public void SendMail2()
{
uint ulResult = 0;
IntPtr hSession = IntPtr.Zero;
uint ulFlags = MAPI.MAPI_LOGON_UI | MAPI.MAPI_NEW_SESSION;

ulResult = MAPI.Logon(IntPtr.Zero, null, null, 0, 0, ref hSession);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine(" MAPILogon() fn failed...");
return;
}

MapiMessage message = new MapiMessage();
message.lpszSubject = "Greetings From C#";
message.lpszNoteText = "Hello Mr...Sundara rajan";
message.lpOriginator = IntPtr.Zero;//AllocOrigin();
message.nRecipCount = 1;
message.lpRecips = AllocRecips();

ulResult = MAPI.SendMail(hSession, IntPtr.Zero, message,0, 0);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine("SendMail() fn failed...");
return;
}

ulResult = MAPI.Logoff(hSession, IntPtr.Zero, 0, 0);

if (ulResult != MAPI.SUCCESS_SUCCESS)
{
Console.WriteLine("Logoff() fn failed...");
return;
}

Marshal.FreeHGlobal(message.lpRecips);
}

private IntPtr AllocOrigin()
{
MapiRecipDesc recipient = new MapiRecipDesc();
recipient.ulRecipClass = MAPI.MAPI_ORIG;
recipient.lpszName = "sundar";
recipient.lpszAddress = "sundararajan.svks@gmail.com";
recipient.ulEIDSize = 0;
recipient.lpEntryID = IntPtr.Zero;

Type rtype = typeof(MapiRecipDesc);
int rsize = Marshal.SizeOf(rtype);
IntPtr ptrr = Marshal.AllocHGlobal(rsize);

Marshal.StructureToPtr(recipient, ptrr, false);
return ptrr;

}
private IntPtr AllocRecips()
{
MapiRecipDesc recipient = new MapiRecipDesc();
recipient.ulRecipClass = MAPI.MAPI_TO;
recipient.lpszName = "sundararajan";
recipient.lpszAddress = "sundararajan_svks@yahoo.com";
recipient.ulEIDSize = 0;
recipient.lpEntryID = IntPtr.Zero;

Type rtype = typeof(MapiRecipDesc);
int rsize = Marshal.SizeOf(rtype);
IntPtr ptrr = Marshal.AllocHGlobal(rsize);
Marshal.StructureToPtr(recipient, ptrr, false);
//Marshal.PtrToStructure(
return ptrr;


}
static void Main(string[] args)
{

Program p = new Program();
//p.SendMail();
p.SendMail2();
Console.ReadKey();
}
}
}

Labels:

MAPISendMail in C# Problem

ulResult = MAPI.SendMail(hSession, IntPtr.Zero, message,0, 0);

it works well But if i modified it as follows will not send mail...


ulResult = MAPI.SendMail(hSession, IntPtr.Zero, message,MAPI.MAPI_DIALOG, 0);

Labels:

Monday, September 10, 2007

Configure yahoo in Outlook

To Configure yahoo in Outlook, we have to download

yPOPS application and install and run this application then configure the yahoo with outlook with the following :

 

Error 1:


---------------------------

Microsoft Outlook

---------------------------

Either there is no default mail client or the current mail client cannot fulfill the messaging request. Please run Microsoft Outlook and set it as the default mail client.

---------------------------

OK

---------------------------



When trying to send an email you get an error message "Either there is no default mail client or the current mail client cannot fulfill the messaging request. Please run MS Outlook and set it as the default mail client." RESOLUTION:


Install MS Outlook (not Outlook Express). Quit all mail-aware programs. This includes any MS Office programs and follow these steps to set Outlook as your default e-mail program:


Solution :

----------------

Start MS Internet Explorer version 5.0 or later.

On the "Tools" menu, click "Internet Options".

On the "Programs" tab, in the "E-mail" list, click to select "Microsoft Outlook". Do not click "Outlook Express".

Click "OK".






Error 2:

I developed the sample application with the MAPISendMail () fn in VC++.


MAPISendMail() fn succeeded But I got the mail in the Outlook's OutBox folder.But the mail is not sent to the specified email Id...



I enabled the "Forwarding and Pop" -> Enable POP access option from the



4.20 to 5.30 - I faced the above problem.


Set of Steps Taken :


1.So I set the status of the Firewall as "Allow All". Now also I got the problem that is message sent to the Outbox folder. So there is no problem with firewall.

2. I manually sent the mail from Outlook. It is also not working . It sends data to the Outbox folder. This is the cause of the problem. First set the mail settings properly in outlook Express.



I solved this problem By doing the following things:

1.By Enabling My Server Requires authentication




Moreover I have opened the Microsoft outlook and checks whether the MAPISendMail() fn works well …

MAPISendMail() fn failed with Outlook.


MAPISendMail() returns MAPI_E_FAILURE ( return code : 2) , if I opened the outlook.

So I opened the Outlook Express and tested the MAPISendMail() fn , it works well …







Tools ->accounts select the account name



Gmail Settings in Outlook Express:


Run the MAPI only when Outlook Express is Opened…









Friday, September 07, 2007

Directshow Transform Filter development

1. Open the Empty Win32 DLL
2.Add the stdafx.h , ColorToGray.h and ColorToGray.cpp
3.stdafx.h content is as follows

#pragma once
#include
//#include
#include
#include
#include
#include
#include

3.1. ColorToGray.def content as follows :

EXPORTS
DllGetClassObject PRIVATE
DllCanUnloadNow PRIVATE
DllRegisterServer PRIVATE
DllUnregisterServer PRIVATE



4. I added the linker library files as follows

C:\DXSDK\Samples\C++\DirectShow\BaseClasses\Debug_Unicode\strmbasd.lib
winmm.lib

5. I added the following keyword in a Project->Settings->Linker ->Output->Entry Point option
DllEntryPoint@12

6. I added the
regsvr32 /s "$(TargetPath)" to the Project->Settings->Post Build link step...

7.I got this error :

LIBCMTD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main

So I Modified Project->Settings->C++->General ->Preprocessor definitions as follows :

WIN32,_DEBUG,_WINDOWS,DEBUG

8. I made it as "not using precompile header files"
Project->Settings->C++ ->Not Using Precompiled Headers


Finally I got this Error :

Creating library Debug/ColorToGray.lib and object Debug/ColorToGray.exp
LIBCMTD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
Debug/ColorToGray.dll : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.





4.ColorToGray.h File Contents :





class CColorToGray : public CTransformFilter
{
public:

DECLARE_IUNKNOWN; //For Query the Interface and Release

static CUnknown *WINAPI CreateInstance(LPUNKNOWN punk, HRESULT *phr);
CColorToGray(TCHAR *tszName, LPUNKNOWN punk, HRESULT *phr);
~CColorToGray();

HRESULT CheckInputType(const CMediaType *mtIn );
HRESULT CheckTransform(const CMediaType *mtIn,
const CMediaType *mtOut);


HRESULT DecideBufferSize( IMemAllocator *pAlloc,
ALLOCATOR_PROPERTIES *ppropInputRequest

);
HRESULT GetMediaType ( int iPosition,
CMediaType *pMediaType
);

HRESULT Transform ( IMediaSample *pIn,
IMediaSample *pOut
);

HRESULT SetMediaType(PIN_DIRECTION direction, const CMediaType *pmt);




private:

BOOL canPerformTransform(const CMediaType *pMediaType) const;

VIDEOINFOHEADER m_VihOut;
VIDEOINFOHEADER m_VihIn;

};

5.ColorToGray.cpp contents as follows :

#include "stdafx.h"
#include "ColorToGray.h"

// {1CCD0EC0-3E1E-43d4-B467-DDD1CBD0B9CE}
DEFINE_GUID(CLSID_ColorToGray,
0x1ccd0ec0, 0x3e1e, 0x43d4, 0xb4, 0x67, 0xdd, 0xd1, 0xcb, 0xd0, 0xb9, 0xce);



// setup data - allows the self-registration to work.
const AMOVIESETUP_MEDIATYPE sudPinTypes =
{ &MEDIATYPE_NULL // clsMajorType
, &MEDIASUBTYPE_NULL }; // clsMinorType

const AMOVIESETUP_PIN psudPins[] =
{ { L"Input" // strName
, FALSE // bRendered
, FALSE // bOutput
, FALSE // bZero
, FALSE // bMany
, &CLSID_NULL // clsConnectsToFilter
, L"" // strConnectsToPin
, 1 // nTypes
, &sudPinTypes // lpTypes
}
, { L"Output" // strName
, FALSE // bRendered
, TRUE // bOutput
, FALSE // bZero
, FALSE // bMany
, &CLSID_NULL // clsConnectsToFilter
, L"" // strConnectsToPin
, 1 // nTypes
, &sudPinTypes // lpTypes
}
};

const AMOVIESETUP_FILTER sudColorToGray =
{ &CLSID_ColorToGray // clsID
, L"ColorToGray Filter Test" // strName
, MERIT_DO_NOT_USE // dwMerit
, 2 // nPins
, psudPins }; // lpPin



CFactoryTemplate g_Templates[] =
{
{
L"ColorToGray Filter Test", // Filter Name
&CLSID_ColorToGray, //CLASS ID
CColorToGray::CreateInstance, // it will be called whenever the COM object is created
NULL, // Init Function is not needed
&sudColorToGray //Color ToGray AM_MOVIE_SETUP filter

}

};

int g_cTemplates = sizeof(g_Templates)/sizeof(g_Templates[0]);


CUnknown *WINAPI CColorToGray::CreateInstance(LPUNKNOWN punk, HRESULT *phr)
{

CColorToGray *pNewObject = new CColorToGray(NAME("ColorToGray"), punk, phr );

if (pNewObject == NULL)
{
*phr = E_OUTOFMEMORY;
}

return pNewObject;

}

CColorToGray::CColorToGray(TCHAR *tszName, LPUNKNOWN punk, HRESULT *phr):CTransformFilter(tszName,punk,CLSID_ColorToGray)
{


}

CColorToGray::~CColorToGray()
{


}

HRESULT CColorToGray::CheckInputType(const CMediaType *pMediaType )
{

if(canPerformTransform(pMediaType))
{
return S_OK;
}

return VFW_E_TYPE_NOT_ACCEPTED;

}
HRESULT CColorToGray::CheckTransform(const CMediaType *mtIn,
const CMediaType *mtOut)
{
if (canPerformTransform(mtIn))
{
if (*mtIn == *mtOut)
{
return NOERROR;
}
}
return E_FAIL;

}


HRESULT CColorToGray::DecideBufferSize( IMemAllocator *pAlloc,
ALLOCATOR_PROPERTIES *pProperties
)
{

// Is the input pin connected
if (m_pInput->IsConnected() == FALSE) {
return E_UNEXPECTED;
}

ASSERT(pAlloc);
ASSERT(pProperties);
HRESULT hr = NOERROR;

pProperties->cBuffers = 1;

// Get input pin's allocator size and use that
ALLOCATOR_PROPERTIES InProps;
IMemAllocator * pInAlloc = NULL;
hr = m_pInput->GetAllocator(&pInAlloc);
if (SUCCEEDED (hr))
{
hr = pInAlloc->GetProperties (&InProps);
if (SUCCEEDED (hr))
{
pProperties->cbBuffer = InProps.cbBuffer;
}
pInAlloc->Release();
}

if (FAILED(hr))
return hr;

ASSERT(pProperties->cbBuffer);

// Ask the allocator to reserve us some sample memory, NOTE the function
// can succeed (that is return NOERROR) but still not have allocated the
// memory that we requested, so we must check we got whatever we wanted

ALLOCATOR_PROPERTIES Actual;
hr = pAlloc->SetProperties(pProperties,&Actual);
if (FAILED(hr)) {
return hr;
}

ASSERT( Actual.cBuffers == 1 );

if ( pProperties->cBuffers > Actual.cBuffers ||
pProperties->cbBuffer > Actual.cbBuffer) {
return E_FAIL;
}
return NOERROR;
return hr;


}


HRESULT CColorToGray::GetMediaType ( int iPosition,
CMediaType *pMediaType
)
{

// Is the input pin connected
if (m_pInput->IsConnected() == FALSE) {
return E_UNEXPECTED;
}
// This should never happen
if (iPosition < 0) {
return E_INVALIDARG;
}
// Do we have more items to offer
if (iPosition > 0) {
return VFW_S_NO_MORE_ITEMS;
}

*pMediaType = m_pInput->CurrentMediaType();
return NOERROR;


}

HRESULT CColorToGray::SetMediaType(PIN_DIRECTION direction, const CMediaType *pmt)
{
if (direction == PINDIR_INPUT)
{
ASSERT(pmt->formattype == FORMAT_VideoInfo);
VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*)pmt->pbFormat;

// WARNING! In general you cannot just copy a VIDEOINFOHEADER
// struct, because the BITMAPINFOHEADER member may be followed by
// random amounts of palette entries or color masks. (See VIDEOINFO
// structure in the DShow SDK docs.) Here it's OK because we just
// want the information that's in the VIDEOINFOHEADER stuct itself.

CopyMemory(&m_VihIn, pVih, sizeof(VIDEOINFOHEADER));
}
else // output pin
{
ASSERT(direction == PINDIR_OUTPUT);
ASSERT(pmt->formattype == FORMAT_VideoInfo);
VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*)pmt->pbFormat;


CopyMemory(&m_VihOut, pVih, sizeof(VIDEOINFOHEADER));
}

return S_OK;
}

HRESULT CColorToGray::Transform ( IMediaSample *pIn,
IMediaSample *pOut
)
{
HRESULT hr = S_OK;

BYTE* pbIn = NULL;
BYTE* pbOut= NULL;


CMediaType *pmt = 0;
if (S_OK == pOut->GetMediaType((AM_MEDIA_TYPE**)&pmt) && pmt)
{

// Notify our own output pin about the new type.
m_pOutput->SetMediaType(pmt);
DeleteMediaType(pmt);
}

pIn->GetPointer(&pbIn);
pOut->GetPointer(&pbOut);


unsigned long i = 0;


for(i = 0 ; i < m_VihOut.bmiHeader.biSizeImage; i++)
{
pbOut[i] = pbIn[i] ^ 0xff;
}


return hr;


}

//Private methods
BOOL CColorToGray::canPerformTransform(const CMediaType *pMediaType) const
{
// we accept the following image type: (RGB24, ARGB32 or RGB32)
if (IsEqualGUID(*pMediaType->Type(), MEDIATYPE_Video)) {
if (IsEqualGUID(*pMediaType->Subtype(), MEDIASUBTYPE_RGB24)) {
VIDEOINFOHEADER *pvi = (VIDEOINFOHEADER *) pMediaType->Format();
return (pvi->bmiHeader.biBitCount == 24);
}
if (IsEqualGUID(*pMediaType->Subtype(), MEDIASUBTYPE_ARGB32)) {
VIDEOINFOHEADER *pvi = (VIDEOINFOHEADER *) pMediaType->Format();
return (pvi->bmiHeader.biBitCount == 32);
}
if (IsEqualGUID(*pMediaType->Subtype(), MEDIASUBTYPE_RGB32)) {
VIDEOINFOHEADER *pvi = (VIDEOINFOHEADER *) pMediaType->Format();
return (pvi->bmiHeader.biBitCount == 32);
}
}
return FALSE;
}

STDAPI DllRegisterServer()
{
//Next Register and unregister the DLL without the AMovieDllRegisterServer2() fn
return AMovieDllRegisterServer2(TRUE);
}

STDAPI DllUnregisterServer()
{
return AMovieDllRegisterServer2(FALSE);

}

Labels: