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:

9 Things That Motivate Employees More Than Money

January 26th, 2012 No comments

 

The ability to motivate employees is one of the greatest skills an entrepreneur can possess. Two years ago, I realized I didn’t have this skill. So I hired a CEO who did.

Josh had 12 years in the corporate world, which included running a major department at Comcast. I knew he was seasoned, but I was still skeptical at first. We were going through some tough growing pains, and I thought that a lack of cash would make it extremely difficult to improve the company morale.

I was wrong.

With his help and the help of the great team leaders he put in place, Josh not only rebuilt the culture, but also created a passionate, hard-working team that is as committed to growing and improving the company as I am.

Here are nine things I learned from him:

  1. Be generous with praise. Everyone wants it and it’s one of the easiest things to give. Plus, praise from the CEO goes a lot farther than you might think. Praise every improvement that you see your team members make. Once you’re comfortable delivering praise one-on-one to an employee, try praising them in front of others.
  2. Get rid of the managers. Projects without project managers? That doesn’t seem right! Try it. Removing the project lead or supervisor and empowering your staff to work together as a team rather then everyone reporting to one individual can do wonders. Think about it. What’s worse than letting your supervisor down? Letting your team down! Allowing people to work together as a team, on an equal level with their co-workers, will often produce better projects faster. People will come in early, stay late, and devote more of their energy to solving problems.
  3. Make your ideas theirs. People hate being told what to do. Instead of telling people what you want done; ask them in a way that will make them feel like they came up with the idea. “I’d like you to do it this way” turns into “Do you think it’s a good idea if we do it this way?”
  4. Never criticize or correct. No one, and I mean no one, wants to hear that they did something wrong. If you’re looking for a de-motivator, this is it. Try an indirect approach to get people to improve, learn from their mistakes, and fix them. Ask, “Was that the best way to approach the problem? Why not? Have any ideas on what you could have done differently?” Then you’re having a conversation and talking through solutions, not pointing a finger.
  5. Make everyone a leader. Highlight your top performers’ strengths and let them know that because of their excellence, you want them to be the example for others. You’ll set the bar high and they’ll be motivated to live up to their reputation as a leader.
  6. Take an employee to lunch once a week. Surprise them. Don’t make an announcement that you’re establishing a new policy. Literally walk up to one of your employees, and invite them to lunch with you. It’s an easy way to remind them that you notice and appreciate their work.
  7. Give recognition and small rewards. These two things come in many forms: Give a shout out to someone in a company meeting for what she has accomplished. Run contests or internal games and keep track of the results on a whiteboard that everyone can see. Tangible awards that don’t break the bank can work too. Try things like dinner, trophies, spa services, and plaques.
  8. Throw company parties. Doing things as a group can go a long way. Have a company picnic. Organize birthday parties. Hold a happy hour. Don’t just wait until the holidays to do a company activity; organize events throughout the year to remind your staff that you’re all in it together.

Share the rewards—and the pain. When your company does well, celebrate. This is the best time to let everyone know that you’re thankful for their hard work. Go out of your way to show how far you will go when people help your company succeed. If there are disappointments, share those too. If you expect high performance, your team deserves to know where the company stands. Be honest and transparent.

(Taken from Ilya Pozin )

Categories: General Tags:

When and how to use GC.KeepAlive in .Net

August 27th, 2011 No comments

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

Useful Eclipse Shortcut Keys

June 28th, 2011 Comments off

A friend of mine is a newbie to eclipse, he asked me for a list of shortcut keys in eclipse for quick and productive development process. It took me a while but I have found a document that I have prepared for myself a few years ago. I am posting it here, it might be useful to somebody else too. Shortcut keys make life that little bit quicker! They aid you in working faster and become very handy when programming in Eclipse. For a full list of shortcuts, in Eclipse 3.1 and above you can press Ctrl+Shift+L for a handy popup. CTRL + D – Delete row No more need to grab the mouse and select the line. Ctrl+Shift+T – Open Java Type Start typing the name and the list gets smaller. Try typing the capital letters of the class only (e.g. type “CME” to find “ConcurrentModificationException”) Ctrl+Shift+R -? Find Resource Use this to look for XML files, text files, or files of any other type. which are in your workspace. Ctrl+E – Open Editor Drop-Down Presents a popup window listing currently opened files. Start typing to limit the list or simply use the down arrow key. Read more…

