Καλώς ορίσατε στο dotNETZone.gr - Σύνδεση | Εγγραφή | Βοήθεια

C# and .NET Tips and Tricks

Quests in programming in .NET

Παρουσίαση με Ετικέτες

Όλες οι Ετικέτε... » .NET   (RSS)
Slow Performance. Is it the Entity Framework or you?

A lot of times, I get claims and concerns from colleagues and partners that EF is slow and it cannot compare to writing your own SQL queries for the database directly. In this post, we will try to clarify to what extent the above statement is true.

Suppose that you have the following simple schema in your database:

Let's examine some EF queries and approaches that affect performance:

Querying the data in the Locations table

Suppose you want to get some data from the Locations table. You may use the following:

using (LocationsContext ctx = new LocationsContext())
{
	var Locations = ctx.Locations.ToList();
}

Several runs of the above query yield approximately 3600ms to retrieve 80000 records. But wait a minute. Since we want only to display those data and not process them we do not need the proxies created for monitoring those objects by EF so we can effectively disable them as follows:

using (LocationsContext ctx = new LocationsContext())
{
	ctx.Configuration.ProxyCreationEnabled = false;
	var Locations = ctx.Locations.ToList();
}

Now the new time for 80000 records is approximately 3300ms that is 300ms faster than the previous case. But wait a minute again. We probably do not need all the fields from the table, just the ones we want to display. So we switch the above to a projection, by selecting only the properties we need:

using (LocationsContext ctx = new LocationsContext())
{
	ctx.Configuration.ProxyCreationEnabled = false;
	var Locations = ctx.Locations.select(x=>new{...}).ToList();
}

Now the new time for 80000 records is approximately 1300ms that is 2000ms faster than the previous case. If this is still to slow for us, now is the time to create a stored procedure in the SQL Database and see the result.

using (LocationsContext ctx = new LocationsContext())
{
	ctx.Configuration.ProxyCreationEnabled = false;
	var Locations = ctx.spDemo().ToList();
}

Now the new time for 80000 records is approximately 700ms that is 600ms faster than the previous case.

The whole idea in the example above is about "iterative refinement". If we would monitor the process with steps it would be as follows:

  • First you prototype with just plain LINQ. It is ultra fast, you do not need to change the database in any way and you get the results you want
  • Then you disable the proxies to have some performance increase
  • As the specs settle and you know which fields you need you create the projection
  • If the result is still to slow for you then you may end up creating a stored procedure in the database and using it

In all of the above the "key point" is that the change is localized in the query itself and does not affect any code surrounding it. This means that is can be done in any part of the development process.

Posted: Τρίτη, 17 Ιουνίου 2014 11:02 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία: ,
Visual Studio 2012 tips that will improve your coding speed - Web developers

Disable "Start Page"

There is no reason to wait every time for the "Start Page" to load its contents from the internet and display. So the best thing to do is disable it using the checkbox at the left, bottom of it

Switch between/Execute programs on taskbar without the mouse

You can use the Win + Number to switch between the open programs in the taskbar. If the program is not running it will execute, otherwise it will get the focus. Win + Shift + Number will open a new instance of the progam on the taskbar. Those are extremely useful especially when you are doing web development and want to be able to switch between browser windows and VS. Finaly, the most important Win + Ctrl + Shift + Number will run the program as administrator.

Associate "Open Containing folder to a shortcut

Go to "Quick Launch" and start typing "Keyboard...". Select "Environment -> Keyboard". In the "Show command containing" write "OpenContaining" and select the match at the list below. Assign the shortcut key (eg press "Ctrl + Shift + O" and then assign).

Install useful extensions

For each one of the following go to VS2012 -> Tools -> Extensions and Updates and write their name in the "Search box".

  • Indent Guides: Provide lines to show you indentation and where blocks of code open/close.
  • Web Essentials 2012: Toolbox that provides a lot of useful features for web developemnt such as CSS3 editor enhancements and Typescript support. For more info see here.
  • Mindscape Web Workbench: Support for new web frameworks such as SASS,LESS and Coffescript . For more info see here.
  • Hide Main Menu: Save those extra pixels by hiding the menu. It can be displayed by pressing the "Alt" key.
  • Color Theme Editor: Change the VS2012 color theme.
  • TroutZoom: Automatically applies the zoom level you specify to one window to all.
  • Zen Coding: Super fast HTML writing (similar to the popular package for Sublime) more info.

Stop going up and down in the same file

