Latest

Loading...

Wednesday, October 22, 2008

HyperlinkButton Control in Silverlight 2

This is the second article as promised. Today we’ll look at HyperlinkButton control in Silverlight 2.
Good news for all. Silverlight 2 RC 0 has been released. So the blogarticles henceforth are compliant with RC 0.
HyperlinkButton control is a button control which when clicked displays the linked web page.
Look at the small snippet below. It shows how to use the control.


<HyperlinkButton HorizontalAlignment="Left" Margin="106,4,0,4" Width="52" NavigateUri="http://paddyt.blogspot.com" TargetName="_self" Content="Profile" Height="17" Foreground="#FFB86B26" x:Name="lnkProfile"/>

The two most important properties here are: NavigateUri and TargetName.
NavigateUri is set to the web page url to be linked.
TargetName is set to the window or frame where the linked web page can be opened. One can use “_blank”, “_parent”, “_top”, “_search”, “_self” or “” values.
There are various useful properties like IsEnabled, IsMouseOver, IsFocused etc.
We can manipulate the control programmatically also.

Saturday, August 30, 2008

Popup control in Silverlight 2

Silverlight 2 is about to release in few months. I'm going to update you the various new controls in Silverlight 2. This is the first blog in this series.

When we talk about pop-ups, we always talk about pop-up windows. Though the name of control is Popup, it will never lauch a pop-up window here.

Popup control is used to display content on top of existing Silverlight content. The pop-up contents are displayed within the Silverlight control region. Popup control can be used to display help information when the user hovers any control. It cn be used for any such temporary information.

Popup control uses Child property for its content which can be set to any UIElement control.

Popup control has IsOpen property. If IsOpen is set to true, Popup is shown.

Popup can be created declaratively or programmatically.

Let's try first with declarative way. See the below Xaml for the demo:

< UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ControlsDemo.Page"
Width="640" Height="480" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" >
< Grid x:Name="LayoutRoot" Background="White" >
< Button x:Name="test" Click="test_Click" Width="100" Height="50" HorizontalAlignment="Left" Margin="138,42,0,0" VerticalAlignment="Top" d:LayoutOverrides="Width, Height" Content="Show Popup" / >
< Popup x:Name="tstPopUp" Width="335" Height="114" HorizontalAlignment="Center" VerticalAlignment="Center" VerticalOffset="93" HorizontalOffset="138" >
< Grid Height="113" Width="334" >
< Grid.Background >
< LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0" >
< GradientStop Color="#FF5182D3"/ >
< GradientStop Color="#FFFFFFFF" Offset="1"/ >
< /LinearGradientBrush >
< /Grid.Background >
< TextBlock Height="113" Width="330" Margin="0,0,0,0" VerticalAlignment="Top" Text="This is a test message for popup. Testing popups in Silverlight..." TextWrapping="Wrap" Foreground="#FFF6F1F1"/ >
< /Grid >
< /Popup >
< Rectangle Height="120" HorizontalAlignment="Stretch" Margin="87,116,313,0" VerticalAlignment="Top" Fill="#FF5EC643" Stroke="#FF000000" OpacityMask="#FF42D23F"/ >
< /Grid >
< /UserControl >



Below I've given the code to toggle popup on the "Show Popup" button. I've taken the green rectangle to show you how the popup overlays Silverlight content. This code must be written in Page.Xaml.cs file if the XAML is in Page.xaml.

private void test_Click(object sender, RoutedEventArgs e)
{
tstPopUp.IsOpen = (!(tstPopUp.IsOpen));
}

Try it. We'll see how to work with Popup control programmatically in next blog. Stay tuned!

Wednesday, July 9, 2008

Dynamic Stylesheet Assignment Dependent on Browser

I've two stylesheets. One for Internet Explorer & other for other browsers. When the client is IE, the web page should have IE-specific stylesheet attached. For rest of the browsers, the web page must use the other stylesheet.
Demo: Get two stylesheets with body background set to two different colors.

body
{
background-color:blue;
}
body
{
background-color:black;
}

Add the following code to Page_Load event handler:
protected void Page_Load(object sender, EventArgs e)
{
HtmlLink lnk = new HtmlLink();
if (Request.Browser.Type.Contains("IE"))
{
lnk.Href = "~/StyleSheet.css";
}
else
{
lnk.Href = "~/StyleSheet2.css";
}
lnk.Attributes.Add("rel", "stylesheet");
lnk.Attributes.Add("type", "text/css");
this.Header.Controls.Add(lnk);
}
Test with Internet Explorer & some other browser like Mozilla, Opera etc.

Thursday, June 5, 2008

Table-layout Templates in VS 2008

Table layout templates vanished from VS 2008. Don’t worry. Same kind of layout we can have with few style-sheets & table markup structure.

When we take table header template, it generates markup as follows:


< table border="0" cellpadding="0" cellspacing="0" style="width: 100%; height: 100%">
< tr >
< td style="height: 200px" >
< /td >
< /tr
< tr >
< td >
< /td >
< /tr >
< /table >

Now to have similar structure in our web pages designed in VS 2008, one can use the style & markup shown below:(One can also copy & paste the markup shown above from VS 2005 in VS 2008.),
table
{
border-spacing: 0px;
display: block;
width: 100%;
height: 100%;
border-width: 0px;
}
#td1
{
height:200px;
}
************************************************************
< table> <tr><td id="td1"></td></tr><tr><td></td></tr></table>


Similarly one can create for other templates as follows:


Side: Use the above style-sheet & below markup

<table><tr><td id="td1"></td><td></td></tr></table>

Footer: Use the above style sheet & below markup.

<table><tr><td></td></tr><tr> <td id="td1"></td></tr></table>

Header & Side: Add following style-rule to style sheet
#td2
{
width:200px;
}
& use below markup

<table><tr><td colspan="2" id="td1"></td></tr><tr><td id="td2"></td><td></td></tr></table>

Header, Footer & Side:Use the below style

table
{
border-spacing: 0px;
display: block;
width: 100%;
height: 100%;
border-width: 0px;
}
#td1,#td3
{
height:200px;
}
#td2
{
width:200px;
}

& the below markup

<table><tr><td colspan="2" id="td1"></td></tr><tr><td id="td2"></td><td></td>
</tr><tr><td colspan="2" id="td3"></td></tr></table>


Horizontal Split:Use first style-sheet above & below markup
<table><tr><td></td></tr><tr><td></td></tr></table>

Vertical Split:Use the first style-sheet & below markup
<table><tr><td></td><td></td></tr></table>

Monday, May 26, 2008

Delegates in C#

Pointer is a variable, which stores address of some memory location. The memory location can be the storage for some value or beginning of function. When it points to function, it is function pointer. Function pointer has address of the function.

Function pointers are not safe. In thousand lines of code, if we have to invoke the function using function pointer, we cannot assure that the pointer points to function without going through the code.
We cannot ensure the number of parameters to the function or the order of parameters. Order of parameters refer to data types. What will happen if we invoked a function with function pointer & pointer is not pointing to function? What will happen if we invoked a function with function pointer & number of arguments are more or less passed? What will happen if we invoked a function with function pointer & order of parameters is wrong? (e.g. Function accepts int first & we pass string first.)

In all cases, our application will crash. In essence, Function pointers are not type-safe.

.NET has got a concept of delegates which are type-safe function pointers with ability to point to multiple functions. Delegates are declared in C# using keyword delegate.

public delegate void DisplayDelegate(string msg);

Declaration of delegate is just like function declaration. That is, the delegate must be declared with return data type & parameters. Parameter names are not relevant.

Internally, a class "DisplayDelegate" is generated which derives from System.MulticastDelegate. System.MulticastDelegate derives from System.Delegate. System.Delegate is the base class. One can create the object of "DisplayDelegate" class. The constructor accepts the function which has same signature as that of delegate declaration.
using System;

namespace DelegateDemo
{
public delegate void DisplayDelegate(string msg);
class Program
{
static void Main(string[] args)
{
DisplayDelegate del = new DisplayDelegate(Show);
del("Hello, delegate!!!");
//Or del.Invoke("Hello, delegate!!!");
}
static void Show(string str)
{
Console.WriteLine(str);
}
}
}
To invoke function using delegate, use Invoke function on delegate object with parameter values for the function. The function wrapped in delegate can be static or instance function.

Let's see, how delegates are type-safe? When one creates a delegate object, the delegate is aware of the parameters required. Wherever you call the function using delegate, compiler will not compile the program if,

  • function specified in constructor is not with appropriate function signature.
  • the number of parameters are less or more while invoking the function.
  • the order of parameters is not appropriate.
In essence, delegates are type-safe. One can catch the errors at compile-time only using delegates

A single delegate can have multiple functions. All functions must have same signature like delegate. Delegate invokes functions in FIFO(First-In,First-Out) order. If the function has return value, return value of last function invoked will be returned by delegate. Return values of all other functions are lost.

System.Delegate class has two static methods Combine and Remove. Use the methods to provide the delegate with multiple functions.
using System;
using System.Windows.Forms;

namespace DelegateDemo
{
public delegate void DisplayDelegate(string msg);
class Program
{
static void Main(string[] args)
{
DisplayDelegate del = new DisplayDelegate(Show);
DisplayDelegate del1 = new DisplayDelegate(Print);
del = (DisplayDelegate)Delegate.Combine(del, del1);
del("Hello,World!!!");
del = (DisplayDelegate)Delegate.Remove(del, del1);
del("Hi!!!");
}
static void Show(string str)
{
MessageBox.Show(str);
}
static void Print(string msg)
{
Console.WriteLine(msg);
}
}
}

System.Delegate has two properties Method and Target. The derived class have these properties inherited. "Method" property gets the method represented by delegate. "Target" gets the instance/object on which the delegate operates. "Target" returns null for static methods.
static void Main(string[] args)
{
DisplayDelegate del = new DisplayDelegate(Show);
Console.WriteLine(del.Method.Name);
if(del.Target!=null)
Console.WriteLine(del.Target.ToString());
}

If delegate has multiple functions, one can use GetInvocationList method of System.Delegate class to retrieve System.Delegate[] array.

static void Main(string[] args)
{
DisplayDelegate del = new DisplayDelegate(Show);
DisplayDelegate del1 = new DisplayDelegate(Print);
del = (DisplayDelegate)Delegate.Combine(del, del1);
foreach (DisplayDelegate minf in del.GetInvocationList())
{
Console.WriteLine(minf.Method.Name);
}
}

Wednesday, May 21, 2008

Number Flip in numeric data types

Look at the code below. It prints -128 as output. Oops!!! How?

using System;

namespace NumberFlipDemo
{
class Program
{
static void Main(string[] args)
{
sbyte i = 127;
i++;
Console.WriteLine(i.ToString());
}
}
}
Let dig out the answer.
If we look at carefully, signed byte has range from -128 to 127.
Three methods to represent negative numbers:
Signed Magnitude -->Two representations for 0; -1 repsentated as 81.
1's Complement --> Two Representation for 0; -1 represented as FE.
2'Complement --> Single Representation for 0; -1 represented as FF.
How negative numbers are represented in the machine? Let's check.See the code here.

static void Main(string[] args)
{
sbyte i = -1;
Console.WriteLine(i.ToString("x"));
//parameter "x" to ToString gives hex o/p.
}

Output is FF. Machine uses 2's complement.

How to compute 2's Complement representation?Consider we want to represent -2 in 2's complement.
Take binary representation of 2 i.e. 0000 0010. Complement all bits. Result is 1111 1101. Now add 1 to it. We will get 1111 1110 i.e. FE.

To compute 2's complement representation of a number. First complement the bits of binary representation of the number absolute.( abs(-2)=2). Add bit 1 to the complemented bits. The result is 2's complement.
Now back to our question. Why the above code snippet gives wrong o/p without any error?
Consider that size of integer is 2 bits. Hence range of numbers to be accomodated in integer data type is -2 to 1. Let put binary representation of all these numbers in a table.

1--> 01
0--> 00
-1 --> 11 (2's complement)
-2 --> 10 (2's complement)


Now if my integer variable has a extreme positive value i.e. 1 e.g. i=1;
Add 1 to i.

i+1=1+1 =>(01)+(01)=(10)=> -2
i has value 1 i.e. binary 01. Add 1 bit to it.See the result. It gives us 10 which is being binary representation for -2.

In same fashion, number flips to -128 in case of signed byte. The theory is applicable to all whole number data types i.e. byte, sbyte,int, short, long.


Be careful while making choice of data type!!! The theory applies to all programming lanaguages.

Tuesday, May 20, 2008

Extension Methods in C# 3.0

Developer code for assemblies. Compile it & publish it for client use. User of assembly may like to have some additional functionality in data types of the assembly. e.g int or Int32 do not have function to convert integer to complex number. ComplexNumber is the new data type defined by user.

Now with C# 3.0 has provided with the concept of extension methods. Extension methods enable us to extend the functionality of data types already defined. No source code of the assembly is available to modify & recompile the assembly. Still one can extend the data types functionality.

Inheritance also provides capability to extend the functionality but the extended functionality is available only for derived classes & not to the base class. e.g Consider I'd like to have a ToInt function in String class. If I use inheritance approach, I have to create new derived type. So I cannot use methods of derived type on my String objects.

Extension methods are written in static class. The method should also a static method. First parameter of the method must be of type being extended. The first parameter must have this keyword before it.

See the code below.

public static class ExtensionInt
{
public static Complex ToComplex(this int val)
{
Complex temp = new Complex();
temp.Real = val;
return temp;
}
}

Complex is the type defined as follows:

public class Complex
{
public int Real;
public int Imag;
public override string ToString()
{
return (Real.ToString() + "+i" + Imag.ToString());
}
}


Use the method ToComplex for int or Int32.
static void Main(string[] args)
{
int i = 5;
Console.WriteLine(i.ToComplex().ToString());
}

Sealed classes can take advantage of extension methods. LINQ makes use of extension methods defined in Enumerable static class. The class extends functionality of objects implementing IEnumerable interface. To use the extension methods from Enumerable class refer the assembly System.Core.