The URI prefix is not recognized (Silverlight).

Today I came across an error - which I thought a tedious task, but it will take less than 5sec to fix. :)

I have a Silverlight UserControl hosted in a Asp.net website. The Silverlight project reads a xml from the Xap package(ClientBin of the hosting application- here asp.net website) using WebClient. I was getting this exception:
"The URI prefix is not recognized"

This is my code.
void wClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                string productList = e.Result;
            }
            else
            {
                string Message = "Error Occured";
            }
        }

        public void LoadXml()
        {
            WebClient wClient = new WebClient();
            wClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wClient_DownloadStringCompleted);
            wClient.DownloadStringAsync(new Uri("Products.xml", UriKind.Relative));
        }



This error was caused because the startup project was the Silverlight Project not the Hosting Application. Just make the Hosting Asp.net application as Startup project.

Reader-Writer Problem

semaphore mutex = 1; // Controls access to the reader count
semaphore db = 1; // Controls access to the database
int rdrCount; // The number of reading processes


public void Reader()
{
while (true) // loop forever
{
Wait(mutex); // gain access to rdrCount
rdrCount = rdrCount + 1; // increment the rdrCount
if (rdrCount == 1)
Wait(db); // if this is the first process to read the database,
// a Wait on db is executed to prevent access to the database by a Writer
Signal(mutex); // allow other processes to access rdrCount
read_db(); // read the database
Wait(mutex); // gain access to rdrCount
rdrCount = rdrCount - 1; // decrement rdrCount
if (rdrCount == 0)
Signal(db); // if there are no more processes reading from database, allow Writer
Signal(mutex); // allow other processes to access rdrCountuse_data();
// use the data read from the database (non-critical)
}
}



public void Writer()
{
while (true)
{ // loop forever
create_data(); // create data to enter into database (non-critical)
Wait(db); // gain access to the database
write_db(); // write information to the database
Signal(db); // release exclusive access to the database
}
}

ToolTip

Today I was trying to reuse xaml of a WPF in Silverlight 5 and came across this difference.
In WPF :
<TextBlock Text="{Binding FirstName}" ToolTip="{Binding FullName}"/>


In Silverlight:
 <TextBlock Text="{Binding FirstName}"> <ToolTipService.ToolTip> <ToolTip Content="{Binding FullName}"/> </ToolTipService.ToolTip> </TextBlock>

Converter

Data Binding is one of the most power propery of WPF. Ex: Binding the background color of the TextBlock to the color that is selected in the ListBox. The following code adds a Background property to the TextBlock and uses the attribute binding syntax to bind to the value of the selected item in the ListBox:

<TextBlock 
    Width="248" 
    Height="24" 
    x:Name="tbSelectedColor" 
    Text="{Binding ElementName=lbColor, Path=SelectedItem.Content,Mode=OneWay}"
    Background="{Binding ElementName=lbColor, Path=SelectedItem.Content,Mode=OneWay}"/>

In this example the a property of type string is our binding source object which is binded to the Color property? If there is a typo in the source object string or if we want to databind two properties that have incompatible types it will stop working.
Converts converter is a user defined class, which implements the IValueConverter interface. IvalueConverter provides a way to apply custom logic to a binding by implementing the Convert and ConvertBack methods. Converters can change data from one type to another, translate data based on cultural information, or modify other aspects of the presentation.

Convert(): The data binding engine calls this method when it propagates a value from the binding source to the binding target. A return value of DependencyProperty.UnsetValue indicates that the converter produced no value and that the binding uses the FallbackValue, if available, or the default value instead.
A return value of Binding.DoNothing indicates that the binding does not transfer the value or use the FallbackValue or default value.

ConvertBack(): The data binding engine calls this method when it propagates a value from the binding target to the binding source.
The implementation of this method must be the inverse of the Convert method.
A return value of DependencyProperty.UnsetValue indicates that the converter produced no value and that the binding uses the FallbackValue, if available, or the default value instead.
A return value of Binding.DoNothing indicates that the binding does not transfer the value or use the FallbackValue or default value.