You are writing code in a big file and you find yourself going up and down within the file to see some definitions and keep coding. You can select the file you work and then click "Window" -> "Split" and you have two windows open with the same file so that you can have each one in a different position within the file. When you are donw "Window" -> "Remove Split"

Useful shortcuts

  • Ctrl+Alt+L Focus to the solution explorer.
  • Ctrl + -/ Ctrl + Shift + - Backward/Forward to the places I have been with my cursor in a file with code
  • Ctrl + , Very intelligent search within the solution (it also searches camelcase like for MainWindowViewModel you can search from MWVM
  • Ctrl + >/ Ctrl + Shift + < Zoom in and out
  • Ctrl + Alt + Space Switch between suggestion and completion mode in intellisense
  • Ctrl + ] + s Selects the active file in the "Solution Explorer"

New solution explorer view

In big solutions sometimes you need to constantly navigate between two different locations in the solution explorer. Well not any more. Right click on the folder containing some code files in solution explorer and select "New Solution Explorer View". You will get a second view with only those files.

For more information check out this very good presenation from Teched 2013 Europe.

Posted: Δευτέρα, 8 Ιουλίου 2013 7:40 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
A simple way to detect memory leaks in C# and how to create one with events :)

In this post we will see a simple code fragment that can be used to detect memory leaks (more specific objects that are not cleaned by the garbage collector) and we will do it in the context of an interesting memory leak that can be created when using event delegates.

The memory leak with event delegates

Suppose you have an application in WPF with a single window that presents some money values in a specific currency (say EURO). At a specific instance you may have more than one such windows open.

Now a requirement comes that defines that you need to be able to change the currency (say from euro to dollar) and have this change be reflected immediately to any currently open window displaying the money value. One easy way to tackle this is shown in the following figure:

The "settings" object is static with a static property "Currency" with the current currency and an event called "OnCurrencyChanged" that is fired when the currency is changed. The "Window" class ("window1" nad "window2" objects) defines a method "currencyChanged". When a window is opened it attaches the "currencyChanged" method to the "OnCurrencyChanged" event. This method will be called whenever the event is fired and will be responsible for converting the money values in the windows. Let's see some code for that. First the "settings" class:

public static class settings
{
    public static event Action OnCurrencyChanged;

    public static void ChangeCurrency(string newCurrency)
    {
        //...
        if (OnCurrencyChanged != null)
            OnCurrencyChanged(newCurrency);
    }

}				

The code for the window with the money values has the "currencyChanged" method:

public partial class MoneyWindow : Window
{
    public MoneyWindow()
    {
        InitializeComponent();
    }

    public void currencyChanged(string newCurrency)
    {
        // Change the view to reflect the change here
    }
}				

The initializer of the window with the money values will be as follows:

MoneyWindow dlg = new MoneyWindow();
dlg.Show();
settings.OnCurrencyChanged += dlg.currencyChanged;	

Which in other words defines that when the window is created it will be listening to the "OnCurrencyChanged" event.

And you have your memory leak right there! Even if you close the window in some time, the event you have attached still keeps it "connected" to your application and therefore it will never be garbage collected. Just for a reminder, the objects are destroyed by the garbage collector when there are no other objects pointing to them. But in this case you have an "implicit" connection with the event. If you execute the demo application (here) you will see that opening and closing the window keeps consuming more and more memory which never gets freed (it helps to have the "Task Manager" open to test that). The solution is simple and it just requires you to unsubscribe from the event with "-=" when the window is closed. But say you are in a large application you are not sure whether an object gets garbage collected or not and wanna check that then what can you do?.

Detecting memory leaks

Or better checking whether an object will get garbage collected. Implement in your project a class like the following:

public static class MemoryLeak
{
    public static WeakReference Reference { get; private set; }

    public static void CheckObject(object ObjToCheck)
    {
        MemoryLeak.Reference = new WeakReference(ObjToCheck);
    }

    public static void IsItDead()
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        if (MemoryLeak.Reference.IsAlive)
            Debug.WriteLine("Still here");
        else
            Debug.WriteLine("I 'm dead");
    }
}				

The code creates a weak reference to an object. The "weak reference" means that while it keeps a reference to the object this does not prevent the garbage collector from cleaning it (in other words this reference does not count in terms of collecting the object when not referenced). So we create the reference and then by calling "IsItDead" we just force the GC to collect any unneeded objects. If the object in question still persists then we have a memory leak.

For our example above, when we create the window we create a weak reference to the window object. Then we create a button that calls the "IsItDead" method. If we do not have a memory leak then the method should return "Still here" while the window is open and "I 'm dead" a while after the window is closed.

