Sunday, August 4, 2013

Extension Methods (C# Programming Guide) Part I

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable andSystem.Collections.Generic.IEnumerable<T> types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable<T> appears to have instance methods such as GroupBy, OrderBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type "dot" after an instance of an IEnumerable<T> type such as List<T> or Array. 
The following example shows how to call the standard query operator OrderBy method on an array of integers. The expression in parentheses is a lambda expression. Many standard query operators take lambda expressions as parameters, but this is not a requirement for extension methods. For more information, see Lambda Expressions (C# Programming Guide).
class ExtensionMethods2    
{

    static void Main()
    {            
        int[] ints = { 10, 45, 15, 39, 21, 26 };
        var result = ints.OrderBy(g => g);
        foreach (var i in result)
        {
            System.Console.Write(i + " ");
        }           
    }        
}
//Output: 10 15 21 26 39 45
Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
The following example shows an extension method defined for the System.String class. Note that it is defined inside a non-nested, non-generic static class:
namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}
The WordCount extension method can be brought into scope with this using directive:
using ExtensionMethods;
And it can be called from an application by using this syntax:
string s = "Hello Extension Methods";
int i = s.WordCount();
In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method. Therefore, the principle of encapsulation is not really being violated. In fact, extension methods cannot access private variables in the type they are extending.
In general, you will probably be calling extension methods far more often than implementing your own. Because extension methods are called by using instance method syntax, no special knowledge is required to use them from client code. To enable extension methods for a particular type, just add a using directive for the namespace in which the methods are defined. For example, to use the standard query operators, add this using directive to your code:
using System.Linq;
(You may also have to add a reference to System.Core.dll.) You will notice that the standard query operators now appear in IntelliSense as additional methods available for most IEnumerable<T> types.
NoteNote
Although standard query operators do not appear in IntelliSense for String, they are still available.

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself. In other words, if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method. When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds. The following example demonstrates how the compiler determines which extension method or instance method to bind to.

The following example demonstrates the rules that the C# compiler follows in determining whether to bind a method call to an instance method on the type, or to an extension method. The static class Extensions contains extension methods defined for any type that implements IMyInterface. Classes A, B, andC all implement the interface.
The MethodB extension method is never called because its name and signature exactly match methods already implemented by the classes.
When the compiler cannot find an instance method with a matching signature, it will bind to a matching extension method if one exists.
// Define an interface named IMyInterface. 
namespace DefineIMyInterface
{
    using System;

    public interface IMyInterface
    {
        // Any class that implements IMyInterface must define a method 
        // that matches the following signature. 
        void MethodB();
    }
}


// Define extension methods for IMyInterface. 
namespace Extensions
{
    using System;
    using DefineIMyInterface;

    // The following extension methods can be accessed by instances of any  
    // class that implements IMyInterface. 
    public static class Extension
    {
        public static void MethodA(this IMyInterface myInterface, int i)
        {
            Console.WriteLine
                ("Extension.MethodA(this IMyInterface myInterface, int i)");
        }

        public static void MethodA(this IMyInterface myInterface, string s)
        {
            Console.WriteLine
                ("Extension.MethodA(this IMyInterface myInterface, string s)");
        }

        // This method is never called in ExtensionMethodsDemo1, because each  
        // of the three classes A, B, and C implements a method named MethodB 
        // that has a matching signature. 
        public static void MethodB(this IMyInterface myInterface)
        {
            Console.WriteLine
                ("Extension.MethodB(this IMyInterface myInterface)");
        }
    }
}


// Define three classes that implement IMyInterface, and then use them to test 
// the extension methods. 
namespace ExtensionMethodsDemo1
{
    using System;
    using Extensions;
    using DefineIMyInterface;

    class A : IMyInterface
    {
        public void MethodB() { Console.WriteLine("A.MethodB()"); }
    }

    class B : IMyInterface
    {
        public void MethodB() { Console.WriteLine("B.MethodB()"); }
        public void MethodA(int i) { Console.WriteLine("B.MethodA(int i)"); }
    }

    class C : IMyInterface
    {
        public void MethodB() { Console.WriteLine("C.MethodB()"); }
        public void MethodA(object obj)
        {
            Console.WriteLine("C.MethodA(object obj)");
        }
    }

    class ExtMethodDemo
    {
        static void Main(string[] args)
        {
            // Declare an instance of class A, class B, and class C.
            A a = new A();
            B b = new B();
            C c = new C();

            // For a, b, and c, call the following methods: 
            //      -- MethodA with an int argument 
            //      -- MethodA with a string argument 
            //      -- MethodB with no argument. 

            // A contains no MethodA, so each call to MethodA resolves to  
            // the extension method that has a matching signature.
            a.MethodA(1);           // Extension.MethodA(object, int)
            a.MethodA("hello");     // Extension.MethodA(object, string) 

            // A has a method that matches the signature of the following call 
            // to MethodB.
            a.MethodB();            // A.MethodB() 

            // B has methods that match the signatures of the following 
            // nethod calls.
            b.MethodA(1);           // B.MethodA(int)
            b.MethodB();            // B.MethodB() 

            // B has no matching method for the following call, but  
            // class Extension does.
            b.MethodA("hello");     // Extension.MethodA(object, string) 

            // C contains an instance method that matches each of the following 
            // method calls.
            c.MethodA(1);           // C.MethodA(object)
            c.MethodA("hello");     // C.MethodA(object)
            c.MethodB();            // C.MethodB()
        }
    }
}
/* Output:
    Extension.MethodA(this IMyInterface myInterface, int i)
    Extension.MethodA(this IMyInterface myInterface, string s)
    A.MethodB()
    B.MethodA(int i)
    B.MethodB()
    Extension.MethodA(this IMyInterface myInterface, string s)
    C.MethodA(object obj)
    C.MethodA(object obj)
    C.MethodB()
 */

Saturday, August 3, 2013

silverlight Question (PART I)

What is XAML ?
Extensible Application Markup Language (XAML, pronounced zammel) is a declarative XML-based language created by Microsoft which is used to initialize structured values and objects.

What is the difference between WPF and Silverlight?
Silverlight uses a particular implementation of a XAML parser, with that parser being part of the Silverlight core install. In some cases, the parsing behavior differs from the parsing behavior in Windows Presentation Foundation (WPF), which also has a particular implementation.

Can you name built-in layout panels you have been using with Silverlight?

You are looking for Canvas, StackPanel and Grid

What is Storyboard?

Storyboard is a Silverlight class with controls animations with a timeline, and provides object and property targeting information for its child animations 
Given XAML below
Code:
<Canvas>
<Ellipse x:Name="ellipseTest" Height="20" Width="20" Canvas.Left="0" Canvas.Top="10" />
</Canvas>

How can you set image Source dynamically from C# application to” test.png” file?
Surprisingly it is not as straight forward as it might sound, but anyone who seriously worked with Silverlight should be easily answer it.

One of the ways is: 
Code:
img.Source = new BitmapImage(new Uri("test.png", UriKind.Relative));

Given XAML below
Code:
<Canvas>
< Rectangle x:Name="test" Height="20" Width="20" Canvas.Left="0" Canvas.Top="10" />
</Canvas>

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:
1- Input events
2- 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.

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.
Quote: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.
Quote:What is a .xap file?
A .xap file is a Silverlight-based application package (.xap) that is generated when the Silverlight project is built.
Quote: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.
Quote: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.
Quote: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.

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.
Code:
<UserControl x:Class="SilverlightApplication2.MainPage"
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="300"><Grid x:Name="LayoutRoot" Background="White"></Grid></UserControl>

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.
Code:
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)

Interview and Question and Answer

Categories


.NET Certifications Interview Questions.NET Framework Interview QuestionsADO.NET Interview Questions
Aptitute Test Interview QuestionsASP.NET Interview QuestionsASP.NET AJAX Interview Questions
ASP.NET MVC Interview QuestionsAzure Interview QuestionsBest Practices Interview Questions
BizTalk Server Interview QuestionsC# Interview QuestionsCloud Interview Questions
CMS Interview QuestionsCSS Interview QuestionsDotNetFunda.Com Interview Questions
Error and Resolution Interview QuestionsF# Interview QuestionsFunction Points (FPA) Interview Questions
HR Interview QuestionsHTML 5 Interview QuestionsIIS Interview Questions
Interview Questions Interview QuestionsJavaScript Interview QuestionsjQuery Interview Questions
Kinect Interview QuestionsLightSwitch Interview QuestionsLINQ Interview Questions
Management Interview QuestionsMobile Development Interview QuestionsMule Interview Questions
Networking Interview QuestionsNews and Community Interview QuestionsNoSql Interview Questions
OOPS Interview QuestionsOracle Interview QuestionsOthers Interview Questions
Pattern and Practices Interview QuestionsPostgreSQL Interview QuestionsPowerShell Interview Questions
Product Reviews Interview QuestionsProject Management Interview QuestionsQA (Testing) Interview Questions
Regular Expressions Interview QuestionsSEO Interview QuestionsSharePoint Interview Questions
Silverlight Interview QuestionsSql Server Interview QuestionsUML Interview Questions
VB.NET Interview QuestionsVisual Studio 2010/12 Interview QuestionsWCF Interview Questions
Web Analytics Interview QuestionsWeb Services, Remoting Interview QuestionsWindows 8 Interview Questions
Windows Forms Interview QuestionsWindows Metro Interview QuestionsWindows Phone Interview Questions
WPF Interview QuestionsWWF Interview QuestionsXML Interview Questions

Commonly Asked WPF Interview & Ans Part I

Commonly Asked WPF Interview Questions and Answers (Part 1)

In this aritcle on "Commonly Asked WPF Interview Questions and Answers (Part 1)", I will focus on very simple and basic WPF interview questions which a WPF developer should know. These WPF interview questions are based on general introduction of WPF, XAML, MVVM Pattern, Comparison of WPF and Silverlight, Layout Panels in WPF and WPF UserControls / CustomControls.

1. What is WPF?

The Windows Presentation Foundation is Microsofts next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher.

WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

2. What is XAML?

Extensible Application Markup Language, or XAML (pronounced "zammel"), is an XML-based markup language developed by Microsoft. XAML is the language behind the visual presentation of an application that you develop in Microsoft Expression Blend, just as HTML is the language behind the visual presentation of a Web page. Creating an application in Expression Blend means writing XAML code, either by hand or visually by working in the Design view of Expression Blend.

3. What is MVVM Pattren?

Model-View-ViewModel (MVVM) pattern splits the User Interface code into 3 conceptual parts - Model, View and ViewModel.

Model is a set of classes representing the data coming from the services or the database.

View is the code corresponding to the visual representation of the data the way it is seen and interacted with by the user.

ViewModel serves as the glue between the View and the Model. It wraps the data from the Model and makes it friendly for being presented and modified by the view. ViewModel also controls the View's interactions with the rest of the application

4. What is the difference between MVVM and MVC patterns?

MVVM Model-View ViewModel is similar to MVC, Model-View Controller.

The controller is replaced with a View Model. The View Model sits below the UI layer. The View Model exposes the data and command objects that the view needs. You could think of this as a container object that view goes to to get its data and actions from. The View Model pulls its data from the model.

5. What are the similarities and differences between WPF and Silverlight?

Similarities between Silverlight and WPF

1. Silverlight and WPF both use XAML.
2. Silverlight and WPF share same syntax, code and libraries.


Difference between WPF and Silverlight

1. WPF  is tool for writing full-featured desktop applications that run on Windows while Silverlight is for web application.

2. WPF competes with Windows Forms only for writing desktop applications while Silverlight competes with Flash, Java web apps etc.

6. What is the need of layout panels in WPF?

Layout of controls is critical to an applications usability. Arranging controls based on fixed pixel coordinates may work for an limited enviroment, but as soon as you want to use it on different screen resolutions or with different font sizes it will fail. WPF provides a rich set built-in layout panels that help you to avoid the common pitfalls.

7. What are the different types of layout panels in WPF?

There are mainly 5 types of layout panels in WPF. These are: 

Grid Panel
Stack Panel
Dock Panel
Wrap Panel
Canvas Panel


8. How to create a User Control and then how to use it in a WPF application?

User Controls are commonly used in a WPF application. So you should know this concept and you should be able to write a simple program to show how usercontrols are created and used in WPF application. I am sharing a link which created and uses usercontrol in very simple manner. Have a look:

9. What is the difference between UserControl and CustomControl in WPF?

UserControl (Composition)

Composes multiple existing controls into a reusable "group"
Consists of a XAML and a code behind file
Cannot be styled/templated
Derives from UserControl


CustomControl (Extending an existing control)

Extends an existing control with additional features
Consists of a code file and a default style in Themes/Generic.xaml
Can be styled/templated
The best approach to build a control library.

Commonly Asked WPF Interview Questions and Answers (Part 2)

I had written some basic WPF interview questions and answers in my previous article "Commonly Asked WPF Interview Questions and Answers (Part 1)". Now its time to dive deep into the WPF and explore some advanced but commonly asked WPF questions. I have written separate articles on following WPF interview questions, so I would not be answering these questions here but I would provide links for them where you can study them in detail. These WPF interview questions cover the concepts of Dependency and Attached Properties, Routed Events and Commands in WPF, Different Modes of Bindings in WPF, Static and Dynamic Resources, Window and Page Controls, Relations of Window Forms and Silverlight with WPF etc.

Following is the list of WPF interview questions and you can find detailed answers of these questions by clicking on them.