43
WCF, WPF, Silverlight, LINQ, Azure and EF 4.0 interview questions 1. What is SOA, Services and Messages ? SOA is a collection of well-defined services. A service is an autonomous (business) system that accepts one or more requests and returns one or more responses via a set of published and well defined interfaces. Each of these individual services can be modified independently of other services to help respond to the ever-evolving market conditions of a business. 2. What is the difference between Service and Component? It is natural to be confused about the terms component and service, and what they mean. A component is a piece of compiled code that can be assembled with other components to build applications. Components can also be easily reused within the same application or across different applications. This helps reduce the cost of developing and maintaining the application once the components mature within an organization. Components are usually associated with the object-oriented programming (OOP) paradigm. A service is implemented by one or more components, and is a higher-level aggregation. Component reuse seems to work well in homogeneous environments; service orientation fills the gap by establishing reuse in heterogeneous environments by aggregating one or more components into a service and making them accessible through messages using open standards. These service definitions are deployed with the service, and they govern the communication from the consumers of the service via various contracts and policies, among other things. 3. What are basic steps to create a WCF service ? To create a WCF service, please follow these steps: 1. Launch Visual Studio 2008.

WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

  • Upload
    abhi

  • View
    236

  • Download
    3

Embed Size (px)

Citation preview

Page 1: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

WCF, WPF, Silverlight, LINQ, Azure and EF 4.0 interview questions

1. What is SOA, Services and Messages ?

SOA is a collection of well-defined services.

A service is an autonomous (business) system that accepts one or more requests and returns one or more responses via a set of published and well defined interfaces. Each of these individual services can be modified independently of other services to help respond to the ever-evolving market conditions of a business.

2. What is the difference between Service and Component?

It is natural to be confused about the terms component and service, and what they mean. A component is a piece of compiled code that can be assembled with other components to build applications. Components can also be easily reused within the same application or across different applications. This helps reduce the cost of developing and maintaining the application once the components mature within an organization. Components are usually associated with the object-oriented programming (OOP) paradigm.

A service is implemented by one or more components, and is a higher-level aggregation. Component reuse seems to work well in homogeneous environments; service orientation fills the gap by establishing reuse in heterogeneous environments by aggregating one or more components into a service and making them accessible through messages using open standards. These service definitions are deployed with the service, and they govern the communication from the consumers of the service via various contracts and policies, among other things.

3. What are basic steps to create a WCF service ?

To create a WCF service, please follow these steps:

1. Launch Visual Studio 2008.2. Click on File -> new -> project, then select WCF service application.3. It will create a WCF service application template.

4. What are various ways of hosting WCF service? Depending on the requirements you have for your host, there are four general categories

for hosting your WCF services, as follows: Self-hosting in a managed .NET application Hosting in a Windows service Hosting in different versions of IIS Hosting on the Windows Azure platform

5. What are endpoints, address, contracts and bindings? The above terminologies are the core on which SOA stands. Every service must expose

one or more ends by which the service can be available to the client. End consists of three important things where, what and how:-

• Contract (What)

Page 2: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method.• Address (Where)

An Address indicates where we can find this service. Address is a URL, which points to the location of the service.• Binding (How)

Bindings determine how this end can be accessed. It determines how communications is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.

6. What is the difference of hosting a WCF service on IIS and Self hosting?

Self hosting: the services that are the hosted inside any managed application, such as console applications or windows application are known as self-hosted services. This type of hosting is very flexible and easy to use, but is suitable only during development or demonstration phases of a distributed application.

IIS: A WCF service is hosted in IIS to enable a client to access the servie over the internet. When a WCF service is hosted on IIS, it acquires the benefits of IIS such as process lifetime management and automatic update after configuration changes.

7. What is the difference between BasicHttpBinding and WsHttpBinding?

BasicHttpBinding: - This binding is used when we need to use SOAP over HTTP. This binding can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized form like MTOM.

 WsHttpBinding: - It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with it also supports reliable message transfer, security and transaction. WS-Reliable Messaging, security with WS-Security, and transactions with WS-Atomic Transaction supports reliable message.

8. Can you explain transactions in WCF (theory)?

Transactions provide a way to group a set of actions or operations into a single indivisible unit of execution. A transaction is a collection of operations with the following properties:

Atomicity. This ensures that either all of the updates completed under a specific transaction are committed and made durable or they are all aborted and rolled back to their previous state. 

Consistency. This guarantees that the changes made under a transaction represent a transformation from one consistent state to another. For example, a transaction that transfers money from a checking account to a savings account does not change the amount of money in the overall bank account. 

Isolation. This prevents a transaction from observing uncommitted changes belonging to other concurrent transactions. Isolation provides an abstraction of concurrency while

Page 3: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

ensuring one transaction cannot have an unexpected impact on the execution of another transaction. 

Durability. This means that once committed, updates to managed resources (such as a database record) will be persistent in the face of failures. 

Windows Communication Foundation (WCF) provides a rich set of features that enable you to create distributed transactions in your Web service application.

WCF implements support for the WS-AtomicTransaction (WS-AT) protocol that enables WCF applications to flow transactions to interoperable applications, such as interoperable Web services built using third-party technology. WCF also implements support for the OLE Transactions protocol, which can be used in scenarios where you do not need interop functionality to enable transaction flow.

You can use an application configuration file to configure bindings to enable or disable transaction flow, as well as set the desired transaction protocol on a binding. In addition, you can set transaction time-outs at the service level using the configuration file. For more information.

