WPF StringFormat example in Binding



In this small article we will see how we can use StringFormat when we use Binding.
In the example we have use one Date Picker and one TextBlock. The TextBlock isbound with the SelectedDate property of the DatePicker.And we have used StringFormat property to modify the text shown in TextBlock.

Sample Code:

Difference between BOSS and LEADER



Have you ever wondered, what is the difference between a BOSS and a LEADER?
Some may feel that they both have same role to play whereas others may feel that they are different.
But we must know that Leadership cannot be demanded – only earned and deserved.
In this article we have listed some of the differences which we feel exists between them and their roles. It is a must read for people, who are in any leadership position in any organization, and then decide whether they are a BOSS or a LEADER.
















Custom / Partial Projection in LINQ to Hashtable / Dictionary

Like SQL we can project partial or custom data in output. In the output of LINQ Query it will be an enumerable collection of anonymous type. This anonymous type is being created by using new operator in the select clause and member fields are generated dynamically in the select new part of the LINQ.

Consider a data dictionary and structure as followed:
public static Dictionary<int, marks> stuResult;
public struct marks
{
   public int m_hindi;
   public int m_english;
   public int m_maths;
}

Consider marks is structure datatype which contains marks details of a student. stuResult Dictionary contains RollNo(int), as key and object of marks as its value. Now we have to find out the Total marks obtained by each students. To find this LINQ will be as:

Where Clause with LINQ to Hashtable / Dictionaries

In this article, we will discuss How can we use where clause in LINQ to Object(Hastable / Dictionaries). Many time  while working with the Dictionaries or Hashtables, we may require to find out the values from them which satisfies some specific criteria. In that case we used to write iterations and then find the values which satisfies the criteria. Maybe writing the loop is a easy task for the beginners, but writing code for checking the values and performing the operations are so boring and tedious task.For the checking the values   for specific criteria we need to declare intermediate variables etc. But by using LINQ, this can be done so easily with few lines of code even without using iterations.

LINQ: Join operations on Hashtables / Dictionaries

In this example we will discuss, how to perform Join operation on dictionaries / hash tables. 
Consider 2 Dictionaries, one dictionary contains Roll No (Int) as key and a Structure (marks) (which contains marks of student) as value. Another dictionary contains Roll No(Int) as key and Name of Student (String) as value. Now we have to find name of students and corresponding marks of the students. 

So in this case we will perform Join on the key of both dictionaries and will have enumerable collection of KeyValue pairs (key will be name of student and value will have marks details) in the query result.

     var QueryResult = from mrks in stuResult.AsEnumerable<KeyValuePair<int, marks>>()
                       join pd in stuPDetails.AsEnumerable<KeyValuePair<int, string>>()
                       on mrks.Key equals pd.Key
                       select new KeyValuePair<String, marks>(pd.Value, mrks.Value);

Above mentioned LINQ query will perform join operation on the key values of the dictionaries. Finally selects the new KeyValue pairs having String(Name of Student) as key, marks(Marks details of the student) as value.

Example of JOIN on Dictionaries

C# Sending Information / data from Child to Parent class using events and delgates

In the previous post C# Notify Parent From Child using events and delegates , we were just notifying the parent class about some processing happening in the child class.

 But we were not sending any information or data to parent class about what processing is happening in child class. We have taken the same example taken in C# Notify Parent From Child using events and delegates and modified a bit so that we can send information to parent about the processing happening in Child class.
Previously, in Parent we were getting information that some key is pressed in Child Class. Now we will send the information that which key is pressed in Child class.

We have modified the delegate to be method with parameters. Now the signature of the event handler will also change. Also we have defined a custom class "CustomEventArgs" which has one public property i.e Key, which has the information about the pressed key.

Now whenever Child class raises an event, it will create and instance of CustomEventArgs and send it to all the event listeners. So all the event listeners, in our case the Parent class, will get the information about which key is pressed.

Source Code:


Operations on specific elements of array by using LINQ

Here I am considering count operation has to be performed on array. As we know that if sum of specific elements of array is to be found, then we have to iterate the array and check whether element of the array satisfies the predicate or not. If it satisfies then increase the count else ignore it. But how is it, if I say that we need not to iterate the array to find the count or any such kind of operations.

