Archive

Posts Tagged ‘C#’

How to use the full screen in Windows Phone 7 application

June 1st, 2011 1 comment

While looking on Window’s Phone 7 device (or emulator), one can see in the upper part of screen the area, named “Status Bar”. See the next image:



Read more…

How to marshall C++ reference parameter to C#.NET using C++/CLI

May 11th, 2011 No comments

Suppose you have some very complicate function written in either C or native C++. And suppose you want to use it in your C#.NET managed code. Obviously, marshalling is required.
There are generally 3 possible options for marshalling:
1) COM
3) C++/CLI
2) Pinvoke (Platform Invokation)

Since making a COM wrapper for native code (ATL e.t.c) is not trivial, and C++/CLI is usually used for more complicated cases, most used way is platform invokation: define the function as “static extern”, add “DllImport” attribute, define some parameters and – eureka! – the required managed function is ready for using…
In case of native C++ class’s method, the process is a bit more complicated, because compiler concatenates a class & method names in some strange form. Still, the new method name could be acheived using known for all “Dependency Walker” application.

Read more…

Categories: .Net, C#, C++/CLI Tags: ,

Working with System.Timers.Timer causing memory leaks

April 21st, 2011 2 comments

Short preamble,

Recently we had very serious problem with our application written in C#.NET; sometimes it has been completely stuck. This wasn’t easy reproducible scenario. As we started investigate the issue and debugging, more and more interesting things came up (not all code was written by our team, so debugging was not very easy thing). Memory almost wasn’t affected, but there was another symptom: thread count was growing and growing.

Finally the problem was discovered as following:
Read more…

Categories: .Net, C# Tags: , , ,

How to find all types which derive from given type.

April 16th, 2011 No comments

Suppose you need to find all types in assembly, which derive from given type (using C#.NET). What we need is reflection, to collect all types in a given assembly, using “Assembly.GetTypes” and then to select the required types only.

1) As a first attempt, we will use a function “IsSubclassOf” for every type in assembly:

public IEnumerable<Type> GetAllTypesDerivedFrom(Type type)
{
        var types = Assembly.GetAssembly(type).GetTypes();
        return types.Where(curType => curType.IsSubclassOf(type));
}

This works good. So, why this attempt is not a solution? Because the function “IsSubclassOf” works with classes, but not with interfaces. It returns “false” for interface.
Read more…

Categories: .Net, C# Tags: ,

How to do mapping of NCLOB into string in NHibernate

April 11th, 2011 2 comments

I want to describe some error, which is accepted, while mapping NCLOB in NHibernate.

Working with Oracle database, we use “NVARCHAR2” type for strings. But this type has a constrain: it could contain no more then 2000 characters. If one needs to store some long text in Oracle, he will use an NCLOB type.

But, while mapping this type, next error is accepted:
ORA-01461: can bind a LONG value only for insert into a LONG column“.

How can we avoid this error? Two ways are possible:

1) Setting coulumn’s type to “AnsiString”:

        <property name="Contents" column="CONTENTS" type="AnsiString"/> 

Read more…

Categories: .Net, NHibernate Tags: , , , , ,

A problem with using static member in a class C#.NET

April 9th, 2011 3 comments

Today, I would like to tell about some bug I had in my C#.NET code, and a simple way to fix it.

When needed a transform matrix 3 x 3, I wrote a simple class Matrix3X3; this class includes static feilds “Zero” and “Ones” for Zero-Matrix and Ones-Matrix appropriately.
Let’s take a brief look of the implementation:

class Matrix3X3
{
        public static Matrix3X3 Zero = new Matrix3X3(0);
        public static Matrix3X3 Ones = new Matrix3X3(1);

        // class members ...

        public Matrix3X3(double value)
        {
                // Fill the whole matrix with same value.
                // ...
        }

        // class methods ...
}

Read more…

Categories: .Net Tags: , , ,

Simple singleton pattern with inheritance in C#.NET (part 2)

March 13th, 2011 1 comment

In my previous post about singleton inheritance, I’ve presented a simple singleton design pattern implementation in C#.NET, and a more advance implementation method, which allows to inherit from base singleton class. In the curent post, I will show several ways, to make the singleton thread-safe.
While saying “thread-safe singleton”, one usually means the singleton creation; another functions/properties are handled regular way to be threadsafe. Singleton creation must take place only once.
Classic pattern, providing a solution for this issue, is double-checked locking. Why 2 checks are needed? Because, after the first time creation, the lock is redundant. So we just prevent it by additional check. Using this pattern, singleton creation looks like this:

Read more…

Categories: .Net, Design Tags: , , ,

Simple singleton pattern with inheritance in C#.NET (part 1)

March 12th, 2011 No comments

Singleton is very simple and widely used Design Pattern. This pattern is described in a lot of blogs, articles and books (e.g. GoF = Gang of Four). According to GoF,  singleton’s job is to “Ensure a class has one instance, and provide a global point of access to it”. In a general case, singleton can be extended, in order to ensure a class has n instances, while 1 ≤ n < ∞.

