Archive

Archive for the ‘.Net’ 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:

When and how to use GC.KeepAlive in .Net

August 27th, 2011 1 comment

Let’s look on the following C# code example (ignore the correctness of the code and its logic)

    /// <summary>
    /// Indicates any service Logger for example
    /// </summary>
    class MyService
    {
        public MyService(string fileName)
        {
            //Do some initializations
        }

        public static void DoSomething()
        {
            //some calculations, or logs creation
        }
    }
    //*************************************************
    /// <summary>
    /// Usage example class 
    /// </summary>
    class MyLogic
    {
        public void Foo()
        {
            //cals static method of the initialized service
            MyService.DoSomething();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Create our service 
            MyService myService = new MyService("temp.txt");
            //Wait here for user
            Console.ReadLine();
        }
    }

Read more…

Categories: .Net, GC 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: ,

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

How to kill applications and Processes on remote machine

March 28th, 2011 No comments

How to kill applications/Processes on remote machine
 
One of the requirements was to reboot processes that are running on Server machine, were number of possibilities how to implement such task and not to break our distributed design. Finally we decide to run simple script that kills desired processes.

After quick search on the web I have decided to use taskkill utility which supplied desired functionality.

As alternative tool we have tried pskillsysinternal development command, works nice but I failed to set force kill, so there were cases when the pskill operation didn’t succeeded.

Pskill usage example:

pskill \\serverName -u administrator -p password Process1.exe

 

taskkill usage example:

taskkill /s serverName /f /u administrator /p system /t /im Process1.exe

 
Read more…

Categories: .Net, General Tags:

Documenting your code and Using Visual Studio IntelliSense tool

March 28th, 2011 No comments

One of useful tools in any IDE that you developing at its ability to document your code with nice XML format. I will focus on VS2010 this is main tool that we are using at our development process.

There are some external tools that help and trying to automate documentation process, tools like GhostDoc. Of cause those tools can’t replace the programmer notes.

So when our code documented with Xml Documentation /// IDE ItelliSense uses this information in order to display this info about Class, method, Property and Data Member see following print screen from one of the System diagnostic classes.

 
Read more…

Categories: .Net Tags:

Draw Progress Bar in Janus GridEx cell content

March 27th, 2011 No comments

Draw Progress Bar in Janus GridEx cell content

As following my previous post [post] how to create customizable cell content, I decided to post progressbar sample CSharp code.
See full implementation of Progress bar cell in Janus GridEx control.

C# Usage example

 

private readonly ProgressBarCellRenderer m_progressBarCellRenderer = new ProgressBarCellRenderer

                {BorderPen = new Pen(Color.LightGray)};

 

Perform drawing on each OnDrawGridArea method callback.

void OnDrawGridArea(object sender, DrawGridAreaEventArgs args)

{

     if (e.Column.Key == MyColumn)

     {

         GridEXCellCollection currentRowCells = e.Row.Cells;

 

         double total = GetValue();

 

         if (total == 0)

            return;

 

         m_progressBarCellRenderer.DrawProgressBar(

                                                args

                                              , total

                                              , "custom text");

      }

}

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

.Net Framework 4.0 and VS2010 – things that I don’t like

March 11th, 2011 No comments

There are many great improoves (e.g. TPL – see my post about Task Parallel Library)

Still, there are some disadvantages, I would like to list:

1. Help interface is uncomfortable, there is no possibility to search by Index like it was working in “chm” in VS2003-8

Update: after installing Visual Studio 2010 Service Pack 1 (SP1) – help user interface become more user friendly and handy.
2. CLR debugger doesn’t working any more (SDK v2.0) – such behavior is very crucial for our clients and deployment process.

  • Native code debugger cause my VS2010 to stuck all the time.

3. GAC changes – why v2.0 and v4.0 assemblies are located in different locations?
a. Why simple copy/paste operation doesn’t working like its work today with c:\windows\assemblies directory.
b. Why we need to manage two different GAC’s?
Detailed info regarding GAC can be found here: http://msdn.microsoft.com/en-us/magazine/dd727509.aspx

Read more…

Categories: .Net Tags: ,

NHibernate configuration, set database connection credentials

March 11th, 2011 No comments

NHibernate configuration, set database connection credentials

Our team started to use NHibernate ORM, it used in part of the components of our Application (Mostly stand alone services).
There are interesting issues bloomed up:
How to use the same DB credentials while you are using NHibernate and standard ADO approach to retrieve, save and update your data. We have plenty Legacy code that cannot move to use NHibernate configuration file. Our main application used standard sql connection string from App.Config file, of cause we doesn’t want to maintain two configuration files.

“hibernate.cfg.xml” file contains basic configuration settings, used by NHibernate; for more detail see … [web site] User Id=;Password=;Data Source=;Pooling=false

Read more…

Categories: .Net, NHibernate Tags: ,