Interview questions

  1. Given an array of integers write a function in C# to sum all the numbers that are even (any developer should be able to quickly write this out on a white board or paper, no need for tooling).

Ans:

public int sum(int[] list)

{

int sum = 0;

for(int i=0;i<list.Length;i++)

{

if(list[i]%2==0)

{

sum = sum + list[i];

}

}

return sum;

}

  1. What is a REST service and how would you build one in .Net?

Ans:

REST stands for Representational State Transfer. It is an architectural concept for building inter-operable light weight web services which helps to access and manipulate the web resources identified though URI (Uniform Resource Identifier). It was introduced by Roy Fielding. Like WWW (World Wide Web, REST identifies all resources on server through a unique URI. For example: http://yoursite.com/employee/1 to access the employee information with id 1. The REST web service accepts a requests for a resource and returns response in almost every data interchange formats like XML, JSON, HTML, etc.

Creating WebApi project in Visual Studio 2015

  1. Open Visual Studio 2015. Click New > Project
  2. Select Web templates and ASP.Net Web Application.
  3. Select Empty template and check Web API for “Add folders and core reference for”. Refer below image.

Click OK.

This will create a new empty WebApi project with all required Nuget packages, default routing setup required to create your first web API.

  1. Add a Web API controller by right clicking Controllers folder and Add > Controller. Select WebAPI 2.0 controller with read/write actions.

I have only added a simple Get() and Get(id) action methods to return hardcoded employee information for simplicity.

Employee API Controller

public class EmployeeController : ApiController
{
// GET api/
public IEnumerable Get()
{
return new[] { new Employee { Id = 1, Name = “Tom”, Gender = “Male” }, new Employee { Id = 2, Name = “John”, Gender = “Male” } };
}

// GET api//5
public Employee Get(int id)
{
return new Employee() { Id = 1, Name = “Tom”, Gender = “Male” };
}

// POST api/
public void Post([FromBody]string value)
{
//post code
}

// PUT api//5
public void Put(int id, [FromBody]string value)
{
//put code
}

// DELETE api//5
public void Delete(int id)
{
//delete code
}
}
//Employee model

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
}

  1. Press F5 to execute the application.

Visiting http://localhost:56323/api/employee will list all the employees.

Visiting http://localhost:56323/api/employee/1 will list employee information for employee id 1.

Note– replace the port # with your project’s port number.

  1. How do you typically work with a database in .Net?

Ans:

           Normally we create database in SQL server 2012 and use entity framework to access it. And update web.config with connection string to get access to database.

  1. What is dependency injection and what frameworks have you used?

Ans: Dependency Injection (DI) is a design pattern that demonstrates how to create loosely coupled classes. DI provides implementation of Inversion of Control. There are different frameworks(containers) we used to achieve Dependency injection. I used MEF, Ninject, StructureMap frameworks to achieve DI.

  1. What is an anti-forgery token and why would you use it?

Ans: A great feature in ASP.NET MVC is the AntiForgeryToken. This Generates a hidden form field (anti-forgery token) that is validated when the form is submitted. The anti-forgery token can be used to help protect your application against cross-site request forgery. To use this feature, all you need to do is add the following HTML helper to your form so it is submitted as part of the form post:@Html.AntiForgeryToken() 

  1. How is programming with interfaces beneficial/detrimental to testing?

Ans:  using interfaces we are decoupling classes and due to decouple we can independently test each component.

  1. What is an Angular component? Why would you use one?

Ans: Component is combination of template and class. Template contains view layout, html and includes bindings and directives whereas class supports view, created using typescript.

Use component have some advantages

  1. Components only control their own View and Data
  2. Components have a well-defined public API – Inputs and Outputs
  3. Components have a well-defined lifecycle 
  1. What does the keyword `this` in JavaScript mean? If I opened up chrome dev tools and typed `this` what would I get in return?

Ans:  ‘this’ is the current execution context of a function. In chrome it is showing window object which is global object for current instance

 

  1. What is the difference between an inner and outer join?

Ans:  An inner join finds and returns matching data from tables, while an outer join finds and returns matching data and some dissimilar data from tables.

  1. What is a foreign key? What problems might you run into when deleting data with a foreign key in a related table?  How do you overcome this?

Ans: foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table or the same table. When deleting data with a foreign key getting error of referential integrity constraints to solve this error add constrain of on cascade delete while creating foreign key.

11. Get array of only once appearance of element
int[] xs = { 1, 2, 3, 3, 4 };

Ans1: var reslt =
from t in xs
group xs by t into grp
where grp.Count() == 1
select grp.Key;