Transaction attributes in the System.ServiceModel namespace allow you to do the following:

Configure transaction time-outs and isolation-level filtering using the ServiceBehaviorAttribute attribute.

Enable transactions functionality and configure transaction completion behavior using the OperationBehaviorAttribute attribute. 

Use the ServiceContractAttribute and OperationContractAttribute attributes on a contract method to require, allow or deny transaction flow. 

9. How can we self host WCF service ?

Self Hosting1. This requires adding a managed code to host the process.2. The code could be either a Windows form application or Console application.3. Here host process must be running before client makes a call to the service.4. Mainly Console applications are used for the purpose of self hosting.5. The Console/Windows application must specifically create and open an instance of ServiceHost object.6. The ServiceHost then remains open and available until it is no longer needed.7. Configuration about the Service is being kept in the App.Config file.

10. What are the different ways of implementing WCF Security?There are four core security features that WCF addresses:-

Confidentiality: This feature ensures that the information does not go in wrong hands when it travels from the sender to the receiver.

Integrity: This feature ensures that the receiver of the message gets the same information

Page 4: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

that the sender sends without any data tampering. 

Authentication: This feature verifies who the sender is and who the receiver is. 

Authorization: This feature verifies whether the user is authorized to perform the action they are requesting from the application.

11. How can we implement transport security plus message security in WCF ?

transport security using WsHttp binding with HTTPS security.

Step 1:- Create a simple service using WCF project The first step is to create a simple WCF project. So click on new project and select WCF service project. By default WCF project creates a default function ‘GetData()’. We will be using the same function for this sample.

Step 2 :- Enable transport level security in the web.config file of the service  Next step is to enable transport security in WsHttp binding. This is done using the ‘Security’ XML tag as shown in the below code snippet.

Step 3:- Tie up the binding and specify HTTPS configuration Tie up the bindings with the end points. So use the ‘bindingConfiguration’ tag to specify the binding name. We also need to specify the address where the service is hosted. Please note the HTTS in the address tag.

Change ‘mexHttpBinding’ to ‘mexHttpsBinding’ in the second end point.

 Step 4:- Make the web application HTTPS enabled  Now that we are done with the WCF service project creation and the necessary configuration changes are done. It’s time to compile the WCF service project and host the same in IIS application with HTTPS enabled.

We will be using ‘makecert.exe’ which is a free tool given by Microsoft to enable HTTPS for testing purpose. MakeCert (Makecert.exe) is a command-line tool that creates an X.509 certificate that is signed by a system test root key or by another specified key. The certificate binds a certificate name to the public part of the key pair. The certificate is saved to a file, a system certificate store, or both.

You can get the same from “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin” or you can also get it from windows SDK.

You can type the below thing through your dos prompt on “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin”. Please note “compaq-jzp37md0” is the server name so you need to replace with your PC name.  makecert -r -pe -n "CN= compaq-jzp37md0 " -b 01/01/2000 -e 01/01/2050 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12

Page 5: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

So click on the server certificate tab and you will then be walked through an IIS certificate wizard. Click ‘Assign a existing certificate’ from the wizard.You can see a list of certificates. The “compaq-jzp37md0” certificate is the one which we just created using ‘makecert.exe’.

Step 5:- Consume the service in a web applicationIt’s time to consume the service application in ASP.NET web. So click on add service reference and specify your service URL. You will shown a warning box as shown in the below figure. When we used makecert.exe we did not specify the host name as the service URL. So just let it go. 

Step 6:- Suppress the HTTPS errors‘makecert.exe’ creates test certificates. In other words it’s not signed by CA. So we need to suppress those errors in our ASP.NET client consumer. So we have created a function called as ‘IgnoreCertificateErrorHandler’ which return true even if there are errors. This function is attached as a callback to ‘ServicePointManager.ServerCertificateValidationCallback’.

-> message level security :  message security using Wshttp with X509 certificates.

 Step 1:- Create client and server certificates Create two certificates one for the server and the other for the client using makecert.exe. You can get makecert.exe from “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin” folder. So you can goto dos prompt and run the below command snippet. makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WCfServer -sky exchange -pemakecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WcfClient -sky exchange -pe Currently we have specified that we want to create the client key with ‘WcfClient’ name and server key with ‘WCFServer’. The certificates should be created for the current user and should be exportable.Step 2 :- Copy the certificates in trusted people certificates Go to start à run and type MMC and press enter. You will be popped with the MMC console. Click on file à Add/remove snap-in. You will be popped up with a Add/Remove Snap-in , click on the add button , select certificates and select ‘My user Account’.You can see the certificates created for client and server in the personal certificates folder. We need to copy those certificates in trusted people à certificates folder. Step 3 :- Specify the certification path and mode in the WCF service web.config file Now that we have created both the certificates we need to refer these certificates in our WCF project.So we have created two projects one which has the WCF service and the other project is a web application which will consume the WCF service.Let’s open the web.config file of the WCF service and enter two important things:-• Where the certificate is stored, location and how WCF application should find the same. This is defined using ‘serviceCertificate’ tag as shown in the below snippet.• The ‘certificationvalidationmode’ defines how client certificates will be authenticated.

The above two points is clubbed together and entered in the web.config file of the WCF service.

Page 6: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

Step 4 :- Define bindings

 Now that we have defined our certificates and authentication type we need to define that the authentication values will be sent through message using certificates. You can see we have defined the ‘WsHttpBinding’ with message attribute specifying that the WCF client needs to send a certificate for validation.

