Wednesday, July 25, 2007

C# Tips

1.How to Write debug string in C# ?

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

Labels:

Effective C# mechanisms

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.

Labels:

Identify the unreleased COM objects in Directshow Filter

- Identified the unreleased objects in a filter by calling Directshow fn...
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)

Labels:

Tuesday, July 24, 2007

Boxing and UnBoxing in C#

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

Labels:

STL samples with pointers

Today I developed the STL map pointer spike application...


#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;
}

Labels: ,

Monday, July 23, 2007

Video Rendering_Event Notification

About Video Rendering in DirectShow :

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(&pF));
if (SUCCEEDED(hr))
{
hr = pGraph->AddFilter(pF, wszName);
if (SUCCEEDED(hr))
*ppF = pF;
else
pF->Release();
}
return hr;

Labels:

Generics

C# 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 C {}. Templates allow them.


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.

Labels: ,

Cross thread operation failure in .NET 2.0

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.

Labels: ,

Friday, July 20, 2007

Cross thread operation failure , Use Invoke, BeginInvoke fn...

Cross thread operation failure :

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();
}
}
}

Labels: , ,

Difference between Delegate and Delegate With event

Is there any difference between the 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.

Labels: , ,

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>

19-july-2007

To day I have to develope the sample graph application...

Regards
Sundararajan.A

XML Schema

Data types in XML schemas :
-------------------------------
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...

Labels:

Monday, July 16, 2007

XML Basics

Components of an XML document :

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 :

williams - author is an element.

XML document must always have a root element.A root element contains all other elements in the document.



charles dickens
Hitchkock


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

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 )
--------------------------------------------------------
Harry Potter

Example for Element content (contains other elements)
--------------------------------------------

Elements can contain other elements. this other elements are called child elements.


charles
Dickens


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
Red
Green


Attributes :
------------------------
Attributes provide additional information about the elements in which they are declared.
An attribute consists of name-value pair.

Example :
Barbie Doll

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 :

the price of the toy is < 200

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 :
John grisham The client

Correct format :
John grisham The client

5.XML tags are case-sensitive.



Working with XML schemas and namespaces :

MSXML 6.0 parser supports XML schemas.

Labels: ,

dotNet Framework basics

Components of .NET framework :
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

Labels:

Wednesday, July 11, 2007

Random Notes

Diffference between SDI and MDI :
----------------------------------------------------
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.

Labels:

Tuesday, July 10, 2007

Hi ,


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...

Labels:

Monday, July 09, 2007

The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET initiative. It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. The CLR runs a form of bytecode called the Microsoft Intermediate Language (MSIL), Microsoft's implementation of the Common Intermediate Language.

Developers using the CLR write code in a high level language such as C# or VB.Net. At compile-time, a .NET compiler converts such code into MSIL (Microsoft Intermediate Language) code. At runtime, the CLR's just-in-time compiler (JIT compiler) converts the MSIL code into code native to the operating system. Alternatively, the MSIL code can be compiled to native code in a separate step prior to runtime. This speeds up all later runs of the software as the MSIL-to-native compilation is no longer necessary

Some important services provided by CLR:
Memory management
Thread management
Exception handling
Garbage collection
Security
Prior to runtime Is it possible to convert IL code to the native machine code ? yes... .NET has the options for it.
How is it possible ?
you have to do following:

first disassemble your code using ILDASM.exe

DLL : ildasm YourCode.dll /output:YourCode.il
EXE: ildasm YourCode.exe /output:YourCode.il

this creates an il file and a res file

then you have to assemble this il and res file with ILASM.exe

DLL: ilasm YourCode.il /dll /resource:YourCode.res /output:YourCode.dll
EXE :ilasm YourCode.il /exe /resource:YourCode.res /output:YourCode.exe

After those two steps you have an PE in native code
You find a more detail instruction on those two tools in msdn - "ILDASM.exe" and "ILASM.exe"

or do the following :
It is possible to compile the IL code in a .NET assembly into Native Code using the command line tool ngen.exe. (see the Framework documentation
for more info on it). The tool also installs the compiled code into the native image cache.

what is ngen.exe ?
Native Image Generator (Ngen.exe)

The Native Image Generator creates a native image from a managed assembly and installs it into the native image cache on the local computer.
Running Ngen.exe on an assembly allows the assembly to load and execute faster, because it restores code and data structures from the native image cache rather than generating them dynamically.(This implies the IL code is not converted to machine code everytime)
ngen [options] [assemblyName |assemblyPath ]
A native image is a file containing compiled processor-specific machine code.

Labels:

The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET initiative. It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. The CLR runs a form of bytecode called the Microsoft Intermediate Language (MSIL), Microsoft's implementation of the Common Intermediate Language.