Ans2: var a= xs.GroupBy(g => g).Where(g => g.Count() == 1).Select(g => g.First());

12. Parse below json string
string json =@”{‘Emp1’: ‘10000’,’Emp2′: ‘20000’,}”;

Answer :

Salary sal = JsonConvert.DeserializeObject(json);

string EmployeeName = sal.a;
int Salary= sal.b;

 

Advertisements

MEF: Managed Extensibility Framework and Dependency Injection (DI) with asp.net MVC

You can download word document here…

The Managed Extensibility Framework (MEF) is a composition layer for .NET that improves the flexibility, maintainability and testability of large applications.

Its basic purpose is to plug-in components to an already running application.

To achieve dependency injection(DI) we use MEF framework

Assembly used to achieve MEF is System.ComponentModel.Composition.dll

Example

Below is MVC application to get all users.

Create new MVC application in Visual Studio

1

Project structure in solution explorer as below

2

Now, create class library MEF.Entities and create User entity in it like below

3

Now crate class library MEF.Repository and create interface IUserRepository and concrete class UserRepository in it as below

IUserRepository.cs

4

UserRepository.cs

5

Now create “Infrastructure” folder in MEF.Mvc and add MEFControllerFactory.cs  class in it as follows

public class MEFControllerFactory : DefaultControllerFactory

{

private readonly CompositionContainer _container;

public MEFControllerFactory(CompositionContainer container)

{

_container = container;

}

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)

{

if (controllerType == null)

return null;

try

{

Lazy<object, object> export = _container.GetExports(controllerType, null, “Controller”).FirstOrDefault();

if (export == null)

return base.GetControllerInstance(requestContext, controllerType);

else

return (IController)export.Value;

}

catch (InvalidOperationException ex)

{

throw ex;

}

catch (Exception ex)

{

throw ex;

}

}

public override void ReleaseController(IController controller)

{

((IDisposable)controller).Dispose();

}

}

Resolve errors by adding references “System.ComponentModel.Composition” and add import “using System.Web.Routing;”

6

Add below code in Global.asax file and resolve dependencies by adding references

//MEF Related Code

//Create catalogs

AggregateCatalog catalog = new AggregateCatalog();

DirectoryCatalog dirCatalog = new DirectoryCatalog(“bin”);

catalog.Catalogs.Add(dirCatalog);

//Create the composition container

CompositionContainer composition = new CompositionContainer(catalog);

//Below code for MVC controllers

IControllerFactory mefControllerFactory = new

MEFControllerFactory(composition);

ControllerBuilder.Current.SetControllerFactory(mefControllerFactory);

Now we want to inject our Repository in HomeController for that do below steps

  1. Open UserRepository.cs file and add attribute [Export(typeof(IUserRepository))] at top of class, this indicates that this class we want to export to our HomeController.

In code this will look like below

[Export(typeof(IUserRepository))]

public class UserRepository:IUserRepository

{ …….

Add reference of using System.ComponentModel.Composition; at top in code

  1. In home controller add same attribute on top of it as below

[Export(“Controller”,typeof(HomeController))]

public class HomeController : Controller

{ ……..