I came across a requirement where the ListBox Height must change according to the Size of ListBox. In this example there is a ListBox with 10 Items and a Delete button which delete items from the ListBox. As the Item Count changes(here reduces) Height also changes.We can do this using Converters. The Height of the ListBox is binded with the ItemCount. 

xaml
<Window x:Class="WpfConverters.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfConverters"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:WidthConverter x:Key="converter"/>
    </Window.Resources>
    <Grid>
        <ListBox Name="personListBox" ItemsSource="{Binding PersonList}" 
                 Margin="40,8,313,12" Width="150" 
                 Height="{Binding Path=PersonList.Count, Converter={StaticResource converter}}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Name}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button Content="Delete" Height="23" 
                HorizontalAlignment="Left" Margin="243,41,0,0" 
                Name="DeleteButton" VerticalAlignment="Top" Width="75"
                Command="{Binding DeleteCommand}" CommandParameter="{Binding}"/>
    </Grid>
</Window>


Converter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace WpfConverters
{
    class WidthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var listCount = value as int?;
            if (listCount.HasValue)
            {
                if (listCount == 0)
                    return 10;
                else if (listCount < 2)
                    return 100;
                else if (listCount >= 3)
                    return 200;
                else if (listCount >= 5)
                    return 250;
            }
            return 400;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


ViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace WpfConverters
{
    public class ViewModel : INotifyPropertyChanged
    {
        public ICommand DeleteCommand { get; private set; }
        public ViewModel()
        {
            PersonList = new ObservableCollection<Person>();
            PersonList.Add(cust1);
            PersonList.Add(cust2);
            PersonList.Add(cust3);
            PersonList.Add(cust4);
            PersonList.Add(cust5);
            PersonList.Add(cust6);
            PersonList.Add(cust7);
            PersonList.Add(cust8);
            DeleteCommand = new RelayCommand(ExecuteDeleteCommand, CanExecuteDeleteCommand);
        }

        Person cust1 = new Person() { Name = "Alice", Age = 20 };
        Person cust2 = new Person() { Name = "Bob", Age = 21 };
        Person cust3 = new Person() { Name = "Mark", Age = 22 };
        Person cust4 = new Person() { Name = "Jay", Age = 23 };
        Person cust5 = new Person() { Name = "Mike", Age = 23 };
        Person cust6 = new Person() { Name = "Linda", Age = 22 };
        Person cust7 = new Person() { Name = "Maya", Age = 21 };
        Person cust8 = new Person() { Name = "Susan", Age = 20 };

        ObservableCollection<Person> personList;

        public ObservableCollection<Person> PersonList
        {
            get { return personList; }
            set { personList = value; OnPropertyChanged("PersonList"); }
        }

        public void ExecuteDeleteCommand(object parameter)
        {
            PersonList.Remove(PersonList.LastOrDefault());
        }

        public bool CanExecuteDeleteCommand(object parameter)
        {
            if (personList.Count == 0)
                return false;
            else
                return true;            
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (null != PropertyChanged)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WpfConverters
{
   public class Person
    {
        string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
    }
}

Reference:
1. http://msdn.microsoft.com/en-us/magazine/cc163299.aspx
2. http://wpftutorial.net/ValueConverters.html

C# Interface

We have two Classes ClassOne & ClassTwo and two interfaces InterfaceOne and InterfaceTwo.
Is this code valid?
interface InterfaceOne

{
void InterfaceOneMethod();
}

interface InterfaceTwo
{
void InterfaceTwoMethod();
}

class ClassOne : InterfaceOne, ClassTwo
{
public void InterfaceOneMethod()
{
//Some Code
}
}

class ClassTwo
{
}

Ans: Base class must come before interface.

class ClassOne :   ClassTwo, InterfaceOne

{
public void InterfaceOneMethod()
{
//Some Code
}
}

WinForm Interview Question(C#)

Q. There is a WinForm(Form1) with a Button(Open Form2). If the user clicks the button it should open another WinForm(Form2). If the user again click on the Button in Form1, he should get a message saying that Form2 is already open.

Ans: In Form1's Button click event add this code.

 private void Form1Bttn_Click(object sender, EventArgs e)

{
bool FormOpen = false;

//Application.OpenForms propety: Gets a collection of open forms
//owned by the application.
foreach (Form S in Application.OpenForms)
{
if (S is Form2)
{
FormOpen = true;
}
}

if (FormOpen == true)
{
MessageBox.Show("Form already open.");
}

else
{
Form MyForm = new Form2();
MyForm.Show();
}
}

Alternating Rows in an ItemsControl

We can give different styles to each row in a Control which uses ItemControl for representing a collection of Items.

The AlternationCount and ItemsControl.AlternationIndex properties of Itemcontrol class enable the user to specify the appearance for two or more alternating item containers.

The AlternationCount is the number of rows that form a sequence. If AlternationCount is set to 1, the list will alternate after every item.
Each Item(here DataGridItem) have an ItemsControl.AlternationIndex which allow the user to determine how it is numbered in the sequence. ItemsControl.AlternationIndex begins at 0, increments until it is (AlternationCount - 1), and then restarts at 0. So if the AlternationCount is 2 we can apply style to 2 Items(First Items's AlternationIndex =0, Second Item's AlternationIndex =1 and Third Item's AlternationIndex = 0, ie it will reset.)

   <Window.Resources>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="AntiqueWhite"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="PaleGoldenrod"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="2">
<Setter Property="Background" Value="Lavender"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="3">
<Setter Property="Background" Value="Pink"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<DataGrid x:Name="GridViewNames" AlternationCount="4">
<DataGrid.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=FistName}"/>
<TextBlock Text="{Binding Path=LastName}"/>
</StackPanel>
</DataTemplate>
</DataGrid.ItemTemplate>
</DataGrid>
</Grid>


Refrence:http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.alternationcount.aspx

WPF Brushes

In WPF everything is visible because it is painted with Brush.Brushes enable the user to paint user interface (UI) controls with anything from simple, solid colors to complex sets of patterns and images.A brush is used to describe background of a button, the foreground of text(font color), and the filling color of the shape.

A Brush "paints" an area with its output. Different brushes have different types of output. Brushes can paint an area with a solid color/with a gradient/pattern/ image/ drawing.
There are diffenrent types of Brushes.

  1. SolidColorBrush
  2. LinearGradientBrush
  3. RadialGradientBrush
  4. ImageBrush

SolidColorBrush: paints an area with a solid Color. We can fill the area either with the predefined color provided by the Colors class or using RGB color codes.(Color Picker)


<Ellipse Stroke="Black" StrokeThickness="2" Margin="35,130,435,324">
<Ellipse.Fill>
<SolidColorBrush Color="DarkOrange"></SolidColorBrush>
</Ellipse.Fill>
</Ellipse>
<Label Content="SolidColorBrush" Height="30"
HorizontalAlignment="Left" Margin="35,80,0,0"
Name="SolidColorBrushLabel" VerticalAlignment="Top"
Width="100" Background="DarkOrange"/>

LinearGradientBrush: paints an area with a linear gradient. A linear gradient blends two or more colors across a line, the gradient axis. Use GradientStop objects to specify the colors in the gradient and their positions.
The default linear gradient is diagonal. In the default, the StartPoint of a linear gradient is (0,0), the upper-left corner of the area being painted, and its EndPoint is (1,1), the lower-right corner of the area being painted. The colors in the resulting gradient are interpolated along the diagonal path. If we want to the linear gradient Horizontal, set the StartPoint="0,0" and EndPoint="0,1" and for Vertical gradient StartPoint="0,0" and EndPoint="1,0"(Refresh X-Y Cartesian Coordinate System you learned in high school math class.:)) -



A line was added to highlight the interpolation path of the gradient from the start point to the end point.



<Grid>
<Rectangle Height="100" HorizontalAlignment="Left"
Margin="55,125,0,0" Name="LinearGradientBrushRectangle"
Stroke="Black" VerticalAlignment="Top" Width="180" >
<Rectangle.Fill>
<LinearGradientBrush>
<GradientStop Color="#660033" Offset="0.0" />
<GradientStop Color="#FFCC00" Offset="0.5" />
<GradientStop Color="#BABA21" Offset="1" />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Label Content="LinearGradientBrush " Height="30"
HorizontalAlignment="Left" Margin="70,70,0,0"
Name="LinearGradientBrushLabel" VerticalAlignment="Top" >
<Label.Background>
<LinearGradientBrush>
<GradientStop Color="#660033" Offset="0.0" />
<GradientStop Color="#FFCC00" Offset="0.5" />
<GradientStop Color="#BABA21" Offset="1" />
</LinearGradientBrush>
</Label.Background>
</Label>
</Grid>

RadialGradientBrush: paints an area with a radial gradient. A radial gradient blends two or more colors across a circle.



    <Grid>
<Polygon Points="300,200 400,125 400,275 300,200" Margin="-183,-12,161,12">
<Polygon.Fill>
<RadialGradientBrush GradientOrigin="0.5,0.5">
<GradientStop Color=" #800080" Offset="0"/>
<GradientStop Color="Sienna" Offset="0.5"/>
<GradientStop Color="#4AA02C" Offset="1">
</GradientStop>
</RadialGradientBrush>
</Polygon.Fill>
</Polygon>
<Label Content="RadialGradientBrush " Height="30" HorizontalAlignment="Left" Margin="138,76,0,0" Name="RadialGradientBrushLabel" VerticalAlignment="Top" >
<Label.Background>
<RadialGradientBrush GradientOrigin="0.5,.7">
<GradientStop Color=" #800080" Offset="0"/>
<GradientStop Color="Sienna" Offset="0.5"/>
<GradientStop Color="#4AA02C" Offset="1"/>
</RadialGradientBrush>
</Label.Background>
</Label>
</Grid>


ImageBrush: paints an area with a ImageSource.



<Grid>
<Label Content="ImageBrush" Height="30"
HorizontalAlignment="Left" Margin="129,47,0,0"
Name="ImageBrushLabel" VerticalAlignment="Top"
FontWeight="Bold" >
<Label.Background>
<ImageBrush Viewbox="0.6,0.3,0.6,0.7" ImageSource="Image\ImageBrush.png"/>
</Label.Background>
</Label>
<Ellipse Height="80" HorizontalAlignment="Left"
Margin="95,101,0,0" Name="ImageBrushEllipse"
Stroke="Black" VerticalAlignment="Top" Width="145" >
<Ellipse.Fill>
<ImageBrush ImageSource="Image\ImageBrush.png"/>
</Ellipse.Fill>
</Ellipse>
</Grid>


References: http://msdn.microsoft.com/en-us/library/system.windows.media.brush.aspx

WPF Styles

Before starting WPF styles lets check some of the properties and classes used in styling.
In WPF everything is visible because it is painted with Brush.A brush is used to describe background of a button, the foreground of text(font color), and the filling color of the shape.

Brushes Tutorial


BasedOn:Gets or sets a defined style that is the basis of the current style.
Dispatcher:Gets the Dispatcher this DispatcherObject is associated with. (Inherited from DispatcherObject.)
IsSealed:Gets a value that indicates whether the style is read-only and cannot be changed.
Resources:Gets or sets the collection of resources that can be used within the scope of this style.
Setters:Gets a collection of Setter and EventSetter objects.
TargetType: Gets or sets the type for which this style is intended.
Triggers: Gets a collection of TriggerBase objects that apply property values based on specified conditions.





References: http://msdn.microsoft.com/en-us/library/system.windows.style.aspx

WPF ListBox Template Binding using MVVM

MVVM pattern can be described as follows:

Model: The data access layer.
View: The GUI(Windows, Graphics, controls,..) and the codebehind file) or in other-words a view is a .xaml/.xaml.cs pair.
ViewModel: Can be compared to a Controller, who binds data between the View and the Model. It passes the commands form View to Model.

Our example is a simple data binding of ListBox.

  • Create a new WPF project.

  • Create three folders to the project- Model,View and ViewModel.

  • Delete the MainWindow.xaml from the project, and create a new WPF window in View folder. I named it ListBoxView.( It is a clean practice to postfix views with 'View', view models with 'ViewModel' and Models with 'Model')

  • Modify the App.xaml and App.xaml.cs as follows.

  •  <!--App.xaml--> 

    <Application x:Class="ListBoxSampleNamespace.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Startup="Application_Startup">
    <Application.Resources>

    </Application.Resources>
    </Application>


    //App.xaml.cs 
    public partial class App : Application
    {

    private void Application_Startup(object sender, StartupEventArgs e)
    {
    ListBoxView myView = new ListBoxView();
    Application.Current.MainWindow = myView;
    myView.Show();
    }
    }


  • We are going to display the details of the People in a ListBox. So lets create a 'PeopleDataModel' class in the Model folder.

  • namespace ListBoxSampleNamespace.Model
    {
    public class PeopleDataModel
    {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public PeopleDataModel(string fname, string lname, int age)
    {
    this.FirstName = fname;
    this.LastName = lname;
    this.Age = age;
    }
    }
    }

  • Create a class named 'ViewModel.cs' in the ViewModel folder.

  • // Interaction logic for ListboxTemplateViewModel
    namespace ListBoxSampleNamespace.ViewModel
    {
    public class ListboxTemplateViewModel
    {
    public ObservableCollection<PeopleDataModel> PeopleDataCollection { get; set; }

    public ListboxTemplateViewModel()
    {
    public class ListboxTemplateViewModel : INotifyPropertyChanged
    {
    public ObservableCollection<PeopleDataModel> PeopleDataCollection { get; set; }

    public ListboxTemplateViewModel()
    {
    PeopleDataCollection = new ObservableCollection<PeopleDataModel>();

    PeopleDataCollection.Add(new PeopleDataModel("FirstName1", "LastName1", 27));
    PeopleDataCollection.Add(new PeopleDataModel("FirstName2", "LastName2", 32));
    PeopleDataCollection.Add(new PeopleDataModel("FirstName3", "LastName3", 57));
    PeopleDataCollection.Add(new PeopleDataModel("FirstName4", "LastName4", 51));
    }
    }
    }

    The ViewModel class has list of PeopleDataModel. ObservableCollection is built-in generic collection used for databinding, it can raises events automatically when an item is added or removed.(Right now we are not raising events in this example).

  • The View’s DataContext is wired up to the associated ViewModel using this code in the application startup.

  • /// Interaction logic for ListBoxView.xaml

    public partial class ListBoxView : Window
    {
    public ListBoxView()
    {
    InitializeComponent();
    DataContext = new ListBoxSampleNamespace.ViewModel.ListboxTemplateViewModel();
    }
    }
    }

  • Now we have define the View and bind data to it.

  • <ListBox x:Name="PeopleListBox" Width="300" MaxHeight="150" ItemsSource="{Binding PeopleDataCollection}" IsSynchronizedWithCurrentItem="True">
    <ListBox.ItemTemplate>
    <DataTemplate>
    <Border BorderBrush="Orange" BorderThickness="2" Background="OrangeRed">
    <StackPanel Orientation="Vertical">
    <TextBlock FontSize="12" Text="{Binding Path=FirstName}" />
    <TextBlock FontSize="12" Text="{Binding Path=LastName}" />
    <StackPanel>
    <TextBlock FontSize="10" Text="{Binding Path=Age}" />
    </StackPanel>
    </StackPanel>
    </Border>
    </DataTemplate>
    </ListBox.ItemTemplate>
    </ListBox>


    The ItemsSource="{Binding PeopleDataCollection}"of the ListBox defines the Binding source. Without a DataTemplate, our ListBox currently looks like this:



    This happens because without specific instructions, the ListBox just calls ToString when trying to display the objects in the PeopleDataCollection.
    Therefore, we can overrides the ToString method, then the ListBox displays the string representation of each object in the underlying Collection(PeopleDataCollection).In our example add this code to the PeopleDataModel class.

     public override string ToString()
    {
    string result = null;
    result = FirstName +LastName+ Age.ToString();
    return result;
    }


    Still this method is inflexible. Also, if we want to bind to XML data, we cannot override ToString().
    Therefore the solution is to define a DataTemplate. Set the ItemTemplate property of the ListBox to a DataTemplate. What we specify in the DataTemplate becomes the visual structure of our data object.
    We are giving instructions that each item appears as three TextBlock elements within a StackPanel. Each TextBlock element is bound to a property of the PeopleDataModel class.

    When you run this program:


A simple WPF DataGrid application to show the ProductName and ProductID from Database using Entity Framework.

  1. Create a new WPF Project.

  2. Rename the Main window to DataGridSample.xaml( Make sure you rename the StartupUri in App.xaml too).

  3. Drag and drop DataGrid to this window and Name it ProductDataGrid.

  4. <DataGrid Name="ProductDataGrid"  AutoGenerateColumns="False" Height="120" Width="350" Margin="10" />

  5. Create a table named "Products" in your Database( I use SQL Server 2008)



  6. Create Model Classes with the Entity Framework.
  7. Create Model.

  8. Create an instance of this Model in your Codebehind class.(Here the ProductEntity)

  9. ProductEntities _Product = new ProductEntities();

  10. Use this LINQ query to get the ProductName and ProductID

  11. var prod = from p in _customer.Products
    select new { ProdId = p.ProductId, ProdName = p.ProductName };

  12. We have to bind the DataGrid columns are bind to ProdID and ProdName, so we have to add this code to the DataGrid Control in the DataGridSample.xaml


  13. <DataGrid Name="ProductDataGrid" AutoGenerateColumns="False" Height="120"  Width="350" Margin="10" ItemsSource="{Binding}" >
    <DataGrid.Columns>
    <DataGridTextColumn Header=" Product Name" Binding="{Binding ProdId}"/>
    <DataGridTextColumn Header=" Product Name" Binding="{Binding ProdName}"/>
    </DataGrid.Columns>
    </DataGrid>

  14. Use DataContext to bind DataGrid to "prod".
ProductDataGrid.DataContext = prod;

DataBindingSample.cs
------------------------
public partial class DataBindingSample: Window
{
//Model class Instance.
ProductEntities _Product;

public DataBindingSample()
{
InitializeComponent();
_Product = new ProductEntities();
var prod = from p in _Product.Products
select new { ProdId = p.ProductId,
ProdName = p.ProductName };
ProductDataGrid.DataContext = prod;
}
}


DataBindingSample.xaml
------------------------
<StackPanel>
<DataGrid Name="ProductDataGrid" AutoGenerateColumns="False" Height="120" Width="300" Margin="10" ItemsSource="{Binding}" >
<DataGrid.Columns>
<DataGridTextColumn Header=" Product ID" Binding="{Binding ProdId}"/>
<DataGridTextColumn Header=" Product Name" Binding="{Binding ProdName}"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>



ASP.Net Interview Questions and Answers.


  1. Can you put the ViewState in the Session if yes how and why?

  2. Yes. we can store ViewState in Session.But this Session require good chunk of memory on the server.


    // Store ViewState to Session
    ViewState["myViewState"] = "ASP.Net";
    Session["mySession"] = ViewState["myViewState"];

    // Retrieve ViewState from Session
    ViewState["RetrievedValue"] = Session["mySession"];
    String ViewStateValue = ViewState["RetrievedValue"].ToString();


Value and Reference Types

Value type is a data type which are either built-in types, or structure(struct) or an enumeration(enum).When value-type instance are created, only a single space in memory is allocated to store the value.

Reference type are referred to as objects including Classes, Interfaces, Delegates, Instances arrays, and as well as the built in reference types. When reference types is created two spaces are allocated one for instance and another for its reference.

The runtime deals with the value types and reference types in two different ways.

theStruct myStruct1 = new theStruct();
myStruct1.X = 10;

//Struct is a value type,
//myStruct2 becomes an independent copy of myStruct1, with its own fields.
theStruct myStruct2 = myStruct1;
myStruct2.X = 20;
Console.WriteLine("myStruct1: {0}", myStruct1.X);
Console.WriteLine("myStruct2: {0}", myStruct2.X);

Output
 
myStruct1:10
myStruct2:20

Now Repeat the same with a reference type.

The output will be 20,20.

Singleton Design Pattern

Singleton design pattern allows to create only one instance of the class by providing only one global point to access it.
This can be achieved by:

    1. Making the constructor private/protected.
    2. Create a static function which returns an instance of the class only after ensuring class has no other instance.


namespace OopConcept
{
///
/// Class without explicit contructor
///

class singleton
{
private static singleton singletonInstance = null;

///
/// To prevent instantiation.
///

private singleton()
{

}
public static singleton getInstance()
{
if (singletonInstance == null)
{
singletonInstance = new singleton();
}
return singletonInstance;
}

}
///
/// Main Class -
///

class MainClass
{
public static void Main()
{
// Cannot create an instance with 'new' Keyword.
singleton firstInstance = singleton.getInstance();
singleton secondInstance = singleton.getInstance();

if (firstInstance == secondInstance)
{
Console.WriteLine("Two instances are same");
Console.Read();
}
}
}
}

Constructors in C#.

C# creates default constructor for all classes. We do not need to create a constructor explicitly. There will be a default constructor.


namespace OopConcept
{
///
/// Class without explicit contructor
///

class mainClass
{
private int m_int;

static void Main(string[] args)
{
//*******>No error*******
mainClass myMainClass = new mainClass();
}
}
}


But when we create a parametrized constructor the default constructor will be removed..


class mainClass
{
private int m_int;

///
/// Parametrized contructor created by the user.
///

///

public mainClass(int num)
{
this.m_int = num;
}
static void Main(string[] args)
{
//*******ERROR********
mainClass myMainClass = new mainClass();
}
}

WPF Styles..

Allow the user to create visually compelling affects and by customizing the appearance.

Some features of styles are :

  • Style exists only within one WPF app. - cannot be applied to anything outside of the WPF application in which they exist, nor can they be applied to any WinForms controls hosted within a WPF Window.

  • separation of presentation and logic. This means that designers can work on the appearance of an application by using only XAML at the same time that developers work on the programming logic by using C# or Visual Basic.


Let see an example without style.


<StackPanel>
<Label Background="YellowGreen"
FontStyle="Normal"
Padding="8,4"
Margin="4"
Height="38"
Width="68">Without</Label>
<Label Background="YellowGreen"
FontStyle="Normal"
Padding="8,4"
Margin="4"
Width="70"
Height="34">Style</Label>
</StackPanel>

WPF User Control....

A Simple program using User Control in WPF.

Reuse the userControl which takes the user name and password.

1. Create new project in WPF(I named the project UserControlSample).

2. Add a new user control to that project (Right Click and Add -> User Control). Since my user control takes user name and password I renamed my user control as RegisterUserControl.

3. Add two labels two text boxes RegisterUserControl.

RegisterUserControl.xaml


<Window x:Class="UserControlSample.RegisterWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:UserControlSample"
Title="RegisterWindow"
Height="400"
Width="400"
Loaded="
Window_Loaded">
<Grid>
<local:RegisterUserControl
Margin="0,-21,40,21"
Height="268">
</local:RegisterUserControl>
<Button Content="Button"
Height="23"
HorizontalAlignment="Left"
Margin="208,256,0,0"
Name="Login"
VerticalAlignment="Top"
Width="75" />
</Grid>
</Window>


The RegistrationWindow uses the RegisterUserControl to add User name and password to it.

RegisterWindow.xaml


<UserControl x:Class="UserControlSample.RegisterUserControl"
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>
<Label Content="UserName"
Height="28"
HorizontalAlignment="Left"
Margin="28,63,0,0"
Name="label1"
VerticalAlignment="Top"
Width="77" />
<Label Content="Password"
Height="28"
HorizontalAlignment="Left"
Margin="28,112,0,0"
Name="label2"
VerticalAlignment="Top"
Width="77" />
<TextBox Height="28"
HorizontalAlignment="Left"
Margin="140,63,0,0"
Name="UsernameTextBox"
VerticalAlignment="Top"
Width="120" />
<TextBox Height="28"
HorizontalAlignment="Left"
Margin="140,112,0,0"
Name="PasswordTextBox"
VerticalAlignment="Top"
Width="120" />
</Grid>
</UserControl>


I also added a login button to our main RegisterWindow.