You can download the demo project here

Posted: Κυριακή, 26 Μαΐου 2013 5:31 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία: ,
Inversion of Control (IoC) and Dependency Injection (DI) and why they are important.

In this blog post, we are going to see how and when  Dependency Injection (DI) and Inversion of Control(IoC) can be applied for writing nice and maintainable code. Note that although there are plenty of tools out there that give you the ability to apply DI out of the box, in this post we are going to implement such a tool on our own gaining valuable insight on the workings of IoC and DI.

 

Suppose that in your code you have two classes (A,B) like the following:

public class A
{
public A(){}
public void Method1(){ }
public void Method2() { }
}

public class B
{
private A _a;
public B()
{
_a = new A();
_a.Method1();
_a.Method2();
}
}

 

That is, we have a class A that has two methods and class B that has a field of type A which is initialized and used in the constructor. Whenever we have such situation we say that “B depends on A” since B needs to create and use A directly. Also, B “has the control” of the creation of A. We will show that dependency graphically with an arrow as follows:

 

image

 

If you implement a new class A1 with the same functionality as A and want to use A1 in B, then you would need to change in B the type of field _a to A1 and its instantiation and recompile the project. If you use A only in one class in your program and your program is a single .exe file (no .dlls) then the merits of IoC cannot be shown and in my opinion you may introduce an unnecessary overhead if you apply it. But let’s see how this changes if the previous condition does not apply.

 

Suppose now that your app is a single .exe file but you have more than one class using A, say B,C,D. Each one of those classes (B,C,D) have a field of type A and use it in their code (B,C,D depend on A).

 

image

 

Switching now from A to A1 requires you to go to “each and every one” of the classes that use A (in a big project this also means that you have to remember which classes are those-in our example B,C,D) and make the appropriate changes. As you must have realized, such process, is error prone and takes time. This problem is created because B,C,D depend on A and B,C,D have the control of creating instances of A.

 

When you use Inversion of Control in the previous situation (changing A to A1) you only need to change a single line of code. So lets see how this works:

 

  1. We create an interface (IA) that has the methods of A. A and A1 should implement this interface.
  2. All classes that use (depend on) A now should use (depend on) IA.
  3. We either need to pass an instance that implement IA in the constructor of those classes or we need to implement a third class Creator that creates objects that implement IA and B,C,D should use this class to get instances that implement IA.

 

If we pass instances that implement IA in the constructors the code looks like the following:

interface IA {
void Method1();
}

public class A:IA {
public A(){}
public void Method1(){ }
}

public class B {
private IA _a;
public B(IA AImplementation) {
_a = AImplementation;
_a.Method1();
}
}

 

In the initial implementation “B had the control of creating A and B depended on A”. In this implementation “the user of B has the control of creating A and B does not depend on A but on IA”. This is Inversion of Control. Now if C,D also follow the same implementation changing from A to A1 does not affect them at all as long as you pass to their constructors and object of type A1 instead of an object of type A. Therefore the previous issue of having to change B,C,D to switch from A to A1 has been solved by using Ioc.

 

Of course, a lot of you would argue that you still have to change the instantiation of A to A1 to each and every one of the classes that create B,C,D to pass the correct parameter in the constructor. For this reason you can use a creator class (a factory) that returns objects that implement IA and use this to create your classes.

 

If we use a creator class and not pass the IA object in the constructor, the code looks like the following:

interface IA {
void Method1();
}

public class A:IA {
public A(){}
public void Method1(){ }
}

public static class Creator {
public A GetIA() {return new A();}
}

public class B {
private IA _a;
public B() {
_a = Creator.GetIA();
_a.Method1();
}
}

See that now _a in B is of type IA and B asks the Creator to get an instance of A. A implements IA. C,D classes would also use IA and the Creator to get an instance that implements A. A1 would need to implement IA also and switching from A to A1 would only require changing the method GetIA in the creator to return a new instance of A1 instead of A. This “Creator” class is usually called a “factory”.

 

Inversion of Control has enabled such a change to be fast, efficient and error free. You can change from A to A1 by changing one line and you can use a new A2 easily by making it implement IA. The drawback is that the amount of code we have written has tripled.

 

Inversion of Control has also another very important benefit in the case where your project uses a .dll. Imagine that you have your ASP.NET MVC project using a class library project which is your business layer. Then, your final deployment consists of the web app and the library dll. If your class A is part of your library and B is part of your web app and you do not use IoC, each time you change from A to A1 you need to recompile the whole project. On the contrary if you use IoC and a factory, the interface IA resides in the library the creator class (factory) resides also in the library and your B class in the web app uses IA. Therefore changing from A to A1 requires you to recompile only the library (.dll) and not all the project facilitating easy and fast deployment in changes.

 