  1. Add Constructor as below and resolve errors by adding reference for repository project MEF.Repository

7

4. Now in action method of HomeController get all users from our repository using contract IUserRepository and put debugger and execute and see result below

8

Accept decimal number with 2 decimal places only in .NET MVC

1.Create project in MVC with name “DecimalNumberDemo” as below

1

2. Create common.js file in script folder and paste below code in it. Below code is refer from http://stackoverflow.com/

// Validation on KeyPress event of Amount to check entered value is decimal value accepting 2 decimal places only e.g. 99.99

function validateFloatKeyPress(el, evt) {

var charCode = (evt.which) ? evt.which : event.keyCode;

//var charCode = evt.keyCode;

var number = el.value.split(“.”);

if (charCode != 46 && (charCode < 48 || charCode > 57)) {

return false;

}

//just one dot

if (number.length > 1 && charCode == 46) {

return false;

}

//get the carat position

var caratPos = getSelectionStart(el);

var dotPos = el.value.indexOf(“.”);

if (caratPos > dotPos && dotPos > -1 && (number[1].length > 1)) {

return false;

}

return true;

}

// Get position of ‘carat’ for decimal value validation

function getSelectionStart(o) {

if (o.createTextRange) {

var r = document.selection.createRange().duplicate()

r.moveEnd(“character”, o.value.length)

if (r.text == “”) return o.value.length

return o.value.lastIndexOf(r.text)

} else return o.selectionStart

}

3. Add textbox in HomeController’s Index.cshtml view file as below.

6

4. Run application you will see below output.

2

5. Now refer common.js in BundleConfig.cs fie as below

3

6. Add @Scripts.Render(“~/scripts/decimalNumber”) in _Layout.cshtml as below

4

7. Run application and try to enter alphabets or any other character it won’t accept that only accept decimal number with max length 10 and 2 decimal places as below.

5

You can download word document here accept-decimal-number-with-2-decimal-places-only-in

AutoEventWireup attribute in page directive in ASP.NET

The ASP.NET page framework supports an automatic way to associate page events and methods. If the AutoEventWireup attribute of the Page directive is set to true, the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit Handles clause or delegate is needed.

AutoEventWireup is an attribute in Page directive.
AutoEventWireup is a Boolean attribute that indicates whether the ASP.NET pages events are auto-wired.
AutoEventWireup will have a value true or false. By default it is true.

There is no event or method associated with Page_Load. Those events whose inline event is not there but that should be executed, for that purposed AutoEventWireup=”true”.

Disadvantages of AutoEventWireup attribute

AutoEventWireup uses fixed naming convention for the events. Page events handlers have specific predictable names. This limits your flexibility in how you name event handlers.
If you do set AutoEventWireup to true, Visual Studiowill generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs. As a consequence, you should always leave AutoEventWireup set to false when working in Visual Studio.
Another disadvantage is that performance is adversely affected, because ASP.NET searches for methods at run-time. For a Web site with high traffic volumes, the impact on performance could be significant.

AutoEventWireup=”true” target is for page events only. In case of AutoEventWireup method are not case sensitive. (Page_Load or page_load both will work).

If AutoEventWireup=”false” but still you want to executed Page event (Page_Load). In this you have to explicitly code for it.

Function for conversion of a Indian Rupees into words: Parameter – accept a Currency,Returns the number in words format. You can use this function in Excel, VBA, VB6,.NET

Function RupeesToWord(ByVal MyNumber)
Dim Temp
Dim Rupees, Paisa As String
Dim DecimalPlace, iCount
Dim Hundreds, Words As String
Dim place(9) As String
place(0) = ” Thousand ”
place(2) = ” Lakh ”
place(4) = ” Crore ”
place(6) = ” Arab ”
place(8) = ” Kharab ”
On Error Resume Next
‘ Convert MyNumber to a string, trimming extra spaces.
MyNumber = Trim(Str(MyNumber))

‘ Find decimal place.
DecimalPlace = InStr(MyNumber, “.”)

‘ If we find decimal place…
If DecimalPlace > 0 Then
‘ Convert Paisa
Temp = Left(Mid(MyNumber, DecimalPlace + 1) & “00”, 2)
Paisa = ” and ” & ConvertTens(Temp) & ” Paisa”

‘ Strip off paisa from remainder to convert.
MyNumber = Trim(Left(MyNumber, DecimalPlace – 1))
End If

‘===============================================================
Dim TM As String ‘ If MyNumber between Rs.1 To 99 Only.
TM = Right(MyNumber, 2)

If Len(MyNumber) > 0 And Len(MyNumber) <= 2 Then
If Len(TM) = 1 Then
Words = ConvertDigit(TM)
RupeesToWord = "Rupees " & Words & Paisa & " Only"

Exit Function

Else
If Len(TM) = 2 Then
Words = ConvertTens(TM)
RupeesToWord = "Rupees " & Words & Paisa & " Only"
Exit Function

End If
End If
End If
'===============================================================

' Convert last 3 digits of MyNumber to ruppees in word.
Hundreds = ConvertHundreds(Right(MyNumber, 3))
' Strip off last three digits
MyNumber = Left(MyNumber, Len(MyNumber) – 3)

iCount = 0
Do While MyNumber “”
‘Strip last two digits
Temp = Right(MyNumber, 2)
If Len(MyNumber) = 1 Then

If Trim(Words) = “Thousand” Or _
Trim(Words) = “Lakh Thousand” Or _
Trim(Words) = “Lakh” Or _
Trim(Words) = “Crore” Or _
Trim(Words) = “Crore Lakh Thousand” Or _
Trim(Words) = “Arab Crore Lakh Thousand” Or _
Trim(Words) = “Arab” Or _
Trim(Words) = “Kharab Arab Crore Lakh Thousand” Or _
Trim(Words) = “Kharab” Then

Words = ConvertDigit(Temp) & place(iCount)
MyNumber = Left(MyNumber, Len(MyNumber) – 1)

Else

Words = ConvertDigit(Temp) & place(iCount) & Words
MyNumber = Left(MyNumber, Len(MyNumber) – 1)

End If
Else

If Trim(Words) = “Thousand” Or _
Trim(Words) = “Lakh Thousand” Or _
Trim(Words) = “Lakh” Or _
Trim(Words) = “Crore” Or _
Trim(Words) = “Crore Lakh Thousand” Or _
Trim(Words) = “Arab Crore Lakh Thousand” Or _
Trim(Words) = “Arab” Then

Words = ConvertTens(Temp) & place(iCount)

MyNumber = Left(MyNumber, Len(MyNumber) – 2)
Else

‘=================================================================
‘ if only Lakh, Crore, Arab, Kharab

If Trim(ConvertTens(Temp) & place(iCount)) = “Lakh” Or _
Trim(ConvertTens(Temp) & place(iCount)) = “Crore” Or _
Trim(ConvertTens(Temp) & place(iCount)) = “Arab” Then

Words = Words
MyNumber = Left(MyNumber, Len(MyNumber) – 2)
Else
Words = ConvertTens(Temp) & place(iCount) & Words
MyNumber = Left(MyNumber, Len(MyNumber) – 2)
End If

End If
End If

iCount = iCount + 2
Loop

RupeesToWord = “Rupees ” & Words & Hundreds & Paisa & ” Only”
End Function

‘ Conversion for hundreds
‘*****************************************
Private Function ConvertHundreds(ByVal MyNumber)
Dim Result As String

‘ Exit if there is nothing to convert.
If Val(MyNumber) = 0 Then Exit Function

‘ Append leading zeros to number.
MyNumber = Right(“000” & MyNumber, 3)

‘ Do we have a hundreds place digit to convert?
If Left(MyNumber, 1) “0” Then
Result = ConvertDigit(Left(MyNumber, 1)) & ” Hundreds ”
End If

‘ Do we have a tens place digit to convert?
If Mid(MyNumber, 2, 1) “0” Then
Result = Result & ConvertTens(Mid(MyNumber, 2))
Else
‘ If not, then convert the ones place digit.
Result = Result & ConvertDigit(Mid(MyNumber, 3))
End If

ConvertHundreds = Trim(Result)
End Function

‘ Conversion for tens
‘*****************************************
Private Function ConvertTens(ByVal MyTens)
Dim Result As String

‘ Is value between 10 and 19?
If Val(Left(MyTens, 1)) = 1 Then
Select Case Val(MyTens)
Case 10 : Result = “Ten”
Case 11 : Result = “Eleven”
Case 12 : Result = “Twelve”
Case 13 : Result = “Thirteen”
Case 14 : Result = “Fourteen”
Case 15 : Result = “Fifteen”
Case 16 : Result = “Sixteen”
Case 17 : Result = “Seventeen”
Case 18 : Result = “Eighteen”
Case 19 : Result = “Nineteen”
Case Else
End Select
Else
‘ .. otherwise it’s between 20 and 99.
Select Case Val(Left(MyTens, 1))
Case 2 : Result = “Twenty ”
Case 3 : Result = “Thirty ”
Case 4 : Result = “Forty ”
Case 5 : Result = “Fifty ”
Case 6 : Result = “Sixty ”
Case 7 : Result = “Seventy ”
Case 8 : Result = “Eighty ”
Case 9 : Result = “Ninety ”
Case Else
End Select

‘ Convert ones place digit.
Result = Result & ConvertDigit(Right(MyTens, 1))
End If

ConvertTens = Result
End Function

Private Function ConvertDigit(ByVal MyDigit)
Select Case Val(MyDigit)
Case 1 : ConvertDigit = “One”
Case 2 : ConvertDigit = “Two”
Case 3 : ConvertDigit = “Three”
Case 4 : ConvertDigit = “Four”
Case 5 : ConvertDigit = “Five”
Case 6 : ConvertDigit = “Six”
Case 7 : ConvertDigit = “Seven”
Case 8 : ConvertDigit = “Eight”
Case 9 : ConvertDigit = “Nine”
Case Else : ConvertDigit = “”
End Select
End Function

What is the difference between VARCHR and CHAR in SQL?

The char is a fixed-length character data type, the varchar is a variable-length character data type.

Because char is a fixed-length data type, the storage size of the char value is equal to the maximum size for this column. Because varchar is a variable-length data type, the storage size of the varchar value is the actual length of the data entered, not the maximum size for this column.

You can use char when the data entries in a column are expected to be the same size.
You can use varchar when the data entries in a column are expected to vary considerably in size.

TextBox text in Proper Case

Private Sub TextBox2_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.Leave
TextBox2.Text = StrConv(TextBox2.Text, VbStrConv.ProperCase)
End Sub