Consider an integer array (arr is an array for our code) having n elements. we have to find out how many elements are there which are greater than or equals to 75.

Iteration method to find the count

            int count = 0;
            for (int i = 0; i < arr.Length; i++)
                if (arr[i] >= 75) count++;

What, if we can write SQL like query in C# also to perform these kind of operations. LINQ introduced in .net framework 3.5, provides us such facilities.

LINQ for above Operation

Introduction to LINQ

Language INtegrated Query (LINQ) was introduced very 1st with the .Net framework 3.5. it bridges the gap between the world of objects and world of data.
LINQ extends the language by so called query expressions, which looks like a SQL Statement, by which we can extract and process data from array, Enumerable collection of classes, XML documents, MS SQL Tables, third party data sources etc.

List and Details of Query Operators/Keywords of LINQ

1. from: from keyword is used to mention the datasource on which the LINQ is applied..

2. where: The where operator/clause is similar to the where clause in the SQL. It is used to provide the conditions which is to be satisfied. 

3. select:  select operator is used to perform the projection on the collection to select the elements from the collection.

C# Notify Parent From Child using events and delegates

While creating an application, we often come across scenarios where we have parent child relationship between objects.

When we want to pass some information from parent to child, it is very simple as we have the reference of the child object in the parent and we pass the information using message passing technique, where we call some public method of child and achieve the desired result.

But many times while creating applications, we find some requirement where we need to notify the parent class that some processing has happened in child class. Based on that we need to do something in parent class. Notifying parent from child is not direct way as child do not hold reference of parent.
Note : We can always pass parent's reference to child but it is not the conventional way and can cause issues while maintaining the application. So this is not recommended.
So, we can achieve this using delegates. We can create and event in child using delegate. Parent will listen to this event. Whenever some processing happens in child, child can raise event and whoever is listening to this event will get notified that some processing has happened in child.

Sample Code:

events in C#

An event allows a class or resource to notify the other classes or resource, when something required event occurs. The resource that raises the events is knows as publisher and the resource that handles the event is known as subscriber. In C# visual application we handle events like button clicked, combo box selection changed events etc. Similarly, we can raise our custom events when requires.

Overview of events

  • Publisher determines when to raise event, and subscriber determines how to handle the event.
  • An event can have multiple subscribers, and subscriber can handle multiple events.
  • An event that has no subscriber is never raised.
  • Events are typically used for user actions.
  • When an event has multiple subscriber than event handlers are invoked synchronously.
  •  Events are actually based on the EventHandler delegates.

Example of Events

delegates in C#

A delegate is a type that references a method. Once a delegate is bound to a method, it behaves like method. It can be used like other methods.


public delegate void valueEntered(string value);

Any method that matches the delegate's signature including return type, parameters etc, can be assigned to the delegate.

delegate's Overview

  • It is like a function pointer in C++.
  • It allows methods to be passed as parameters
  • It can be used as callback method.
  • In this method's signature need not to be exactly same as delegate's.
                     For Example:
                                public class type1 { }
                    public class type2 : type1 { }
                    public delegate type1 delegateEx();
                    class Program
                       {
                          static void Main(string[] args)
                           {
                             delegateEx de = new delegateEx(MethodType1);
                             delegateEx de1 = new delegateEx(MethodType2);
                           }
                          public static type1 MethodType1() { return new type1(); }
                          public static type2 MethodType2() { return new type2(); }
                        }
                   
          type1 and type2 are 2 different classes but type2 inherits type1 so It is allowed in delegates.
  • C# 2.0 introduces concept of Anonymous method which allows programmer to pass code block as parameter in method.

delegate's Example

WPF How to use Resource Dictionary in C#



To know what is Resource Dictionary,example of Resource dictionary, how we can add Resource Dictionary and how we can use it from XAML visit here:

Now there may be a case where we need to access a resource dictionary that we have defined in our project, from C# code.
If we have already merged our resource dictionary in XAML, it is easy to access the inner resources using thecontrol.FindResource("<<ResourceKey>>"); method.
 But, if we haven’t merged the resources in XAML and we still need to use the resource dictionary, we have options to use it directly inC# code. 