How can one build a singleton?

Two steps to make some class to be a singleton:
1) Forbid straightforword creation => let constructor be private (or protected in some cases).
2) Provide general access point => static property (or function), which allows an access to object.

Let’s see the code:

Read more…

Categories: .Net, Design Tags: , , ,

Effective iteration over STL container.

March 6th, 2011 No comments

Today I had a chance to recall a little bit, what is STL and how should it be used effectively.
Let’s take a brief look of the next code in C++, which makes iteration over STL’s map:

std::map<int, std::string> 		myMap;
std::map<int, std::string>::iterator	myIter;

for (myIter = myMap.begin(); myIter != myMap.end(); myIter++) //bad performance
{
	std::cout << *myIter << std::endl;
}

Can you see the performance problem? Actually there are 2:

1) The loop checks the stop condition every iteration, i.e. compares iterator to the value returned by “myMap.end()”.
The “end” function is called in every iteration, even though the return value doesn’t change during the loop.

2) Using postfix operator++ is more expensive then prefix operator, because postfix operator must make a local copy of the object. Object is created by the copy constructor, and if the object is “heavy” enough, this additional action could harm the performance. Lets compare implementations of both operators:

iterator& operator++()
{
	_Ptr = _Acc::_Next(_Ptr);
	return (*this);
}

iterator operator++(int)
{
	iterator _Tmp = *this; // Calling the copy constructor
	++*this;
	return (_Tmp);
}

Hence, we should do very easy changes, and the improved code looks like this:

std::map<int, std::string> 		myMap;
std::map<int, std::string>::iterator	myIter, endIter = myMap.end() ;

for (myIter = myMap.begin(); myIter != endIter; ++myIter) //good  performance
{
	std::cout << *myIter << std::endl;
}

Remark:
Many good advices about effective using STL library are described in a book “Effective STL” by Scott Meyers.

Categories: C++ Tags: ,

Janus GridEx customizable cell content

March 5th, 2011 No comments

Recently i had accomplished interesting task, which include to add time duration data to one of the existing Grids in our Winform desktop application. We are working with 3rdParty controls Janus (Janus.Windowa.GridEx).

Unfortunately not all our controls are WPF, so we still need to “struggle” WinForms to make any special changes in UI.

The problem was that our product manager wanted to make usage of the same visual column for different types of data – such as >int and System.TimeSpan. As you can see they have completely different presentation.
00:00:03.45334
After some thinking we have decided to add additional column of Type Syste.TimeSpan and make this column hidden to the end user.

MyColumns = m_gridControl.RootTable.Columns;
MyColumns["durationColumnName"].Visible = false;

Read more…

Categories: .Net, C# Tags: , ,

Bitmap construction from raw buffer in C#.NET

March 4th, 2011 No comments

Recently, I needed to get an image’s buffer from the network, and to store it in a file system.
If needed to work with image files, one can use a C#.NET “Bitmap” class, existing within “System.Drawing” namespace.

This class encapsulates a GDI+ bitmap and supports the next formats: BMP, PNG, JPG, GIF, TIFF and EXIF.
And it has a good API. It is very friendly class. After the object exists, saving appropriate file is a straight forward action:


Bitmap bitmap = ...
bitmap.Save("TargetImageFileName.bmp"); //format selection is possible

But, how the “Bitmap” object should be created from given buffer in memory?
Quick search in MSDN supplied the next solution:


Byte[] buffer = Proxy.GetImageBuffer();
ImageConverter converter = new ImageConverter();
Image image = (Image) converter.ConvertFrom(buffer);
Bitmap bitmap = new Bitmap(image);

// Work with the bitmap ...

This could be a great solution, but not in given case.
The ”ConvertFrom” function of  ”ImageConverter” is looking for image’s header. The buffer contains a pure raw data, and hence is decoded in a wrong way. As a result of memory corruption, ”ArgumentException” is thrown.

So, what is good solution?

In order to initialize “Bitmap” object from a raw data buffer, first we must supply image’s metadata. We must “teach” the Bitmap object about image, it is going to contain.


public Bitmap CreateBitmapFromRawDataBuffer(byte[] buffer)
{
        // Prepare required image's metadata.
        Size imageSize = new Size(300, 200); // Known size.
        PixelFormat imagePixelFormat = PixelFormat.Format16bppGrayScale; // Known type.

        // Set bitmap known image's metadata.
        Bitmap bitmap = new Bitmap(imageSize.Width, imageSize.Height, imagePixelFormat);

        // Prepare working rectangle.
        Rectangle wholeBitmap = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

        // Lock all bitmap's pixels.
        BitmapData bitmapData = bitmap.LockBits(wholeBitmap, ImageLockMode.WriteOnly, imagePixelFormat);

        // Copy the buffer into bitmapData.
        Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);

        // Unlock  all bitmap's pixels.
        bitmap.UnlockBits(bitmapData);

        return bitmap;
}

That’s all. It works. Use carefully.

Categories: .Net Tags: ,