Step5 :- Tie up the bindings with end point Once done we need to tie up this binding with the end point. This is done by using ‘bindingConfiguration’ tag as shown in the below code snippet.

Step 6 :- Make your web application client for consuming the WCF service That’s all we need to from the WCF service perspective. So compile the WCF service and reference the same in the ASP.NET web application using ‘Service reference’. Below is the code snippet where we have referenced the service and called the ‘GetData’ function of the service/ 

Step 7 :- Define certificates in WCF clientSo let’s start the process of defining certificates in the WCF client. The way we have defined authentication certification mode and the path of the certificate, in the same way we need to define it for WCF client. You can see we have defined the authentication mode as ‘peertrust’ and we have specified the client certificate name as ‘WcfClient’.

 Step 8 :- Tie up the behavior with end point on WCF clientWe need to tie up the above defined behavior with the end point. You can see we have bounded the behavior using ‘behaviorConfiguration’ property. We also need to specify that the DNS value will be ‘WcfServer’ which your server certificate name.

12. How can we do WCF instancing?

Instancing: Controls new object creation and manages object lifetime. The default is PerCall, which creates a new object on each method call. Generally, in sessionoriented services, providing either PerSession or Shareable may provide better performance, albeit at the cost of concurrency management.

13. How can we do WCF Concurency and throttling?

Concurrency: Controls threading behavior for an object and whether it supports reentrant calls. It’s valid only if the Instancing property is not PerCall.

Throttling: Managed through configuration, when concurrency allows for multiple calls, to limit the number of concurrent calls, connections, total instances, and pending operations

14. Can you explain the architecture of Silverlight?

Page 7: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

There is a particular value in the combined set of tools, technologies, and services included in the Silverlight platform: They make it easier for developers to create rich, interactive, and networked applications. Although it is certainly possible to build such applications using today's Web tools and technologies, developers are hindered by many technical difficulties, including incompatible platforms, disparate file formats and protocols, and various Web browsers that render pages and handle scripts differently. A rich Web application that runs perfectly on one system and browser may work very differently on another system or browser, or may fail altogether. Using today's large array of tools, protocols, and technologies, it is a massive and often cost-prohibitive effort to build an application that can simultaneously provide the following advantages:

Ability to create the same user experience across browsers and platforms, so that the application looks and performs the same everywhere.

Integration of data and services from multiple networked locations into one application using familiar .NET Framework classes and functionality.

A media-rich, compelling, and accessible user interface (UI). Silverlight makes it easier for developers to build such applications, because it

overcomes many of the incompatibilities of current technologies, and provides within one platform the tools to create rich, cross-platform, integrated applications.

15. What are the basic things needed to make a silverlight application?

Silverlight applications can be written in any .NET programming language. As such, any development tools which can be used with .NET languages can work with Silverlight, provided they can target the Silverlight CoreCLR for hosting the application, instead of the .NET Framework CLR. Microsoft has positionedMicrosoft Expression Blend as a companion tool to Visual Studio for the design of Silverlight User Interface applications. Visual Studio can be used to develop and debug Silverlight applications. To

Page 8: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

create Silverlight projects and let the compiler target CoreCLR, Visual Studio requires the Silverlight Tools for Visual Studio

16. How can we do transformations in SilverLight?

There are times when you want to transform your object in various ways. For example you would like to tilt the object in 45 degree; you would like skew the object or rotate the object. Below are some important transformation example which you can achieve using Silverlight.

Below is a simple example which uses ‘RotateTransform’ to tilt the text at 45 degree.

<TextBlock HorizontalAlignment="Center" Text="Text rotated by 45 degree"><TextBlock.RenderTransform><RotateTransform Angle="45" /></TextBlock.RenderTransform></TextBlock>                        

Below is a simple example which uses ‘ScaleTransform’ to scale the text to ‘2’.

<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Text="Text scaled with 2"><TextBlock.RenderTransform><ScaleTransform ScaleX="2"/> </TextBlock.RenderTransform></TextBlock>

Below is a simple example which uses ‘RenderTransform’ to position your text at a particular X and Y position.

<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Text="Text with X/Y values"><TextBlock.RenderTransform><TranslateTransform X="-100" Y="-100"/></TextBlock.RenderTransform></TextBlock>

In case you want skew your object, below is a simple XAML code snippet which skews you rectangle object at 45 degree.

Page 9: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

<Rectangle Fill="Chocolate" Stroke="Black" Width="100" Height="100"><Rectangle.RenderTransform><SkewTransform AngleX="45"/></Rectangle.RenderTransform></Rectangle>

There situations when you would like to apply two or more transformation types on an object. In those scenarios you can use ‘TransformGroup’ to apply multiple transformation. Below is a code snippet which shows ‘SkewTransform’ and ‘RotateTransform’ applied in a group to  the rectangle object.

<Rectangle Fill="Chocolate" Stroke="Black" Width="100" Height="100"><Rectangle.RenderTransform><TransformGroup>

<SkewTransform AngleX="45"/><RotateTransform Angle="45"/>

</TransformGroup></Rectangle.RenderTransform></Rectangle>

17. Can you explain animation fundamentals in SilverLight?Let’s create a simple animation shown below. We will create a rectangle object whose height will increase in an animated manner. You can see from the below figure how the animation will look like. We will execute this animation using ‘DoubleAnimation’ object

Figure :- Rectangle height animation So the first step is to define the rectangle object. Below is the XAML code snippet for which defines the rectangle object with height and width equal to 100 and chocolate background.  

Page 10: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

<Grid x:Name="LayoutRoot" Background="White"><Rectangle x:Name="RectAnimated" Fill="Chocolate" Stroke="Black"Width="100" Height="100"></Rectangle></Grid>

As a second step we need to define when the animation will be trigger. You can see from the below code snippet we have defined that the story board will be invoked when the rectangle object is loaded. <Grid x:Name="LayoutRoot" Background="White"> <Rectangle x:Name="RectAnimated" Fill="Chocolate" Stroke="Black"Width="100" Height="100"><Rectangle.Triggers><EventTrigger RoutedEvent="Rectangle.Loaded"><BeginStoryboard>

</Storyboard></BeginStoryboard></EventTrigger></Rectangle.Triggers></Rectangle></Grid>

Finally we have put in the ‘DoubleAnimation’ object which uses the ‘Height’ as the target property which will be animated ‘100’ value to ‘300’ value in 5 seconds. Also note that target name is the rectangle object ‘RectAnimated’. We have also define ‘AutoReverse’ as ‘true’ which means once it reaches ‘300’ it will restart from ‘100’.  <Grid x:Name="LayoutRoot" Background="White"> <Rectangle x:Name="RectAnimated" Fill="Chocolate" Stroke="Black"Width="100" Height="100"><Rectangle.Triggers><EventTrigger RoutedEvent="Rectangle.Loaded"><BeginStoryboard><Storyboard x:Name="myStoryboard"><DoubleAnimationStoryboard.TargetName="RectAnimated"Storyboard.TargetProperty="Height"From="100" By="300" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" /></Storyboard></BeginStoryboard></EventTrigger></Rectangle.Triggers></Rectangle></Grid>

18. What are the different layout methodologies in SilverLight?

Page 11: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

There are three ways provided by Silverlight for layout management - Canvas, Grid and Stack panel. Each of these methodologies fit into different situations as per layout needs. All these layout controls inherit from Panel class.

19. Can you explain one way , two way and one time bindings?

One Way Binding

In one way bindings, data flows only from object to UI and not vice-versa. For instance, you can have a textbox called as TxtYear which is binded with an object having property Year. So when the object value changes, it will be reflected on the Silverlight UI, but the UI cannot update the year property in the object.

It is a three step procedure to implement one way binding. First, create your class which you want to bind with the Silverlight UI.  For instance, below is a simple class called ClsDate with a Year property.

public class clsDate{private int _intYear;public int Year{set{_intYear = value;}get{return _intYear;}}}

In the second step, you need to tie up the Year property with a Silverlight UI textbox. To bind the property, you need to specify ‘Binding Path=Year’ in the text property of the textbox UI object. Year is the property which we are binding with the textbox UI object.

<TextBox x:Name="txtCurrentYear" Text="{Binding Path=Year}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

The final step is to bind the textbox data context with the date object just created.

Page 12: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

public partial class Page : UserControl{public Page(){InitializeComponent();clsDate objDate = new clsDate();objDate.Year = DateTime.Now.Year;txtCurrentYear.DataContext = objDate;}}

Two Way Binding

Two way binding ensures data synchronization of data between UI and objects. So any change in object is reflected to the UI and any change in UI is reflected in the object.

To implement two way binding, there are two extra steps in addition to the steps provided for OneWay. The first change is that we need to specify the mode as TwoWay as shown in the below XAML code snippet.

<TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=TwoWay}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

The second change is that we need to implement INotifyPropertyChanged interface. Below is the class which shows how to implement the INotifyPropertyChanged interface. Please note that you need to importSystem.ComponentModel namespace.

public class clsDate : INotifyPropertyChanged{public event PropertyChangedEventHandler PropertyChanged;private int _intYear;public int Year{set{_intYear = value;OnPropertyChanged("Year");}get{

Page 13: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

return _intYear;}}private void OnPropertyChanged(string property){if (PropertyChanged != null){PropertyChanged(this,new PropertyChangedEventArgs(property));}}}

The binding of data with data context is a compulsory step which needs to be performed.

One Time Binding

In one time binding, data flows from object to the UI only once. There is no tracking mechanism to update data on either side. One time binding has marked performance improvement as compared to the previous two bindings discussed. This binding is a good choice for reports where the data is loaded only once and viewed.

<TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=OneTime}" Height="30" Width="150"

VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

20. How can we consume WCF service in SilverLight?Step 1: Create Your WCF ServiceStep 2: Enable Cross Domain for Your WCF ServiceStep 3: Add the WCF Service ReferenceStep 4: Call the Service

21. How can we connect databases using SilverLight?Below are 7 important steps which we need to follow to consume a database WCF service

in Silverlight.

Step 1: Create the Service and Data Service ContractBelow is a simple customer table which has 3 fields ‘CustomerId’ which is an identity column, ‘CustomerCode’ which holds the customer code and ‘CustomerName’ which has the name of the customer. We will fire a simple select query using WCF and then display the data on the Silverlight grid.

Field Datatype

CustomerId int

CustomerCode nvarchar(50)

CustomerName

nvarchar(50)

As per the customer table specified above, we need to first define the WCF data contract. Below is the customer WCF data contract.

Page 14: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

[DataContract] public class clsCustomer { private string _strCustomer; private string _strCustomerCode;

[DataMember] public string Customer { get { return _strCustomer; } set { _strCustomer = value; } }

[DataMember] public string CustomerCode { get { return _strCustomerCode; } set { _strCustomerCode = value; } } }We also need to define a WCF service contract which will be implemented by WCF concrete classes.

[ServiceContract] public interface IServiceCustomer { [OperationContract] clsCustomer getCustomer(int intCustomer); }

Step 2: Code the WCF ServiceNow that we have defined the data contract and service contract, it’s time to implement the service contract. We have implemented the ‘getCustomer’ function which will return the ‘clsCustomer’ datacontract. ‘getCustomer’ function makes a simple ADO.NET connection and retrieves the customer information using the ‘Select’ SQL query.public class ServiceCustomer : IServiceCustomer { public clsCustomer getCustomer(int intCustomer) { SqlConnection objConnection = new SqlConnection(); DataSet ObjDataset = new DataSet(); SqlDataAdapter objAdapater = new SqlDataAdapter(); SqlCommand objCommand = new SqlCommand

("Select * from Customer where CustomerId=" + intCustomer.ToString()); objConnection.ConnectionString =

System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ToString();

objConnection.Open();

Page 15: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

objCommand.Connection = objConnection; objAdapater.SelectCommand = objCommand; objAdapater.Fill(ObjDataset); clsCustomer objCustomer = new clsCustomer(); objCustomer.CustomerCode = ObjDataset.Tables[0].Rows[0][0].ToString(); objCustomer.Customer = ObjDataset.Tables[0].Rows[0][1].ToString(); objConnection.Close(); return objCustomer; } }

Step 3: Copy the CrossDomain.xml and ClientAccessPolicy.XML FileThis WCF service is going to be called from an outside domain, so we need to enable the cross domain policy in the WCF service by creating ‘CrossDomain.xml’ and ‘ClientAccessPolicy.xml’. Below are both the code snippets. The first code snippet is for cross domain and the second for client access policy.

<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM

"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> <cross-domain-policy> <allow-http-request-headers-from domain="*" headers="*"/> </cross-domain-policy>

<?xml version="1.0" encoding="utf-8" ?> <access-policy> <cross-domain-access> <policy> <allow-from http-request-headers="*"> <domain uri="*"/> </allow-from> <grant-to> <resource include-subpaths="true" path="/"/> </grant-to> </policy> </cross-domain-access> </access-policy>

Step 4: Change the WCF Bindings to ‘basicHttpBinding’Silverlight consumes and generates proxy for only basicHttpBinding, so we need to change the endpoint bindings accordingly.

<endpoint address="" binding="basicHttpBinding" contract="WCFDatabaseService.IServiceCustomer">

Step 5: Add Service ReferenceWe need to consume the service reference in Silverlight application using ‘Add service reference’ menu. So right click the Silverlight project and select add service reference.

Page 16: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

Step 6: Define the Grid for Customer Name and Customer CodeNow on the Silverlight side, we will create a ‘Grid’ which has two columns, one for ‘CustomerCode’ and the other for ‘CustomerName’. We have also specified the bindings using ‘Binding path’ in the text block.

<Grid x:Name="LayoutRoot" Background="White"> <Grid.ColumnDefinitions> <ColumnDefinition></ColumnDefinition> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="20"></RowDefinition> <RowDefinition Height="20"></RowDefinition> </Grid.RowDefinitions> <TextBlock x:Name="LblCustomerCode" Grid.Column="0"

Grid.Row="0" Text="Customer Code"></TextBlock> <TextBlock x:Name="TxtCustomerCode" Grid.Column="1"

Grid.Row="0" Text="{Binding Path=CustomerCode}"></TextBlock> <TextBlock x:Name="LblCustomerName" Grid.Column="0"

Grid.Row="1" Text="Customer Name"></TextBlock> <TextBlock x:Name="TxtCustomerName" Grid.Column="1"

Grid.Row="1" Text="{Binding Path=Customer}"></TextBlock> </Grid>

Step 7: Bind the WCF Service with the GRIDNow that our grid is created, it's time to bind the WCF service with the grid. So go to the code behind of the XAML file and create the WCF service object. There are two important points to be noted when we call WCF service using from Silverlight:

We need to call the WCF asynchronously, so we have called getCustomerAsynch. Please note this function is created by WCF service to make asynchronous calls to the method / function.

Once the function completes its work on the WCF service, it sends back the message to the Silverlight client. So we need to have some kind of delegate method which can facilitate this communication. You can see that we have created a getCustomerCompleted method which captures the arguments and ties the results with the grid datacontext.

public partial class Page : UserControl{ public Page() { InitializeComponent(); ServiceCustomerClient obj = new ServiceCustomerClient(); obj.getCustomerCompleted += new EventHandler<getCustomerCompletedEventArgs>

(DisplayResults); obj.getCustomerAsync(1); } void DisplayResults(object sender, getCustomerCompletedEventArgs e) {

Page 17: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

LayoutRoot.DataContext = e.Result; }}

You can now run the project and see how the Silverlight client consumes and displays the data.

22. What is LINQ and can you explain same with example?

LINQ is a uniform programming model for any kind of data access. LINQ enables you to query and manipulate data independently of data sources. Below figure 'LINQ' shows how .NET language stands over LINQ programming model and works in a uniformed manner over any kind of data source. It’s like a query language which can query any data source and any transform. LINQ also provides full type safety and compile time checking.LINQ can serve as a good entity for middle tier. So it will sit in between the UI and data access layer.

Figure - LINQ

 Below is a simple sample of LINQ. We have a collection of data ‘objcountries’ to which LINQ will is making a query with country name ‘India’. The collection ‘objcountries’ can be any data source dataset, datareader, XML etc. Below figure ‘LINQ code snippet’ shows how the ‘ObjCountries’ can be any can of data. We then query for the ‘CountryCode’ and loop through the same.

Page 18: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

Figure: - LINQ code snippet

23. Can you explain a simple example of LINQ to SQL?So let’s first start with a simple LINQ to SQL example and then we will try to understand how we can establish relationship in LINQ entities. Step 1:- Define Entity classes using LINQ When we design project using tiered approach like 3-tier or N-tier we need to create business classes and objects. For instance below is a simple class which defines a class which is mapped to a country table as shown below. You can see we how the class properties are mapped in one to one fashion with the table. These types of classes are termed as entity classes. 

In LINQ we need to first define these entity classes using attribute mappings. You need to import “System.Data.Linq.Mapping;” namespace to get attributes for mapping. Below is the code snippet which shows how the ‘Table’ attribute maps the class with the database table name ‘Customer’ and how ‘Column’ attributes helps mapping properties

Page 19: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

with table columns. 

[Table(Name = "Customer")]public class clsCustomerEntityWithProperties{private int _CustomerId;private string _CustomerCode;private string _CustomerName;

[Column(DbType = "nvarchar(50)")]public string CustomerCode{set{_CustomerCode = value;}get{return _CustomerCode;}}

[Column(DbType = "nvarchar(50)")]public string CustomerName{set{_CustomerName = value;}get{return _CustomerName;}}

[Column(DbType = "int", IsPrimaryKey = true)]public int CustomerId{set{_CustomerId = value;}get{return _CustomerId;}}}

 

Page 20: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

Below is a more sophisticated pictorial view of the entity classes mapping with the customer table structure.  

 Step 2:- Use the datacontext to bind the table data with the entity objects. 

The second step is use the data context object of LINQ to fill your entity objects. Datacontext acts like a mediator between database objects and your LINQ entity mapped classes. 

So the first thing is to create the object of datacontext and create a active connection using the SQL connection string.

DataContext objContext = new DataContext(strConnectionString);

The second thing is to get the entity collection using the table data type. This is done using the ‘gettable’ function of the datacontext.

Table<clsCustomerEntity> objTable =objContext.GetTable<clsCustomerEntity>();

Once we get all the data in table collection it’s time to browse through the table collection and display the record. 

foreach (clsCustomerEntity objCustomer in objTable){Response.Write(objCustomer.CustomerName + "<br>");}

24. How can we optimize LINQ relationships queries using ‘DataLoadOptions’?

Page 21: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

First let’s try to understand how LINQ queries actually work and then we will see how round trips happen. Let’s consider the below database design where we have 3 tables -- customer, addresses and phone. There is one-many relationship between customer and addresses, while there is one-one relationship between address table and phones.

We have created three entities as per the table design: ClsCustomerWithAddresses ClsAddresses ClsPhone

We have defined the relationships between them using ‘EntitySet’ and ‘EntityRef’.

Page 22: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

To fill the entity objects with data from table is a 5 step process. As a first step, the datacontext connection is created using the connection string, LINQ query is created and then we start browsing through customer, addressand phones.

Analyzing the LINQ SQL Round TripsOk, now that we have analyzed that it takes 5 steps to execute a LINQ query, let’s try to figure out on which step the LINQ query actually fires SQL to the database. So what we will do is run the above LINQ code and analyze the same using SQL profiler.Just so that we do not catch a lot of SQL Server noise, we have only enabled RPC and SQL batch events.

Now when you run the query, you will find the below things: The execution of actual SQL takes place when the foreach statement is iterated on the

LINQ objects. The second very stunning thing you will notice is that for every entity, a separate

query is fired to SQL Server. For instance, for customer one query is fired and then separate queries for address and phones are fired to flourish the entity object. In other words, there are a lot of round trips.

Page 23: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

Avoiding Round Trips using DataLoadOptionsWe can instruct LINQ engine to load all the objects using ‘DataLoadOptions’. Below are the steps involved to enable ‘DataLoadOptions’.The first step is to create the data context class:

DataContext objContext = new DataContext(strConnectionString);The second step is to create the ‘DataLoadOption’ object:DataLoadOptions objDataLoadOption = new DataLoadOptions();Using the LoadWith method, we need to define that we want to load customer with address in one SQL.objDataLoadOption.LoadWith<clsCustomerWithAddresses>

(clsCustomerWithAddresses => clsCustomerWithAddresses.Addresses);

Every address object has phone object, so we have also defined saying that the phone objects should be loaded for every address object in one SQL.objDataLoadOption.LoadWith<clsAddresses>(clsAddresses => clsAddresses.Phone);Whatever load option you have defined, you need to set the same to the data context object using ‘LoadOptions’ property.

objContext.LoadOptions = objDataLoadOption;Finally prepare your query:var MyQuery = from objCustomer in objContext.GetTable<clsCustomerWithAddresses>()select objCustomer;

Start looping through the objects:

foreach (clsCustomerWithAddresses objCustomer in MyQuery){ Response.Write(objCustomer.CustomerName + "<br>");

foreach (clsAddresses objAddress in objCustomer.Addresses) { Response.Write("===Address:- " + objAddress.Address1 + "<br>"); Response.Write("========Mobile:- " + objAddress.Phone.MobilePhone + "<br>"); Response.Write("========LandLine:- " + objAddress.Phone.LandLine + "<br>"); }}Below is the complete source code for the same:DataContext objContext = new DataContext(strConnectionString);DataLoadOptions objDataLoadOption = new DataLoadOptions();objDataLoadOption.LoadWith<clsCustomerWithAddresses>

