Pages

Thursday, 30 May 2013

Commonly Used WPF Namespaces

Commonly Used WPF Namespaces

I have tried to compile a list of common WPF namespaces used in any WPF application. While developing my WPF application, I noticed some commonly and frequently used namespaces which I had to include in each and every file, so I tried to list them down in a single place in the form of an article.

If you are preparing for WPF interview, this article will surely help you as namespaces related questions are frequently asked in WPF interviews.

I have taken all the references of namespaces mentioned below from microsoft documentation.

If any common namespace is missing, you can mention them in comments below. So here goes the list of common WPF namespaces.


Provides types that enable integration of rich media, including drawings, text, and audio/video content in Windows Presentation Foundation (WPF) applications.

Related namespaces:

System.Windows.Media.Animation
System.Windows.Media.Effects
System.Windows.Media.Imaging
System.Windows.Media.Media3D
System.Windows.Media.TextFormatting
System.Windows.Navigation


Provides access to a library of shapes that can be used in Extensible Application Markup Language (XAML) or code.


Provides types that support navigation, including navigating between windows and navigation journaling.


Provides types to support the Windows Presentation Foundation (WPF) input system.


The System.Windows.Forms namespace contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in in the Microsoft Windows operating system.


Contains types that support FixedDocument, FlowDocument, and XML Paper Specification (XPS) document creation.


Contains classes used for binding properties to data sources, data source provider classes, and data-specific implementations of collections and views.


Provides classes to create elements, known as controls, that enable a user to interact with an application. The control classes are at the core of the user's experience with any application because they allow a user to view, select, or enter data or other information.


Provides support for Windows Presentation Foundation (WPF) UI Automation clients.


Provides classes to interact with and manipulate ink on the Windows Presentation Foundation (WPF) platform.


Contains types that provide managed code access to the enhanced functionality of the Windows 7 taskbar.


This WPF namespace is used when you use INotifyPropertyChanged interface in your application.


This namespace is used to implement ObservableCollection in your WPF application.


Microsoft.Practices.Prism.dll
Microsoft.Practices.Prism.UnityExtensions.dll
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.Unity.dll

Wednesday, 29 May 2013

Online Accredited Degree Programs and Distance Learning offered by Kalpan University

Online Accredited Degree Programs and Distance Learning offered by Kalpan University

Kalpan University provides a lot of online accredited degree programs and courses in various streams to the students all around the world. Kalpan University is a higher education online distance learning university which offers undergraduate, graduate and post graduate degree online programs.

Kalpan University conducts regular academic lectures through video conferencing, live audio & video streaming facilities. All of the University’s academic staff is available round the clock, and can be contacted by students via email.

Kalpan University also offers several new scholarships and grants for first-time enrolling students.

About Kalpan University

Kalpan University was founded in 1937 by Kalpan Group. Kalpan Group also owns the Washington Post. Kalpan University is headquartered in Davenport, Iowa, U.S., but has formal administrative office in Fort Lauderdale, Florida.

Kalpan University Accreditation Status

Kaplan University Online is accredited under the charter of Higher Learning Commission and is a member of the North Central Association of Colleges and Schools (NCA).

Kalpan Univerisity nursing school is accredited by the Commission of Collegiate Nursing Education (CCNE).

Online Accredited Degree Programs offered by Kalpan University

As stated at the begining of article, Kalpan University provides a lot of online degree and distance learning programs to the students residing all around the world. Following is the list of online degree programs offered by Kalpan University.

1. Online Arts and Sciences Degrees
2. Online Law and Criminal Justice Degrees
3. Online Nursing Degrees
4. Online Health Sciences and Medical Degrees
5. Online Business, Finance, MBA and Management Degrees
6. Online Accounting Degrees
7. Online Information Systems and Technology, Communication and various Engineering Degrees

Kalpan University Faculty and Student Enrollment Statistics

1. About 60,000 students have been enrolled by Kalpan University till now.
2. There are more than 3600 professors and instructors in Kalpan University.

Friday, 24 May 2013

SONAR: Tool for Maintaining Coding Standards and Conventions


SONAR: Tool for Maintaining Coding Standards and Conventions

SONAR is an open source platform used by development teams to manage source code quality. Sonar has been developed with this main objective in mind: make code quality management accessible to everyone with minimal effort. 

Sonar provides code analyzers, reporting tools, manual reviews, defect-hunting modules, and TimeMachine as core functionalities. It also comes with a plugin mechanism enabling the community to extend the functionality, making Sonar the one-stop-shop for source code quality by addressing not only the developer’s requirements, but also the manager’s needs.

Coding standards are defined by sets of rules governing programming style for a particular programming language. Although they differ from language to language, the objective is the same—to provide consistent, clean, readable code. Of course, development teams have different requirements and develop their own rule sets customized to their own preferences and programming habits. However, while the coding standards matter is subjective, the goal remains the same and many common rules apply to all projects among different programming languages.

Features of SONAR: 

1. Offers reports on duplicated code, coding standards, unit tests, code coverage, complex code, potential bugs, comments and design and architecture.

2. Primary supported language is Java. Other languages are supported with extensions. Several open source and commercial extensions can cover the following languages: C, C#, PHP, Flex, Groovy, JavaScript, Python, PL/SQL, COBOL and Visual Basic 6.

Why to use SONAR?

Most mature software development companies or departments define their coding standards.  The intentions is simple; ensure all code looks alike to ease reading, writing, maintaining and communicating code.  As a first effort, these coding conventions may be expressed in some form of standalone document, but conventions that are not being enforced are simply a waste of time. In this case SONAR is very helpful which can enforce these coding standards to developers and management.

Components of SONAR

Sonar is made of a fairly simple and flexible architecture that consists of three components:

1. A set of source code analyzers that are grouped in a Maven plugin and are triggered on demand. The analyzers use configuration stored in the database. Although Sonar relies on Maven to run analysis, it is capable to analyze Maven and non-Maven projects.

2. A database to not only persist the results of the analysis, the projects and global configuration but also to keep historical analysis for TimeMachine. 5 database engines are currently supported : Oracle, MySQL, Derby (demo only), PostgreSQL and MS SQLServer.

3. A web reporting tool to display code quality dashboards on projects, hunt for defects, check TimeMachine and to configure analysis.

C# Best Coding Practices for Developers to Follow


C# Best Coding Practices for Developers to Follow

In this article, I will try to list down some C# best practices which a C# developer must follow during development of a project. These common guidelines include use of proper naming conventions in C#, where and why to use value type and reference type variables, using properties instead of public variables in the class, using nullable types, proper exception handling, using runtime constants instead of compile time, using StringBuilder for concatenation, using foreach for collections, proper handling of comments and regions, use of IDisposable Interface etc. Lets dive deep into these C# best practices.

1. Use proper naming convention

A) Always use Camel case (A word with the first letter lowercase, and the first letter of each subsequent word-part capitalized) while declaring variables.

B) Use Pascal (A word with the first letter capitalized, and the first letter of each subsequent word-part capitalized) naming format while declaring Properties.

C) Avoid all uppercase or lowercase names for properties, variables or method names. Use all uppercase when declaring const variables.

D) Never use a name that begins with a numeric character.

E) Always prefer meaningful names for your class, property, method, etc. This will be very useful for you to maintain the code in future. For example, “P” will not give proper meaning for a class. You will find it difficult to know about the class. But if you use “Person”, you will easily understand by it.

F) Never build a different name varied by capitalization. It is a very bad practice. It will not be useful while developing code, as you will not know what is “person” class and what is “Person” class!!! But from the above scenario, it can be very easily understandable that “person” is an instance variable of “Person” class.

G) DO NOT use Abbreviations.

H) DO NOT use Underscores in identifiers.

I) Don't use the same name used in .NET Framework. People who are new to your code have great difficulty to understand it easily.

J) Avoid adding prefixes or suffixes for your identifiers.

K) Always use “I” as prefix for Interfaces. This is a common practice for declaring interfaces.

L) Always add “Exception” as suffix for your custom exception class. It will give better visibility to your exception class.

M) Never prefix or suffix the class name to its property names. It will unnecessarily increase the property name. If “Firstname” is a property of “Person” class, you can easily identify it from that class directly. No need to write “PersonFirstname” or “FirstnameOfPerson”.

N) Prefix “Is”, “Has” or “Can” for boolean properties like “IsVisible”, “HasChildren”, “CanExecute”. These give proper meaning to the properties.

O) Don't add prefix for your controls, instead write proper name to identify the control.

P) Declare all member variables at the top of a class, with static variables at the very top. This will make your code more readable. You dont need to find the variable in class if they are declared at the top and static variables are loaded at first so they have to be on very top so code flow and your code match.

2. Decide between value type and reference type. 

Whenever you need to create a type, first ask yourself a question “What you want and Why you want it?”. If you could answer your question, you can decide between the type you want to use. If you want to store your data, use value types and when you want to create an instance of your type by defining the behavior, use reference types. Value types are not Polymorphic whereas, the Reference types can be. Value types are most efficient in terms of memory utilization over reference types and produce less help fragmentation & garbage. If you want to pass values to a method implementation, decide what you want to do and based upon your requirement, decide between value types and reference types. Use of reference type variables actually change the original value but use of value type will create a copy of the original variable and pass across the method. Thus, it protects your original value from accidental changes.
    
3. Always use Properties instead of Public Variables

Reason behind this is, it makes your code properly encapsulated in OOPs environment. By using getters & setters, you can restrict the user directly accessing the member variables. You can restrict setting the values explicitly thus making your data protected from accidental changes. Also, properties give you easier validation for your data.

4. Use Nullable data types whenever required

Sometimes, you may need to store null as the value of an integer, double or boolean variable. So how can you do this? The normal declaration doesn't allow you to store the null as value. C# now has the feature of nullable data types. Just a small change in your declaration. That’s it!!! You are good to go for storing nullvalues. Only you have to use the “?” modifier. You have to place it just after the type.
    
5. Prefer Runtime constants over Compile time constants
        
Runtime constants are always preferred than the Compile time constants. Here you may ask what is runtime constant and what is compile time constant. Runtime constants are those which are evaluated at the runtime and declared with the keyword “readonly”. On the other side, compile time constants are static, evaluated at the time of compilation and declared with the keyword “const”.

6. Prefer String.Format() or StringBuilder for string concatenation

Any operation in the string will create a new object as string is a mutable object. If you want to concatenate multiple strings, it is always better to use string.Format() method or StringBuilder class for the concatenation.
    
7. Always prefer Foreach() loop

The foreach statement is a variation of do, while or for loops. It actually generates the best iteration code for any collection you have. When you are using collections, always prefer to use the foreach loop as the C# compiler generates the best iteration code for your particular collection. Have a look into the following implementation:
    
8. Properly utilize Try/Catch/Finally block

Properly utilize the try/catch/finally blocks. If you know that the code you wrote may throw some Exception, use the try/catch block for that piece of code to handle the exception. If you know that, the fifth line of your 10 lines code may throw exception, it is advisable to wrap that line of code only with thetry/catch block. Unnecessary surrounding lines of code with try/catch will slow down your application. Use the finally block to clean up any resources after the call. If you are doing any database call, close the connection in that block. The finally block runs whether your code executes properly or not. So, properly utilize it to cleanup the resources.

Catch only that Exception that you can handle. Catch only those which you expect and order it accordingly. Finally at the end, if you want, add the generic Exception to catch any other unknown exceptions. This gives you a proper way to handle the exception. Suppose, your code is throwingNullReferenceException or ArgumentException. If you directly use the Exception class, it will be very difficult to handle in your application. But by catching the exception properly, you can handle the problem easily.
    
9. Use IDisposable Interface

Use IDisposable interface to free all the resources from the memory. Once you implement IDisposableinterface in your class, you will get a Dispose() method there. Write code there to free the resources.
    
10. Keep Class size small

A class should adhere to Single Responsibility Principal.

“The single responsibility principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.” 

"THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE."

Each responsibility is an axis of change. When the requirements change, that change will be manifest through a change in responsibility amongst the classes. If a class assumes more than one responsibility, then there will be more than one reason for it to change. If a class has more then one responsibility, then the responsibilities become coupled. Changes to one responsibility may impair or inhibit the class’ ability to meet the others. This kind of coupling leads to fragile designs that break in unexpected ways when changed.

11. Avoid obsolete comments

"A comment that has gotten old, irrelevant, and incorrect is obsolete. Comments get old quickly.  It is best not to write a comment that will become obsolete.  If you find an obsolete comment, it is best to update it or get rid of it as quickly as possible.  Obsolete comments tend to migrate away from the code they once described.  They become floating islands of irrelevance and misdirection in the code."

Try to avoid comments on individual method or short class. Because most comments i have ever seen is trying to describe the purpose/intentions. Some cases comments are meaningless. Developers writes comments to increase the readability & maintainability . Make sure your comments are not making any noise. It will be great if you could name a method more meaningful instead of comments. I am suggesting because method names are more affective than comments. Most of the comments are meaningless noise.
    
12. Avoid unnecessary Region in Class

Regions are a feature of VS that allow you to surround blocks of code. It could be a single or multiple methods. The region exists because it is easier to navigate around the large file. The regions are used to hide ugly code or class that have exploded in size . If a class does too many things it also violates the Single Responsibility Principle. So next time whenever you will think for adding a new region to your file take step back and ask that is it possible to separate your region into a separate class.

13. Keep methods short

Split your logic into several small and simple methods. If methods are too long, sometimes it is difficult to handle them. It is always better to use a number of small methods based upon their functionality instead of putting them in a single one. If you break them in separate methods and in future you need to call one part, it will be easier to call rather than replicating the code. Also, it is easier to do unit testing for the small chunks rather than a big code. So, whenever you are writing a piece of code, first think of what you want to do. Based upon that, extract your code in small simple methods and call them from wherever you want. In general, a method should never be more than 10-15 lines long.
    
14. Avoid too many parameters

Declare a class instead of too many parameters. Creating a class that puts all these parameters together. This is generally a better design and valuable abstraction.

15. Avoid complex expression

Complex expression have some meaning behind them it is just hidden by those multiple expressions. We can Encapsulated the complex expression into that object by using a property. That code will be easier to read.

16. Consider Warnings as Error

We should remove warning as much as possible so they never turn into runtime errors.

17. Avoid multiple Exit points

This rule is very easy to follow. Developer should try to maintain single exit point and entry point

Conclusion: Always write better code. From my point of view better code has following characteristics:

A) Code that is easy to write, modify and extend
B) Code that has values and cares about quality
C) Code that is clean and talks/convey meaning
        
Why we need conventions

A) They help you transfer knowledge across projects
B) They help you learn code more quickly on a new project
C) They emphasize relationships among related items

10 Interesting Unix Commands You Should Know


10 Interesting Unix Commands You Should Know

Following is the collection of some of the interesting unix commands which you should know. These unix commands are based on network connections, SVN, find, list, history, lsof, sudo, until, git and cat. If you know some extra unix commands like following, please share them. Here goes the list of unix commands which I thought I must share.

1. How to get your top 100 unix commands?

history | sed "s/^[0-9 ]*//" | sed "s/ *| */\n/g" | awk '{print $1}' | sort | uniq -c | sort -rn | head -n 100 > commands.txt

2. How to copy a file to all subfolders of a directory using unix command?

find . -type d -exec cp pathtofile {}/ \;

3. How to delete all .svn folders from current directory using unix command?

find . -type d -name '.svn' -print -exec rm -rf {} \;

4. How to list all network connections (including which app they belong to)?

lsof -i -nP

5. How to run the last command as root?

sudo !!

6. How to execute the previous command until it is successful?

until !!; do :; done

7. How to display summary of git commit ids and messages for a given branch?

git log --pretty='format:%Cgreen%H %Cred%ai %Creset- %s'

8. How to list all file extensions present in the current directory?

ls | perl -lne '++$x{lc $1} if /[.](.+)$/ }{ print for keys %x'

9. How to get your top 10 commands with number of times you have used it?

cat .bash_history | cut -f 1 -d\ | sort | uniq -c | sort -r | head

10. How to generate list of usernames from an svn logs (Run from top level of the svn project)?

svn log | grep -E "r[0-9]+ \| .+ \|" | awk -F"|" '{print $2}' | sort | uniq > ~/authors.txt

Saturday, 18 May 2013

Difference between IEnumerable, ICollection and IList Intrefaces in C#

Difference between IEnumerable, ICollection and IList Intrefaces in C#

Below article demonstrates the difference between IEnumerable, ICollection and IList Intrefaces. IEnumerable interface is the core interface and is implemented by ICollection and IList. Lets have a look.

IEnumerable

Its a core interface which is used to iterate over collection of specified type. Mainly implements two methods:

MoveNext: which is of boolean type which tells whether there are more records to move on or not.

GetCurrent: which returns the current record from the collection.
 
ICollection: Implements IEnumerable

It is an interface used to manipulate generic collections, as it implements IEnumerable interface so its obvious that this will also implements methods MoveNext and GetCurrent, so with this interface you can iterate through collection. Apart from this its also having its own methods like:

Add: Adds record at the end of collection
Remove: Removes specified item from collection
Contains: Its a boolean type method which tells whether collection contains the specified item or not.

IList

Interface which is collection of non-generic type objects and can be accessed by index. It is the interface which implements two interfaces ICollection and IEnumerable. So its obvious that this will Implements the methods of the both the interfaces. Its own methods are:

Insert: Insert the given item at specified Index.
RemoveAt: Removes the item from specified Index.
IndexOf: Retrieves the item from specified Index.

SUO File in .NET Visual Studio Projects

SUO File in .NET Visual Studio Projects

The solution user options (.suo) file is a structured storage, or compound, file stored in a binary format. You save user information into streams with the name of the stream being the key that will be used to identify the information in the .suo file. (as per Microsoft Documentation)

What information does the suo file contain?

A Solution user option file, is a binary file, which is specific to a given user, and is not version controlled. The .suo files contain user dependant information, like the state of the solution explorer and your last configuration settings like:

1. Visual Studio TABS Information

What tabs you left open the last time you worked on the project in visual studio, so those tabs are open again when you reload the project in Visual Studio. So, suo files track which windows were open when the solution was closed and opens those again when visual studio is again opened.

2. Breakpoint Information and Watch Window Settings

suo file also contains all your breakpoints. When you debug your project next time when you load visual studio, same breakpoints are hit again.

3. Information about startup project

If in your solution, you have more than one projects and you have made one of the project as startup project, suo file will contain that information in it. Next time when you run the visual studio, you will see the same project is set as startup project.

Problems with suo files:

Sometimes the suo file gets so large which affects the performance of visual studio and visual studio becomes slow and starts hanging. In such scenarios, you must delete suo file from your project.

Tuesday, 14 May 2013

What is the Need of Prism and Composite Applications in .NET?


What is the Need of Prism and Composite Applications in .NET?

Prism is used to design and build rich, flexible, and easy-to-maintain Windows Presentation Foundation (WPF) desktop applications. Prism helps you to make WPF application with loosely coupled components and these components can be easily integrated into the main application. These types of applications are known as composite applications. 

Prism is also used in Silverlight and Windows Phone 7 applications.

Advantages of Prism and Composite Applications

1.  Prism helps in creating an application from modules that can be built, assembled / integrated, and, optionally, deployed by independent teams using WPF or Silverlight.

2. Minimize cross-team dependencies and allow teams to specialize in different areas, such as user interface (UI) design, business logic implementation, and infrastructure code development.

Components of Prism and Composite Applications

1. Shell: The shell is the host application into which modules are loaded. The shell provides the top-level window or visual element that will then host the different UI components provided by the loaded modules.

2. Regions. Regions are logical placeholders defined within the the Shell into which views of Modules are displayed. 

3. Modules: Modules are packages of functionality that can be independently developed, tested, and deployed. The module contains the views and services specific to a piece of the application's functionality. 

Modules use shell's regions for placing content. During initialization, modules use the RegionManager to locate regions in the shell and add one or more views to those regions or register one or more view types to be created within those regions. 

4. Catalog: In a composite application, modules must be discovered and loaded at run time by the host application. In Prism, a module catalog is used to specify which modules to are to be loaded, when they are loaded, and in what order.

5. Bootstrapper: The bootstrapper is used to connect the application with the Prism Library and the Unity or MEF containers and initialize them.

Prism Library source code includes the source code for the Prism Library assemblies, including the core Prism functionality, plus Unity and MEF extensions, which provide additional components for using Prism with the Unity Application Block (Unity) and the Managed Extensibility Framework.

Monday, 13 May 2013

Difference between Build, Rebuild and Clean Solution in Visual Studio?


Difference between Build, Rebuild and Clean Solution in Visual Studio?

Build means compile and link only the source files that have changed since the last build, while Rebuild means compile and link all source files regardless of whether they changed or not. 

The Build Solution option compiles only those project files and components that have changed since the last build. For example consider that you have two projects Proj1 and Proj2 in your solution MySolution. When you compile the solution using Build Solution option after making some changes to Proj1 only Proj1 will be compiled and built but Proj2 will not be compiled since there are no changes to it.

A rebuild removes all the old files (performs a clean) and then builds all the files again.

Rebuild = Clean + Build

Rebuild Solution option builds all project files and components irrespective of the changes made to them.  For example consider that you have two projects Proj1 and Proj2 in your solution MySolution. When you compile the solution using Rebuild Solution option after making some changes to Proj1, both Proj1 and Proj2 will be compiled and built even though there are no changes made to Proj2.

Build is the normal thing to do and is faster. Sometimes the versions of project target components can get out of sync and rebuild is necessary to make the build successful. In practice, you never need to Clean.

When you build the project, the dll file are created/modified, but dll created date does not change. But when you Rebuild your project, the dll files are newly created with the current date .

Types of Build:

There are two types of build. A Release build is optimized and it does not contain any additional code that is created to allow you to debug the program in visual studio. A Debug build is not optimized, and it contains additional code that is used when you are debugging your program.

Difference between Encapsulation and Abstraction in OOPS


Difference between Encapsulation and Abstraction in OOPS

Abstraction and Encapsulation are two important Object Oriented Programming (OOPS) concepts. Encapsulation and Abstraction both are interrelated terms. 

Real Life Difference Between Encapsulation and Abstraction

Encapsulate means to hide. Encapsulation is also called data hiding.You can think Encapsulation like a capsule (medicine tablet) which hides medicine inside it. Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation. 

Abstraction refers to showing only the necessary details to the intended user. As the name suggests, abstraction is the "abstract form of anything". We use abstraction in programming languages to make abstract class. Abstract class represents abstract view of methods and properties of class.

Implementation Difference Between Encapsulation and Abstraction

1.  Abstraction is implemented using interface and abstract class while Encapsulation is implemented using private and protected access modifier.

2. OOPS makes use of encapsulation to enforce the integrity of a type (i.e. to make sure data is used in an appropriate manner) by preventing programmers from accessing data in a non-intended manner. Through encapsulation, only a predetermined group of functions can access the data. The collective term for datatypes and operations (methods) bundled together with access restrictions (public/private, etc.) is a class.

3. Example of Encapsulation

Class Encapsulation
{
    private int marks;

    public int Marks 
   {
      get { return marks; }
      set { marks = value;}
    }
}

4. Example of Abstraction

abstract class Abstraction
{
    public abstract void doAbstraction();
}

public class AbstractionImpl: Abstraction
{
    public void doAbstraction()
   {
       //Implement it
   }
}

Commonly Asked WPF Interview Questions and Answers (Part 2)


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.














Well, this is not the end, I will come with some more WPF interview questions on styles, themes, prism, composites, shell, MEF later on.

Wednesday, 8 May 2013

Difference between Dependency Property and Attached Property in WPF


Difference between Dependency Property and Attached Property in WPF

Attached properties are a type of dependency property. But there is a minor difference between dependency property and attached property in WPF. Lets try to understand them.

1. Concept and Usage of Attached Property and Dependency Property

Attached properties allows container to create a property which can be used by any child UI elements whereas dependency property is associated with that particular elements and can help in notification of changes and reacting to that changes.

Attached properties are basically meant for the container elements.like if you have a grid and you have grid.row, now this is considered to be an attached property of a grid element. Also you can use this property in texbox, button etc to set its place in the grid.

Attached properties are used a lot for layout-related information. For example, Canvas needs Left/Top coordinates, Grid needs a Row and a Column, DockPanel needs a Dock information etc. It would be a mess if all of this had to be declared on every control that can be layouted. So they are declared on the corresponding panel, but used on any control.

2. Implementation of Attached Property and Dependency Property

Attached properties and normal dependency properties include the methods used to register them with the DependencyObject. 

For attached properties, DependencyProperty.RegisterAttached and DependencyProperty.RegisterAttachedReadOnly are used and for dependency properties DependencyProperty.Register and DependencyProperty.RegisterReadOnly are used.

The difference between DependencyProperty.Register() and DependencyProperty.RegisterAttached() is that .Register() is used to register a 'regular' dependency property on a DependencyObject, while .RegisterAttached() is used to set an 'attached' dependency property.

Difference between StaticResource and DynamicResource in WPF


Difference between StaticResource and DynamicResource in WPF

There are lot of differences between Static Resource and Dynamic Resource in WPF. Lets try to understand them with the help of examples below:

1. The major difference between static and dynamic resources is that static resource will evaluate the resource only once while dynamic resource will be evaluated every time the resource needed.

2. Dynamic resource has more performance overhead than static resources because it look up for resources every time it requested or needed.

3. Static resource is faster but it takes little more time to load page or window than dynamic resource because dynamic resources are loaded when you actually use them.

Example of Static and Dynamic Resources

Below example gives you clear picture about Static and Dynamic resource markup extension.

XAML

<Window.Resources>
    <SolidColorBrush Color="LightBlue" x:Key="buttonBackground" />
</Window.Resources>
<StackPanel Name="stkPanel">
    <Button Name="Button1" Content="Button1"
            Background="{StaticResource buttonBackground}"/>
    <Button Name="Button2" Content="Button2"
            Background="{DynamicResource buttonBackground}"/>
    <Button Name="Button3" Content="Button3"
            Background="{StaticResource buttonBackground}"/>
</StackPanel>

Code behind

void StaticAndDynamicResources_Loaded(object sender, RoutedEventArgs e)
{
    stkPanel.Resources["buttonBackground"] = Brushes.Yellow;
}

Output

As shown in above example, three buttons are using buttonBackground resource defined in windows.resources element. Button1 and Button3 are using static resource markup extension while button2 is using dynamic resource markup extension. After loading of my window, I have changed color of buttonBackground resource from Lightblue to Yellow in code behind. So when I run my application, Button2 will have yellow background and rest of the buttons will have LightBlue background. The reason behind for not changing background of Button1 and Button3 because both button uses static resource and static resource is loaded only once with application while button2 uses dynamic resource and it changes every time when it accessed. 

Conclusion: The demerit of DynamicResource is that it reduces application performance because resources are retrieved every time they are used. The best practice is to use StaticResource until there is a specific reason to use DynamicResource.

Binding Modes in WPF: TwoWay, OneWay, OneTime and OneWayToSource


Binding Modes in WPF: TwoWay, OneWay, OneTime and OneWayToSource

The Mode attribute defines the binding mode that will determine how data flows between the source and the target. There are four types of binding modes in WPF:

1. TwoWay Binding Mode
2. OneWay Binding Mode
3. OneTime Binding Mode
4. OneWayToSource Binding Mode

1. TwoWay Binding Mode

You have the view connected with its ViewModel, so every change you make in one of them is reflected into the other. To obtain that kind of behavior, you have to implement the interface INotifyPropertyChange in your ViewModel or using Dependency Properties, instead of normal CLR properties.The default however is two-way.

This type of binding is appropriate for editable forms or other fully-interactive UI scenarios. Most properties default to OneWay binding, but some dependency properties (typically properties of user-editable controls such as the Text property of TextBox and the IsChecked property of CheckBox) default to TwoWay binding. A programmatic way to determine whether a dependency property binds one-way or two-way by default is to get the property metadata of the property using GetMetadata and then check the Boolean value of the BindsTwoWayByDefault property.

2. OneWay Binding Mode

In one way mode, data flows from the source to the target each time a change is made on the source (ViewModel). OneWay binding is the default binding mode for the TextBlock's Text property and does not need to be specified. 

This type of binding is appropriate if the control being bound is implicitly read-only. For instance, you may bind to a source such as a stock ticker or perhaps your target property has no control interface provided for making changes, such as a data-bound background color of a table. If there is no need to monitor the changes of the target property, using the OneWay binding mode avoids the overhead of the TwoWay binding mode.

3. OneTime Binding

Like OneWay binding, OneTime binding sends data from the source to the target; however, it does this only when the application is started. When the DataContext changes, it does not listen for change notifications in the source. 

OneTime binding causes the source property to initialize the target property, but subsequent changes do not propagate. This means that if the data context undergoes a change or the object in the data context changes, then the change is not reflected in the target property. This type of binding is appropriate if you are using data where either a snapshot of the current state is appropriate to use or the data is truly static. This type of binding is also useful if you want to initialize your target property with some value from a source property and the data context is not known in advance. This is essentially a simpler form of OneWay binding that provides better performance in cases where the source value does not change.

4. OneWayToSource Binding Mode

OneWayToSource is the reverse of OneWay binding. Unlike OneWay and OneTime binding, OneWayToSource binding sends data from the target to the source.