Wednesday, August 01, 2007
User Defined message creation
ForExample if we want to post our own message, we have to create our own message .
Each and every message have a unique number. Using this number, windows identifies the message.
Normally some messages are predefined. Ex : WM_LBUTTONDOWN
it is having the unique ID . using this ID, the windows takes appropriate action for left button down event.
if we are creating our own message, that will not be mingle with the existing ID.
Assume that WM_LBUTTONDOWN message ID number is 0x0008 .
if we are creating our own message with this ID, the windows will takes appropriate action for the LButtonDown.
To overcome this we have to use it as follows :
#define WM_USERMSG WM_APP + 1
#define WM_USERMSG2 WM_APP + 2
and so on.
How can we handle our own message in an application ?
For Adding handler to the user defined message , MFC has ON_COMMAND() message handler.
Here is the testing of custom message :
#define WM_USERMSG WM_APP + 1
How to send custom message to the application ?...
::SendMessage(
HWND, // Parent window
WM_USERMSG, // User defined message
1, // wparam value...
2 // lparam value
) ;
the user can pass their own data through wparam and lparam parameter.
in win32 application we can handle this message in the window procedure as follows :
switch( uMsg)
{
case WM_USERMSG :
int i = (int) wparam; // value will be 1
int j = (int) lparam; // value will be 2 for the above program...
break;
}
In MFC we can add handler to the user defined message using ON_COMMAND() macro..
afx_msg LRESULT OnUserMessage(WPRAM wp, LPARAM lp);
ON_COMMAND( WM_USERMSG, OnUserMessage)
LRESULT CMFCDlg:: OnUserMessage(WPRAM wp, LPARAM lp)
{
int i = (int)wp; // value will be 1
int j = (int) lp; // value will be 2 // if we used the SendMessage(hwnd,WM_USERMSG, 1,2)
retrurn 0;
}
Comma Testing
void CommaTesting()
{
int a,int b;
a= 20,b = 20;
printf("\n Value of a = %d \t b = %d",a,b);
}
int main(int argc, char* argv[])
{
CommaTesting();
return 0;
}
the Output is :
Value of a = 10 b = 20
Two input Filter client application ( Must display two input videos and output video)
1.I displayed two input filter's output video in a window and created the separate graph builder to display the input video...
So the input and output video is different so we need to synchronize them.
But at the time only one graph builder is running...(One after the another )
Solution :
It is not at all the best approach ...Because it is tough to synchronize input video with the Two input filter's output video.
1.we can use T filter ( So that we can make multiple renderer filters in a single graph...)
For Setting the video window,
normally we query the IVideoWindow interface from the the Graph builder...
This is a bad approach... if the graph have a single renderer filter it is ok...
if the graph have multiple renderer filters, then how is it possible to the multiple window handle to the graph ?...
Answer :
we can Query the IVideoWindow from the renderer filter so that it is possible to set the control handle to all the renderer filters in a graph...
2.we can use Sample grabber callback ( In this approach we have to read the data frm the callback and display it in a window...
Wednesday, July 25, 2007
C# Tips
Using System.Diagnostics.Debug.Writeline() fn, we can write the debug string
2.How do we play default window sounds in C# ?
in .NET 2.0,
System.Media namespace is available. To play for example the classical beep sound, you could use the following code:
System.Media.SystemSounds.Beep.Play();
Similarly, you could play the “Question” sound with this code:
System.Media.SystemSounds.Question.Play();
The System.Media namespace is defined in System.dll, so there are no new DLLs you would need to add to your project’s references to use the above code.
3.What does the /target: command line option do in the C# compiler?
All the /target: options except module create .NET assemblies. Depending on the option, the compiler adds metadata for the operating system to use when loading the portable executable (PE) file and for the runtime to use in executing the contained assembly or module.
module creates a module. The metadata in the PE does not include a manifest. Module/s + manifest make an assembly - the smallest unit of deployment. Without the metadata in the manifest, there is little the runtime can do with a module.
library creates an assembly without an entry point, by setting the EntryPointToken of the PE's CLR header to 0. If you look at the IL, it does not contain the .entrypoint clause. The runtime cannot start an application if the assembly does not have an entry point.
exe creates an assembly with an entry point, but sets the Subsystem field of the PE header to 3 (Image runs in the Windows character subsystem - see the _IMAGE_OPTIONAL_HEADER structure in winnt.h). If you ILDASM the PE, you will see this as .subsystem 0x0003. The OS launches this as a console app.
winexe sets the Subsystem field to 2. (Image runs in the Windows GUI subsystem). The OS launches this as a GUI app.
4.What is the difference between const and static readonly?
The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.
In the static readonly case, the containing class is allowed to modify it only
in the variable declaration (through a variable initializer)
in the static constructor (instance constructors, if it's not static)
static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.
Instance readonly fields are also allowed.
Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.
class Program
{
public static readonly Test test = new Test();
static void Main(string[] args)
{
test.Name = "Program";
test = new Test(); // Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
}
}
class Test
{
public string Name;
}
On the other hand, if Test were a value type, then assignment to test.Name would be an error.
5.How do I get and set Environment variables?
Use the System.Environment class.Specifically the GetEnvironmentVariable and SetEnvironmentVariable methods.Admitedly, this is not a question specific to C#, but it is one I have seen enough C# programmers ask, and the ability to set environment variables is new to the Whidbey release, as is the EnvironmentVariableTarget enumeration which lets you separately specify process, machine, and user.
Brad Abrams blogged on this way back at the start of this year, and followed up with a solution for pre-Whidbey users.
6.Preprocess Win32 Messages through Windows Forms
In the unmanaged world, it was quite common to intercept Win32 messages as they were plucked off the message queue. In that rare case in which you wish to do so from a managed Windows Forms application, your first step is to build a helper class which implements the IMessageFilter interface. The sole method, PreFilterMessage(), allows you to get at the underlying message ID, as well as the raw WPARAM and LPARAM data. By way of a simple example:
public class MyMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// Intercept the left mouse button down message.
if (m.Msg == 513)
{
MessageBox.Show("WM_LBUTTONDOWN is: " + m.Msg);
return true;
}
return false;
}
}
At this point you must register your helper class with the Application type:
public class mainForm : System.Windows.Forms.Form
{
private MyMessageFilter msgFliter = new MyMessageFilter();
public mainForm()
{
// Register message filter.
Application.AddMessageFilter(msgFliter);
}
…
}
At this point, your custom filter will be automatically consulted before the message makes its way to the registered event hander. Removing the filter can be accomplished using the (aptly named) static Application.RemoveMessageFilter() method.
7.Be aware of Wincv.exe :
When you install the .NET SDK / VS.NET, you are provided with numerous stand alone programming tools, one of which is named wincv.exe (Windows Class Viewer). Many developers are unaware of wincv.exe, as it is buried away under the C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin subdirectory (by default).
This tool allows you to type in the name of a given type in the base class libraries and view the C# definition of the type. Mind you, wincv.exe will not show you the implementation logic, but you will be provided with a clean snapshot of the member definitions.
8.What is the equivalent to regsvr32 in .NET?
Where you once used Regsvr32 on unmanaged COM libraries, you will now use Regasm on managed .NET libraries.
“Regsvr32 is the command-line tool that registers .dll files as command components in the registry“
“Regasm.exe, the Assembly Registration tool that comes with the .NET SDK, reads the metadata within an assembly and adds the necessary entries to the registry, which allows COM clients to create .NET Framework classes transparently. Once a class is registered, any COM client can use it as though the class were a COM class. The class is registered only once, when the assembly is installed. Instances of classes within the assembly cannot be created from COM until they are actually registered.“ If you want to register an assembly programmatically, see the RegistrationServices class and ComRegisterFunctionAttribute
Effective C# mechanisms
1. Use 'as' and 'is' keywords instead of casting.
the ‘as' and ‘is' keywords instead of casting. It's true that those keywords let you test runtime type information without writing try / catch blocks or having exceptions thrown from your methods. It's also true that there are times when throwing an exception is the proper behavior when you find an unexpected type. But the performance overhead of exceptions is not the whole story with these two operators. The as and is operators perform run time type checking, ignoring any user defined conversion operators. The type checking operators behave differently than casts.
runtime performance as one justification for choosing among different language constructs, it's worth noting that very few Effective Items are justified strictly based on performance. The simple fact is that low-level optimizations aren't going to be universal. Low level language constructs will exhibit different performance characteristics between compiler versions, or in different usage scenarios. In short, low-level optimizations should not be performed without profiling and testing.
2.String Concatenation is expensive
string concatenation is an expensive operation. Whenever you write code that appears to modify the contents of a string, you are actually creating a new string object and leaving the old string object as garbage.
3.Checking the Length property is faster than an equality comparison
Some people have commented that this idiom:
if ( str.Length != 0 )
is preferable to this one:
if ( str != "" )
The normal justification is speed. People will tell you that checking the length of the string is faster than checking to see if two string are equal. That may be true, but I really doubt you'll see any measurable performance improvement.
4.String.Equal is better than == ( Refer gnana prakash anna's article)
5.Boxing and Unboxing are bad
This is true, boxing and unboxing are often associated with negative behaviors in your program. Too many times, the justification is performance. Yes, boxing and unboxing cause performance issues.
Identify the unreleased COM objects in Directshow Filter
DbgDumpObjectRegister();
-what I observed...
Using this fn, I got the debug information in a DebugView...
So I am looking it with BDL Video Overlay Filter.
In the BDL overlay filter, All the pin and filter objects are released properly. whereas in BDL VideoQuality Filter,
I got the debug information as VideoQuality Filter and its input output pins objects are not released...
So I added NonDelegatingAddRef() and NonDelegatingRelease() fn in the video quality Filter.
So This caused the program. There I incremented the m_cRef which is a counter for the number of objects created in a system.
Before Debug information , VideoQuality::NonDelegatingQueryInterface() fn is called...
So the Filter and Pin objects are in use. So i Cut the code
VideoQuality::NonDelegatingAddRef()
VideoQuality::NonDelegatingRelease() fn ...
Now it is working...
How can we dump the COM objects that are not released...
For this one, I called the
DbgDumpObjectRegister() as the ending line of the filter's destructor.( VideoQuality::~VideoQuality() fn)
Tuesday, July 24, 2007
Boxing and UnBoxing in C#
C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap.
The conversion of value type to reference type is known as boxing and
converting reference type back to the value type is known as unboxing.
Example :
Int32 x = 10;
object o = x ; // Implicit boxing
Console.WriteLine("The Object o = {0}",o); // prints out 10
//-----------------------------------------------------------
Int32 x = 10;
object o = (object) x; // Explicit Boxing
Console.WriteLine("The object o = {0}",o); // prints out 10
STL samples with pointers
#include <map>
using namespace std;
typedef map <int,int* > IntMap;
typedef map < int,int* >::iterator IntIter;
void MapPtrTesting()
{
IntMap m_Map;
IntIter iter;
int *p = new int();
*p = 10;
m_Map[0] = p;
iter = m_Map.find(1);
if( iter == m_Map.end())
{
printf("\n Invalid Search...");
return;
}
printf("\n Find the values :%d", *(iter->second));
for(iter = m_Map.begin(); iter != m_Map.end(); iter++)
{
printf( " Value of %d at ",(*iter).first);
printf(" Value is %d",*((*iter).second));
delete (*iter).second;
}
m_Map.clear();
}
int main (int argc, char* argv[])
{
printf("Hello World!\n");
MapPtrTesting();
return 0;
}
STL List sample application :
#include "stdafx.h"
#include <list >
using namespace std;
typedef list<int* > IntegerPtr;
list<int*>::iterator listIter;
void IntegerPtrTesting()
{
IntegerPtr *m_pIntegerPtr = new IntegerPtr();
int* p = new int();
*p = 10;
m_pIntegerPtr->insert(++m_pIntegerPtr->begin(),p);
for(listIter = m_pIntegerPtr->begin(); listIter != m_pIntegerPtr->end(); ++listIter)
{
printf("Value is %d",*(*listIter));
}
for(listIter = m_pIntegerPtr->begin(); listIter != m_pIntegerPtr->end(); ++listIter)
{
delete (*listIter);
*listIter = NULL;
}
m_pIntegerPtr->clear();
if(m_pIntegerPtr)
{
delete m_pIntegerPtr;
m_pIntegerPtr = NULL;
}
}
int main(int argc, char* argv[])
{
printf("Hello World!\n");
IntegerPtrTesting();
return 0;
}
Monday, July 23, 2007
Video Rendering_Event Notification
DirectShow provides several filters that render video:
Video Renderer filter.
This filter is available for all platforms that support DirectX, and has no particular system requirements. The Video Renderer uses DirectDraw whenever possible to render the video; otherwise, it uses GDI. This filter is the default video renderer on platforms earlier than Windows XP.
Video Mixing Renderer Filter 7 (VMR-7).
The VMR-7 is available on Windows XP, where it is the default video renderer. The VMR-7 always uses DirectDraw 7 for rendering. It provides many powerful features not available in the older Video Renderer filter, including a plug-in model where the application controls the DirectDraw surfaces used for rendering.
Video Mixing Renderer Filter 9 (VMR-9). The VMR-9 is a newer version of the Video Mixing Renderer that uses Direct3D 9 for rendering. It is available for all platforms that support DirectX. It is not the default renderer, however, because it has higher system requirements than the Video Renderer filter.
Windowed Mode and Windowless Mode
A DirectShow video renderer can operate in either windowed mode or windowless mode.In windowed mode, the renderer creates its own window to display the video. Typically you will make this window the child of an application window.
In windowless mode, the renderer draws the video directly onto an application window. It does not create its own window. For more information about this mode
Responding to Events :
While a DirectShow application is running, events can occur within the filter graph. For example, a filter might encounter a streaming error. Filters alert the Filter Graph Manager by sending events, which consist of an event code and two event parameters. The event code indicates the type of event, and the event parameters supply additional information. The meaning of the parameters depends on the event code
three events that are very common:
The EC_COMPLETE event indicates that playback has completed normally.
The EC_USERABORT event indicates that the user has interrupted playback. Video renderers send this event if the user closes the video window.
The EC_ERRORABORT event indicates that an error has caused playback to halt.
Using Event Notification :
An application can instruct the Filter Graph Manager to send a Windows message to a designated window whenever a new event occurs.
For Example, if the user closes the window , then the playback must be closed and COM objects must be released.So From Windows application to
Filtergraph manager, we can pass the message.
//Defining new WIndows message
#define WM_GRAPHNOTIFY WM_APP + 1
Next, query the Filter Graph Manager for the IMediaEventEx interface and call the IMediaEventEx::SetNotifyWindow method:
IMediaEventEx *g_pEvent = NULL;
g_pGraph->QueryInterface(IID_IMediaEventEx, (void **)&g_pEvent);
g_pEvent->SetNotifyWindow((OAHWND)g_hwnd, WM_GRAPHNOTIFY, 0);
This method designates the specified window (g_hwnd) as the recipient of the message. Call the method after you create the filter graph, but before running the graph.
WM_GRAPHNOTIFY is an ordinary Windows message. Whenever the Filter Graph Manager puts a new event on the event queue, it posts a WM_GRAPHNOTIFY message to the designated application window. The message's lParam parameter is equal to the third parameter in SetNotifyWindow. This parameter enables you to send instance data with the message. The window message's wParam parameter is always zero.
In your application's WindowProc function, add a case statement for the WM_GRAPHNOTIFY message:
case WM_GRAPHNOTIFY:
HandleGraphEvent();
break;
In the event handler function, call the IMediaEvent::GetEvent method to retrieve events from the queue:
I have to implement this calls in VideoQualityClient GUI application.
void HandleGraphEvent()
{
// Disregard if we don't have an IMediaEventEx pointer.
if (g_pEvent == NULL)
{
return;
}
// Get all the events
long evCode, param1, param2;
HRESULT hr;
while (SUCCEEDED(g_pEvent->GetEvent(&evCode, ¶m1, ¶m2, 0)))
{
g_pEvent->FreeEventParams(evCode, param1, param2);
switch (evCode)
{
case EC_COMPLETE: // Fall through.
case EC_USERABORT: // Fall through.
case EC_ERRORABORT:
CleanUp();
PostQuitMessage(0);
return;
}
}
}
Add the Filter By class ID :
HRESULT AddFilterByCLSID(
IGraphBuilder *pGraph, // Pointer to the Filter Graph Manager.
const GUID& clsid, // CLSID of the filter to create.
LPCWSTR wszName, // A name for the filter.
IBaseFilter **ppF) // Receives a pointer to the filter.
{
if (!pGraph || ! ppF) return E_POINTER;
*ppF = 0;
IBaseFilter *pF = 0;
HRESULT hr = CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, reinterpret_cast
if (SUCCEEDED(hr))
{
hr = pGraph->AddFilter(pF, wszName);
if (SUCCEEDED(hr))
*ppF = pF;
else
pF->Release();
}
return hr;
Generics
Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
It is like a C++ template.
VC++.NET 2005 supports both generics and templates..NET generics differ from C++ templates.
difference is that specialization of a .NET generic class or method occurs at runtime whereas specialization occurs at compile time for a C++ template.
Key differences between generics and C++ templates:
Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime
The common language runtime specifically supports generics in MSIL. Because the runtime knows about generics, specific types can be substituted for generic types when referencing an assembly containing a generic type. Templates, in contrast, resolve into ordinary types at compile time and the resulting types may not be specialized in other assemblies.
Generics specialized in two different assemblies with the same type arguments are the same type. Templates specialized in two different assemblies with the same type arguments are considered by the runtime to be different types.
Generics are generated as a single piece of executable code which is used for all reference type arguments (this is not true for value types, which have a unique implementation per value type). The JIT compiler knows about generics and is able to optimize the code for the reference or value types that are used as type arguments. Templates generate separate runtime code for each specialization.
Generics do not allow non-type template parameters, such as
template
Generics do not allow explicit specialization (that is, a custom implementation of a template for a specific type). Templates do.
Generics do not allow partial specialization (a custom implementation for a subset of the type arguments). Templates do.
Generics do not allow the type parameter to be used as the base class for the generic type. Templates do.
Generics do not allow type parameters to have default values. Templates do.
Templates support template-template parameters (e.g.
template class X> class MyClass ), but generics do not.
Cross thread operation failure in .NET 2.0
within the user created thread , if we tried to add or update the control, that will cause the Cross thread operation failure .
Description of the problem :
During Runtime, .NET CLR checks whether the control is accessed at the thread where it is created. otherwise .NET CLR will display the Cross thread operation failure.
For Example if we added the list box to the form, within the user created thread, if we add item to the list box , this will produce
cross thread operation failure error.
How to solve the cross thread operation failure problem :
All the controls are derived from Control class.
Thread Safety
Only the following members are safe for multithreaded operations: BeginInvoke, EndInvoke, Invoke, InvokeRequired, and CreateGraphics.
For other methods, the developer is responsible for thread safe.(The developer has to write code to make it as thread safe..)
How I solved the problem:
-------------------------------------
By calling the Invoke() method, I solved the problem...
Note : BeginInvoke() or Invoke() blocks the thread until it updates the data to the control.
delegate void UpdateControl(string text);
void UpdateList(string text)
{
if(listbox1.InvokeRequired)
{
UpdateControl updateCtl = new UpdateControl( UpdateList);
listbox1.Invoke(updateCtl, text);
}
else
{
listbox1.Items.Add(text); // Add item to the list box...
}
}
void ThreadProc () // Cross thread's operation failure
{
UpdateList( "Sundar");
}
InvokeRequired member is true, if the cross thread operation execution takes place. ( this will be done by the framework by comparing the thread instance)
Full sample application with code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace CrossThreadInvoke
{
public partial class Form1 : Form
{
private Thread thread1 = null;
private ThreadStart threadStart1 = null;
delegate void UpdateControl (string text);
public Form1()
{
InitializeComponent();
threadStart1 = new ThreadStart(ThreadProcedure);
thread1 = new Thread(threadStart1);
}
private void UpdateList(string text)
{
if (listBox1.InvokeRequired)
{
UpdateControl m_UpdateControl = new UpdateControl(UpdateList);
listBox1.Invoke(m_UpdateControl, text);
}
else
{
listBox1.Items.Add(text);
}
}
private void ThreadProcedure()
{
int i = 0;
while (true)
{
if (i > 10)
{
break;
}
UpdateList("Sundar");
i++;
}
thread1.Abort();
}
private void btnStart_Click(object sender, EventArgs e)
{
thread1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
thread1.Abort();
}
}
}
BeginInvoke() :
it is working in the same way as Invoke() fn...
Check the following sample application :
BeginInvoke() Sample application :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace CrossThread
{
public partial class Form1 : Form
{
private Thread thread1 = null;
private ThreadStart threadStart1 = null;
public delegate void UpdateList(string text);
public UpdateList m_UpdateList = null;
public Form1()
{
InitializeComponent();
m_UpdateList += new UpdateList(SetToList1);
threadStart1 = new ThreadStart(AddToList1);
thread1 = new Thread(threadStart1);
}
public void SetToList1(string text)
{
listBox1.Items.Add(text);
}
private void AddToList1()
{
try
{
int i = 10;
while (true)
{
if (i <= 0) break;
listBox1.BeginInvoke(m_UpdateList, "sundar");
i--;
Thread.Sleep(1000);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Invoke() fns are thread safe.
In case of Invoke() fn what happens ...
void UpdateList(string text)
{
if( listbox1.InvokeRequired )
{
UpdateControl m_UpdateControl = new UpdateControl(UpdateList);
listbox1.Invoke( m_UpdateControl, text);
}
else
{
listbox1.Items.Add( text);
}
}
How this code works ...
Main thread is available to the C# application until we closes the application.
Application.Run() method in C# begins running a standard application message loop in the Form's main thread.
Each and Every thread has its own message queue for messages. if any event occurs in the thread will be added to the corresponding thread's message queue.
while we are accesing the listbox from cross thread, the thread instance is checked ...
For Cross thread, InvokeRequired field is set to true.
Invoke() fn executes a delegate on the thread that owns the control's underlying window handle.
The delegate is executed in the thread which the control is created . Until the completion of the delegate execution,
the current thread is blocked .
This is also same to BeginInvoke() fn . At which scenario we will use Invoke() and BeginInvoke()...
Normally for UI update we will use Invoke() method.
For UI data updation, we will use BeginInvoke() method.
For Example Updating the text to the list box we can use BeginInvoke() method.
For Example adding controls to the tab controls we may go for Invoke() fn. BeginInvoke() fn execution is much faster than Invoke() fn.
Friday, July 20, 2007
Cross thread operation failure , Use Invoke, BeginInvoke fn...
In Visual studio 2005, if we are accessing the control within a form, at run time we will get
Cross thread operation failure.
.NET runtime checks whether the control is used in the thread which created the control. if it is used within the thread at which the control is created, then it will allows execution.
otherwise the .NET runtime will throws an exception.
in the following example if we are creating the thread within that thread if we try to add data to the listbox. .NET runtime will throws exception at
runtime.
For Cross thread operation, we have to call the Invoke() or BeginInvoke() fn to update the control.
Invoke() and BeginInvoke() fns are thread safe. all other threads are not thread safe. the user has to make it as thread safe.
within Thread function, we called the
listBox1.BeginInvoke(m_UpdateList, "sundar");
which inturn updates the listbox. BeginInvoke() or Invoke() blocks the thread until it updates the data to the control.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace CrossThread
{
public partial class Form1 : Form
{
private Thread thread1 = null;
private ThreadStart threadStart1 = null;
public delegate void UpdateList(string text);
public UpdateList m_UpdateList = null;
public Form1()
{
InitializeComponent();
m_UpdateList += new UpdateList(SetToList1);
threadStart1 = new ThreadStart(AddToList1);
thread1 = new Thread(threadStart1);
}
public void SetToList1(string text)
{
listBox1.Items.Add(text);
}
private void AddToList1()
{
try
{
int i = 10;
while (true)
{
if (i <= 0) break;
listBox1.BeginInvoke(m_UpdateList, "sundar");
i--;
Thread.Sleep(1000);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnStart_Click(object sender, EventArgs e)
{
try
{
thread1.Start();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
private void btnStop_Click(object sender, EventArgs e)
{
thread1.Abort();
}
}
}
Use of Invoke() fn >>>
Every control has the following members:
InvokeRequired (boolean field)
Invoke() fn
InvokeRequired field is true if the cross thread operation takes place otherwise it will be false.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace CrossThreadInvoke
{
public partial class Form1 : Form
{
private Thread thread1 = null;
private ThreadStart threadStart1 = null;
delegate void UpdateControl (string text);
event UpdateControl m_UpdateControl = null;
public Form1()
{
InitializeComponent();
threadStart1 = new ThreadStart(ThreadProcedure);
thread1 = new Thread(threadStart1);
m_UpdateControl = new UpdateControl(UpdateList);
}
private void UpdateList(string text)
{
if (listBox1.InvokeRequired)
{
listBox1.Invoke(m_UpdateControl, text);
}
else
{
listBox1.Items.Add(text);
}
}
private void ThreadProcedure()
{
int i = 0;
while (true)
{
if (i > 10)
{
break;
}
m_UpdateControl("Sundar");
i++;
}
thread1.Abort();
}
private void btnStart_Click(object sender, EventArgs e)
{
thread1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
thread1.Abort();
}
}
}
Difference between Delegate and Delegate With event
Yes... See the sample
delegate void UpdateControl( string text);
UpdateControl m_UpdateControl = null;
private event UpdateControl m_EventUpdateControl = null;
m_UpdateControl += new UpdateControl( UpdateListCtrl);
m_EventUpdateControl += new UpdateControl( UpdateListCtrl);
private void UpdateListCtrl()
{
listSent.items.Add("Test" + listSent.items.count);
}
we can create the object as follows :
m_UpdateControl = new UpdateControl(UpdateListCtrl); // will work properly
But the following code will not work properly...
m_EventUpdateControl = new UpdateControl(UpdateListCtrl);
we have to change it as
m_EventUpdateControl += new UpdateControl(UpdateListCtrl);
This implies...
we can set the delegate object as null as follows in anywhere like during initialization or within any fn.
m_UpdateControl = null;
But for Event with delegate object, we will not be able to initialize it as null , it affects the other client's delegates also.
m_EventUpdateControl = null; // Exception : we can initialize null for the event with delegate object during initialization.
what it means is that if we use the event keyword no client class can set it to null. This is very important. Multiple clients can use the same delegate. After multiple client have added a function to listen to the callback of the delegate. But now one of the client sets the delegate to null or uses the = sign to add a new call back. This means that the previous invocation list will not be used any more. Hence all the previous client will not get any of the callback even if they have registered for the call back.
Hence we can say that the even keyword adds a layer of protection on the instance of the delegate. The protection prevents
any client to reset the delegate invocation list. They can only add or remove the target from the invocation list.
Wednesday, July 18, 2007
Using Css :
------------------
A stylesheet is a document that contains formatting rules for one or more XML or HTML documents.
we can define our own template for the style of the font.
style.css :
-----------------
CATALOG
{
background-color :#00ff00 ; <!-- Sets the background color as green -->
}
test.xml :
==========
<?xml version = "1.0" ?>
<?xml:stylesheet type ="text/css" href ="D:style.css" ?>
<CATALOG> Sundar
</CATALOG
if we run the test.xml in internet explorer, then IE displays the text "Sundar" with background as Green.
XSL :
----------
CSS doesnot support the reorder,sort and display of elements based on a condition. To Help us perform such operations,
XML supports another style sheet language called Extensible Style Sheet(XSL).
XSL has two parts :
1. XSL Transformations (XSLT)
This XML based language allows us to transform an XML document into other formats such as HTML and XHTML.
2.XML Path ( XPath)
This language is used to access parts of an XML document such as elements and attributes.
XSL contains formatting objects (how the data is to be displayed)
XSLT contains instructions on how an XML document should be transformed in to an HTML or XHTML documents.
XSLT uses XPath expressions to extract specific data from an XML document.
XPath expressions contain mathematical, relational, equality and logical operators to specify the conditions for formatting the XML document.
XSLT Processor reads the XSLT instructions and transforms the XML document into HTML or XHTML document or into another XML document.
This transformed document then uses the XSL formatting objects to display the document in the desired format.
Comparing CSS and XSLT :
XSLT is a superset of the CSS functionality. we can use XSLT to display selective elements or attibutes, sort data on one or more elements,
and process the data based on a condition.
XSLT is an application of XML. XSLT follows XML syntax. XSLT is intended for complex formatting.
Difference between CSS and XSLT
S.No CSS XSLT
1 Simple To use and is suitable for simple documents complex to use
2 cannot reorder,add,delete or perform operations on elements can Reorder,add or delete elements, because it is aware of the structure of
XML document.
3. Doesnot offer access to non-elements such as Allows accessing and manipulating comments,PI values within
attributes, attribute values and PI an XML document
4. Uses less memory Uses more memory and processor power because we can reorder,add, delete
and manipulate the elements that require a tree representation of the document
in memory
5. Doesnot use XML syntax Written using XML and follows XML syntax.
XSLT Processor :
XSLT processor is packaged along with the Microsoft XML parser.
The XML parser can be used to parse an XSLT document, because XSLT is an application of XML. The MSXML parser parses the XSLT style sheet and creates
a tree structure based on the elements and attributes used in the XSLT document. this tree is referred as XSL tree.
The XSLT processor of the MSXML parser takes the transformation information contained in the XSLT stylesheet, applies it to the data
retrieved from the source document, and builds a tree structure referred to as the result tree. This tree is then rendered to various targets, such as web browsers,
pagers and cellphones.
Formatting Data using XSLT :
XSLT provides the following elements to select and format data :
1.stylesheet
2.value-of
3.for-each
4.sort
5.text
stylesheet element :
----------------------------
A Style sheet declaration is added in the XSLT file to instruct the browser that it is a style sheet file.This is required because
the XSLT stylesheet contains instructions to transform the XML document.
<xsl:stylesheet xmllns: xsl = "http://www.w3.org/1999/XSL/Transform" version = "1.0">
value-of element :
-------------------------
this element displays the value of the specified element or attribute.
<xsl:value-of select ="elementName/attributeName" />
For displaying the element value
Example : <FirstName>John </FirstName>
<xsl:value-of select ="FirstName"> - Display the value of the FirstName.
For displaying the attribute value we must prefix @ symbol.
<xsl:value-of select ="@Product">
The for-each element :
--------------------------------
This element is used to instruct the XSLT processor to process the information for each instance of the specified pattern.
<xsl:for-each select ="pattern">
{action to be performed}
</xsl:for-each>
sort element :
--------------------
This element is used to sort data based on the values assigned to elements and attributes.
text Element ;
----------------------
text Element allows us to generate constant text in output. It can be used to display labels.
Example :
<xsl:text> ProductName: </xsl:text>
Formatting Data using XSL formatting objects :
1.XSL -FO is an XML based language that allows us to format XML documents into pages, paragraphs and lists.
It is used to specify pagination, layout, and formatting information for XML documents.
structure of an XSL-FO Document :
<?xml version = "1.0" encoding = "ISO-8859-1" ?>
<fo:root xmlns:fs= "http://www.w3.org/1999/XSL/Format" >
</fo:root>
XML Schema
-------------------------------
1.primitive data types
2.derived data types
3.Atomic
4.List
5.union
Primitive datatype :
------------------------
primitive data types are fundamental datatypes of XSD.
These data types are the basis for defining other data types in XSD.
Primitive datatypes do not contain elements or attributes.
They contain only values.
Primitive Data type Description
string Represents a collection of characters.
decimal Represents decimal numbers.
float 32 bit floating point numbers
boolean
timeDuration Represents certain duration of time
recurringDuration represents a time duration that recurs after a specific interval.
Derived data types :
Derived data types are defined using other datatypes called basetypes.
Derived Data type Base Data type Description
integer Decimal
long Integer
nonNegativeInteger Integer
positiveInteger nonNegativeInteger
int Long
time recurringDuration
date timeDuration
Atomic data types :
Atomic data types can not be broken down into smaller units. These datatypes can be primitive or derived.
For Example, the string primitive data type cannot be further broken down into smaller units, such as characters.
List Datatypes :
Listdata types are derived data types that contain a set of values of atomic data types.For Example, we can derive a point list.
union datatypes :
Union data types are derived from the atomic and list data types .
The Purpose of XML schema : (XSD)
XML schema file is stored with .XSD extension.
XML schema file is used to validate the XML file. In other words, whether the XML file is formulated according to our user requirement can be tested with XML schemas .
XML file is nothing but an instance of a schema...
For Example :
we are defining structure as follows :
struct Allowance // This is what we call it as schema in XML, we call it as XML Schema available in .XSD file
{
float HRA;
float PF;
float ESI;
};
//XML instance this is similar to .XML file
Allowance s = new Allowance ();
s.HRA = 2000;
s.PF = 1000;
s.ESI = 200;
we can validate the .XML file based on the XML schema...
Monday, July 16, 2007
XML Basics
1.Processing Information (PI )
2.Tags
3.Elements
4.Content
5.attributes
6.Entities
7.comments
1.Processing Instruction (PI) :
An XML document usuaally begins with the XML declaration statement called the Processing instruction .
The PI statement provides information on how the XML file should be processed.
The PI statement can be written as :
the PI statement must be written in lower case letters.
UTF-8 specifies the encoding scheme used to create the XML file.
2.Tags :
tags are used to specify a name for a given piece of information. A tag consists of opening and closing angular brackets.
start Tag <>
End Tag >
example :
Sundar
3.Elements
Elements are basic units used to identify and describe the data in XML.
Elements are represented in Tag.
Example :
XML document must always have a root element.A root element contains all other elements in the document.
authors element contains all other elements in an XML and it is the root element.
XML document can contain only one root element.
4.Content
content refers to the information represented by the elements of an XML document.
Example :
Harry Potter is the content .
XML enables us to declare and use elements that can contain different types of information.An element can contain :
1.character or data content
2.Element content
3.combination or mixed content
Example for character or data content (textual information )
--------------------------------------------------------
Example for Element content (contains other elements)
--------------------------------------------
Elements can contain other elements. this other elements are called child elements.
author element contains FirstName and LastName elements.
Example for Combination or mixed content : (textual as well as other elements)
-------------------------------------------------------------------
The product is available in two colors
Attributes :
------------------------
Attributes provide additional information about the elements in which they are declared.
An attribute consists of name-value pair.
Example :
ProdId ="P001" is an attribute.
Elements can have one or more attributes.
Element is used to represent definable unit.
An attribute is used to represent data that further qualifies the element.
Example: font element can have an attribute color to specify the font color. In this case color attribute further qualifies the font element.
Entities :
An Entity is a name that is associated with a block of data, such as chunk of text or a reference to an external file that contains
textual orm binary information.
certain characters, such as < and & can' t be used in XML documents because they have a special meaning.
For Example the < symbol is used as a delimiter for tags.
XML provides predefined entities called internal entities, to enable us to express such characters in an XML document.
An internal entity consists of a name that is associated with a block of information. the name of the internal entity is always preceded by an ampersand (&)
and terminated with a semicolon.
Some Predefined internal entities form the part of the XML specification :
Internal Entity Description
< Used to display the less than (<) symbol
> Used to display the greater than ( >) symbol
& used to display the ampersand (&) symbol
" used to display the double quote( " ) symbol
Example :
entity (< ) replaced with the < symbol in the above statement.
Comments :
Comments are statements to explain the XML code. They used to provide documentation information about the XML file.
The parser ignores comment entries during code execution.
Comments are created using an opening angular bracket followed by an exclamation mark and two hyphens. This is followed by the text that comprises
the comment. Comments are closed using two hyphens followed by a closing angular bracket.
Example :
Rules for creating well formed XML documents :
The rules that govern the well formed XML document are
1.Every start tag must have an end tag.
2.Empty tags must be closed using a forward slash. Example :
3.All attribute values must be given in double quotation marks. Example :
4.Tags must have proper nesting . Opening tags must be closed in reverse order in which they appear.
incorrect format :
Correct format :
5.XML tags are case-sensitive.
Working with XML schemas and namespaces :
MSXML 6.0 parser supports XML schemas.
dotNet Framework basics
1. Common Language Runtime ( CLR )
2. .NET framework base classes
3. User and Program interfaces
CLR Services :
1.Code compilation
2.memory allocation
3.Garbage collection
Converts Source code to IL, IL to JIT compiler.
IL language to machine language conversion takes place at runtime.
Two stages of compilation
1. Source code to IL ( During the process of compilation, compiler also produces meta data about code... )
2.IL to machine code ( Done at Runtime by JIT compiler... )
Meta Data contains the description of code such as classes, interfaces, dependencies and versions of the components.
IL and Meta data constitute an assembly. ( Assembly contains both IL and meta data ).
Meta data describes the assembly's internal version number and details of all the data and object types they contain.
In .NET, Assembly is a single file with the extension .exe or .dll . Assemblies can also contain one or more modules.
During Execution, CLR performs the following steps :
1.Loading assemblies and identifying namespaces :
Assemblies are loaded in the memory. After loading assemblies, CLR identifies namespaces for code in assemblies.
Namespaces are collection of classes. The .NET framework uses namespaces to organise its classes hierarchy.
(Namespaces implicitly have public access and this cannot be changed)
2.JIT compilation :
Before Execution, IL is converted in to machine language by the JIT compiler. Next during the verification process,
the IL code is examined to confirm the following points :
i. Memory allocations for code
ii. Methods are called only thru properly defined types
iii. IL has been correctly generated
3.Garbage Collection :
Garbage Collection process begins after the JIT compilation and manages all the memory allocation and deallocation of an application.
whenever u create an object , the CLR allocates memory for the object from the managed heap.
A managed heap is a region of memory that is available for program execution.if sufficient memory is not available on the managed heap,
the garbage collection process is invoked.
CLR manages the compilation and execution of the managed code to ensure proper functioning of a code.
For Example, CLR take care of
1.Garbage collection
2.Exception Handling
3. Type Safety for managed code.
The unit of execution in the CLR is an assembly. Assembly contains IL and metadata. All assemblies contains manifest which contains information such as assembly name, version and the list of files that form the assembly. The IL code can not be executed if it doesnt have an associted assembly.
Meta data :
describes the assembly's internal version number and details of all the data and object types they contain.
Manifest :
contains assembly name, version and the list of files that form the assembly
.NET framework base class library :
this library provide classes that can be used to accomplish programming tasks such as data base connectivity,string management, data collection
and file access.
Namespaces :
Namespaces help us to create a logical group of classes. Namespaces can be used to avoid naming conflicts between classes which have same names.
the .NET framework uses a dot delimiter between namespaces and classes. System .Console
System is namespace and Console is a class.
Assembly :
An assembly is a single deployable unit that contains all the information about the implementation of classes, structures and interfaces.
the assembly stores all the information about itself. This information is called metadata and includes the
1.name and version number of the assembly
2.security information
3.information about the dependencies and the list of files that constitute an assembly.
Assembly and meta data provide the CLR with the information required for executing an application.
For Example if an application uses a component, the assembly keep track of version number of the component used in the application.
User and program interfaces :
.NET framework provides three types of user interfaces .
1.Windows Forms
2.Web forms
3.Console applications
Advantages of .NET framework ;
1. Multi platform applications
2.Multi language integration
3.Automatica resource management
while creating an application, a programmer may be required to write code for managing resources such as files, memory, network connections and database connectivity. if the programmer does not free those resources, application may not execute properly. The CLR automatically tracks resource usage and relieves a programmer of the task of manual resource management.
4.Ease of deployment
Wednesday, July 11, 2007
Random Notes
----------------------------------------------------
1.What is the difference between simple form & MDI form?
MDI (Multi Document Interface) Form is form that can hold multi forms inside it. Examples -
MDI - Excel
SDI - Notepad
MDI Form Contain the Multiple MDICHILD form and Dialog form
But Simple for do not able to contain any form in it.
MDI forms are certainly helpful for embedding other forms. Something that a lot of people don't know, is that you can make any window that has an hWnd, the child of another form with a simple API call. So, essentially, even top level windows CAN be MDI, but in practice, this is rude.
what is OpenDML ?
OpenDML is an extension to the original Video for Windows (VfW) file format.
It was drawn up to overcome the original 2GByte file length restrictions in avi files. (AVI files must be less than 2 GB size previously, this problem is overcome
by OpenDML)
Object modelling :
Object modelling is useful for designing computer systems, whether those systems are to be implemented in object-oriented languages or not.Most designs are likely to need more than an object-oriented language, such as a database. Object modelling also has a use outside of the design of computer systems. It is an excellent analysis method, and it can be used in business process reengineering, in social science research, or any complex environment where it is important to capture the structure and functionality of some world.
Design is a process which involves
communication
creativity
negotiation
agreement
It is a human process, to produce products for human consumption. Too often the communication, negotiation and agreement aspects are left
Object modelling provides a notation which is clear, consistent, and which can be used to communicate within a software development team, and with the clients and other third-parties which the team need to deal with.
Object modelling consists of looking for objects. Of course, there has to be some boundary. Even sitting at my desk I can see more objects than I could reasonably list. But that is where the beauty of object modelling comes in. It uses observation.
Objects can be described by their attributes and operations. Attributes are the changeable characteristics of an object. Cats have colour, size, weight and a preference for either Kit-E-Kat or Whiskers. Operations are the things an object does or can have done to it. Cats can catch mice, eat, miaow, worm up to owners, and be stroked. In our notation we draw an object such as a cat like this.
Object modelling is about finding objects, their attributes and their operations, and tying them together in an object model. Nothing more. Here are some more objects: Object modelling can be used to design lots of things.
what is Delegation :
The behaviour of an object which is made up of other objects is usually defined by the behaviour of the smaller objects. For example To start a car, you start the engine. Thus the start operation on the car involves calling the start operation on the engine. This is known as delegation. The engine then will switch on the ignition system, switch on the starter motor then switch off the starter motor. This is further delegation.
Tuesday, July 10, 2007
I faced the problem in C++ class as follows :
error C2533: 'VideoQualityUtil::__ctor' : constructors not allowed a return type
VideoQualityUtil::VideoQualityUtil()
{
m_pVideoQualityTool = NULL;
m_pCsvWriter = NULL;
}
So I refered the MSDN documentation for the Error C2533.
MSDN documentation for Error C2533 :
'identifier' : constructors not allowed a return type
A constructor cannot a value or have a return type (not even a void return type).
The following sample generates C2533:
// C2533.cpp
class X
{
public:
X();
};
int X::X()
// try the following line instead
// X::X()
{ // C2533
}
int main()
{
}
Can U identify where my program failed ?....
Scroll to see the Answer ...
.
.
.
Answer :
Sometimes with the help of MSDN, we can't solve the errors...
I found where my code fails...I left the class as follows...
class VideoQualityUtil
{
}
we have to change it as follows :
class VideoQualityUtil
{
}
;
I missed the semi colon...