We have modified the example given here WPF How to use Resource Dictionary in XAML. where we were using ResourceDictionary from XAML.
Below is the XAML and code snippet:
XAML Code:
<UserControl x:Class="WPF_Sample_Project_Test.ResourceDictionaryExample"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
        <Grid>
        <Button x:Name="btnRound"  />
    </Grid> 
</UserControl>
C# Code:

WPF How to use Resource Dictionary in XAML



In this article, we will learn how we can use merge a resource dictionary in WPF XAML.


As we all know, that WPF applications supports rich media and graphics support, styles and templates should be managed in such a way that they can be reused. Styles can be defined in the same XAML file or all the styles and templates which are reusable across different screens can be accumulated in a Resource Dictionary File. 


What is Resource Dictionary?


In Resource Dictionary, one can write reusable styles, DataTemplates, ControlTemplates. One can also define custom definitions for Brush, Color, Background etc.

Each of these custom defined style or template is called as resource and a unique key must be given to each resource.


Steps to add Resource Dictionary

C# : How to read a text file


This is a very basic example where we explain how can we read text files from C#.
We will show three examples:

Example 1:
We will read all the text from a file and store it in a string variable.

For this we will be using C# inbuilt utility function: System.IO.File.ReadAllText

Method signature:
public static string ReadAllText(string path);


Example 2:
We will read all the text from a file line by line and then store each line as an element in a string array.
For this we will be using C# inbuilt utility function: System.IO.File.ReadAllLines

Method signature:
public static string[] ReadAllLines(string path);

We have developed a console application to showcase the feature.The source code for reading file is displayed below:

class Program
    {
        static void Main()
        {
           

            // Read the file as one string.
            string text = System.IO.File.ReadAllText(@"C:\Example1.txt");

            // Display the file contents to the console. Variable text is a string.
            System.Console.WriteLine("*****************EXAMPLE 1*********************");
            System.Console.WriteLine("Contents of Example1.txt = {0} \n \n", text);

Dotnet like Trim method in JavaScript to Trim any string, char or blank spaces

We have already discussed, How to create own extension method in javascript. By using that extension methodology, we will create our own dotnet like trim method, which will able to trim blank spaces, character, string etc.

In this you will able to use the trim methods in your case as as
1. LTrim
       Trim Blank Spaces: var trimmedText = "Akash    ".LTrim();  
                  Output: Akash;
       Trim Some String: var trimmedText = "AkashSS".LTrim("S");
                Output: Akash
2. RTrim

       Trim Blank Spaces: var trimmedText = "    Akash".RTrim();  
                  Output: Akash;
       Trim Some String: var trimmedText = "SSAkash".RTrim("S");
                Output: Akash


3. Trim

       Trim Blank Spaces: var trimmedText = "     Akash    ".Trim();  
                  Output: Akash;
       Trim Some String: var trimmedText = "SSSAkashSS".Trim("S");
                Output: Akash


Code

Book Review: Linux Network Administrators Guide

Unix/ Linux based Operating systems are back bone for any network. Now days 95% companies are using Unix based OS for network administration. The very big reason is that, It is opensource and highly customizable  according to requirement. This book has covered nearly all important administration activities required to manage a Linux network configuration. 

Click on Below Icon to download the book



Google Nexus 7: Technical Specifications, Pros and Cons



Google has announced its new 7 inch tablet Nexus 7 which is manufactured by ASUS. The tablet was the first device to ship with Android 4.1 version, nicknamed "Jelly Bean".

This tablet is amazing without any doubt in terms of its features. But what amazes more is its low price.
Although the market is flooded with Android slates in all prices and sizes, very few have captured the public's imagination. Nexus 7 is the first tablet launched under Google's own Nexus brand. This $199, 7-inch slate cuts very few corners given its aggressive price, packing a powerful quad-core Tegra 3 CPU, a bright high-resolution screen and the company's new Android 4.1 Jelly Bean operating system. Add in an attractive, light-weight design and Google's helpful new voice-driven search app and you have the best 7-inch tablet, a no-brainer purchase for media consumption, gaming and more on the go.
Google Nexus 7




Convert structure to bytes and writing it to a file

Many time we may require to write the data of structure in file in the form of bytes. So consider the structure written below:


[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
        struct student
        {
            [MarshalAs(UnmanagedType.LPWStr,SizeConst=10)]
            public string Name;
            [MarshalAs(UnmanagedType.I4)]
            public int RollNo;
            [MarshalAs(UnmanagedType.I4)]
            public int Marks;
        }

Many I am considering that you know How to convert structure into IntPtr (Click here to know how to convert Structure into IntPtr). So I will write that code directly in Example.

Consider ptrStudent, a IntPtr pointer which is pointing to the unmanaged memory which is containing structure in sequential layout.

Code for getting IntPtr of object of student

st: object of student

IntPtr ptrStudent = Marshal.AllocHGlobal(Marshal.SizeOf(st.GetType()));
Marshal.StructureToPtr(st, ptrStudent, true);

Now we have to get byte[] from IntPtr (ptrStudent).

Structure to IntPtr

Sometimes while working with the unmanaged resouces, we need to convert Marshal-able structure into unmanaged memory and gets its pointer and pass the structure's integer pointer(IntPtr) to unmanaged api.

[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
        struct student
        {
            [MarshalAs(UnmanagedType.LPWStr,SizeConst=10)]
            public string Name;
            [MarshalAs(UnmanagedType.I4)]
            public int RollNo;
            [MarshalAs(UnmanagedType.I4)]
            public int Marks;
        }

To convert structure to Integer pointer we need to use NameSpace: System.Runtime.InteropServices.

Consider the declaration of structure as

            student st = new student();             
            st.Name = "Akash Soni";             
            st.RollNo = 483;             
            st.Marks = 807;


Create object for IntPtr class and allocates memory from the unmanaged memory of specific bytes (which is equals to the size of structure


IntPtr ptrStudent = Marshal.AllocHGlobal(Marshal.SizeOf(st.GetType()));
Now create the unmanaged copy of Structure object 'st' in the unmanaged memory.
Marshal.StructureToPtr(st, ptrStudent, true);

Sample code


introduction to Unmanaged Structure in C#.

In dotnet we are working with managed resources as well as unmanaged resources. Surprisingly, use of unmanaged resources are much more than the managed resources. Memory management, garbage collectors are already available with the dotnet, so its not the problem for the developer. While working with the unmanaged apis we may require to access unmanaged memory by structures.

Suppose we have unmanaged binary developed in C++, which is containing a structure declared as below

typedef struct
{
  char[20]  Name;
  long RollNo;
  long Marks;
}student;

and there is a publicly exposed method which takes Integer pointer (IntPtr) as a parameter. In that case to store the returned value we need to create structures with special attributes StructLayout, which makes it of fixed length and Marshalable.
Unmanaged Structure in c# similar to above structure is as written below

An introduction to JSON

JSON => JavaScript Object Notation

JSON is a language independent, object interchange format. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON Consists of 2-structures
  1. collection of Name / Value pairs which is implemented in languages as Dictionary or HashTable
  2. ordered list of Values, which is implemented in languages as Arrays or Collections

Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework by Jeffrey Richter


SUMMARY Garbage collection in the Microsoft .NET common language runtime environment completely absolves the developer from tracking memory usage and knowing when to free memory. However, you'll want to understand how it works. Part 1 of this two-part article on .NET garbage collection explains how resources are allocated and managed, then gives a detailed step-by-step description of how the garbage collection algorithm works. Also discussed are the way resources can clean up properly when the garbage collector decides to free a resource's memory and how to force an object to clean up when it is freed.

What is Windows Communication Foundation? (An introduction of WCF)


WCF  enables you  to build powerful service-oriented systems, based on connected services and applications. The WCF runtime and its  System.ServiceModel  namespace that represents its primary programming interface, is nothing less than the successor and unification of most distributed systems technologies that developers have successfully used to build distributed applications on the Windows platform. Each WCF service has endpoints where client will interact. Each Endpoint consists of ABC!!! Where ABC denotes Address (Where the service is?), Binding (How service will accessed?) and Contract(What Service will do). 

These endpoints actually makes WCF service interesting. One WCF service can contains more than one end points and each endpoint is having different address.  This means that you can have one service, which is flexible and interoperable for any application requirements.

Details on ABC

Address:

It specifies the address of the service. The address depends on various factors, including the transport protocols we are using for the communication.

List of protocols and base address schema

Protocol Base Address Schema
HTTP http
TCP net.tcp
MSMQ net.msmq
PIPE net.pipe

Create Watermark / HintText Textbox in WPF / XAML

In this example we shall see, how we can add watermark / hint text to wpf controls like textbox. In modern UI based application it is being used very extensively. A snapshot of its usage is added below.












As we can see it eliminates the need of labels against each input controls.
To achieve the same behavior in WPF, we will use System.Windows.Media.VisualBrush. In this visual brush we will add textblock,  and make stylish as we want for the application.

How to insert Input Elements dynamically in your blogspot posts

By using the following steps you can insert input elements in your blogspot post dynamically.

Step 1: Start Writting New Post by clicking on the "Create New Post" button






Step 2: Goto HTML view of your post.






Step 3: Add a div where the Input elements are to be added, and give Id to the div. As in my example I have given the Id of the div as "demoDiv". Add another div which will be used to raise click event to add the button. In this demo I have added the div as "insertElementDemo








WPF: How to change the style of selected and Focused Row with AlternateRowColor of DevExpress Grid Control

To change the style of the selected row we will write a Trigger and will apply style for the row in the trigger. For that we will check for the SelectionState for selected Row & IsFocusedRow for the Focused Row Property.

Trigger For Focused Row

<Trigger Property='dxg:DataViewBase.IsFocusedRow' Value='True'>
       <Setter Property='Background' Value='{DynamicResource FocusedRowBackgroundStyle}'/>
       <Setter Property='BorderBrush' Value='#F2F2F2'/>
       <Setter Property='Foreground' Value='Black'/>
       <Setter Property='BorderThickness' Value='2'/>
 </Trigger>

Trigger For Selected Row


<DataTrigger Binding="{Binding Path=SelectionState}" Value="Selected">
    <Setter Property='Background' Value='{DynamicResource SeletedRowBackgroundStyle}'/>
    <Setter Property='BorderBrush' Value='#F2F2F2'/>
    <Setter Property='Foreground' Value='Black'/>
    <Setter Property='BorderThickness' Value='2'/>
</DataTrigger>

Sample XAML Code

WPF: AlternateRowColor style in devexpress GridControl

Here I am demonstrating how can we assign alternate Row color to a devexpress grid control. To do so we will have to use MultiDataTrigger. In the MultiDataTrigger, we will check that if the row is even and not selected then Even row color will be assigned, if the row is odd and not selected than odd row color will be applied. similarly if the row is selected than no color will be applied and default selection state will be applied.

XAML Code

WPF Disable ListBox Selection Workaround

In this example, we will demonstrate how we can disable the WPF listbox selection.
As we all know, that there is no property in ListBox such as "SelectionMode"= None.
So, instead of disabling the listbox selection, we can override the system colors in such a way that , even when the list box is selected, it appears as if the listbox is not selected.
We are overriding the "HighlightBrushKey" and "ControlBrushKey" as Transparent and "HighlightTextBrushKey" as Black. So the background which gets selected will remain transparent and the foreground will turn black.
Here is the source code for the same:

<Grid >
        <Grid.Resources>
             <x:Array x:Key="StringArrayResource" Type="sys:String">
                <sys:String>List Value1</sys:String>
                <sys:String>List Value2</sys:String>
                <sys:String>List Value3</sys:String>
            </x:Array>
        </Grid.Resources>

  <ListBox Grid.Row="0" ItemsSource="{DynamicResource StringArrayResource}">
            <ListBox.Resources>
                    <SolidColorBrush x:Key='{x:Static SystemColors.HighlightBrushKey}' Color='Transparent'/>
                    <SolidColorBrush x:Key='{x:Static SystemColors.HighlightTextBrushKey}' Color='Black'/>
                    <SolidColorBrush x:Key='{x:Static SystemColors.ControlBrushKey}' Color='Transparent'/>
                </ListBox.Resources>        
        </ListBox>
</Grid>

Screenshots:
Before Overriding System Colors:
 After Overriding System Colors: