Incomplete :
1.MWS to ASF writing problem
2.QT audio Encoding
3.merge Frames Filter ( First Image is displayedbut the successing images are not displayed from the videos )
4.Registry support to DirectX transform Filters
5.Make VideoQualityClient to support YUV formats and make channel selection for performing video quality processing
6.Enable the support of audio codecs in WMINTF ( Ring Buffer returns NULL for audio codecs after the some repeated execution )
Completed :
1.Sample Grabber application developement
2.Sample grabber application with Quicktime video (frame by frame)compression
3.Sample Grabber application with Quicktime temporal video compression
4.QTEncoder class
5.MovieWriter class
6.Null Encoder class
7.Encoder Queue developement for storing the encoded frames in Temporal compression
8.Integrated the QTvideo Encoder class with wmintf...
9.Video board sample application with MainCodec H264 API's
10.Developed the COM wrapper for CEncoder class ( Due to aggregation problem, we stopped the COM wrapper developement for all the encoders)
11. AVi Writer with windows supported codecs
12.AVI writer with Main codec H264 API compression
13.Integrated AVi Writer with WMINTF( uncompressed data is compressed with H264 APIs But we are not added the header to the AVI file. Bala told us that he completed it. But he didnt send it to us yet)
14.Converted the Graphics Object to Win32 Device context for improving IdxGraphApp
15.IdxGraphApp integration to the WMINTF
16.DVB ( DiskRouter)Api application developement (we tested the sample application ...) due to invalid key we give up this development
17. Created the new Catgory "BDL Image processing" for storing the Filters under this category
18.Conversion of NNSTestAgent application as a service
19.NNSTestAgent application developement
20.RemoteServiceController DLL development for NNSTestAgent application
21. HTTP Monitor graph developement and the development of container to hold the list of graph objects
22.Video Quality client application
Directshow Filters Developed :
All the filters have the histogram support.
Filters use OpenCV 1.0 or Gdi+ .
1.Overlay Transform Filter - Overlay text on line path.
2.Zoom Filter
3.Add the Filters with IModuleConfig for setting the Config information
4.RGB Scaling
5.Resize Filter
6.Color To Gray Filter
7.Bitmap Overlay Filter
8.Timecode Burning Filter
9.Blur Filter ( guassian , Pyramid blur) , Blur Effect on line path
10.ChannelBlur
11.ColorBalanceRGB Filter
12.Mirror Filter
13.Morphology Filter
14.Inverse Filter
15.ShiftChannels Filter
16.GammaCorrection Filter
17.Emboss Filter (Emboss Filter implements following techniques :Edge Detect quick, Emboss135 degree, Emboss 90_50, Emboss laplasian, sharpen and Mean removal)
18.Tiles Filter
19.Rotation Filter
20.Mask Filter ( rectangle mask ,Circle and Ellipse mask supported)
21.Rotate 90 Filter ( 90,180,270 degree rotations are supported)
22.Sepia Filter
23.Vortex Filter
24.Water Filter
25.Brightness Filter
26.Random Jitter filter
27.Swirl
28.Sphere
29.Timewarp
30.Pixellate Filter
31.Posterize Filter
32.Threshold
33.Solarize Filter
34.Saturation Filter
35.Hue Filter
36.Luminance Filter
37.Contrast Filter
38.Absolute Difference Filter
39.Video overlay
40.Dyadic Logic Filter
41.Dyadic Arithmetic Filter
42.Image File Source Filter
43.Source Filter for capturing the Desktop screen
44.Motion Detection Filter developement
45. color based motion detection (RGB is more sensitive, if we removed any color component that will affects the entire image,
For motion detection, Color Image is converted to gray scale image and performed the motion detection previosuly )
HSL color H component is responsible for video all other indicates brightness like that. So the normal Image is converted to
the HSL image and then applied the motion detection. it works well.
46.Crop Filter development
47. video Quality Filter currently supports
PSNR,MSAD,Delta, MSE,SSIM and VQM
Histogram have the following options :
1. channel Selection option for creating Histogram
2.Make the source image for Histogam as transform filter's Input or output image and
3.Enable black clipping and White clipping suppport to the histogram property pages.
DirectX transform Filter development : ( uses OpenCV or GDI+ or both gdi+ and OpenCV)
1.Sepia
2.Brightness
3.ColorbalanceRGB
4.Posterize
5.Bitmap overlay filter
6.channel Blur
7.RGB Scaling
8.Vortex Filter
9.Crop Filter developement
10.Gamma correction
11.ShiftChannels
12.Sphere Filter
13.Swirl Filter
14.Random Jitter
15.Pixellate
16.Threshold
17.Water Filter
18.Timewarp filter
19.Emboss ( developed the Sharpen,Removal as a separate filter )
20.Text overlay
21.Dyadic Arithmetic Filter
22.AbsDiff Filter
23.Video overlay Filter
Note :
Read the incomplete things from chat archive...
Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts
Tuesday, August 07, 2007
Monday, August 06, 2007
C# 2.0 New features
C# 2.0 new features (.NET framework SDK):
1.Partial classes allow class implementation across more than one file. This permits breaking down very large classes, or is useful if some parts of a class are automatically generated.
2.Generics or parameterized types. This is a .NET 2.0 feature supported by C#. Unlike C++ templates, .NET parameterized types are instantiated at runtime rather than by the compiler; hence they can be cross-language whereas C++ templates cannot. They support some features not supported directly by C++ templates such as type constraints on generic parameters by use of interfaces. On the other hand, C# does not support non-type generic parameters. Unlike generics in Java, .NET generics use reification to make parameterized types first-class objects in the CLI Virtual Machine, which allows for optimizations and preservation of the type information.
3.Static classes that cannot be instantiated, and that only allow static members. This is similar to the concept of module in many procedural languages.
4.A new form of iterator that provides generator functionality, using a yield return construct similar to yield in Python.
// Method that takes an iterable input (possibly an array) and returns all even numbers.
public static IEnumerable GetEven(IEnumerable numbers)
{
foreach (int i in numbers)
{
if (i % 2 == 0) yield return i;
}
}
5.Anonymous delegates providing closure functionality.
public void Foo(object parameter)
{
// ...
ThreadPool.QueueUserWorkItem(delegate
{
// anonymous delegates have full access to local variables of the enclosing method
if (parameter == ...)
{
// ...
}
// ...
});
}
6.Covariance and contravariance for signatures of delegates
7. The accessibility of property accessors can be set independently. Example:
string status = string.Empty;
public string Status
{
get { return status; } // anyone can get value of this property,
protected set { status = value; } // but only derived classes can change it
}
8.Nullable value types (denoted by a question mark, e.g. int? i = null;) which add null to the set of allowed values for any value type. This provides improved interaction with SQL databases, which can have nullable columns of types corresponding to C# primitive types: an SQL INTEGER NULL column type directly translates to the C# int?.
int? i = null;
object o = i;
if (o == null) Console.WriteLine("Correct behaviour - you have a runtime version from September 2005 or later");
else Console.WriteLine("Incorrect behaviour - you are running a pre-release runtime (from before September)");
When copied into objects, the official release boxes values from Nullable instances, so null values and null references are considered equal.
9. Coalesce operator: (??) returns the first of its operands which is not null
object nullObj = null;
object obj = new Object();
return nullObj ?? obj; // returns obj
The primary use of this operator is to assign a nullable type to a non-nullable type with an easy syntax:
int? i = null;
int j = i ?? 0; // Unless i is null, initialize j to i. Else (if i is null), initialize j to 0.
1.Partial classes allow class implementation across more than one file. This permits breaking down very large classes, or is useful if some parts of a class are automatically generated.
2.Generics or parameterized types. This is a .NET 2.0 feature supported by C#. Unlike C++ templates, .NET parameterized types are instantiated at runtime rather than by the compiler; hence they can be cross-language whereas C++ templates cannot. They support some features not supported directly by C++ templates such as type constraints on generic parameters by use of interfaces. On the other hand, C# does not support non-type generic parameters. Unlike generics in Java, .NET generics use reification to make parameterized types first-class objects in the CLI Virtual Machine, which allows for optimizations and preservation of the type information.
3.Static classes that cannot be instantiated, and that only allow static members. This is similar to the concept of module in many procedural languages.
4.A new form of iterator that provides generator functionality, using a yield return construct similar to yield in Python.
// Method that takes an iterable input (possibly an array) and returns all even numbers.
public static IEnumerable
{
foreach (int i in numbers)
{
if (i % 2 == 0) yield return i;
}
}
5.Anonymous delegates providing closure functionality.
public void Foo(object parameter)
{
// ...
ThreadPool.QueueUserWorkItem(delegate
{
// anonymous delegates have full access to local variables of the enclosing method
if (parameter == ...)
{
// ...
}
// ...
});
}
6.Covariance and contravariance for signatures of delegates
7. The accessibility of property accessors can be set independently. Example:
string status = string.Empty;
public string Status
{
get { return status; } // anyone can get value of this property,
protected set { status = value; } // but only derived classes can change it
}
8.Nullable value types (denoted by a question mark, e.g. int? i = null;) which add null to the set of allowed values for any value type. This provides improved interaction with SQL databases, which can have nullable columns of types corresponding to C# primitive types: an SQL INTEGER NULL column type directly translates to the C# int?.
int? i = null;
object o = i;
if (o == null) Console.WriteLine("Correct behaviour - you have a runtime version from September 2005 or later");
else Console.WriteLine("Incorrect behaviour - you are running a pre-release runtime (from before September)");
When copied into objects, the official release boxes values from Nullable instances, so null values and null references are considered equal.
9. Coalesce operator: (??) returns the first of its operands which is not null
object nullObj = null;
object obj = new Object();
return nullObj ?? obj; // returns obj
The primary use of this operator is to assign a nullable type to a non-nullable type with an easy syntax:
int? i = null;
int j = i ?? 0; // Unless i is null, initialize j to i. Else (if i is null), initialize j to 0.
Wednesday, July 25, 2007
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.
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.
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
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
Monday, July 23, 2007
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.
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.
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();
}
}
}
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
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.
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.
Monday, July 16, 2007
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
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
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.
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.
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.
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.
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.)
------------------------------------
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.)
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
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
Wednesday, June 27, 2007
Threads in .NET
Threads in .NET :
A common use of threads is for all kinds of periodical updates.
.NET offers three different ways:
Windows timers with the
System.WinForms.Timer class
Periodical delegate calling with
System.Threading.Timer class
Exact timing with the
System.Timers.Timer class
System.WinForms.Timer class :
For inexact timing we use the window timer. Events raised from the window timer go through the message pump (together with all mouse events and UI update messages) so they are never exact. The simplest way for creating a WinForms.Timer is by adding a Timer control onto a form and creating an event handler using the control's properties. We use the Interval property for setting the number of milliseconds between timer ticks and the Start method to start ticking and Stop to stop ticking.
System.Threading.Timer
class :
The System.Threading.Timer class is a new waiting thread in the thread pool that periodically calls supplied delegates. To use it you must perform several steps:
Create state object which will carry information to the delegate
Create TimerCallback delegate with a method to be called. You can use static or instance methods.
Create a Timer object with time to wait before first call and periods between successive calls (as names of this two parameters suggests, first parameter should be lifetime of this timer object, but it just don't work that way)
Change the Timer object settings with the Change method (same remark on parameters apply)
Kill the Timer object with the Dispose method
System.Timers.Timer
class :
The final timing options come from the System.Timers.Timer class. It represents server-based timer ticks for maximum accuracy. Ticks are generated outside of our process and can be used for watch-dog control. In the same System.Timers namespace you can find the Schedule class which gives you the ability to schedule timer events fired at longer time intervals.
System.Timers.Timer class is the most complete solution for all time fired events. It gives you the most precise control and timing and is surprisingly simple to use.
Create the Timer object. You can a use constructor with interval setting.
Add your event handler (delegate) to the Tick event
Set the Interval property to the desired number of milliseconds (default value is 100 ms)
Set the AutoReset property to false if you want the event to be raised only once (default is true – repetitive raising)
Start the ticking with a call to the Start() method, or by setting Enabled property to true.
Stop the ticking with call to the Stop() method or by setting the Enabled property to false.
A common use of threads is for all kinds of periodical updates.
.NET offers three different ways:
Windows timers with the
System.WinForms.Timer class
Periodical delegate calling with
System.Threading.Timer class
Exact timing with the
System.Timers.Timer class
System.WinForms.Timer class :
For inexact timing we use the window timer. Events raised from the window timer go through the message pump (together with all mouse events and UI update messages) so they are never exact. The simplest way for creating a WinForms.Timer is by adding a Timer control onto a form and creating an event handler using the control's properties. We use the Interval property for setting the number of milliseconds between timer ticks and the Start method to start ticking and Stop to stop ticking.
System.Threading.Timer
class :
The System.Threading.Timer class is a new waiting thread in the thread pool that periodically calls supplied delegates. To use it you must perform several steps:
Create state object which will carry information to the delegate
Create TimerCallback delegate with a method to be called. You can use static or instance methods.
Create a Timer object with time to wait before first call and periods between successive calls (as names of this two parameters suggests, first parameter should be lifetime of this timer object, but it just don't work that way)
Change the Timer object settings with the Change method (same remark on parameters apply)
Kill the Timer object with the Dispose method
System.Timers.Timer
class :
The final timing options come from the System.Timers.Timer class. It represents server-based timer ticks for maximum accuracy. Ticks are generated outside of our process and can be used for watch-dog control. In the same System.Timers namespace you can find the Schedule class which gives you the ability to schedule timer events fired at longer time intervals.
System.Timers.Timer class is the most complete solution for all time fired events. It gives you the most precise control and timing and is surprisingly simple to use.
Create the Timer object. You can a use constructor with interval setting.
Add your event handler (delegate) to the Tick event
Set the Interval property to the desired number of milliseconds (default value is 100 ms)
Set the AutoReset property to false if you want the event to be raised only once (default is true – repetitive raising)
Start the ticking with a call to the Start() method, or by setting Enabled property to true.
Stop the ticking with call to the Stop() method or by setting the Enabled property to false.
Tuesday, June 26, 2007
Difference between finalize and dispose
Dispose is a method for realse from the memory for an object.
For eg:
For eg:
Thursday, June 21, 2007
Difference between Panel and GroupBox classes?
Difference between Panel and GroupBox classes?
1.Panel is scrollable and the captions can't be displayed in it
S.No Panel GroupBox
1 Can have scroll bars. Can't have scroll bars.
(Scrollable) (Unscrollable)
2. can't have captions can have captions
1.Panel is scrollable and the captions can't be displayed in it
S.No Panel GroupBox
1 Can have scroll bars. Can't have scroll bars.
(Scrollable) (Unscrollable)
2. can't have captions can have captions
Wednesday, June 20, 2007
Marshalling Problem Practically applied
8:22 PM 6/20/2007
Simple DLL Developement :
1. open the simple Win32 DLL project ( TestDll) , it will creates the stdafx.h, stdafx.cpp and TestDll.cpp
2.Add the new header file (TestDll.h)
within the TestDll.h file I added the following code >..
#ifdef DLLDIR_EX
#define DLLDIR __declspec(dllexport) // export DLL information
#else
#define DLLDIR __declspec(dllimport) // import DLL information
#endif
extern "C"
{
bool DLLDIR GetStatusKeyword();
BOOL DLLDIR GetStatusTypedef();
}
within the TestDll.cpp file, I added the following :
#include "TestDll.h"
bool DLLDIR GetStatusKeyword()
{
return false;
}
BOOL DLLDIR GetStatusTypedef()
{
return false;
}
Select menu items as follows ...
Project ->Settings ->C++ -> General option
Add the DLLDIR_EX macro in the "Preprocessor Definitions " text box.
and then compile it
they will show the EXPORTS keyword in a text box and compile the DLL project.
I got the TestDll.dll and TestDll.lib output files .
Develope the C# client application :
Create the C# Console application and add the namespace "System.Runtime.InteropServices" to it
and add the code as follows :
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace TestDLLClient
{
class Win32API
{
[DllImport("TestDLL.dll")]
public static extern bool GetStatusTypedef();
[DllImport("TestDLL.dll")]
public static extern bool GetStatusKeyword();
}
class Program
{
static void Main(string[] args)
{
if (Win32API.GetStatusKeyword())
{
Console.WriteLine("\n GetStatusKeyword() fn succeeded ");
}
else
{
Console.WriteLine("\n GetStatusKeyword() fn failed ");
}
if (Win32API.GetStatusTypedef())
{
Console.WriteLine("\n GetStatusTypedef() fn Succeeded");
}
else
{
Console.WriteLine("\n GetStatusTypedef() fn failed");
}
Console.Read();
}
}
}
Next Copy the Testdll.dll and Testdll.lib to the "debug" folder of the C# client application.
then compile and run the C# application.
we got the output of the C# application is as follows:
GetStatusKeyword() fn succeeded
GetStatusTypedef() fn failed
Guys the problem is not over,
Next I modified the dll code as follows :
bool DLLDIR GetStatusKeyword()
{
OutputDebugString(" \n GetStatusKeyword() fn ..."); // This will writes the string in debug view...
return false;
}
BOOL DLLDIR GetStatusTypedef()
{
return false;
}
Next Compile the DLL project and copy the TestDll.dll and TestDll.lib to the C# client application's "Debug" folder.
Now Compile the C# application and see the result, u may wonder about the things...
The output is as follows :
GetStatusKeyword() fn failed
GetStatusTypedef() fn failed
It is a funny thing...
Note :
TestDLL application is developed in Visual studio 6.
C# client application is developed in .NET 2005...
Any guys got this problem before or try these things ....
Simple DLL Developement :
1. open the simple Win32 DLL project ( TestDll) , it will creates the stdafx.h, stdafx.cpp and TestDll.cpp
2.Add the new header file (TestDll.h)
within the TestDll.h file I added the following code >..
#ifdef DLLDIR_EX
#define DLLDIR __declspec(dllexport) // export DLL information
#else
#define DLLDIR __declspec(dllimport) // import DLL information
#endif
extern "C"
{
bool DLLDIR GetStatusKeyword();
BOOL DLLDIR GetStatusTypedef();
}
within the TestDll.cpp file, I added the following :
#include "TestDll.h"
bool DLLDIR GetStatusKeyword()
{
return false;
}
BOOL DLLDIR GetStatusTypedef()
{
return false;
}
Select menu items as follows ...
Project ->Settings ->C++ -> General option
Add the DLLDIR_EX macro in the "Preprocessor Definitions " text box.
and then compile it
they will show the EXPORTS keyword in a text box and compile the DLL project.
I got the TestDll.dll and TestDll.lib output files .
Develope the C# client application :
Create the C# Console application and add the namespace "System.Runtime.InteropServices" to it
and add the code as follows :
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace TestDLLClient
{
class Win32API
{
[DllImport("TestDLL.dll")]
public static extern bool GetStatusTypedef();
[DllImport("TestDLL.dll")]
public static extern bool GetStatusKeyword();
}
class Program
{
static void Main(string[] args)
{
if (Win32API.GetStatusKeyword())
{
Console.WriteLine("\n GetStatusKeyword() fn succeeded ");
}
else
{
Console.WriteLine("\n GetStatusKeyword() fn failed ");
}
if (Win32API.GetStatusTypedef())
{
Console.WriteLine("\n GetStatusTypedef() fn Succeeded");
}
else
{
Console.WriteLine("\n GetStatusTypedef() fn failed");
}
Console.Read();
}
}
}
Next Copy the Testdll.dll and Testdll.lib to the "debug" folder of the C# client application.
then compile and run the C# application.
we got the output of the C# application is as follows:
GetStatusKeyword() fn succeeded
GetStatusTypedef() fn failed
Guys the problem is not over,
Next I modified the dll code as follows :
bool DLLDIR GetStatusKeyword()
{
OutputDebugString(" \n GetStatusKeyword() fn ..."); // This will writes the string in debug view...
return false;
}
BOOL DLLDIR GetStatusTypedef()
{
return false;
}
Next Compile the DLL project and copy the TestDll.dll and TestDll.lib to the C# client application's "Debug" folder.
Now Compile the C# application and see the result, u may wonder about the things...
The output is as follows :
GetStatusKeyword() fn failed
GetStatusTypedef() fn failed
It is a funny thing...
Note :
TestDLL application is developed in Visual studio 6.
C# client application is developed in .NET 2005...
Any guys got this problem before or try these things ....
Marshalling Problem :(funny )
Marshalling Problem :
if we are accessing the fn in a VC++ DLL from C# application :
Note the following thing :
1.Within the VC++ DLL fn always make the return type as BOOL instead of bool keyword.
Note :
Try the problem with a simple VC++ DLL contains BOOL as a return type and another fn returns bool data type.
Call it from C# application.
Problems I faced :
bool DLLDIR GetStatus()
{
return false;
}
if I accessed this fn from C# application I got the return value as true.
So try it ...
if it gives the true value then add the OutputDebugString() fn to the GetStatus() fn...
and see what will happen ...( Result : it returns false...)
It is the proposed standard to use BOOL instead of bool , if we access it using interoperability mechanism.
if we are accessing the fn in a VC++ DLL from C# application :
Note the following thing :
1.Within the VC++ DLL fn always make the return type as BOOL instead of bool keyword.
Note :
Try the problem with a simple VC++ DLL contains BOOL as a return type and another fn returns bool data type.
Call it from C# application.
Problems I faced :
bool DLLDIR GetStatus()
{
return false;
}
if I accessed this fn from C# application I got the return value as true.
So try it ...
if it gives the true value then add the OutputDebugString() fn to the GetStatus() fn...
and see what will happen ...( Result : it returns false...)
It is the proposed standard to use BOOL instead of bool , if we access it using interoperability mechanism.
Tuesday, June 12, 2007
How to call Unmanaged DLL from C# application ?
How to call Unmanaged DLL from C# application ?
I develeoped the win32 DLL.
I added the code in the DLL header file as follows :
#ifdef DLLDIR_EX
#define DLLDIR __declspec(dllexport) // export DLL information
#else
#define DLLDIR __declspec(dllimport) // import DLL information
#endif
extern "C"
{
bool DLLDIR GetSysInfo(char* pszSystemName);
};
DLL implementation file I added its defn
How I accessed the DLL in C# ?
VC++ DLL is an Unmanaged code.
This is following way How I accessed that file...
I just copied the .DLL and .LIB files from my DLL project.
and copied it to the debug folder of the C# application
Within C# application
using System.Runtime.InteropServices; // For Interoperability
[DllImport("RemoteSystemDLL.dll")]
public static extern bool GetSysInfo(StringBuilder buf);
and called this GetSysInfo() fn in my application.
// this is the C++ function exposed by the dll
I develeoped the win32 DLL.
I added the code in the DLL header file as follows :
#ifdef DLLDIR_EX
#define DLLDIR __declspec(dllexport) // export DLL information
#else
#define DLLDIR __declspec(dllimport) // import DLL information
#endif
extern "C"
{
bool DLLDIR GetSysInfo(char* pszSystemName);
};
DLL implementation file I added its defn
How I accessed the DLL in C# ?
VC++ DLL is an Unmanaged code.
This is following way How I accessed that file...
I just copied the .DLL and .LIB files from my DLL project.
and copied it to the debug folder of the C# application
Within C# application
using System.Runtime.InteropServices; // For Interoperability
[DllImport("RemoteSystemDLL.dll")]
public static extern bool GetSysInfo(StringBuilder buf);
and called this GetSysInfo() fn in my application.
// this is the C++ function exposed by the dll
Thursday, April 19, 2007
Windows Services application
Create a Normal C# windows Services application :
-----------------------------------------------------
After creating the application
add the installer to it...
To add installers to your service application :
-----------------------------------------------
In Solution Explorer, access Design view for the service for which you want to add an installation component.
Click anywhere within the designer's surface.
In the Description area of the Properties window, click the Add Installer link.
A new class, ProjectInstaller, and two installation components, ServiceProcessInstaller and ServiceInstaller, are added to your project, and property values for the service are copied to the components.
Click the ServiceInstaller component and verify that the value of the ServiceName property is set to the same value as the ServiceName property on the service itself.
To determine how your service will be started, click the ServiceInstaller component and set the StartType property to the appropriate value.Value Result
Manual The service must be manually started after installation. For more information, see Starting Services.
Automatic The service will start by itself whenever the computer reboots.
Disabled The service cannot be started.
To determine the security context in which your service will run, click the ServiceProcessInstaller component and set the appropriate property values. For more information, see Specifying the Security Context for Services.
Override any methods for which you need to perform custom processing. For more information, see Overriding Default Methods on Installation Components.
Perform steps 1 through 6 for each additional service in your project.
Note For each additional service in your project, you must add an additional ServiceInstaller component to the project's ProjectInstaller class. The ServiceProcessInstaller component added in step three works with all of the individual service installers in the project.
Create your setup project and custom action to deploy and install your service. For more information on setup projects, see Setup Projects. For more information on custom actions, see Walkthrough: Creating a Custom Action.
After the installer is added to our windows services,
I selected the ServiceProcessInstaller1 control's properties...
I modified the "Account" property of the serviceProcessInstaller1 as "LocalService".
ServerInstaller1 control have the "name" property which holds the name of the service listed in "Administrative tools ".
//and then run the service from the
InstallUtil :
-----------------
In command prompt
installutil windowsServices1.exe //Install the services in Service Control manager
installutil -u windowsServices1.exe // Uninstall the services in Service control manager...
Starting the Service Manually :
----------------------------------
There are several ways you can start a service that has its StartType process set to Manual — from Server Explorer, from the Windows Services Control Manager, or from code. It is important to note that not all of these methods actually start the service in the context of the Services Control Manager; the Server Explorer and programmatic methods of starting the service actually manipulate the controller.
To manually start a service from Server Explorer
In Server Explorer, add the server you want if it is not already listed. For more information, see Accessing and Initializing Server Explorer.
Note The Servers node of the Server Explorer is not available in the Standard Edition of Visual Basic and Visual C# .NET. For more information, see Visual Basic Standard Edition Features or Visual C# Standard Edition Features.
Expand the Services node, and then locate the service you want to start.
Right-click the name of the service, and click Start.
To manually start a service from Services Control Manager
Open the Services Control Manager by doing one of the following:
In Windows 2000 Professional, right-click My Computer on the desktop, and then click Manage. In the dialog box that appears, expand the Services and Applications node.
- or -
In Windows 2000 Server, click Start, point to Programs, click Administrative Tools, and then click Services.
Note In Windows NT version 4.0, you can open this dialog box from Control Panel.
You should now see your service listed in the Services section of the window.
Select your service in the list, right-click it, and then click Start.
To See more about Windows Services :
--------------------------------------
www.c-sharpcorner.com
http://www.c-sharpcorner.com/UploadFile/prvn_131971/BirthdayWishScheduler02022006012557AM/BirthdayWishScheduler.aspx
-----------------------------------------------------
After creating the application
add the installer to it...
To add installers to your service application :
-----------------------------------------------
In Solution Explorer, access Design view for the service for which you want to add an installation component.
Click anywhere within the designer's surface.
In the Description area of the Properties window, click the Add Installer link.
A new class, ProjectInstaller, and two installation components, ServiceProcessInstaller and ServiceInstaller, are added to your project, and property values for the service are copied to the components.
Click the ServiceInstaller component and verify that the value of the ServiceName property is set to the same value as the ServiceName property on the service itself.
To determine how your service will be started, click the ServiceInstaller component and set the StartType property to the appropriate value.Value Result
Manual The service must be manually started after installation. For more information, see Starting Services.
Automatic The service will start by itself whenever the computer reboots.
Disabled The service cannot be started.
To determine the security context in which your service will run, click the ServiceProcessInstaller component and set the appropriate property values. For more information, see Specifying the Security Context for Services.
Override any methods for which you need to perform custom processing. For more information, see Overriding Default Methods on Installation Components.
Perform steps 1 through 6 for each additional service in your project.
Note For each additional service in your project, you must add an additional ServiceInstaller component to the project's ProjectInstaller class. The ServiceProcessInstaller component added in step three works with all of the individual service installers in the project.
Create your setup project and custom action to deploy and install your service. For more information on setup projects, see Setup Projects. For more information on custom actions, see Walkthrough: Creating a Custom Action.
After the installer is added to our windows services,
I selected the ServiceProcessInstaller1 control's properties...
I modified the "Account" property of the serviceProcessInstaller1 as "LocalService".
ServerInstaller1 control have the "name" property which holds the name of the service listed in "Administrative tools ".
//and then run the service from the
InstallUtil :
-----------------
In command prompt
installutil windowsServices1.exe //Install the services in Service Control manager
installutil -u windowsServices1.exe // Uninstall the services in Service control manager...
Starting the Service Manually :
----------------------------------
There are several ways you can start a service that has its StartType process set to Manual — from Server Explorer, from the Windows Services Control Manager, or from code. It is important to note that not all of these methods actually start the service in the context of the Services Control Manager; the Server Explorer and programmatic methods of starting the service actually manipulate the controller.
To manually start a service from Server Explorer
In Server Explorer, add the server you want if it is not already listed. For more information, see Accessing and Initializing Server Explorer.
Note The Servers node of the Server Explorer is not available in the Standard Edition of Visual Basic and Visual C# .NET. For more information, see Visual Basic Standard Edition Features or Visual C# Standard Edition Features.
Expand the Services node, and then locate the service you want to start.
Right-click the name of the service, and click Start.
To manually start a service from Services Control Manager
Open the Services Control Manager by doing one of the following:
In Windows 2000 Professional, right-click My Computer on the desktop, and then click Manage. In the dialog box that appears, expand the Services and Applications node.
- or -
In Windows 2000 Server, click Start, point to Programs, click Administrative Tools, and then click Services.
Note In Windows NT version 4.0, you can open this dialog box from Control Panel.
You should now see your service listed in the Services section of the window.
Select your service in the list, right-click it, and then click Start.
To See more about Windows Services :
--------------------------------------
www.c-sharpcorner.com
http://www.c-sharpcorner.com/UploadFile/prvn_131971/BirthdayWishScheduler02022006012557AM/BirthdayWishScheduler.aspx
Windows Services Error
Windows Services Error :
---------------------------
---------------------------
Services
---------------------------
The Service1 service on Local Computer started and then stopped. Some services stop automatically if they have no work to do, for example, the Performance Logs and Alerts service.
---------------------------
OK
---------------------------
I got this error because I had the MessageBox.Show() to display message box
during Start() and Stop() of the Windows service...
Solution :
I removed the MessageBox from the windows Services...
---------------------------
---------------------------
Services
---------------------------
The Service1 service on Local Computer started and then stopped. Some services stop automatically if they have no work to do, for example, the Performance Logs and Alerts service.
---------------------------
OK
---------------------------
I got this error because I had the MessageBox.Show() to display message box
during Start() and Stop() of the Windows service...
Solution :
I removed the MessageBox from the windows Services...
Subscribe to:
Posts (Atom)