Extra’s – DOT NET Chapter Wise Interview Questions
Question 1:
What is Multi-Targeting in .NET?
Answer:
In previous versions of Visual Studio, every version was tied up with a framework. For instance Visual Studio 2003 only works with 1.1 and Visual Studio 2005 only work with 2.0.
From Visual Studio 2008 they have added multi-targeting feature. You can use same Visual Studio with different versions of .NET framework (See Figure 20.1). So if you click on project properties you can now change the framework version to different types and check if your code is compatible with old version.
Question 2:
What are portable class libraries?
Answer:
The whole point of creating a class library project is reusability. Now we want this reusability not only within a .NET project, not across .NET projects but across different types of .NET projects. Now different types of .NET projects means project which we create using templates of WPF, Windows, Silverlight, Windows phone, etc., as shown in Figure 20.2.
Now each one of these project types run on different platforms and have different flavors of .NET frameworks. For example Silverlight application runs inside a browser and has a down sized version of .NET.
So in a Silverlight project if you try to reference a simple “Class project” you would end with a below error.That’s where portable class libraries are useful (See Figure 20.3). By creating a portable class we can reference it in any kind of .NET project types.
To create a portable class we need to use the portable class template which is available in Visual Studio as shown in the Figure 20.4.
Question 3:
What is NuGet?
Answer:
The amount of frameworks and libraries from both Microsoft (MVC, EF, etc.) and Non-Microsoft open sources (NUnit, Log4Net, etc.) are huge in numbers. These frameworks and libraries keep updating to newer versions and it’s very difficult to keep a track of the same.
As a Visual Studio developer if you need to reference these frameworks or libraries, you need to do the following:
- Search the library URL (Uniform Resource Locator).
- Install the library or probably unzip it at some place.
- Reference the DLL in your Visual Studio Project.
- If library demands also make appropriate changes to the App.config or Web.config file.
In case you want to revert back you need to follow the above process in a vice-versa fashion.
This is where “NuGet” makes our life easy. “NuGet” is a Visual Studio Extension which helps us to search, locate the library, download them, reference them in Visual Studio project and also make appropriate changes to App and Web config files (See Figure 20.5).
So once you click on “Manage NuGet Packages…”, you can go and search the framework and click on install. Figure 20.7 shows a simple image where I have searched the new version of Entity framework and now we need to just click on the Install button to add the same to your Visual Studio Project.
Question 4:
How can we Unit test private methods using VSTS?
Answer:
In order to invoke private methods in VSTS (Visual Studio Team System) unit test we have a class called as “PrivateObject”. Create the object of “PrivateObject” class and pass the class whose private method needs to be invoked, in our case “isNegative” is the private method which has a integer input parameter.You can then use the “PrivateObject” object to invoke the private methods / functions as shown in the below code.
PrivateObject o = new PrivateObject(typeof(Maths)); bool b = Convert.ToBoolean(o.lnvoke(“lsNegative”, -1));
Question 5:
Is it good to practice to Unit test Private methods?
Answer:
No. When we say Unit it’s a class. So if we test the public methods the private methods get tested internally as well. If you are testing private methods of a class that means there is something seriously wrong with the class design.
publicclassMaths { publicint Add(int numl, int num2) { if(IsNegative(numl) && IsNegative(num2)) { thrownewException("Number should not be negative"); } return num1 + num2; } privatebool IsNegative(int num) { if (num > 0) { returntrue; } else { returnfalse; } } }
For instance in the above “Maths” class there is a private function “IsNegative”, if you are testing this method that means “Maths” class is overloaded with responsibility. “Maths” class should only be doing arithmetic operations (Add, Subtract, etc.), but it is also loaded with responsibility of doing validation.
So probably it’s a good idea to move the validation to a separate class called as “Validator” who will do the numeric checks and then use this class inside the “Maths” class.
You can then write test cases on the “Validator” class separately which is a cleaner approach than the previous approach of using “PrivateObj ect” and invoking them via reflection.
public class Validator { private bool IsNegative(int num) { if (num > 0) { return true; } else { return false; } }
Question 6:
What is Mock testing?
Answer:
Let’s say you want to Unit test a data access layer class. But before any call is made to the data access class it calls an email class. This email component is not functional because we have still not received email server configuration details. Below is a simple code with comments depicts this situation.
So now how do we Unit test data access layer because the Email class will never allow us to execute the data access layer code. This is achieved by mocking ( by passing ) the e-mail code.
public class Email { public bool SendEmailO { // not configured throws error } } public class ClsCustomerDAL { public bool SaveRecord(string strCustomerName) { Email obj = new Email(); obj.SendEmail(); // This line throws a error // Data acess code goes at this place but this place is never reached because // the error is throw in the previous line return true; } }
Question 7:
How can we implement Mocking?
Answer:
You can implement mocking by using open source mocking frameworks like Rhino mocks (a dynamic mock object framework for the .NET platform), MOQ (Mock-you; mocking library for .NET), etc.
For example if we want to mock the Email class method by using MOQ tool we need to write the below code. Create the Email object using the Mock class of MOQ framework.
Mock<Email> target = new Mock<Email>();
Then write the code which you want to execute rather than executing the actual code. For instance now I want to just “return true” in a hard code manner.
target. Setup(x => x.SendEmailO).Returns(true);
Now any calls to the “target” email object will always return true.
Question 8:
So are we saying Microsoft does not have mock frameworks?
Answer:
In Visual Studio 2012 Microsoft has introduced “Fakes” which has two great features “Stubs” and “Shims” which will help us achieve mock testing.
Question 9:
Define code coverage.
Answer:
Code coverage is a measure used during software testing which describes how much part of your source code has been tested. So if you see that critical part of your code is not tested by your test case probably you need to update the test case accordingly to get a better coverage result.
To see how much code coverage has been done by test cases.
Click on TESTt menu -> Analyze Code Coverage —^ All Tests (See Figure 20.9).
Once the coverage runs its shows a detail report as shown in Figure 20.10 stating which section do not have coverage. For instance in the below report it stating that the “Calculate” method of maths has 25% code which is not covered by the test cases.
Question 10:
What is Cyclomatic complexity and how to measure the same?
Answer:
Cyclomatic complexity helps you measure code complexity. Higher the code complexity, more it is prone to errors and more important it becomes unit test for that specific code.
Cyclomatic complexity number depends on how many different execution paths your code can execute depending on varying inputs. More the code paths, more the complexity.
For example take the below code. There is nothing complex in the below code, we do not have many execution paths. We just have lots of code lines which does variable initialization. So the cyclomatic complexity of the below code is “1”.
public void Cancel() { Num1 = 0; Num2 = 0; Operation = " "; Pie = 3.14; Num5 = 0; Operation1 = " "; Num20 = 0; Numx = 0; OperationStart = " "; PieMore = 3.145; Num6 = 0; Operationnew = " "; }
But now take the example of below code. There are 4 branch conditions in the below code as shown in the below Table. So the cyclomatic complexity is “4”.
Input | Output | |
Path 1 | Operation.Length ==0 | Exception thrown |
Path 2 | Operation == “+” | Numl + Num2 |
Path 3 | Operation == | Numl – Num2 |
Path 4 | Any other inputs | Numl* Num2 |
public int Calculate() { if (Operation.Length == 0) { throw new Exception(" Operation not sepecified"); } ' if (Operation == "+") { return Num1 + Num2; } else if (Operation == " +") { return Num1 } else { return Num2 } return 0; }
To measure code complexity using Visual Studio, click on Analyze -> Calculate Code Metric for the solution. This feature is available only for Visual Studio ultimate editions.
Once done you should get the cyclomatic complexity as shown in the Figure 20.11.
Question 11:
What is the use of extern keyword and DLLImport attribute?
Answer:
If you want to call functions which are not written using .NET framework, we need to use the extern keyword. So let’s say we want to call “MessageBox” function which belongs to Windows API (Application Programming Interface).
So the first thing we need to import “interopServices” namespace.
using System. Runtime. InteropServices;
Later we need to use the extern keyword to create the method as shown below. Also note this method has to be decorated with “Dllimport” attribute.
[Dlllmport(“User32. dll’)] public static extern int MessageBox(int h. string m, string c, int type);
Once the static function is created, you can call “MessageBox” function later as shown in the below code.
MessageBox(0, “Test”, “My Message Box”, 0);
Question 12:
What is the difference between Debug and Release?
Answer:
Debug and Release are build modes, where Debug is used to build the code in development mode and Release is for production / go live as shown in Figure 20.12 environment.
In Release mode the code is more optimized and any debugging related code or debug constants are removed before going to production.
Question 13:
What is the use of Debug directive?
Answer:
#debug is a preprocessor directive. Now many times you want some code to run while you are debugging but you do want those code shipped to production environment.
For instance in the below code we want todisplay operating system onlyduring debugging but this code we do not want in to be pushed to production server. To achieve this we can use the debug directive.
You can see the below code we have wrapped dispiay operating version code in #if debug condition.This code will be excluded when release compiling happens.
#if DEBUG // This code will not be shipped to production. Console.WriteLine(System.Environment.OSVersion); #endif // This code will be shipped to production, for (int i = 0; i < 5 ; i++) { Console.WriteLine(i); }
Question 14:
What does the word scalability, scale-up and scale-out means?
Answer:
Scalability is the ability of a system to handle growing amount of load without degrading performance. Consider you have system which runs with 100 users efficiently. Let’s say over a period of time your load increases to 500 users, your system still has the ability to handle the load and provide the same efficiency.
You can achieve scalability by two ways either you can Scale-up or Scale-out. In scale-up we have only one machine and we increase the processing power of the machine by adding more processors, more RAMs (Random Access Memory), more hard disks, etc. So if your load increases you add more RAMs, more processor, etc., but you do not add extra physical machines.
In Scale-out, as your load increases you add more computers and you have load balancers in front of those machines to distribute load appropriately.