Tuesday 28 February 2012

IMultiValueConverter In Silverlight:-


Silverlight does not support IMultiValueConverter.There may be scenorios like binding the label with FullName using FirstName and LastName propertys.So we can achieve this using Dependency Propertys.

->Create a User class.

public class User
 {
        public string FirstName { get; set; }

        public string LastName { get; set; }
}

->Create a MyLabel class and inherit from Label class.

 public class MyLabel : Label
    {
        //Full name property.
        public string FullName
        {
            get
            {
                return (string)GetValue(FullNameProperty);
            }
            set
            {
                SetValue(FullNameProperty, value);
            }

        }

        //Dependency property for fullname.
        public static readonly DependencyProperty FullNameProperty = DependencyProperty.Register("FullName", typeof(string), typeof(MyLabel), null);

        //Constructor.
        public MyLabel()
        {
            //Adding load event.
            Loaded += new RoutedEventHandler(MyLabel_Loaded);
        }

        //Load event.
        void MyLabel_Loaded(object sender, RoutedEventArgs e)
        {
            //Add the fullname and lastname.
            this.Content = FullName + this.Content;
        }
    }

->Add the MyLabel control in xaml for FullName.

<UserControl x:Class="SilverlightIMultiValueConverter.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" Loaded="UserControl_Loaded"
             xmlns:dep="clr-namespace:SilverlightIMultiValueConverter">

    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox Name="lstUsers">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="50"></ColumnDefinition>
                            <ColumnDefinition Width="50"></ColumnDefinition>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Text="{Binding Path=FirstName}"></TextBlock>
                        <TextBlock Grid.Column="1" Text="{Binding Path=LastName}"></TextBlock>
                        <dep:MyLabel Grid.Column="2" FullName="{Binding FirstName}" Content="{Binding Path=LastName}"></dep:MyLabel>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

->In user control load event bind the listbox.
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //User list
            List<User> lstUser = new List<User>();

            //Adding users.
            lstUser.Add(new User() { FirstName = "David", LastName = "Jackson});
            lstUser.Add(new User() { FirstName = "ANDERSON", LastName = "ANDI"});
            lstUser.Add(new User() { FirstName = "ANDRA", LastName = "Jackson”});

            //Set the itemsource here.
            lstUsers.ItemsSource = lstUser;
        }


Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

IValueConverter In Silverlight:-


While binding data the IValueConverter gives flexibility.For this we have to  implement IValueConverter and use Convert function.

->Create a User class.

public class User
 {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }
 }

->Create a Converter class and implement IValueConverter methods.

public class Converter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //Check the parameter.
            if (parameter.ToString() == "Message")
            {
                //Create custom message here by using first name.
                return "Hai " + value.ToString();
            }
            else
            {
                return null;
            }
        }

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

->Add the Converter class in xaml as static resource.
<UserControl x:Class="SilverlightIValueConverter.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" Loaded="UserControl_Loaded"
    xmlns:con="clr-namespace:SilverlightIValueConverter">
    <UserControl.Resources>
        <con:Converter x:Name="converter"></con:Converter>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox Name="lstUsers">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions >
                            <ColumnDefinition Width="100"></ColumnDefinition>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Name="txtFirstName" Text="{Binding Path=FirstName}"></TextBlock>
                        <TextBlock Grid.Column="1" Name="txtLastName" Text="{Binding Path=LastName}"></TextBlock>
                        <TextBlock Grid.Column="2" Name="txtAge" Text="{Binding Path=Age}"></TextBlock>
                        <TextBlock Grid.Column="3" Name="txtAddress" Text="{Binding Path=Address}"></TextBlock>
                        <TextBlock Grid.Column="4" Name="txtMessage" Text="{Binding Path=FirstName,Converter={StaticResource converter},ConverterParameter=Message}"></TextBlock>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

->In user control load event bind the listbox.
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //User list
            List<User> lstUser = new List<User>();

            //Adding users.
            lstUser.Add(new User() { FirstName = "David", LastName = "Jackson", Age = 23, Address = "WC" });
            lstUser.Add(new User() { FirstName = "ANDERSON", LastName = "ANDI", Age = 23, Address = "WC" });
            lstUser.Add(new User() { FirstName = "ANDRA", LastName = "Jackson", Age = 23, Address = "WC" });

            //Set the item source here.
            lstUsers.ItemsSource = lstUser;
        }


Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

Database Accessing In Silverlight:-


We can’t access database directly in Silverlight.The most comman ways to get database access is 1.Wcf services.2.Wcf RIA services.
1.Using first way we have to create wcf service and add database accessing logic in wcf service.
2.The best way is wcf RIA(Rich internet applications).
->Create Silverlight project and check the enable WCF RIA Services checkbox.

->For this example I have created a simple database table like below.

->Click Silverlight web project and add ADO.NET Entity Data Model file
and select  connection and table from you database.

.->Your model should look like this when you are done.

->Build solution.
-> Click Silverlight web project and add Domain Service Class.Check your table,
    Enable editing check boxes and Generate associated classes for metadata.

Now you can put all your server side data access code and logic into the UserService.cs class.
->Build solution.
->Goto Silverlight application properties select you web project in Wcf RIA Services link dropdown.

Here we have to use context for calling methods in UserService.
In MainPage add data grid.
<sdk:DataGrid  Name="dgUsers"/>

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
      //The DomainContext corresponding to the 'UserService' DomainService.
      DatabaseAccess.Web.UserContext objContext = new Web.UserContext();

      //Set the item source.
      dgUsers.ItemsSource = objContext.Users;

      //Query the users.
      objContext.Load(objContext.GetUsersQuery());

}

Custom Methods:-
We can add our own methods in UserService.cs class.
Add CustomGetUser function in UserService.cs class.
[Invoke]
public List<User> CustomGetUsers()
{
            string connectionString = "you connection string…";
            SqlConnection sqlConnection = new SqlConnection(connectionString);
            DataSet objSet = new DataSet();
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = sqlConnection;
            sqlCommand.CommandText = "SELECT [iUserId],[vcUserName],[vcCity],[vcCountry],[vcMobile] FROM [Blog].[dbo].[User]";
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
            sqlDataAdapter.SelectCommand = sqlCommand;
            sqlDataAdapter.Fill(objSet);

            List<User> lstResult = new List<User>();
            User item;

            if (objSet.Tables.Count > 0)
            {
                foreach (DataRow dr in objSet.Tables[0].Rows)
                {
                    item = new User();
                    item.iUserId = Convert.ToInt32(dr["iUserId"].ToString());
                    item.vcUserName = dr["vcUserName"].ToString();
                    item.vcCity = dr["vcCity"].ToString();
                    item.vcCountry = dr["vcCountry"].ToString();
                    item.vcMobile = dr["vcMobile"].ToString();
                    lstResult.Add(item);
                }
            }
            return lstResult;
}

Call this function from main page as
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
            //Call the function.
            objContext.CustomGetUsers(CallBack, null);

}

//Callback.
void CallBack(InvokeOperation<List<User>> e)
{
  if (!e.HasError)
     {
         //User list.
         List<User> lstUsers = new List<User>();

         //Get the users list.
         lstUsers = e.Value;

          //Set the item source.
          dgUsers.ItemsSource = lstUsers;
        }
   }


Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com