Categories: Java Tags: , ,

How to mark a binary file as Debug/Release in C++

June 4th, 2011 1 comment

As all probably know, while developing a project, we compile it using Debug mode, whereas compiling for deployment purpose is performed in Release mode. Still, sometimes we need to combine Debug and Release binaries. For instance one might want to compile in Debug, but to use 3rd party’s binaries in Release. In this case, we’d like to have some simple way to distinguish binary files according to thier compiling type.

In some projects this goal is achieved by adding a character “d” in the end of Debug binary file. E.g. file named “Engine.dll” is called “Engined.dll” in Debug version. It works, but it is no plesant, because the project must have two different structures: one for Debug and another for Release.

Read more…

Categories: C++, General 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: ,

How to extend Windows Phone 7 emulator’s functionality (unlock)

May 10th, 2011 2 comments

While programming to Windows Phone 7 (or another mobile device), very important instrument is the device’s emulator, integrated into development environment. Visual Studio 2010 supplies an emulator; while compiling & running our code (using either Silverlight or XNA technology), the emulator is running and creating an environment for our application. By the way, full Visual Studio 2010 is not must for development on WinPhone7; one can use a free environment “Microsoft Visual Studio 2010 Express” instead.

Read more…

Categories: Windows Phone 7 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: , , , , ,

Batch Count Number of Lines in Text File

May 6th, 2011 No comments

Recently I came across the need to count the number of lines in a text file, so I decided to explore Command Shell options.

My first thought was to use Find command, but I was not able to find a new line character, so I decided to count lines, which are not containing the certain string:

find /c /n /v "***///" CreateLogTable.sql

This approach works not bad, but it opens a breach in cases when the string, which is used as a search token, can be actually a part of the file.

After some more research I found out that there is another batch command, called FindStr. This command supports regular expressions and allows us to count the number of lines without any exceptions:

findstr /R /N "^" CreateLogTable.sql | find /c ":"
Categories: General 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: , , ,

EJB3 Asynchronous messaging with WebSphere7.0

April 2nd, 2011 9 comments

In enterprise applications when you have to delivery a message and even if the destination is down and you do not want to wait for a response in real time we better use JMS to work with asynchronous messaging. A Message Driven Bean is a stateless enterprise bean. A container typically manages a pool of such objects. As messages arrive, the container will take an MDB from the pool and have it process a message. If the processing succeeds, the message is removed from the queue; otherwise it remains on the queue. Basically, we can create a JMS component using the annotation @ MessageDriven and also implementing the interface java.jms.MessageListener. In this article, we will create a simple example and then deploy it/test it on Websphere 7.0 with EJB3 Feature Pack.

Setting up the JMS Provider and the Destination

We will use WebSphere Application Server 7.0 JMS Provider. In my previous Asynchronous messaging using JMS on WebSphere 7.0 article I have demonstrated how to create an Integration Bus, JMS Provider, Connection Factory, Destination and Activation specifications in WebSphere 7.0 so I will assume that we are familiar with that. Read more…

Categories: Java Tags: , ,

3 simple ways to create singleton pattern in C++

March 31st, 2011 5 comments

In my previous posts (part 1 and part 2), I’ve presented singleton design pattern implementation in C# .NET. In order to complete the subject, I would like to present singleton pattern implementation in old good native C++.

1) Basic singleton: static function “GetInstance” provides the access point; constructor, copy constructor and operator= are hidden from the user. The singleton is allocated upon first demand (lazy initialization). Null pointer is used to constrol first access, hence must be initialized in a C++ way – out of the class (as a static member).

class CKeyboard
{
public:
	static CKeyboard* GetInstance() 
	{
		if (!m_pInstance)
			m_pInstance = new CKeyboard();
		return m_pInstance;
	}

private:
	CKeyboard() {}
	CKeyboard(const CKeyboard&);
	CKeyboard& operator=(const CKeyboard&); 

private:
	static CKeyboard *m_pInstance;
};

CKeyboard* CKeyboard::m_pInstance = NULL;

Read more…

Categories: C++, Design Tags: , ,