(clsCustomerWithAddresses => clsCustomerWithAddresses.Addresses);objDataLoadOption.LoadWith<clsAddresses>(clsAddresses => clsAddresses.Phone);objContext.LoadOptions = objDataLoadOption;var MyQuery = from objCustomer in objContext.GetTable<clsCustomerWithAddresses>()select objCustomer;

foreach (clsCustomerWithAddresses objCustomer in MyQuery){

Page 24: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

Response.Write(objCustomer.CustomerName + "<br>");

foreach (clsAddresses objAddress in objCustomer.Addresses) { Response.Write("===Address:- " + objAddress.Address1 + "<br>"); Response.Write("========Mobile:- " + objAddress.Phone.MobilePhone + "<br>"); Response.Write("========LandLine:- " + objAddress.Phone.LandLine + "<br>"); }}

Now if you run the code LINQ has executed only one SQL with proper joins as compared to 3 SQL for every object shown previously.

25. Can we see a simple example of how we can do CRUD using LINQ to SQL?

Step 1 :- Create the entity customer class

So as a first step we create the entity of customer class as shown in the below code snippet. [Table(Name = "Customer")]public class clsCustomerEntity{private int _CustomerId;private string _CustomerCode;private string _CustomerName;

[Column(DbType = "nvarchar(50)")]public string CustomerCode{set{_CustomerCode = value;}

Page 25: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

get{return _CustomerCode;}}

[Column(DbType = "nvarchar(50)")]public string CustomerName{set{_CustomerName = value;}get{return _CustomerName;}}

[Column(DbType = "int", IsPrimaryKey = true,IsDbGenerated=true)]public int CustomerId{set{_CustomerId = value;}get{return _CustomerId;}}}Step 2:- Create using LINQCreate data context So the first thing is to create a ‘datacontext’ object using the connection string.DataContext objContext = new DataContext(strConnectionString); Set the data for insert

Once you create the connection using the ‘DataContext’ object the next step is to create the customer entity object and set the data to the object property.clsCustomerEntity objCustomerData = new clsCustomerEntity();objCustomerData.CustomerCode = txtCustomerCode.Text;objCustomerData.CustomerName = txtCustomerName.Text;Do an in-memory updateWe then do an in-memory update in entity objects itself using ‘InsertOnSubmit’ method. objContext.GetTable<clsCustomerEntity>().InsertOnSubmit(objCustomerData); 

Page 26: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

Do the final physical commitFinally we do a physical commit to the actual database. Please note until we do not call ‘SubmitChanges()’ data is not finally committed to the database.

objContext.SubmitChanges();The final create LINQ codeBelow is the final LINQ code put together.DataContext objContext = new DataContext(strConnectionString);clsCustomerEntity objCustomerData = new clsCustomerEntity();objCustomerData.CustomerCode = txtCustomerCode.Text;objCustomerData.CustomerName = txtCustomerName.Text;objContext.GetTable<clsCustomerEntity>().InsertOnSubmit(objCustomerData);objContext.SubmitChanges();

Step 3:- Update using LINQSo let’s take the next database operation i.e. update.

Create data contextAs usual we first need to create a ‘datacontext’ object using the connection string as discussed in the create step.DataContext objContext = new DataContext(strConnectionString);

Select the customer LINQ object which we want to update

Get the LINQ object using LINQ query which we want to update var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>()where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text)select objCustomer; Finally set new values and update data to physical database Do the updates and call ‘SubmitChanges()’ to do the final update.clsCustomerEntity objCustomerData = (clsCustomerEntity)MyQuery.First<clsCustomerEntity>();objCustomerData.CustomerCode = txtCustomerCode.Text;objCustomerData.CustomerName = txtCustomerName.Text;objContext.SubmitChanges(); The final code of LINQ update

Below is how the final LINQ update query looks like.

DataContext objContext = new DataContext(strConnectionString);var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>()where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text)select objCustomer;clsCustomerEntity objCustomerData = (clsCustomerEntity)MyQuery.First<clsCustomerEntity>();objCustomerData.CustomerCode = txtCustomerCode.Text;

Page 27: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

objCustomerData.CustomerName = txtCustomerName.Text;objContext.SubmitChanges();

Step 4:- Delete using LINQLet’s take the next database operation delete.

DeleteOnSubmit

We will not be going through the previous steps like creating data context and selecting LINQ object , both of them are explained in the previous section. To delete the object from in-memory we need to call ‘DeleteOnSubmit()’ and to delete from final database we need use ‘SubmitChanges()’.

objContext.GetTable<clsCustomerEntity>().DeleteOnSubmit(objCustomerData);objContext.SubmitChanges();

Step 5 :- Self explanatory LINQ select and read

Now on the final step selecting and reading the LINQ object by criteria. Below is the code snippet which shows how to fire the LINQ query and set the object value to the ASP.NET UI.

DataContext objContext = new DataContext(strConnectionString);

var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>()where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text)select objCustomer;

clsCustomerEntity objCustomerData = (clsCustomerEntity)MyQuery.First<clsCustomerEntity>();txtCustomerCode.Text = objCustomerData.CustomerCode;txtCustomerName.Text = objCustomerData.CustomerName;

26. How can we call a stored procedure using LINQ?Simple 6 steps to use stored procedure in LINQ

Step 1:- Create a stored procedureStep 2:- Create the LINQ EntityStep 3:- Inherit from DataContext classStep 4:- Attribute using Function attributeStep 5:- Invoke Executemethod callStep 6:- Finally we call the data context in client

