Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, June 23, 2013

.NET Developer Interview Question: What is IDisposable?

Garbage collector as a part of CLR has the responsibility of managing memory allocation to native .NET objects which are called managed objects. C#, VB.NET and other .NET languages which are garbage collected languages does not provide a way for developers to finalize a managed object in their application directly. However not all resources you use in your program is a managed one. Examples of unmanaged objects are window handles, open files, streams and database connections. While CLR's garbage collector automatically releases the memory allocated to managed objects (when they are not needed any longer), it will not be possible to know when garbage collection will occur with unmanaged objects and developers need to take the matter into their own hands. 

When calling a class that implements the IDisposable interface, use the try/finally pattern to make sure that unmanaged resources are disposed, even if an exception interrupts your application. you can use the using statement (Using in Visual Basic) instead of the try/finally pattern.

IDisposable interface is defined as follows:
public interface IDisposable
{
   void Dispose();
}

When writing a class for IDisposable interface, make the dispose method of the class public so that other classes can call the methods:
public class MyClass : IDisposable
{
   public void Dispose()
   {
     //Handle your finalization process here ...
   }
}

Wednesday, June 19, 2013

.NET Developer Interview Question: What is Deferred Execution?

According to MSDN definition, "Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required". The main benefit of using deferred execution is that it can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of chained queries or manipulations.


In .NET and Microsoft technologies, C# is supporting deferred execution via using yield keyword (LINQ extensively uses deferred execution as one way of executing its queries).


C# Example:
public class Program
{
    static void Main()
    {
       foreach (int value in ComputePower(2, 30))
       {
          Console.Write(value);
       }
    }

    public static IEnumerable ComputePower(int number, int exponent)
    {
       int exponentNum = 0;
       int numberResult = 1;
  
       // Continue loop until the exponent count is reached.
       while (exponentNum < exponent)
       {
          numberResult *= number;
          exponentNum++;
     
          yield return numberResult;
       }
    }
}

In the above example, the computation of the 2 power 30 will be deffered to where the for-each looped value is used, which will boost up the performance of this chunk of code.


 LINQ Example:
class Program
{
    static void Main(string[] args)
    {
        string[] stringArray = { "abc", "def", "ghi" };

        var q = from str in stringArray.ConvertCollectionToUpperCase()
                select str;

        foreach (string str in q)
            Console.WriteLine("Main: str {0}", str);
    }
    
    public static IEnumerable 
                   ConvertCollectionToUpperCase(this IEnumerable source)
    {
        foreach (string str in source)
        {
            Console.WriteLine("ToUpper: source {0}", str);
            yield return str.ToUpper();
        }
    }
}

In the above example, the same happens with the LINQ queries. Once you use the value of str in the for-each loop, result of ConvertCollectionToUpperCase will be executed. 

Saturday, February 9, 2013

A Step-by-Step Beginner Tutorial on Writing Unit Tests NUnit with C#

In this tutorial, you will learn how to setup and run NUnit tests inside a project. There are many useful tutorials but in my opinion, they are just too complex and time consuming as a start-up guide. Authors tend to put their own models to test and it is time consuming to read and understand their code to begin with. Also most people have their own domain and do not have time reading other people's domain, right?

So let's start our brief tutorial right here to let you stand on your feet in no time!


1. Create your project

You need to consider that you can have any type of project, you like. Working with NUnit does not restrict you to create an additional Unit Test Project (like Visual Studio's Test Suite):



Now, you need to add NUnit DLLs. Right click on project references, Click on add references:




Find NUnit assembly, check it:




Add a package (folder) to your project and name it something relevant like "Tests":




Add a Test Class and by that I mean just a normal class. What you should do is to add the following line at the top of your class:
using NUnit.Framework;

Now, here comes the main part. In a NUnit test class, beside the actual tests, they are other objects  which have their own methods from other classes. Why? Because in real-world scenarios a unit is not as simple as predicting a sum of two integers. In each method to be tested, a mixture of object from other classes is involved. Since it is called "Unit Test", we do not care whether those other second hand objects are working correctly. We create mocks out of them, and make them to act as we expect them to be. You might ask now when do we test their functionality? The answer is of course when we Unit-Test them. Now if you are really good you also might ask what if something gets lost in between? Yeah, no worries! Integration Testing or Behavior-Design-Development (BDD) is the answer.


Here is a complete layout of your unit test class. You can read the name of the methods and the comments and after that I trust that you can implement your own ideas, instead of reading my mind:
namespace HelloWorldNUnit.Tests
{
    [TestFixture]
    class UnitTest
    {

        [TestFixtureSetUp]
        public void RunsOnceBeforeAll()
        {
            // 1. Runs Once Before All of The Following Methods
            // Declare Global Objects Which Are Global For Test Class, e.g. Mock Objects
        }
        
        
        [SetUp]
        public void RunOnceBeforeEachTest()
        {
            // 2. Runs Twice; Once Before Test Case 1 and Once Before Test Case 2
            // Declare Objects Which Are Shared Among Tests, e.g. Shared Mocks
        }

        [Test]
        public void TestCaseNumberOne()
        { 
            // 3. Runs Once; This is your Test!
        }

        [Test]
        public void TestCaseNumberTwo()
        {
            // 4. Runs Once; This is your Test!
        }

        
        [TearDown]
        public void RunOnceAfterEachTests()
        {
            // 4. Runs Twice; Once after Test Case 1 and Once After Test Case 2
            // Dispose Objects Used in Each Test which are no longer required
        }

        [TestFixtureTearDown]
        public void RunOnceAfterAll()
        {
            // 5. Runs Once After All of The Aformentioned Methods
            // Dispose all Mocks and Global Objects
        }
    }
    
}

Build you solution. Find NUnit Gui Application (Default location is C:\Program Files (x86)\NUnit 2.6.2\bin). Go to File, then select Open Project and browse your application's EXE file (Again the default will be ~your-project-path\project-name\bin\Debug):




Now you can see the two aformentioned tests. If you put some logic there, build and then select File and then Reload Project, You can click on Run button and see that if your tests are passing/failing:



Happy Testing!   

Tuesday, February 5, 2013

Develop a Browser App for Windows Phone 7

I personally have had a resistance toward developing applications for Windows Phone. However some days ago I started playing around with it and I can honestly say that it did not disappoint me at all. There is a high chance that you do not like the user experience which Windows Phone 7 provides, however I can tell you coding for Windows Phone 7 is really nice, easy and fun!

Prerequisites

It is assumed that you already have installed the following components:

  • Visual Studio 2010 for Windows Phone
  • .NET Framework 4
  • Windows Phone SDK 7.1


1. Create Your First Windows App Project

Open your visual studio, click on "New Project" and inside the Installed Templates section, choose your preferred language (This tutorial covers C# template).



A pop-up window then asks for the Target Windows Phone OS version which should be set to Windows Phone OS 7.1.

The template will create a MainPage.xaml file. Double-click on the file, and what you see resembles to the following picture:





2. Add UI Elements

Now browse to the MainPage.xaml file and  find the part of XAML file which defines StackPanel element:

      
      



You can see that it contains two TextBlocks where you can see the application name and page title. In the first TextBlock, change the Text property to "A Windows Phone App" and in the second one to "Mini Browser". As you can see, the changes affect the UI in the Preview panel.

Next, we need to add a TextBox (which user will put the website address), a Button and a Browser element.  For this, inside the MainPage.xaml, find the ContentPanel Grid :


Now, we need to open the Grid element and insert those elements inside the ContentPanel Grid element with the following lines of code:


3. Add Button Event Handler

In the preview panel, double click on the Go button. You will be directed inside the MainPage.xaml.cs file:

public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void Go_Click(object sender, RoutedEventArgs e)
        {
        }
    }

When the Go button is clicked, the browser navigates to the URL and the result will be shown inside the webbrowser element. For this, we add the following code inside the Go_Click button:
 
string HTTP = "http://";
string website = HTTP + URL.Text;
MiniBrowser.Navigate(new Uri(website, UriKind.Absolute));


Save all the modifications.


4. Run the application

Select the Windows Phone Emulator for the debugging in your toolbar:




Yes, the application is up and running. You should that it is working correctly both in Portrait  mode:



and also Landscape mode: