Saturday, 30 November 2013

ASP.NET - .NET Interview Questions and Answers - 2

25. What is tracing? Where is it used?
Tracing displays the details about how the code was executed. It refers to collecting information about the application while it is running. Tracing information can help you to troubleshoot an application. It enables you to record information in various log files about the errors that might occur at run time. You can analyze these log files to find the cause of the errors.

In .NET, we have objects called Trace Listeners. A listener is an object that gets the trace output and stores it to different places, such as a window, a file on your locale drive, or a SQL Server.

The System.Diagnostics namespace contains the predefined interfaces, classes, and structures that are used for tracing. It supplies two classes, Trace and Debug, which allow you to write errors and logs related to the application execution. Trace listeners are objects that collect the output of tracing processes.

26. What is the difference between authentication and authorization?
Authentication verifies the identity of a user and authorization is a process where you can check whether or not the identity has access rights to the system. In other words, you can say that authentication is a procedure of getting some credentials from the users and verify the user's identity against those credentials. Authorization is a procedure of granting access of particular resources to an authenticated user. You should note that authentication always takes place before authorization.

27. How can you register a custom server control to a Web page?
You can register a custom server control to a Web page using the @Register directive.

28. Which ASP.NET objects encapsulate the state of the client and the browser?
The Session object encapsulates the state of the client and browser.

29. Differentiate globalization and localization.
The globalization is a technique to identify the specific part of a Web application that is different for different languages and make separate that portion from the core of the Web application. The localization is a procedure of configuring a Web application to be supported for a specific language or locale.

30. What is ViewState?
The ViewState is a feature used by ASP.NET Web page to store the value of a page and its controls just before posting the page. Once the page is posted, the first task by the page processing is to restore the ViewState to get the values of the controls.

ASP.NET - .NET Interview Questions and Answers

1. What is ASP?
Active Server Pages (ASP), also known as Classic ASP, is a Microsoft's server-side technology, which helps in creating dynamic and user-friendly Web pages. It uses different scripting languages to create dynamic Web pages, which can be run on any type of browser. The Web pages are built by using either VBScript or JavaScript and these Web pages have access to the same services as Windows application, including ADO (ActiveX Data Objects) for database access, SMTP (Simple Mail Transfer Protocol) for e-mail, and the entire COM (Component Object Model) structure used in the Windows environment. ASP is implemented through a dynamic-link library (asp.dll) that is called by the IIS server when a Web page is requested from the server.
2. What is ASP.NET?
ASP.NET is a specification developed by Microsoft to create dynamic Web applications, Web sites, and Web services. It is a part of .NET Framework. You can create ASP.NET applications in most of the .NET compatible languages, such as Visual Basic, C#, and J#. The ASP.NET compiles the Web pages and provides much better performance than scripting languages, such as VBScript. The Web Forms support to create powerful forms-based Web pages. You can use ASP.NET Web server controls to create interactive Web applications. With the help of Web server controls, you can easily create a Web application.
3. What is the basic difference between ASP and ASP.NET?
The basic difference between ASP and ASP.NET is that ASP is interpreted; whereas, ASP.NET is compiled. This implies that since ASP uses VBScript; therefore, when an ASP page is executed, it is interpreted. On the other hand, ASP.NET uses .NET languages, such as C# and VB.NET, which are compiled to Microsoft Intermediate Language (MSIL).
4. In which event are the controls fully loaded?
Page load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that view state is not fully loaded during this event
5. How can we identify that the Page is Post Back?
Page object has an "IsPostBack" property, which can be checked to know that is the page posted back.
6. What is the lifespan for items stored in ViewState?
The items stored in ViewState live until the lifetime of the current page expires including the postbacks to the same page.

7. How information about the user's locale can be accessed?
The information regarding a user's locale can be accessed by using the System.Web.UI.Page.Culture property.
8. What is the difference between SQL notification and SQL invalidation?
The SQL cache notification generates notifications when the data of a database changes, on which your cache item depends. The SQL cache invalidation makes a cached item invalid when the data stored in a SQL server database changes.
9. Which is the parent class of the Web server control?
The System.Web.Ul.Control class is the parent class for all Web server controls.
10. Can you set which type of comparison you want to perform by the CompareValidator control?
Yes, by setting the Operator property of the CompareValidator control.
11. What is the behavior of a Web browser when it receives an invalid element?
The behavior of a Web browser when it receives an invalid element depends on the browser that you use to browse your application. Most of the browsers ignore the invalid element; whereas, some of them display the invalid elements on the page.
12. What are the advantages of the code-behind feature?
The code-behind feature of ASP.NET offers a number of advantages:

  • Makes code easy to understand and debug by separating application logic from HTML tags
  • Provides the isolation of effort between graphic designers and software engineers
  • Removes the problems of browser incompatibility by providing code files to exist on the Web server and supporting Web pages to be compiled on demand.

13. How do you sign out from forms authentication?
The FormsAuthentication.Signout() method is used to sign out from the forms authentication.
14. What is AutoPostBack?
If you want a control to postback automatically when an event is raised, you need to set the AutoPostBack property of the control to True.
15. What is the function of the ViewState property?
The ASP.NET 4.0 introduced a new property called ViewStateMode for the Control class. Now you can enable the view state to an individual control even if the view state for an ASP.NET page is disabled.
16. Why do you use the App_Code folder in ASP.NET?
The App_Code folder is automatically present in the project. It stores the files, such as classes, typed data set, text files, and reports. If this folder is not available in the application, you can add this folder. One of the important features of the App_Code folder is that only one dll is created for the complete folder, irrespective of how many files it contains.
17. Define a multilingual Web site.
A multilingual Web site serves content in a number of languages. It contains multiple copies for its content and other resources, such as date and time, in different languages.
18. What is an ASP.NET Web Form?
ASP.NET Web forms are designed to use controls and features that are almost as powerful as the ones used with Windows forms, and so they are called as Web forms. The Web form uses a server-side object model that allows you to create functional controls, which are executed on the server and are rendered as HTML on the client. The attribute, runat="server", associated with a server control indicates that the Web form must be processed on the server.

19. What is the difference between a default skin and a named skin?
The default skin is applied to all the Web server controls in a Web form, which are of similar type, and it does not provide a Skin ID attribute. The named skin provides a Skin ID attribute and users have to set the Skin ID property to apply it.
20. What is IIS? Why is it used?
Internet Information Services (IIS) is created by Microsoft to provide Internet-based services to ASP.NET Web applications. It makes your computer to work as a Web server and provides the functionality to develop and deploy Web applications on the server. IIS handles the request and response cycle on the Web server. It also offers the services of SMTP and FrontPage server extensions. The SMTP is used to send emails and use FrontPage server extensions to get the dynamic features of IIS, such as form handler.
21. What is Query String? What are its advantages and limitations?
The Query String helps in sending the page information to the server.

The Query String has the following advantages:

  • Every browser works with Query Strings.
  • It does not require server resources and so does not exert any kind of burden on the server.

The following are the limitations of Query String:
  • Information must be within the limit because URL does not support many characters.
  • Information is clearly visible to the user, which leads to security threats.
22. What is actually returned from server to the browser when a browser requests an .aspx file and the file is displayed?
When a browser requests an .aspx file then the server returns a response, which is rendered into a HTML string.
23. How can you display all validation messages in one control?
The ValidationSummary control displays all validation messages in one control.
24. Which two new properties are added in ASP.NET 4.0 Page class?
The two new properties added in the Page class are MetaKeyword and MetaDescription.

Thursday, 28 November 2013

WPF/MVVM Quick Start Tutorial

Introduction

Assuming that you have a decent understanding of C#, getting started in WPF isn't too difficult. I started looking at WPF a while ago, and didn't find many helpful MVVM tutorials. Hopefully this article addresses that.
As with learning any new technology, you get the benefit of hindsight. From my perspective, almost every tutorial on WPF I've come across is inadequate for one of several reasons:
  • The example is all in XAML.
  • The example glosses over the key facts that would actually make your life easier.
  • The example tries to show off WPF/XAML's capabilities with lots of pointless effects that aren't helping you.
  • The example uses classes that have properties that appear far too similar to framework keywords and classes, and are therefore difficult to identify in the (XAML) code as being user defined (the ListBox GroupStyle's Name attribute is a complete headache for novices).
So to address this, I've written this based on what I would have liked to have found as the #1 hit on Google after typing 'WPF Tutorial'. This article may not be 100% correct, or even do things 'the one true way', but it will illustrate the main points that I wish I had found in one place 6 months ago.
I will quickly introduce some topics, then show an example that explains or demonstrates each point. Accordingly, I haven't really attempted to make the GUIs pretty, that's not the point of this article (see the bullet points above).
As this tutorial is quite long, I've elided quite a lot of code for brevity, so please download the attached zip file, and look at the examples (.NET 4.0/VS2010). Each example builds on the previous one.

The Basics

  1. The most important thing about WPF is data binding. In short, you have some data, typically in a collection of some sort, and you want to display it to the user. You can 'bind' your XAML to the data.
  2. WPF has two parts, the XAML which describes your GUI layout and effects, and the code-behind that is tied to the XAML.
  3. The neatest and probably most reusable way to organise your code is to use the 'MVVM' pattern: Model, View, ViewModel. This has the aim of ensuring that your View contains minimal (or no) code, and should be XAML-only.

The Key Points You Need to Know

  1. The collection you should use to hold your data is the ObservableCollection<>. Not a list, not a dictionary, but an ObservableCollection. The word 'Observable' is the clue here: the WPF window needs to be able to 'observe' your data collection. This collection class implements certain interfaces that WPF uses.
  2. Every WPF control (including 'Window's) has a 'DataContext' and Collection controls have an 'ItemsSource' attribute to bind to.
  3. The interface 'INotifyPropertyChanged' will be used extensively to communicate any changes in the data between the GUI and your code.

Example 1: Doing It (mostly) Wrong

The best way to start is an example. We will start with a Song class, rather than the usual Person class. We can arrange songs into Albums, or one large collection, or by Artist. A simple Song class would be as follows:
    public class Song
    {
        #region Members
        string _artistName;
        string _songTitle;
        #endregion

        #region Properties
        /// The artist name.
        public string ArtistName
        {
            get { return _artistName; }
            set { _artistName = value; }
        }

        /// The song title.
        public string SongTitle
        {
            get { return _songTitle; }
            set { _songTitle = value; }
        }
        #endregion
    }
In WPF terminology, this is our 'Model'. The GUI is our 'View'. The magic that data binds them together is our 'ViewModel', which is really just an adapter that turns our Model into something that the WPF framework can use. So just to reiterate, this is our 'Model'.
Since we've created a Song as a reference type, copies are cheap and light on memory. We can create our SongViewModel quite easily. What we need to consider first is, what are we going to (potentially) display? Suppose we just care about the song's artist name, not the song title, then the SongViewModel could be defined as follows:
public class SongViewModel
{
    Song _song;

        public Song Song
        {
            get
            {
                return _song;
            }
            set
            {
                _song = value;
            }
        }

        public string ArtistName
        {
            get { return Song.ArtistName; }
            set { Song.ArtistName = value; }
        }
}
Except that this isn't quite correct. Since we're exposing a property in our ViewModel, we would obviously want a change to the song's artist name made in the code to be automatically shown in the GUI, and vice versa:
SongViewModel song = ...;
// ... enable the databinding ...
//  change the name
song.ArtistName = "Elvis";
//  the gui should change
Notice that in all the examples here, we create our view model *declaratively*, i.e., we do this in the XAML:
<Window x:Class="Example1.MainWindow"
        xmlns:local="clr-namespace:Example1">
    <Window.DataContext>
        <!-- Declaratively create an instance of our SongViewModel -->
        <local:SongViewModel />
    </Window.DataContext>
This is equivalent to doing this in your code-behind MainWindow.cs:
    public partial class MainWindow : Window
    {
        SongViewModel _viewModel = new SongViewModel();
        public MainWindow()
        {
            InitializeComponent();
            base.DataContext = _viewModel;
        }
    }
And removing your DataContext element in the XAML:
<Window x:Class="Example1.MainWindow"
        xmlns:local="clr-namespace:Example1">
    <!--  no data context -->
This is our view:
Clicking the button does not update anything, because we have not completely implemented data binding.

Data Binding

Remember I said at the start that I would choose a property that stands out. In this example, we want to display the ArtistName. I chose this name because it is NOT the same as any WPF attribute. There are a countless number of examples on the web that choose a Person class and then a Name attribute (the Name attribute exists on multiple .NET WPF classes). Perhaps the authors of the articles just don't realise that this is particularly confusing for beginners (who are, curiously enough, the target audience of these articles).
There are dozens of other articles about data binding out there, so I won't cover it here. I hope the example is so trivial that you can see what is going on.
To bind to the ArtistName property on our SongViewModel, we simply do this in the MainWindow.xaml:
  <Label Content="{Binding ArtistName}" />
The 'Binding' keyword binds the content of the control, in this case a Label, to the property 'ArtistName' of the object returned by DataContext. As you saw above, we set our DataContext to an instance of SongViewModel, therefore we are effectively displaying _songViewModel.ArtistName in the Label.
Once again: clicking the button does not update anything, because we have not completely implemented data binding. The GUI is not receiving any notifications that the property has changed.

Example 2: INotifyPropertyChanged

This is where we have to implement the cunningly named interface: INotifyPropertyChanged. As it says, any class that implements this interface, notifies any listeners when a property has changed. So we need to modify our SongViewModel class a little bit more:
public class SongViewModel : INotifyPropertyChanged
    {
        #region Construction
        /// Constructs the default instance of a SongViewModel
        public SongViewModel()
        {
            _song = new Song { ArtistName = "Unknown", SongTitle = "Unknown" };
        }
        #endregion

        #region Members
        Song _song;
        #endregion

        #region Properties
        public Song Song
        {
            get
            {
                return _song;
            }
            set
            {
                _song = value;
            }
        }

        public string ArtistName
        {
            get { return Song.ArtistName; }
            set
            {
                if (Song.ArtistName != value)
                {
                    Song.ArtistName = value;
                    RaisePropertyChanged("ArtistName");
                }
            }
        }
        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region Methods

        private void RaisePropertyChanged(string propertyName)
        {
            // take a copy to prevent thread issues
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
There are several things now happening here. Firstly, we check to see if we are going to really change the property: this improves performance slightly for more complex objects. Secondly, if the value has changed, we raise the PropertyChanged event to any listeners.
So now we have a Model, and a ViewModel. We just need to define our View. This is just our MainWindow:
<Window x:Class="Example2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Example2"
        Title="Example 2"  SizeToContent="WidthAndHeight" ResizeMode="NoResize"
        Height="350" Width="525">
    <Window.DataContext>
        <!-- Declaratively create an instance of our SongViewModel -->
        <local:SongViewModel />
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Label Grid.Column="0" Grid.Row="0" Content="Example 2 - this works!" />
        <Label Grid.Column="0" Grid.Row="1" Content="Artist:  " />
        <Label Grid.Column="1" Grid.Row="1" Content="{Binding ArtistName}" />
        <Button Grid.Column="1" Grid.Row="2" Name="ButtonUpdateArtist"
        Content="Update Artist Name" Click="ButtonUpdateArtist_Click" />
    </Grid>
</Window>
To test the databinding, we can take the traditional approach and create a button and wire to its OnClick event, so the XAML above has a button, and Click event, giving the code behind:
    public partial class MainWindow : Window
    {
        #region Members
        SongViewModel _viewModel;
        int _count = 0;
        #endregion

        public MainWindow()
        {
            InitializeComponent();

            //  We have declared the view model instance declaratively in the xaml.
            //  Get the reference to it here, so we can use it in the button click event.
            _viewModel = (SongViewModel)base.DataContext;
        }

        private void ButtonUpdateArtist_Click(object sender, RoutedEventArgs e)
        {
            ++_count;
            _viewModel.ArtistName = string.Format("Elvis ({0})", _count);
        }
    }    
This is ok, but it is not how we should use WPF: firstly, we have added our 'update artist' logic into our code-behind. It does not belong there. The Window class is concerned with windowing. The second problem is, suppose we want to move logic in the *button* click event to a different control, for example, making it a menu entry. It means we will be cut'n'pasting, and editing in multiple places.
Here is our improved view, where clicking now works:

Example 3: Commands

Binding to GUI events is problematic. WPF offers you a better way. This is ICommand. Many controls have a Command attribute. These obey binding in the same way as Content and ItemsSource, except you need to bind it to a *property* that returns an ICommand. For the trivial example that we are looking at here, we just implement a trivial class called 'RelayCommand' that implements ICommand.
ICommand requires the user to define two methods: bool CanExecute, and void Execute. The CanExecute method really just says to the user, can I execute this command? This is useful for controlling the context in which you can perform GUI actions. In our example, we don't care, so we return true, meaning that the framework can always call our 'Execute' method. It could be that you have a situation where you have a command bound to button, and it can only execute if you have selected an item in a list. You would implement that logic in the 'CanExecute' method.
Since we want to reuse the ICommand code, we use the RelayCommand class that contains all the repeatable code we do not want to keep writing.
To show how easy it is to reuse the ICommand, we bind the Update Artist command to both a button and a menu item. Notice that we no longer bind to Button specific Click event, or Menu specific Click event.

Example 4: Frameworks

By now, if you have read closely, you'll probably notice that a lot of this is just repetitive code: raising INPC, or creating commands. This is mostly boilerplate, and for INPC, we can move it to base class that we call 'ObservableObject'. For the RelayCommand class, we just move that into our .NET class library. This is how all of the MVVM frameworks you find on the web begin (Prism, Caliburn, etc.).
As far as the ObservableObject and RelayCommand classes are concerned, they are rather basic and are the inevitable result of refactoring. Unsurprisingly, these classes are practically the same as those by Josh Smith.
So we move these classes into a small class library that we can reuse in future.
The view looks much the same as before:

Example 5: Collections of Songs, Doing It Wrong

As I said before, in order to display collections of items in your View (i.e. the XAML), you need to use an ObservableCollection. In this example, we create an AlbumViewModel, which nicely collects our songs together in something that people understand. We also introduce a simple song database, purely so we can quickly produce some song information for this example.
Your first attempt might be as follows:
    class AlbumViewModel
    {
        #region Members
        ObservableCollection<Song> _songs = new ObservableCollection<Song>();
        #endregion
    }
You might think: "I have a different view model this time, I want to display the songs as an AlbumViewModel, not a SongViewModel".
We also create some more ICommands and attach them to some buttons:
public ICommand AddAlbumArtist {}

public ICommand UpdateAlbumArtists {}
In this example, clicking 'Add Artist' works fine. But clicking 'Update Artist Names', fails. If you read the yellow highlighted note on this page on MSDN, it explains why:
To fully support transferring data values from binding source objects to binding targets, each object in your collection that supports bindable properties must implement an appropriate property changed notification mechanism such as the INotifyPropertyChanged interface.
Our view looks like this:

Example 6: Collections of Songs, the Right Way

In this final example, we fix the AlbumViewModel to have an ObservableCollection of SongViewModels that we created earlier:

 


class AlbumViewModel
{
    #region Members
    ObservableCollection<SongViewModel> _songs = new ObservableCollection<SongViewModel>();
    #endregion
    //  code elided for brevity
}

Now all our buttons that are bound to commands operate on our collection. Our code-behind in MainWindow.cs is still completely empty.
Our view looks like this:

Conclusion

Instantiating Your ViewModel

One last point that is worth mentioning is that when you declare your ViewModel declaratively in the XAML, you cannot pass it any parameters: in other words, your ViewModel must have an implicit, or explicit default constructor. How you add state to your ViewModel is up to you. You may find it easier to declare the ViewModel in the MainWindow.cs code-behind, where you can pass in construction parameters.

Other Frameworks

There are lots of other MVVM Frameworks of wildly different complexity and functionality, targeting WPF, WP7, Silverlight, and any combination of the three.

Finally...

Hopefully these six examples show you how easy it is to write a WPF application using MVVM. I've tried to cover all of the points that I think are important and often discussed in multiple articles.
If you find this article helpful, please feel to vote it up.
If you find faults in this article, or I've said anything wrong, or you have some other issue with it, please leave a comment below explaining why, and how you would fix it.

Wednesday, 27 November 2013

What is a Binding ?

What is Binding in Windows Communication Foundation ?
Windows Communication Foundation is a framework for building services that process XML messages. Windows Communication Foundation allows you to transmit messages using different transport protocols (such as HTTP, TCP, and MSMQ) and using different XML representations (such as text, binary, or MTOM, which is commonly referred to as the message encoding in Windows Communication Foundation). In addition, you can enhance specific messaging interactions with a suite of SOAP protocols, such as the various WS-* specifications around security, reliable messaging, and transactions. All three of these communication concepts—the transport, the message encoding, and the suite of protocols—are central to what happens on the wire at run time.

Interview Question and Answers WCF-10

Will Windows Communication Foundation applications interoperate with Web services built with other technologi
es?

Yes. By default,services built with WCF will communicate with other services based on the interoperable Web services specifications. This means that WCF services will communicate with any application built on an infrastructure that also conforms to these standards. Microsoft is deeply committed to p
latform interoperability and is an active member of key standards organizations defining the latest Web services standards.


How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag. If no timeout has been specified, the default is considered as 1 minute.

What are the core components of an Windows Communication Foundation service?
A host environment—an application domain and process—in which the service runs;
A service class, implemented in C# or VB.NET or another CLR-based language that implements one or more methods;
One or more endpoints that allow clients to access the service.

What are different elements of WCF Srevices Client configuration file?
WCF Services client configuration file contains endpoint, address, binding and contract.

Interview Question and Answers WCF-9

How does Windows Communication Foundation address Service Oriented Architecture (SOA)?
WCF is the first programming model built from the ground up to provide implicit service-oriented application development, enabling developers to work autonomously and build applications that are more version independent, thereby increasing application resilience to change.

How to deal with operation overloading while exposing the WCF services?
By default overload operations are not supported in WSDL based
operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.

[ServiceContract]
interface Isum
{
[OperationContract(Name = "MultiplyInt")]
int Multiply(int arg1,int arg2);

[OperationContract(Name = "MultiplyDouble")]
double Multiply(double arg1,double arg2);
}


Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case client proxy will have two methods with different name MultiplyInt and MultiplyDouble.

Is Windows Communication Foundation going to interoperate with my existing applications?
The current plan is for Windows Communication Foundation to provide wire-level interoperability with WSE3, System.Messaging, .NET Enterprise Services, and ASMX applications. With minimal or no changes to code, applications built with these technologies will be able to call Windows Communication Foundation services and be callable by Windows Communication Foundation services.


How to configure Reliability while communicating with WCF Services?
Reliability can be configured in the client config file by adding reliableSession under binding tag.

Reliability is supported by following bindings only:
NetTcpBinding
WSHttpBindingWSFederationHttpBinding
WSDualHttpBinding

Interview Question and Answers WCF-8

What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world. The client of a service is merely the party consuming the service.

1. A user has a service with a one-way operation that includes a fault contract, and he
gets an exception when he tries to host the service. Why?
This happens because, to return faults, the service needs some form of a two-way communication channel in place, which is not the case with one-way operations.

2. A user has a service he wants to expose on the Internet, and it needs to send notifications
out to its consumers. Would the WCF Duplex MEP be a good choice for
implementing this?
No. The WCF Duplex MEP can be problematic to enable, even inside an enterprise.
Its implementation depends upon the service establishing a connection back to the consumer, which can’t happen in certain scenarios, such as when the client’s machine uses NAT behind a firewall. On the Internet, where you are never certain
where your consumers are coming from, this type of callback channel would rarely, if ever, work. When you factor in the security risks it could pose and the scalability concerns with the fact that callback channels require the presence of sessions
between client and service, it isn’t a feasible solution.


3. You have a Data contract specifying a Person class from which you derive a Customer class. Does a Customer object automatically have a Data contract as well?
No. The Data contract is not inherited, so any derived class, such as the Customer class, would have to be explicitly declared as having a Data contract as well.


4. Your company has its own proprietary authentication mechanism, and you are required to authenticate every message coming into the service. What is the best way to handle using this mechanism with WCF?
Likely the best way to handle this would be to design a Message contract that accepts these proprietary authentication tokens in the header.

5. Can you support the Rpc SOAP style by using the DataContractSerializer?
Yes. You need only adorn your service with the DataContractFormatAttribute and explicitly set the attribute’s Style property to OperationFormatStyle.Rpc.

6. What does the “ABCs of endpoints” refer to?
The ABCs of endpoints refers to the three required elements that comprise a service endpoint: address, binding, and contract.

7. Which standard binding could be used for a service that was designed to replace an existing ASMX Web service?
The basicHttpBinding standard binding was designed to expose a service as if it were an ASMX Web service. This enables you to support existing clients as applications are upgraded to WCF.

8. What is the main disadvantage of using IIS to host a service?
Using IIS to host your services means that you will not be able to support non-HTTP protocols such as TCP, named pipes, and MSMQ. You will have access to the many built-in features available with IIS such as process recycling and messagebased
activation.

9. Which file specifies the types that your service will expose in IIS?
Service types are exposed through IIS by using the service file. This file must have an .svc file extension and should reside in the application directory for your IIS hosting application. This file will include an @ServiceHost directive, which specifies
the service name and language for the service code files. These files should be located in an App_Code subdirectory.

Interview Question and Answers WCF-7

Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.
They are
1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)
For more details see http://msdn.microsoft.com/en-us/library/bb332338.aspx


What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.

WCF supports following transport schemas
HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ

The sample address for above transport schema may look like
http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

Interview Question and Answers WCF-6

What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.

Basic binding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

TCP binding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

Peer network binding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.


IPC binding
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.


Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

MSMQ integration binding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.
For WCF binding comparison, see http://www.pluralsight.com/community/blogs/aaron/archive/2007/03/22/46560.aspx

Interview Question and Answers WCF-5

What are contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.
WCF defines four types of contracts.

Service contracts

Describe which operations the client can perform on the service.
There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.
[ServiceContract]
interface IMyContract
{
[OperationContract]
string MyMethod( );
}
class MyService : IMyContract
{
public string MyMethod( )
{
return "Hello World";
}
}

Data contracts

Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties.
[DataContract]

class Contact
{
[DataMember]
public string FirstName;
[DataMember]

public string LastName;
}

If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.
Fault contracts
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

Message contracts
Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Policy and Binding
Specifies the transport media such as HTTP or TCP. It aslo includes some of the securoty requirements. which are necessary for Commucation.
What is the address formats of the WCF transport schemas?
Address format of WCF transport schema always follow
[transport]://[machine or domain][:optional port] format.
for example:
HTTP Address Format
http://localhost:8888
the way to read the above url is

"Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting"
When the port number is not specified, the default port is 80.

TCP Address Format
net.tcp://localhost:8888/MyService

When a port number is not specified, the default port is 808:
net.tcp://localhost/MyService

NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.

IPC Address Format
net.pipe://localhost/MyPipe

We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine.

MSMQ Address Format
net.msmq://localhost/private/MyService
net.msmq://localhost/MyService

Interview Question and Answers WCF-4

What are different elements of WCF Srevices Client configuration file?
WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like
<system.serviceModel>
<client>
<endpoint name = "MyEndpoint"
address = "http://localhost:8000/MyService/"
binding = "wsHttpBinding"
contract = "IMyContract"
/>
</client>
</system.serviceModel>



What is Proxy and how to generate proxy for WCF Services?

The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.

The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.

Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.

SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs

When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:

SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs

Interview Question and Answers WCF-2

How to deal with operation overloading while exposing the WCF services?
By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.
[ServiceContract]
interface ICalculator
{
[OperationContract(Name = "AddInt")]
int Add(int arg1,int arg2);
[OperationContract(Name = "AddDouble")]
double Add(double arg1,double arg2);
}

Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case client proxy will have two methods with different name AddInt and AddDouble.



How to configure Reliability while communicating with WCF Services?

Reliability can be configured in the client config file by adding reliableSession under binding tag.
<system.serviceModel>
<services>
<service name = "MyService">
<endpoint
address = "net.tcp://localhost:8888/MyService"
binding = "netTcpBinding"
bindingConfiguration = "ReliableCommunication"
contract = "IMyContract"
/>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name = "ReliableCommunication">
<reliableSession enabled = "true"/>
</binding>
</netTcpBinding>
</bindings>
</system.serviceModel>

Reliability is supported by following bindings only

NetTcpBinding
WSHttpBinding
WSFederationHttpBinding
WSDualHttpBinding

What is Transport and Message Reliability?
Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.

Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.

Interview Question and Answers WCF-3

What is the difference WCF and Web services?
Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.

Second web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc
For more details, read http://msdn.microsoft.com/en-us/library/aa738737.aspx

What are various ways of hosting WCF Services?
There are three major ways of hosting a WCF services
• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.

• Host in application domain or process provided by IIS Server.
• Host in Application domain and process provided by WAS (Windows Activation Service) Server.
What was the code name for WCF?
The code name of WCF was Indigo .
WCF is a unification of .NET framework communication technologies which unites the following technologies:-
NET remoting
MSMQ
Web services
COM+


What are the main components of WCF?
The main components of WCF are
1. Service class
2. Hosting environment
3. End point


How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag.
<client>
<endpoint
binding = "wsHttpBinding"
bindingConfiguration = "LongTimeout"
/>
</client>
<bindings>
<wsHttpBinding>
<binding name = "LongTimeout" sendTimeout = "00:04:00"/>
</wsHttpBinding>
</bindings>
If no timeout has been specified, the default is considered as 1 minute.

interview question and answer WCF - 1

What is three major points in WCF?
1) Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.
2) Contract --- Specifies the interface between client and the server. It’s a simple interface with some attribute.
3) Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols

What is WCF?

The Windows Presentation Foundation (WPF) is a next generation graphics platform that is part of .NET 3.0 and .NET 3.5. It allows you to build advanced user interfaces that incorporate documents, media, 2D and 3D graphics, animations, and web-like characteristics. In just 24 sessions of one hour or less, you will be able to begin effectively using WPF to solve real-world problems, developing rich user interfaces in less time than you thought possible. Using a straightforward, step-by-step approach, each lesson builds on a real-world foundation forged in both technology and business matters, allowing you to learn the essentials of WPF from the ground up

What is WCF?

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.
WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.


Difference between WCF and Web services?
Web Services
1.It Can be accessed only over HTTP
2.It works in stateless environment
WCF
WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services:
IIS
WAS
Self-hosting
Managed Windows Service


What are the various ways of hosting a WCF service?
Self hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of ServiceHost class and the service closes when you call the Close of the ServiceHost class.
Host in application domain or process provided by IIS Server.
Host in Application domain and process provided by WAS (Windows Activation Service) Server.

Silverlight & WPF Interview Questions

What is the difference between WPF and SilverLight?
SilverLight is a browser plugin for running it on web where WPF is used for window application. Though they both make use of XAML.
How to perform Event handling in silver light?.
Silverlight 1.0 uses JavaScript, while Silverlight 2.0 uses C# (managed code) for event handling. We will be describing the event model for Silverlight 2.0.
The event handlers are defined in the code-behind file that backs the XAML definition of your User Interface (UI), namely mypage.xaml.cs.
The Silverlight Event Mode
In Silverlight, there are two event cases:
Input events
Non-input events.
Input Events: The browser that hosts the Silverlight plug-in handles initial input stimulus for the input events. This is because Silverlight works within the plug-in architecture of the hosting browser. From the browser, the event is sent to the Silverlight plug-in.
Then, it is raised as an event in the Silverlight Object Model.
Non-input Events: They report a state change to a particular object, for example, the state change events that report asynchronous download state or progress of actions initiated by Web Client. Some non-input events provide lifetime information of objects at a framework level.
For example the FrameworkElement.Loaded event
Some events, such as OnError, can only be handled by the Silverlight plug-in instance and exist within the HTML Document Object Model (DOM). These events need to be continually exposed and possibly handled by any script working with the plug-in instance in the DOM. Therefore; these events are not passed to the managed programming model.
Can we add the reference of a Class library project in Silverlight application project?
No, You can’t add the reference of a Class library inside the Silverlight application project. You can only add the reference of another Silverlight application project inside a Silverlight application project.
However, you can add the reference of a Web Service or WCF services.
What is Silverlight.js file?
Silverlight.js is a helper file which enables Web sites to create advanced Silverlight installation and instantiation experiences.
For more details visit http://code.msdn.microsoft.com/silverlightjs
What is the .xap file inside ClientBin folder of consuming Silverlight application?
Following is a very good FAQ about the .xap posted on asp.net page.
What does XAP mean?
XAP (pronounced ZAP) is the file extension for a Silverlight-based application package (.xap). This file contains the compressed assemblies and resources of a Silverlight 2 application.
What is a .xap file?
A .xap file is a Silverlight-based application package (.xap) that is generated when the Silverlight project is built.
Why is XAP important?
Tools, such as Visual Studio 2008 with the Microsoft Silverlight Tools Beta 2 for Visual Studio 2008, allow you to create Silverlight applications that are heavily client based using managed code. You can use managed code, such as C# or Visual Basic, and benefit by using the tools that you are used to working with.
How does XAP work?
Once you have created the .xap file (explained below), the Silverlight 2 plug-in downloads the file and runs it in a separate work space.
How do I use a .xap file?
A .xap file is used to contain and transfer the assemblies and resources of a managed code application. This managed code application must be run within the Silverlight 2 browser plug-in.
Visit http://forums.asp.net/t/1277554.aspx for complete details.
What is the use of ClientBin folder?
ClientBin folder is used to place the .xap file of Silverlight application. You can keep this anywhere in your web application but this is the default that is used by the Silverlight.
What is the parent xaml tag of Silverlight page?
UserControl is the parent xaml tag of the Silverlight page. All other tags are placed under UserControl tag. 
How to change the default page of the Silverlight application?
To change the default page of Silverlight application, you need to set the RootVisual property inside the Application_Startup even of App.xaml file.
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new YourPage();
}
When you create a new project in Silverlight through Visual Studio, how many xaml files are created and what are the uses of those files?
When we create a Silverlight application from Visual Studio, two (2) xaml files are created into the Silverlight project.
They are:
1. App.xaml – App.xaml is a file used to declare shared resources like brushes, various style objects etc. and to handle the global application level event (this is almost similar to global.asax file in asp.net application). By default following events are created in the App.xaml.cs file.
Application_Startup
Application_Exit
Application_UnhandledException
ReportErrorToDOM
2. MainPage.xaml or Page.xaml – This page is the default page of the Silverlight application and when the silverlight application runs this becomes the default page to appear (this page is like the default.aspx page of asp.net application)
Which programming language can be used to write the backend of the Silverlight application?
We can either use Visual C# or Visual Basic to code the backend of the silverlight application. Here backend means the code behind files for the Sivlerlight pages.
Which language is used to design the layout in Silverlight?
To design the layout of the Silverlight application, XAML language is used.
Extensible Application Markup Language (XAML) is a declarative XML-based language created by Microsoft which is used as a user interface markup language to define UI elements, data binding, eventing, and other features.