Now wouldn’t  it be nice if we didn’t have to recompile even the library when changing from A to A1? Just have a way to do that by just changing a setting? Can we inject that dependency (A,A1) somehow without having to recompile? This is what we call “Dependency Injection”. How would we implement this without the help of any other libraries?

 

We could keep in a file the class type that needs to be instantiated for the interface and have our “Creator” class (factory) read this file, find out the name of the class that needs to be instantiated and create it by reflection. This would inject the required class in the dependency and thus the term “Dependency Injection”. This means that with dependency injection you do not have to recompile your app when switching from A to A1. The implementation of the creator class for IA should follow the steps below (full code in the project you can download at the end of the post):

 

  1. Open the file with the pairs (interface to implementation).
  2. Find the class name to instantiate
  3. Use reflection to instantiate class from the assembly
  4. Return new object implementing the interface

 

And the file that holds the pair can contain entries as follows:

 

DIandIOCDemo.IA=DIandIOCDemo.A

 

So when should you use Inversion of Control and Dependency Injection?

 

The general rule of thumb is to use it when you have many classes using the methods of a single one and this one may have more than one different “versions”. For example, you are creating your DB Access repositories and you also need to have some fake ones for your tests. Or you have to versions of a class one with lots of debugging info and one without and want to switch between the two at a deployed application.

 

Note that there are fully blown libraries that handle dependency injection such as spring.netthat you should also check out.

 

The project can be downloaded here

.

Shout it

Posted: Πέμπτη, 9 Ιουνίου 2011 7:45 μμ από iwannis | 1 σχόλια
Δημοσίευση στην κατηγορία: ,
Interception and Interceptors in C# (Aspect oriented programming)
In this post, we see how to define specific actions to be executed before or after the execution of every call to a method in our code. This is also known as “ intercepting ” the execution of a method and is related to AOP (Aspect Oriented Programming). We will explore two different ways of achieving this:   Using Microsoft’s Unity framework Using the PostSharp library   CastleDynamicProxy is another library allowing you to intercept methods and resembles a lot to the Unity framework’s approach so it will not be described here. You can also use .NET framewrok’s Emit namespace or CodeDom to create your intercepting Proxy objects from scratch but this approach is out of the scope of this post. Aspect Oriented Programming deals with horizontal concerns in the specifications of your programs. Horizontal concerns are requirements that span through every business logic or specific behavior of your system. Take for example the following figure displaying some typical modules of an e-shop application. The classes

Διαβάστε περισσότερα »

Posted: Κυριακή, 16 Ιανουαρίου 2011 10:38 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
Domain Specific Languages with M - Part 1/3 Defining the syntax
Say you are implementing software for a company that rents items. And you are presented with some bizarre and complex logic on the way renting fees are calculated. To be more specific requirements come to you in the following form: “I want a renting fee scenario where an item for the first month is charged 10$ per day. Then, the same item costs 5$ per week for the next two months. Finally, after this period of three months the fee will be 20$ per month. But this is just one scenario…” Clearly

Διαβάστε περισσότερα »

Posted: Σάββατο, 10 Απριλίου 2010 9:07 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
NHibernate, PropertyChanged event and WPF
A typical implementation of an entity that supports the INotifyPropertyChanged interface for WPF Binding is for example as follows: public class Detail:INotifyPropertyChanged { private long _iD; public virtual long ID { get { return _iD; } set { _iD = value ; if (PropertyChanged != null ) PropertyChanged( this , new PropertyChangedEventArgs("ID"));} } private string _line1; public virtual string Line1 { get { return _line1; } set { _line1 = value ; if (PropertyChanged != null ) PropertyChanged( this

Διαβάστε περισσότερα »

Posted: Παρασκευή, 28 Αυγούστου 2009 4:30 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία: ,
Timers in WPF
There are times when you need a task to execute periodically. There are two ways of achieving this: Use the System.Windows.Threading. DispatcherTimer Use the System.Threading. Timer Say now that you want to implement a class the executes DoSomething() periodically and also informs through a delegate to whoever listens whent the execution is performed. The class for DispatcherTimer is as follows: public class DTimer { private DispatcherTimer timer; public event Action < int > DoSomething; private int _timesCalled

Διαβάστε περισσότερα »

Posted: Παρασκευή, 31 Ιουλίου 2009 8:44 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία: ,