Archive

Archive for the ‘C#’ Category

The possible problem with optional parameters in .Net 4.0

May 2nd, 2012 No comments

Few things regarding code analysis
While running code analysis with all rules turned on i’ve hit awarning on the following line:

Public abstract void Foo(IEnumerable<T> values, bool state= true);

CA1026 : Microsoft.Design : Replace method ‘Foo(IEnumerable, bool)’ with an overload that supplies all default arguments.
MSDN link – http://msdn.microsoft.com/en-us/library/ms182135.aspx
This was very confusing. Is Microsoft suggesting to stop using the cool C#4 feature of optional parameters (bool state= true)?

After digging around we understand why. There’s an implication on using optional parameters. They are compiled as constants at the calling side.
So if you use optional parameters on public API and later want to change the default, that won’t work for clients who already use your API without recompiling.

Bottom line:
Be careful when you use optional parameters. Better not use them on public API.

———————–
Thanks to Ron who bring this example.

Categories: .Net, C# Tags:

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…

Creating event in Abstract class and Raising this event from derived class

May 28th, 2011 1 comment

I won’t explain here hat is Abstract class and why we would like to use it in our Object orientated programming. But I want to discuss some issues that come when we are using events in the base Abstract class.

When we want to create event in abstract class which intended to be raised from derived classes, we discover right away that such code won’t compile.
See following code example where created simple abstract class which have public event. Simple derived class that tries to fire this event from DoMyLogic() method.

public abstract class AbstractSample
    {
        public event EventHandler AbstractEvent;

        public abstract bool IsActionComplete();

        public void Foo()
        {
            //some code 
        }
    }

    public class MyClass : AbstractSample
    {

        public override bool IsActionComplete()
        {
            //implementation
            return true;
        }

        void DoMyLogic()
        {
            //Fire event that was declared in base class
            base.AbstractEvent(this, EventArgs.Empty);//compile error

        }
    }

Read more…

Categories: .Net, C# Tags:

Disassembly for .Net assemblies tool is here – dotPeek(decompile) from JetBrains

May 14th, 2011 No comments

dotPeek from JetBrains (makers of Resharper and many other good developers tools).

As you probably noticed that Reflector (which great tool and useful) not free any more. Here theirs announcement

I in my every day work need such tool that will provide high-quality decompiling capabilities for .Net assemblies.

dotPeek Logo

After some searches in the Internet I have found very promising tool that gives all needed functionality. Tool called dotPeek.

 

Tool is standalone exe file, but it gives look and feel like Visual studio with nice navigation and search features. Hopefuly they will integrate it with Resharper or as additional add-on for VS2010.
Read more…

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

Deep copy against shallow copy in .Net C# dealing with mutable Structs

May 13th, 2011 No comments

In this post I won’t explain the difference between deep copy and shallow copy, what is reference type and Value type – there are plenty stuff about this in the web. I want to share with you some problematic behavior/bug that we found out in application as a result of luck of understanding in current materials.
This issue can be very tricky and hard to debug in runtime, so we need to be wide-awake.

For example you have very simple struct like follows (holds array of points which describes polygon):

public struct MyPolygon
{
	Point[] points;
}

Read more…

Categories: .Net, C# Tags: ,

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: ,

Getting OutOfMemory exception in .Net process, possible solutions.

May 7th, 2011 No comments

Getting OutOfMemoryexception in .Net process, possible solutions.

I want to share with you very interesting and complicated problem that we managed to overcome. I will describe all our resolution procedure step by step. Hope it will help others as it helped us, in any case I have learned a lot.

 

We have encountered a serious problem such as OutOfMemoryException

In my application – WinForm application i have managed code and un-managed (C/C++) 3’rd party code that perform many un-managed memory allocations at beginning of the process load and during runtime.

As we started to suffer from memory problems, we decided to enlarge address space that our process can use from 2 GB to 3 GB. This operation was done by using /LARGEADDRESSAWARE flag for our process and OS configured with /3GB. Unfortunately enlarge address space to our application seems to be good solution, but it didn’t help in our case.

So we started debugging and deeply investigate our Outofmemory problems. As usual main tool that we have used was WinDbg. Interesting things were discovered by using WinDbg and using following command “!address –summary” which shows us that we have not reached 3GB memory limit. Although that we have free memory, the memory wasn’t continuous so the CLR or native code failed to allocate memory. The problem appear to be defragmentation problem.

Read more…

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

NHibernate working with Unsigned Value types like uint, sbyte, short etc.

April 30th, 2011 No comments

NHibernate working with Unsigned Value types like uint, sbyte, short etc.

We want to share one of the first experiences during developing with NHibernate. We immediately bumped in to serious problem with supporting unsigned Value types like

uint, ulong, sbyte

etc .  Natively those types are not fully supported by NHibernate.

You probably will ask “why we need those types?” Data that comes in some special formatting binary way form streaming where packet size is very important, so many optimizations are used. Our task was deserialize those compressed messages and at the end all data have to be stored in database tables. Additional that affected on our solution was demand to serialize data back to binary format from database tables.

The simplest and fast solutions were to duplicate properties int and uint but this was very ugly and not developer friendly proposal (from our point of view of cause). Additionally we have had plenty of such unsigned fields.

private uint m_value;

 

private int VlaueInt

{

get{ return (int)m_value;}

set { m_value = (uint)value; }

}

 

 

public uint ValueUint

{

get { return m_value; }

set { m_value = value; }

}

The second option were implementation of IUserType which means I have to create type that NHibernate can work with, but this solution wasn’t an option for us as well, because we didn’t wanted that our users that are going to use those Types will be aware of NHibernate existence. What will happen if we will choose to move all our data model to Entity framework for example.

Read more…

Categories: .Net, C#, NHibernate 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: ,

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: , ,