WPF Interview Questions – WPF

Level 1

  1. Q: What the first class that is loaded by any new WPF Application project?
    A: App. App.xaml and App.xaml.cs. It is also acceptable if they say App.
  2. Q: What is a DependencyProperty?
    A: Represents a property that can be set through methods such as, styling, data binding, animation, and inheritance. [1]
  3. Q: Name as many layout controls as you can:
    A: Grid, DockPanel, Canvas, WrapPanel, UniformGrid, StackPanel
  4. Q: What tool should you use sketch a mock of your WPF application?
    A: SketchFlow

Level 2

  1. Q: Describe how you would go about writing your own button style?
    A: Make sure the interviewee understands the following:
    - How to copy the default style using Expression Blend.
    - How to change the style
    - How there must be a Style for each state: Enabled, Disabled, Mouseover, pushed, etc…
  2. Q: You need to display a list of items. Which controls are possible options? Of those, which would you use and why?
    A: ItemsControl, ListBox, ListView, DataGrid.
    - Make sure they know that ListBox and ListView can be selected while ItemsControl does not support selection.
    - ListView is more feature rich, as it inherits ListBox, which inherits ItemsControl, and adds features.
    - Make sure they understand what a DataGrid is and how it is different and why they would display a list in a DataGrid.
  3. Q: What can you do in Expression Blend that you cannot do in Visual Studio?
    A: Configure brushes and gradient brushes in the Properties window.
    A: Configure Visual States.
    A: Configure sample data.
    A: Configure Object Timelines
    A: Animation
    A: Many design features…
  4. What can you do in Visual Studio that you cannot do in Expression Blend?
    A: Reformat source code, including XAML, with a hot key.
    A: Include Solution Folders.