27. What is the need of WPF when we had GDI, GDI+ and DirectX?First let us try to understand how display technology has evolved in Microsoft technology. 

User32:- This provides the windows look and feel for buttons and textboxes and other UI elements. User32 lacked drawing capabilities.

GDI (Graphics device interface):- Microsoft introduced GDI to provide drawing capabilities. GDI not only provided drawing capabilities but also provided a high level of abstraction on

Page 28: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

the hardware display. In other words it encapsulates all complexities of hardware in the GDI API.

GDI+:- GDI+ was introduced which basically extends GDI and provides extra functionalities like JPG and PNG support, gradient shading and anti-aliasing. The biggest issue with GDI API was it did not use hardware acceleration and did not have animation and 3D support.

Note: - Hardware acceleration is a process in which we use hardware to perform some functions rather than performing those functions using the software which is running in the CPU.

DirectX: - One of the biggest issues with GDI and its extension GDI+ was hardware acceleration and animation support. This came as a biggest disadvantage for game developers. To answer and server game developers Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D , full color graphics, media streaming facility and lot more. This API no matured when it comes to gaming industry.

WPF: - Microsoft almost had 3 to 4 API's for display technologies, so why a need for one more display technology. DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to develop UI elements like textboxes, button, grids etc using the DirectX technology by which they can exploit the hardware acceleration feature. As WPF stands on the top of directX you can not only build simple UI elements but also go one step further and develop special UI elements like Grid, FlowDocument and Ellipse. Oh yes you can go one more step further and build animations. WPF is not meant for game development. DirectX still will lead in that scenario. In case you are looking for light animation (not game programming) WPF will be a choice. You can also express WPF using XML which is also called as XAML. In other words WPF is a wrapper which is built over DirectX. So let's define WPF. 

WPF is a collection of classes that simplify building dynamic user interfaces. Those classes include a new set of controls, some of which mimic old UI elements (such as Label, Textbox, Button), and some that are new (such as Grid, FlowDocument and Ellipse).

28. Can you explain how we can make a simple WPF application?Open Visual Studio 2008 and choose "File", "New", "Project..." in the main menu.

Choose "WPF Application" as project type.

Choose a folder for your project and give it a name. Then press "OK"

Visual Studio creates the project and automatically adds some files to the solution. A Window1.xaml and an App.xaml. The structure looks quite similar to WinForms, except that the Window1.designer.cs file is no longer code but it's now declared in XAML as Window1.xaml

Page 29: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

Open the Window1.xaml file in the WPF designer and drag a Button and a TextBox from the toolbox to the Window

Select the Button and switch to the event view in the properties window (click on the little yellow lightning icon). Doubleclick on the "Click" event to create a method in the codebehind that is called, when the user clicks on the button.

Note: If you do not find a yellow lightning icon, you need to install the Service Pack 1 for VisualStudio on your machine. Alternatively you can doubleclick on the button in the designer to achieve the same result.

Visual Studio automatically creates a method in the code-behind file that gets called when the button is clicked.

 private void button1_Click(object sender, RoutedEventArgs e){ textBox1.Text = "Hello WPF!";}  The textbox has automatically become assigned the name textBox1 by the WPF designer. Set text Text to "Hello WPF!" when the button gets clicked and we are done! Start the application by hit [F5] on your keyboard.

Page 30: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

29. Can you explain the three rendering modes i.e. Tier 0 , Tier 1 and Tier 2? WPF API first detects the level of hardware acceleration using parameters like RAM of video card , per pixel value etc. Depending on that it either uses Tier 0, Tier 1 or Tier 2 rendering mode.

Tier 0:- If the video card does not support hardware acceleration then WPF uses Tier 0 rendering mode. In other words it uses software acceleration. This corresponds to working of DirectX version less than 7.0.

Tier 1:- If the video card supports partial hardware acceleration then WPF uses Tier 1 rendering mode. This corresponds to working of DirectX version between 7.0 and 9.0.

Tier 2:- If the video card supports hardware acceleration then WPF uses Tier 2 rendering mode. This corresponds to working of DirectX version equal or greater than 9.0.

30. Can you explain the Architecture of WPF?

Above figure shows the overall architecture of wpf. it has three major sections presentation core, presentation framework and milcore. in the same diagram we have shown how other

Page 31: WCF, WPF, Silver Light, LINQ, Azure and EF 4.0 Interview Questions

section like direct and operating system interact with the system. so let’s go section by section to understand how every section works. user32:- it decides which goes where on the screen. directx: - as said previously wpf uses directx internally. directx talks with drivers and renders the content. milcore: - mil stands for media integration library. this section is a unmanaged code because it acts like a bridge between wpf managed and directx / user32 unmanaged api. presentation core ;- this is a low level api exposed by wpf providing features for 2d , 3d , geometry etc. presentation framework:- this section has high level features like application controls , layouts . content etc which helps you to build up your application.

31. What is Azure?32. Can you explain Azure Costing?33. Can we see a simple Azure sample program?34. What are the different steps to create a simple Worker application?35. Can we understand Blobs in steps, Tables & Queues ?36. Can we see a simple example for Azure tables?37. What is Package and One click deploy(Deployment Part - 1) ?38. What is Web.config transformation (Deployment Part-2)?39. What is MEF and how can we implement the same?40. How is MEF different from DIIOC?41. Can you show us a simple implementation of MEF in Silverlight ?