Developers using the CLR write code in a high level language such as C# or VB.Net. At compile-time, a .NET compiler converts such code into MSIL (Microsoft Intermediate Language) code. At runtime, the CLR's just-in-time compiler (JIT compiler) converts the MSIL code into code native to the operating system. Alternatively, the MSIL code can be compiled to native code in a separate step prior to runtime. This speeds up all later runs of the software as the MSIL-to-native compilation is no longer necessary

Some important services provided by CLR:
Memory management
Thread management
Exception handling
Garbage collection
Security
Prior to runtime Is it possible to convert IL code to the native machine code ? yes... .NET has the options for it.
How is it possible ?
you have to do following:

first disassemble your code using ILDASM.exe

DLL : ildasm YourCode.dll /output:YourCode.il
EXE: ildasm YourCode.exe /output:YourCode.il

this creates an il file and a res file

then you have to assemble this il and res file with ILASM.exe

DLL: ilasm YourCode.il /dll /resource:YourCode.res /output:YourCode.dll
EXE :ilasm YourCode.il /exe /resource:YourCode.res /output:YourCode.exe

After those two steps you have an PE in native code
You find a more detail instruction on those two tools in msdn - "ILDASM.exe" and "ILASM.exe"

or do the following :
It is possible to compile the IL code in a .NET assembly into Native Code using the command line tool ngen.exe. (see the Framework documentation
for more info on it). The tool also installs the compiled code into the native image cache.

what is ngen.exe ?
Native Image Generator (Ngen.exe)

The Native Image Generator creates a native image from a managed assembly and installs it into the native image cache on the local computer.
Running Ngen.exe on an assembly allows the assembly to load and execute faster, because it restores code and data structures from the native image cache rather than generating them dynamically.(This implies the IL code is not converted to machine code everytime)
ngen [options] [assemblyName |assemblyPath ]
A native image is a file containing compiled processor-specific machine code.

Labels:

Image convolution

Convolution :
--------------------
Image convolution plays an important role in computer graphics applications.
Convolution of images allows for image alterations that enable the creation of new images from old ones.
Convolution also allows for important features such as edge detection, with many widespread uses.

The convolution of an image is a simple process by which the pixel of an image is multiplied by a kernel, or masked, to create a new pixel value. Convolution is commonly referred to as filtering.

Details :
First, for a given pixel (x,y), we give a weight to each of the surrounding pixels. It may be thought of as giving a number telling how important the pixel is to us. The number may be any integer or floating point number, though I usually stick to floating point since floats will accept integers as well.

The kernel or mask that contains the filter may actually be any size (3x3, 5x5, 7x7); however, 3x3 is very common. Since the process for each is the same, I will concentrate only on the 3x3 kernels. (kernel contains values filled by user).

Second, the actual process of convolution involves getting each pixel near a given pixel (x,y), and multiplying each of the pixel's channels by the weighted kernel value. This means that for a 3x3 kernel, we would multiply the pixels like so:

the pixel value at (x,y) is calculated as follows :

(x-1,y-1) * kernel_value[row0][col0] +
(x ,y-1) * kernel_value[row0][col1] +
(x+1,y-1) * kernel_value[row0][col2] +
(x-1,y ) * kernel_value[row1][col0] +
(x ,y ) * kernel_value[row1][col1] +
(x+1,y ) * kernel_value[row1][col2] +
(x-1,y+1) * kernel_value[row2][col0] +
(x ,y+1) * kernel_value[row2][col1] +
(x+1,y+1) * kernel_value[row2][col2]


neighbour pixels for the given pixel (x, y) :


(x-1,y-1) (x,y-1) (x+1, y-1)

(x-1, y) (x,y) (x+1,y)

(x-1,y+1) (x, y+ 1) (x+1, y+1 )


Kernel matrix :

kernel_value[row0][col0] kernel_value[row0][col1] kernel_value[row0][col2]

kernel_value[row1][col0] kernel_value[row1][col1] kernel_value[row1][col2]

kernel_value[row2][col0] kernel_value[row2][col1] kernel_value[row2][col2]



multiply the neighbour pixels with the kernel matrix :

Labels:

Thursday, July 05, 2007

Compression for Video:

Compression for Video:
An Introduction



Codec. You've heard the word. What does it mean? Its actually two words stuck together to reflect both an ideology and a curse in the digital world.

Codec means compression / decompression, and depending on whether you're the sender or on the receiving end of a particular file, a video or images compression will play a massive factor in your ability to handle it from either end.

There are many different companies and individuals that have developed their own compression algorithms.

For each compression algorithm, you can adjust its properties to create a more or less compressed file

The properties of a particular compressor can be further divided down into compression methods. Most codecs take advantage of someor all of these methods. They are:

· Spatial

· Temporal

· Lossless

· Lossy

· Asymmetrical & Symmetrical



Spatial Compression:

Also called Intra compression, this program, or algorithm, compresses the visual description of an video frame or file by looking for patterns or repetitions among the images pixels.

For example in a picture with a stretch of white sandy beaches, spatial compression will take notice that many of the pixels that comprise the beach area are a similar tan white shade. Rather than describing each of the thousand subtle variations within an area of sand, spatial compression records a much shorter description, such as "All of the pixels in this area are a light tan color"

As you increase the amount of spatial compression, the data rate and file size decrease, and the image loses sharpness and definition. With many codecs, the amount of spatial compression to add is controlled by the quality and data rate options. A low value for these options increases spatial compression, resulting in a larger data or bit rate, but a crisper, vibrant image

Temporal Compression:

Looks for ways to compress the description of the changes that occur during a sequence of frames. It does this by looking for a pattern and repetition over time.

For example, in a video clip with a person speaking in front of a static background, temporal compression notices that the only pixels changing over time are the pixels that make up the speakers face. All of the other pixels don't change (when the camera is motionless). Instead of describing every pixel in every frame, temporal compression describes all of the pixels in the first frame, and then foe every frame that follows, describes only the pixels that are different from the previous frame. This technique is called frame differencing.

If most of the pixels in the frame are different from the previous frame, the codec simply describes the new frame, allowing for every pixel to be described or rendered. Each whole rendered frame is referred to as a keyframe. Each new keyframe becomes a starting point for frame differencing. Most codecs allow you to set keyframes at specific intervals, while other codecs allow you to set keyframes at markers that you've set manually in your project timeline window. Some codecs automatically create a new keyframe on a frame that is significantly different from the previous frame. If you can specify or set fewer keyframes, the data or bit rate and filesize will decrease, however so will your picture quality.

The amount of temporal compression is often controlled by the codecs keyframe settings as well as its quality option. If you set low values for these options will increase temporal compression.

Lossless Compression:

Some codecs use lossless compression, which assures that all of the information in the image or clip is fully preserved after compression. This maintains the full quality of the original, which makes lossless compression useful for final cut editing or for moving clips between systems. However, preserving original image quality limits the degree to which you can control the data or bit rate as well as the file size. The resulting data may be too high for smooth playback on some systems.

Lossy Compression:

A lossy compression discards some of the original pixel info during compression. Take for example an image of a blue sky that contains 83 shades of blue, a lossy codec set to a loss of 25 percent of original quality may only display 64 shades. Lossy codecs usually let you specify how much picture quality you want to sacrifice to lower the data or bit rate and file size. In essence lossy codecs allow you to tailor the playback for a wide variety of audiences.

Lossy compression allows much lower bit rates and file sizes than lossless compression, so you tend to find lossy codec in use for video delivered for CD-ROM or the Internet.

Some codecs are always lossy, such as JPG, or always lossless, such as planar RGB. Other codecs may be set to either lossless or lossy depending on the options you set

Asymmetrical and Symmetrical Compression:

The codec you choose affects your workflow not only in file size or playback speed, but also in the amount of time a file takes to compress a given number of frames. Fast compression helps video, compositing and editing companies creating the images, while fast decompression makes viewing easier.

Many codecs take far more time compressing files than they do decompressing files for playback. This is the reason why a one-minute short may take 5 minutes to compress before playback is possible.

Compression can be likened to a warehouse. You can pack the warehouse as fast as you can unpack it, but if you spend more time organizing and arranging the items, you can fit more items into the warehouse.

Similarly, different codecs require various amounts of time to compress or decompress video. A codec is considered symmetrical when it requires the same amount of time to compress as to decompress a clip. A codec is asymmetrical when the times required to compress and decompress a clip are significantly different. For example, the Cinepak asymmetrical codec decompresses video relatively quickly, making it useful for video files that must play well on both high- and low-end computers, but to achieve this it requires more time when compressing. Symmetry varies depending on the codec and is generally not adjustable within a codec.

A codec is a specified mechanism that handles compression / decompression. Some of these codecs are built into the software you use. QuickTime, Video for Windows, MPG, TIFF, TGA, are some examples of these codecs. Various algorithms built into these codecs are supplied by their manufacturer, or downloadable off of the Internet. Techsmith, DiVx, Cinepak, and Sorenson are examples of these types of Algorithms. Some are better choices when compressing video to stream on the web, or CDR publication, while others work well for Desktop Presentations. Typically, broadcast shows will not be compressed, unless dealing with a limited color palette or severe time restrictions, which limit production and final rendering time.

Compositing:

The visual art of editing and compositing can play an enormous role in the amount of time a sequence of images takes to compress. Compositing allows the user to render each frame in pieces, or layers. By working with layers, an artist gains significantly increased flexibility in the technical and stylistic edits or fixes needed to produce a finished product. Working with a background layer and the main character on a separate layer, the artist can quickly adjust the contrast or brightness of the background without the adjustments influencing the shades of the featured character. An added benefit of working in layers within a compositing or editing package is that at render time temporal compression is applied to layers that don't move in relation to the previous frame on the same layer. A layer that is active with movement, will not have temporal compression applied. Similarly, working in layers also benefits spatial compression because the codec has an easier time separating unrelated objects by virtue of them being on distinct layers. Ultimately, this results in faster compression, increased spatial accuracy, as well as being more symmetrical with a lower bit rate on the playback end of things. The benefit of matting, allows the artist to combine the foreground and background images, seamlessly blending composites into a final rendered image.

System Requirements

If you're capturing video and you want your files to be lossless, a system must be capable of capturing images at a pixel resolution of 720 * 576. Hardware compression should be found on the video capture card itself to optimize performance. The hard disk must spin fast enough to capture frames as they arrive from the video card. If this is not possible, the hard disk will drop frames out of the sequence to keep up with the speed the video card is feeding it. A hard drives average access time, should be about 10 milliseconds and data transfer should support at least 3MB per second but ideally should be around 6MB per second. Use a separate hard disk when capturing data. If your capture software and editing software are accessing the same disk at capture time, performance will suffer. Your capture disk should be defragmented at all times so that the hard drive can capture the images in large blocks. Finally, your system should be equipped with sufficient Ram to be able to load a good chunk of video into memory while editing.

Labels:

Wednesday, July 04, 2007

Calling VC++ function pointer from C#

VS.NET 2005 :
------------------------------------

C# application :
--------------------------

1.Copy the VC++ DLL in to the debug folder of the newly created C# application

[DllImport("TestLib.dll",CallingConvention=CallingConvention.Cdecl)]
public static extern void SetCallback( MulticastDelegate callback );
[DllImport("TestLib.dll",CallingConvention=CallingConvention.Cdecl)]
public static extern void InvokeCallback(int count);

//Declaration For accessing the VC++ DLL function in C#


public delegate void CallbackDelegate( int count );

public static void Callback(int a)
{
Console.WriteLine("Callback: {0}", a);
}


public static void Main()
{
CallbackDelegate del = new CallbackDelegate( Callback );
Console.WriteLine( "Testing generated delegate..." );
SetCallback(del);

for(int i =0; i <5; i++)
{
InvokeCallback(i);
}
}


But I got an error while using this code ...
Function is executed but I got the error "'System.Reflection.Emit.TypeBuilder.Exit' not found".

Solution :
To avoid this error, we used the attribute with the delegate .

[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate void CallbackDelegate( int count );

Now the Error will not occur..


Reason :

The JIT compiler tracks the lifetime of object references in local variables (on the stack). It doesn't know that your unmanaged code uses the delegate. You can override it by using GC.KeepAlive() after the P/Invoke call. That doesn't actually generate any code, it just convinces the JIT compiler that the delegate instance should be kept alive past the call. This feature must have launched a thousand bugs. ( Example 1 in the KeepAlive() MSDN library topic is a scary example.)

Labels:

Tuesday, July 03, 2007

Marshalling

Marshaling : ( COM and .NET InterOp)

1.Data that is passed from .NET to the COM component and the other way around must be converted to
the corresponding representation. This mechanism is also known as marshaling. What happens here
depends on the data type of the data that is passed. Here we have to differentiate between blittable and
non-blittable data types.

Blittable data types have a common representation with both .NET and COM, and no conversion is
needed. Simple data types such as byte, short, int, long, and classes and arrays that only contain these
simple data types belong to the blittable data types. Arrays must be one-dimensional to be blittable.

With non-blittable data types a conversion is needed. The following table lists some of the non-blittable
COM data types with their .NET-related data type. Non-blittable types do need more performance
because of the conversion.



S.NO COM Data type .NET Data type

1 SAFEARRAY Array
2 VARIANT Object
3 BSTR string
4 IUnknown* , IDispatch* Object

Labels:

Monday, July 02, 2007

References and Pointers are Same in C++?

.

.

.

Ans :-



No, they are not.It is important to realize that references and pointers are quite different.



S.No

Pointers

References

1

creating a pointer creates a new object.

creating a reference does not create a new object; it merely creates an alternative name for an existing object.

2

A pointer should be thought of as a separate object with its own distinct set of operations (*p, p->blah, and so on).

the operations and semantics for the reference are defined by the referent; references do not have operations of their own.

In the following example, notice that assigning 0 to the reference j is very different than assigning 0 to the pointer p (the 0 pointer is the same as the NULL pointer; see FAQ 1.09).

int main()

{

int i = 5;

int& j = i; <-- 1

int* p = &i; <-- 2


j = 0; <-- 3

p = 0; <-- 4

}

(1) j is an alias for i

(2) p is a new object, not an alias

(3) Changes i

(4) Changes p; does not affect i