Level 3

  1. What are common Localization/Globalization practices for Localizing/Globalizing WPF?
    A: 1) Use Resources.resx, 2) Use BAML, 3) Use a ResourceDictionary to manage localizable strings.
  2. Q: What are some best practices when using WPF if you plan to build a Localized/Globalized application?
    A: Write UI in XAML
    A: Avoid sizing and positionings, but let objects automatically flow.
    A: Enable TextWrapping.
  3. C# applications usually start with this method:
    ?
    1
    2
    3
    public static void Main(string[] args)
    {
    }
    Q1: Where is this method in a WPF Application?
    A: Under the project and autogenerated class file called App.g.i.cs is created as a partial class of the App class. So the Main function is part of App but found in App.g.i.cs.
    Q2: If you needed to add a line into the Main function, how would you do it?
    A: You add a new class, such as Program.cs, and in the project properties you set Program.cs as the Startup Object.

WPF Interview Questions – Binding

Level 1

  1. Q: How do you bind a bool value to Visibility?
    A: Add a BoolToVisibilityConverter to your resources and then use it as the converter in your Binding.
  2. Q: What is IValueConverter used for?
    A: So that a control or control property can be bound to an element of any data type and the conversion happens in the binding process.
  3. Q: Here is a TextBox.  Change it so that it will bind to the ‘Text’ property of any DataContext.
    <TextBox  />
    A: <TextBox Text=”{Binding Path=Text}” />
  4. Q: What happens if the value you are binding to does not exist?
    A: The error is ignored. If running from Visual Studio, a message is logged in the Output window.

Level 2

  1. You want to use a custom Binding but the control does not support binding in the area you want. What are your options? Which would you choose and why?
    A1: Inherit object and add a Dependency Property – If the object is not sealed this is likely an easier option.
    A2: Create an attached property – The object might be sealed.
  2. Q: How do you bind a button’s Command property to a method?
    A: You don’t. You bind to an ICommand. You create a class that implements ICommand and in that object you connect to your method.
  3. Q: Provide an example of when and why you would use MultiBinding.
    A: When you have multiple values that your which to combine.
    A: When you want to use String.Format in XAML.
  4. Q: What is the Binding syntax for binding to a Static value?
    A:  {x:Static s:MyStaticClass.StaticValue2}

Level 3

  1. Q: Provide a situation in which you have or would use a ConverterParameter.
    A: Any time you have a converter that returns something different based on a parameter.
    A: Look for them to share an example of needing to do this.
  2. What is the correct syntax for binding to a property of a Singleton?
    A: {Binding Source={x:Static sing:MySingletonClass.Instance}, Path=SomeProperty}

WPF Interview Questions – MVVM

Level 1

  1. Q: What is INotifyPropertyChanged used for?
    A: For notifying any observer, usually a WPF control, that the property it is bound to has changed.
  2. Q: What is the purpose of MVVM?
    A: To provide a design pattern that allows for separation of concerns. The UI is independent of the data and the data is independent of the UI.
  3. Do you prefer and MVVM framework or just a few MVVM objects?
    A: No real right answer here, just checking how they actually have implemented MVVM.
  4. Q: What object do most ViewModels inherit from:
    A: Either ObservableObject or ViewModelBase.
  5. Q: How do you implement binding a button click to a method?
    A: Create a class that implements ICommand, often called RelayCommand or RoutedCommand.
    Add an ICommand property to your ViewModel and instantiate the property using your ICommand implementation, RelayCommand or RoutedCommand.

Level 2

  1. What gotchas have you experience while using the MVVM pattern?
    A: No real answer here…just that they have experienced problems proves their experience. Example issues:
    - The ViewModel just becomes a place for all the code-behind.
    - Determining whether the View can, should, or should not reference the ViewModel.
    - Determining if View objects can, should, or should not be in the ViewModel.
    - When breaking Views down, how small to go.
    - When breaking ViewModels down, how small to go.
    - Should an object in the model implement ObservableObject?
  2. Q: Why is it better to use an IValueConverter instead of  performing the conversion in the ViewModel?
    A: This follows the Don’t Repeat Yourself (DRY) principle. It also follows the Single Responsibility Principle (SRP).
    Because you may have to perform the same conversion between multiple View and ViewModel combinations. If each ViewModel has the code, the code is duplicated. If the code is in an IValueConverter, it exists in one place and is resusable.

Level 3

  1. Q: What does this command do and when would you use it? CommandManager.InvalidateRequerySuggested()
    A: It causes the any commands, such as a binding to Button.Command to check again if it can execute.
    It is used when the command runs and the button should be enabled when the command completes, but the button stays disabled. This often occurs when running the command on a thread or by using a BackgroundWorker.
  2. Q: When should you use “code-behind” in MVVM.
    Note: Don’t except ‘never’ as an answer.
    A: When the code only involves the View or WPF Controls in the View.
    A: When you need to implement events that do not support binding to ICommand.

Tuesday, 26 November 2013

WPF Interview Questions and Answers

What is WPF?


Windows Presentation Framework is the new
presentation API in WinFX. WPF is a two and three dimensional graphics engine. It has
the following capabilities:-
v Has all equivalent common user controls like buttons, check boxes sliders etc.
v Fixed and flow format documents
v Has all of the capabilities of HTML and Flash
v 2D and 3D vector graphics
v Animation
v Multimedia
v Data binding

What is XAML?


XAML (pronounced as Zammel) is a declarative XML-based language by which you can
define object and properties in XML. XAML document is loaded by a XAML parser.
XAML parser instantiates objects and set there properties. XAML describes objects,
properties and there relation in between them. Using XAML you can create any kind of
objects that means graphical or non-graphical. WPF parses the XAML document and
instantiates the objects and creates the relation as defined by XAML.

What are attached properties?


These are dependency properties that belong to one class but can be used in another.
Consider the below code snippet:-
<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" />
4 7 9
Height and Width are regular properties of the Rectangle. But Canvas.Top and Canvas.
Left is dependency property as it belongs the canvas class. It’s used by the Rectangle to
specify its position within Canvas.

What is a Routed event?


In a typical WPF application, it contains many elements. These elements exist in an element tree relationship with each other. A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

What are the core WPF assemblies?


The core WPF assemblies are,

WindowsBase.dll:- It defines the core types constituting the infrastructure of WPF API.

PresentationCore.dll:- Defines numerous types constituting foundation of WPF GUI layer.

PresentationFoundation.dll:- It defines WPF control types, animation & multimedia support, data binding suport and other WPF services.

Besides these three libraries WPF also uses an unmanaged binary called milcore.dll which acts as a bridge between WPF assemblies and DirectX runtime layer.

What is the use of System.Windows.Media namespace?


It is the root namespace to several other media related namespaces. It provides different types to work with animations, 3D rendering, text rendering and other multimedia services.

What is WPF?


Microsoft has introduced WPF(Windows Presentation Foundation) API in .NET3.0 framework for the first time. WPF merged all the unrelated APIs into a single unified object model. So if you want to use 3D graphics or multimedia for your application you do not use to need use different APIs. WPF provides all the functionalities you need to develop richer GUI applications.

Using WPF we can develop GUI for both windows application and web application.

How to define a button USING XAML?


To define a button in WPD using XAML use the following syntax,
<Button Name="btnName">btnCaption</Button>


Example:-
<Button Name="btnClick">Click Me</Button>

Here the <Button> element specifies the use of the Button class.

What is the use of "System.Windows.Markup" namespace in WPF?


The System.Windows.Markup namespace provides some helper classes for XAML code.

Which namespace provide classes for integration with WPF and Win32?


The "System.Windows.Interop" namespace provides classes for integration of WPF with Win32.

Which class of the WPF is the base class of all the user-interactive elements?


NOTE: This is objective type question, Please click question title for correct answer.

Which class is the base class of all the visual elements of WPF?


NOTE: This is objective type question, Please click question title for correct answer.

Control class of WPF is derived from which class?


NOTE: This is objective type question, Please click question title for correct answer.

The core classes for User Interface is located in which namespace?


NOTE: This is objective type question, Please click question title for correct answer.

Which namespace provide classes to work with images, sound, video, etc?


The System.Windows.Media namespace provide classes to work with images, sound, video, etc in WPF.

What is the use of System.Windows.Navigation namespace in WPF?


System.Windows.Navigation namespace contains different classes for navigation between windows.

What is 'One-way-to-Source ' binding property?


In One-way-to-Source binding when the target property changes, the source object gets updated.

Which namespace is used to work with 3D in WPF.


The System.Windows.Media.Medi3D namespace is used to work with 3D.

Which of these is not a class defined by System.Windows.Shapes namespace?


NOTE: This is objective type question, Please click question title for correct answer.

Consider this XAML snippet <Window.Resources> <Style x:Key="dd" TargetType="Button"> <Setter Property="Background" Value="Pink"/> <Setter Property="Foreground" Value="Blue"/> </Style> </Window.Resources> <Grid> <Button Height="100" Width="100" Foreground="Yellow" Content="click here" Background="Yellow"/> </Grid> What is the Backcolor of the Button

WPF Interview Questions List

  1. What is WPF?
  2. What are the types sibling libraries in WPF?
  3. What is the difference between WCF and WF?
  4. What is the use of cardspace?
  5. What operating systems does WPF currently support?
  6. What is XAML?
  7. What is the benefit of using a markup language for designing a user interface?
  8. What are the types of binding modes?
  9. What is the difference between a XAML file and a code-behind file?
  10. Which files are automatically added to a new WPF Application project?
  11. What is the purpose of the x:Name attribute in XAML?
  12. What is a feature of XAML that is available when it is compiled rather than interpreted?
  13. What is an attached property?
  14. What kind of documents are supported in WPF?
  15. What is the difference between fixed format documents and flow format documents?
  16. What is the difference between a Panel and a Decorator?
  17. What is the feature of silverlight 4?
  18. What is the purpose of AccessText?
  19. What are the types of Inlines that can be used in a TextBlock?
  20. What is the most common format for declaring a data binding in markup?
  21. Is x:Static the same as a data binding?
  22. How many ways are there to deploy WPF applications, and what are they?
  23. How do navigation applications differ from standard WPF applications?
  24. What type of elements can be hosted in a ToolBar?
  25. What is the simplest and most common way to componentize a complex UI?
  26. What class is used to save and load the content of a RichTextBox?
  27. What are the types of binding in WPF?
  28. What is the difference between key binding and mouse binding?
  29. What type is used to render WPF output to a bitmap?
  30. What is the base class for all renderable types in WPF?
  31. What is a repository?
  32. What are the types of common file dialogs that WPF supports?
  33. What is the name of the FrameworkElement most commonly used to work with media in WPF?
  34. What are two common properties on all the Shape classes?
  35. What are the different types of brushes that WPF offers?
  36. What are the four channels of a WPF Color object?
  37. What are the types of bitmap effects?
  38. What are the two types of transforms present on FrameworkElement?
  39. What is Windows Workflow Foundation?
  40. What is a Workflow?