b

blu

Monday, 31 December 2012

file upload in silverlight 5 using wcf C#


Step 1) Create Silverlight Project with .Web Option
         i.e SilverlightApplication and SilverlightApplication.Web
Step 2) Add WCF service to SilverlightApplication.Web
 
Interface 
     [ServiceContract]
    public interface IService1
    {
        [OperationContract]
      bool uploads(byte[] bytes, String fileName);
    }

Implementation
public class Service1 : IService1
    {
       

 public bool uploads(byte[] bytes ,String fileName)
        {
            bool b = !true;
            try
            {
                fileName = @"C:\inetpub\wwwroot\SilverlightApplication.Web\Uploads\"+fileName;
                MemoryStream ms = new MemoryStream(bytes);
                StreamReader reader = new StreamReader(ms);
                System.IO.File.WriteAllText(fileName,reader.ReadToEnd());
                b = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return b;
        }    }

make sure permissions for uploads folder

Leave Web.config  settings, because .net 4.0 will take care of it.

Step 3)  Run the Service.
         in my App:it is http://localhost:3205/Service1.svc

Step 4) Add Service Reference to SilverlightApplication Project, it will create a proxy class.

Step5)  in the XAML Add button and Label to grid layout
<Grid x:Name="LayoutRoot" Height="378">
        <TextBlock Text="File Uploading in Silverlight using WCF Service" FontSize="16" Foreground="Red" Margin="10,10,-10,332"
                 
>
           
        </TextBlock>       
        <Button Content="Upload File(s)" HorizontalAlignment="Left" VerticalAlignment="Top" Width="159" x:Name="fileuploadone" Margin="192,106,0,0" Click="fileuploadone_Click" Height="27"/>
        <sdk:Label Content="no uploaded files" x:Name="lblfilestats" HorizontalAlignment="Left" Height="123" VerticalAlignment="Top" Width="454" Margin="58,176,0,0"/>

     

    </Grid>

Button handler invokes dialog box to select  a file(s).
Label will display Filename uploaded to server using WCF Service.

Step 6) Invoke upload WCF service client in Button Handler.

        private void fileuploadone_Click(object sender, RoutedEventArgs e)
        {
 try
            {
                OpenFileDialog od = new OpenFileDialog();
                od.Multiselect = true;
                bool? b = od.ShowDialog().GetValueOrDefault(true);
                if (b.HasValue)
                {
                    if (b.Value == true)
                    {
                        ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
                        foreach (FileInfo fi in od.Files)
                        {
                          
                            lblfilestats.Content = fi.Name + fi.Length + fi.Extension;
                            FileStream fs = fi.OpenRead();
                            byte[] bytes = new byte[fs.Length];
                          
                            client.uploadsAsync(bytes,fi.Name);
                            client.uploadsCompleted += client_uploadsCompleted;
                        }
                    }
                    else MessageBox.Show("showdialog returns false");
                    // od.Files
                }
                else MessageBox.Show("showdialog returns no value");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }          

        }

        void client_uploadsCompleted(object sender, ServiceReference1.uploadsCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
                return;
            }
            if (e.Result)lblupload.Content="Success";
            else  lblupload.Content="Failed";

          
        }


Step 7) Check Uploads Folder for uploaded files


Tags:file upload in silverlight 5 using wcf  C#, fileupload in silverlight, upload multiple files from silverlight, upload files using WCF, client side upload using wcf

MVVM in Silverlight

MVVM in Silverlight


Sunday, 30 December 2012

Programatically Add Listbox with Image and Text in Silverlight using VB.NET


Programatically Add Listbox with  Image and Text in Silverlight  using VB.NET

Step 1)    Add listbox to xaml.

Step 2)   Upload images to Silverlight Project.







Step 3)   Add Listbox Items Programatically , it includes images(shown above and with text).

          Dim panel As StackPanel =  New StackPanel() 
            panel.Orientation = Orientation.Horizontal
            Dim img As Image =  New Image() 
            img.Source = New BitmapImage(New Uri("india.jpg", UriKind.Relative))
            img.Height = 50
            img.Width = 50
            Dim blk As TextBlock =  New TextBlock() 
            blk.Text = "India"
            blk.VerticalAlignment = System.Windows.VerticalAlignment.Center
            blk.HorizontalAlignment = System.Windows.HorizontalAlignment.Right
            panel.Children.Add(img) panel.Children.Add(blk) listBox1.Items.Add(panel)
            panel = New StackPanel()
            img = New Image()
            img.Source = New BitmapImage(New Uri("australia.jpg", UriKind.Relative))
            img.Height = 50
            img.Width = 50
             blk = New TextBlock()
            blk.Text = "Australia"
            panel.Children.Add(img) panel.Children.Add(blk) listBox1.Items.Add(panel)
            panel = New StackPanel()
            img = New Image()
            img.Source = New BitmapImage(New Uri("america.jpg", UriKind.Relative))
            img.Height = 50
            img.Width = 50
            blk = New TextBlock()
            blk.Text = "america"
            panel.Children.Add(img) panel.Children.Add(blk) listBox1.Items.Add(panel)
            panel = New StackPanel()
            img = New Image()
            img.Source = New BitmapImage(New Uri("uk.jpg", UriKind.Relative))
            img.Height = 50
            img.Width = 50
            blk = New TextBlock()
            blk.Text = "UK"
            panel.Children.Add(img) panel.Children.Add(blk) listBox1.Items.Add(panel)
            panel = New StackPanel()
            img = New Image()
            img.Source = New BitmapImage(New Uri("sa.jpg", UriKind.Relative))
            img.Height = 50
            img.Width = 50
            blk = New TextBlock()
            blk.Text = "SA"
            Dim panel.Children.AddCType(As panel.Children.Add(img), blk)
 
 
            listBox1.Items.Add(panel)

Step 4) Run the Application.
Tags:Programatically Add Listbox with  Image and Text in Silverlight 5 using VB.NET,Programatically Add Listbox with  Image and Text in Silverlight 5,Listbox with Text and Image in Silverlight, Silverlight Listbox with Text and Image Programatically,Silverlight Listbox

Programatically Add Listbox with Image and Text in Silverlight

Programatically Add Listbox with  Image and Text in Silverlight

Step 1)    Add listbox to xaml.

Step 2)   Upload images to Silverlight Project.







Step 3)   Add Listbox Items Programatically , it includes images(shown above and with text).

           StackPanel panel = new StackPanel();
            panel.Orientation = Orientation.Horizontal;
            Image img = new Image();
            img.Source = new BitmapImage(new Uri("india.jpg", UriKind.Relative));
            img.Height = 50;
            img.Width = 50;
            TextBlock blk = new TextBlock();
            blk.Text = "India";
            blk.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            blk.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            panel.Children.Add(img); panel.Children.Add(blk); listBox1.Items.Add(panel);
            panel = new StackPanel();
            img = new Image();
            img.Source = new BitmapImage(new Uri("australia.jpg", UriKind.Relative));
            img.Height = 50;
            img.Width = 50;
             blk = new TextBlock();
            blk.Text = "Australia";
            panel.Children.Add(img); panel.Children.Add(blk); listBox1.Items.Add(panel);
            panel = new StackPanel();
            img = new Image();
            img.Source = new BitmapImage(new Uri("america.jpg", UriKind.Relative));
            img.Height = 50;
            img.Width = 50;
            blk = new TextBlock();
            blk.Text = "america";
            panel.Children.Add(img); panel.Children.Add(blk); listBox1.Items.Add(panel);
            panel = new StackPanel();
            img = new Image();
            img.Source = new BitmapImage(new Uri("uk.jpg", UriKind.Relative));
            img.Height = 50;
            img.Width = 50;
            blk = new TextBlock();
            blk.Text = "UK";
            panel.Children.Add(img); panel.Children.Add(blk); listBox1.Items.Add(panel);
            panel = new StackPanel();
            img = new Image();
            img.Source = new BitmapImage(new Uri("sa.jpg", UriKind.Relative));
            img.Height = 50;
            img.Width = 50;
            blk = new TextBlock();
            blk.Text = "SA";
            panel.Children.Add(img); panel.Children.Add(blk); 

            
            listBox1.Items.Add(panel);


Step 4) Run the Application.

Using linq to xml binding in silverlight datagrid VB.NET

Using linq to xml binding in silverlight datagrid VB.NET


Step 1) Create Silverlight Project using C#.NET
Step 2) Add a datagrid to  Grid/canvas/statckpanel layout Here Grid Layout

    <Grid x:Name="LayoutRoot" Background="red">
        <sdk:DataGrid
             x:Name="datagrid4"
            AutoGenerateColumns="False"
           ItemsSource="{Binding}"
Grid.Column="01" 
Grid.Row="2"
 HorizontalAlignment="Left"
 Height="150"
 VerticalAlignment="Top"
 Width="330"  
GridLinesVisibility="All" 
Margin="0,0,-180,0">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn
Foreground="Red"  Visibility="Visible"
Binding="{Binding Path=ProductName}"
Header="Prodcutname">
</sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn
Binding="{Binding Path=Quanity}"
Header="Quantity">
</sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn
 Binding="{Binding Path=UnitPrice}"
 Header="UnitPrice">
</sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn
Binding="{Binding Path=Total}"
Header="Total Amount">
</sdk:DataGridTextColumn>
 </sdk:DataGrid.Columns>
 </sdk:DataGrid>

Step 3)  For this example I used SalesOrder.xml shown below
  Note:  Add SalesOrder.xml to ClientBin Directory.
<?xml version="1.0" encoding="utf-8" ?>

<HeaderLines>
  <SalesOrder>
    <Header Date="17-02-04" Type="Quote">
      <SellTo CountryRegion="GB">
       <Name>The Cannon Group PLC</Name>
       <Address>192 Market Square</Address>
       <City>Birmingham</City>
       <Zip>B27 4KT</Zip>
     </SellTo>
     <BillTo CountryRegion="GB">
       <Name>The Cannon Group PLC</Name>
       <Address>192 Market Square</Address>
       <City>Birmingham</City>
       <Zip>B27 4KT</Zip>
     </BillTo>
     <Lines>
       <Item PartNum="LS-150">
         <ProductName>Loudspeaker, Cherry, 150W</ProductName>
         <Quantity>8</Quantity>
         <UnitPrice>12900</UnitPrice>
         <ShipmentDate />
         <Comment>Confirm the voltage is 75W</Comment>
       </Item>
          <Item PartNum="LS-MAN-10">
          <ProductName>Manual for Loudspeakers</ProductName>
          <Quantity>20</Quantity>
            <UnitPrice>100</UnitPrice>
          <ShipmentDate />
          <Comment />
       </Item>
          <Item PartNum="LS-2">
            <ProductName>Cables for Loudspeakers</ProductName>
            <Quantity>10</Quantity>
            <UnitPrice>2100</UnitPrice>
            <ShipmentDate />
            <Comment />
            </Item>
     </Lines>
     <Contact>Mr. Andy Toal</Contact>
     <Terms>14 days</Terms>
    </Header>
  </SalesOrder>
</HeaderLines>

Step 4) Add System.Xml.Linq   to the project

Step 5)  Add a Public class Equivalent to Elements you are going to fetch from XML.
in this case 3 elements 1 compute element.
 note:  if not public day may not be visible.
public Class Item
            Public ReadOnly Property ProductName() As String
                Get
            }
                End Get
            End Property
            Public ReadOnly Property Quanity() As Int32
                Get
            }
                End Get
            End Property
            Public ReadOnly Property UnitPrice() As Double
                Get
            }
                End Get
            End Property
            Public ReadOnly Property Total() As Double
                Get
            }
                End Get
            End Property
 'this is compute element.
End Class

Step 6)  Binding LINQ To XML to Datagrid in Silverlight

 Private  Sub LoadXml()
                Dim client As WebClient =  New WebClient()

                client.OpenReadCompleted += client_OpenReadCompleted
                client.OpenReadAsync(New Uri("SalesOrder.xml",UriKind.Relative))
  End Sub

     Private  Sub client_OpenReadCompleted(ByVal sender As Object, ByVal e As OpenReadCompletedEventArgs)
            Try

                Dim doc As XDocument =  XDocument.Load(e.Result)
                If doc Is Nothing Then
                     MessageBox.Show("doc is null")
                End If
                var query = from ele Function doc.Descendants(ByVal"Item") As in
                                ProductName = ele.Element("ProductName").Value,
                                Quanity = Convert.ToInt32(ele.Element("Quantity").Value),
                                UnitPrice = Convert.ToDouble(ele.Element("UnitPrice").Value),
                                Total =  Convert.ToInt32(ele.Element("Quantity").Value)*
                                         Convert.ToDouble(ele.Element("UnitPrice").Value)
                                        'Total is compute column.
                End Function



             'LINQ to XML result binding it to Silverlight DataGrid.
                datagrid4.ItemsSource = query
            Catch ex As Exception
                MessageBox.Show(ex.Message)

            End Try

     End Sub

Step7)   LINQ TO XML in Silverlight  call LoadXml on PageLoad

Private Function Page1() As Public
            InitializeComponent()
            LoadXml()
End Function

Step 8) Run the Application

using linq to xml binding in silverlight datagrid

Using linq to xml binding in silverlight datagrid


Step 1) Create Silverlight Project using C#.NET
Step 2) Add a datagrid to  Grid/canvas/statckpanel layout Here Grid Layout

    <Grid x:Name="LayoutRoot" Background="red">
        <sdk:DataGrid
             x:Name="datagrid4"
            AutoGenerateColumns="False"
           ItemsSource="{Binding}" 
Grid.Column="01" 
Grid.Row="2"
 HorizontalAlignment="Left"
 Height="150"
 VerticalAlignment="Top"
 Width="330"  
GridLinesVisibility="All" 
Margin="0,0,-180,0">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn
Foreground="Red"  Visibility="Visible" 
Binding="{Binding Path=ProductName}"
Header="Prodcutname">
</sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn 
Binding="{Binding Path=Quanity}"
Header="Quantity">
</sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn
 Binding="{Binding Path=UnitPrice}"
 Header="UnitPrice">
</sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn 
Binding="{Binding Path=Total}"
Header="Total Amount">
</sdk:DataGridTextColumn>
 </sdk:DataGrid.Columns>
 </sdk:DataGrid>

Step 3)  For this example I used SalesOrder.xml shown below
  Note:  Add SalesOrder.xml to ClientBin Directory.
<?xml version="1.0" encoding="utf-8" ?>

<HeaderLines>
  <SalesOrder>
    <Header Date="17-02-04" Type="Quote">
      <SellTo CountryRegion="GB">
       <Name>The Cannon Group PLC</Name>
       <Address>192 Market Square</Address>
       <City>Birmingham</City>
       <Zip>B27 4KT</Zip>
     </SellTo>
     <BillTo CountryRegion="GB">
       <Name>The Cannon Group PLC</Name>
       <Address>192 Market Square</Address>
       <City>Birmingham</City>
       <Zip>B27 4KT</Zip>
     </BillTo>
     <Lines>
       <Item PartNum="LS-150">
         <ProductName>Loudspeaker, Cherry, 150W</ProductName>
         <Quantity>8</Quantity>
         <UnitPrice>12900</UnitPrice>
         <ShipmentDate />
         <Comment>Confirm the voltage is 75W</Comment>
       </Item>
          <Item PartNum="LS-MAN-10">
          <ProductName>Manual for Loudspeakers</ProductName>
          <Quantity>20</Quantity>
            <UnitPrice>100</UnitPrice>
          <ShipmentDate />
          <Comment />
       </Item>
          <Item PartNum="LS-2">
            <ProductName>Cables for Loudspeakers</ProductName>
            <Quantity>10</Quantity>
            <UnitPrice>2100</UnitPrice>
            <ShipmentDate />
            <Comment />
            </Item>
     </Lines>
     <Contact>Mr. Andy Toal</Contact>
     <Terms>14 days</Terms>
    </Header>
  </SalesOrder>
</HeaderLines>

Step 4) Add System.Xml.Linq   to the project

Step 5)  Add a Public class Equivalent to Elements you are going to fetch from XML.
in this case 3 elements 1 compute element.
 note:  if not public day may not be visible.
public class Item
        {
            public String ProductName{get;set;}
            public Int32 Quanity{get;set;}
            public Double UnitPrice{get;set;}
            public Double Total{get;set;} //this is compute element.
        }

Step 6)  Binding LINQ To XML to Datagrid in Silverlight

 void LoadXml()
        {
                WebClient client = new WebClient();
               
                client.OpenReadCompleted += client_OpenReadCompleted;
                client.OpenReadAsync(new Uri("SalesOrder.xml", UriKind.Relative));
        }

     void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try{

                XDocument doc = XDocument.Load(e.Result);
                if (doc == null) MessageBox.Show("doc is null");
                var query = from ele in doc.Descendants("Item")
                            select new Item
                            {
                                ProductName = ele.Element("ProductName").Value,
                                Quanity = Convert.ToInt32(ele.Element("Quantity").Value),
                                UnitPrice = Convert.ToDouble(ele.Element("UnitPrice").Value),
                                Total =  Convert.ToInt32(ele.Element("Quantity").Value)*
                                         Convert.ToDouble(ele.Element("UnitPrice").Value)
                                        //Total is compute column.
                            };

              
             //LINQ to XML result binding it to Silverlight DataGrid.
                datagrid4.ItemsSource = query;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
              
            }

        }


Step7)   LINQ TO XML in Silverlight  call LoadXml on PageLoad

public Page1()
        {
            InitializeComponent();
            LoadXml();
        }
Step 8) Run the Application

Saturday, 29 December 2012

Embedding Custom Fonts in XAML

Embedding Custom Fonts in XAML



Adding custom font to Any control in Silverlight/WPF.

  • Add fonts to fonts directory in your Application(Web/Desktop)
  • In the Font-family Field just refer Fontfilename#FontName.
 <TextBox HorizontalAlignment="Left" Height="84" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="314" Margin="5,42,-169,0" Grid.Row="1" FontFamily="tullyshandregular.ttf#TullysHand" Grid.Column="1" FontSize="18"/>

syntax:   FontFamily="fontfile.ttf#fontname".


How to find font name->just double click on ttf file,  first line will have fontname.

OUTPUT:

Sunday, 23 December 2012

Converting String to Color Object in VB.NET Silverlight


Converting String to Color Object in VB.NET Silverlight


Dim myColor As String =  "Red"
            String xamlString = "<Canvas xmlns=\"http:'schemas.microsoft.com/winfx/2006/xaml/presentation\" Background=\""+myColor +"\"/>";

            Dim c As Canvas = CType(System.Windows.Markup.XamlReader.Load(xamlString), Canvas)
            Dim mistyRoseBrush As SolidColorBrush = CType(c.Background, SolidColorBrush)
            Dim backColor As Color =  mistyRoseBrush.Color

            Dim FinalBrush As SolidColorBrush =  New SolidColorBrush(backColor)

How do I convert a string value to a SolidColorBrush in Silverlight and C#

How do I convert a string value to a SolidColorBrush in Silverlight and C# 



Converting String to Color Object in C# Silverlight


            String myColor = "Red";
            String xamlString = "<Canvas xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" Background=\""+myColor +"\"/>";
            Canvas c = (Canvas)System.Windows.Markup.XamlReader.Load(xamlString);
            SolidColorBrush mistyRoseBrush = (SolidColorBrush)c.Background;
            Color backColor = mistyRoseBrush.Color;
            
            SolidColorBrush FinalBrush = new SolidColorBrush(backColor );

Saturday, 15 December 2012

DataGrid in SilverLight Example Vb.NET

DataGrid in SilverLight Example Vb.NET

        .Create a Silverlight  Project(including web application)

                      Silverlight 4, 5.
             .Add Datagrid and TextBlock to Grid Layout   as shown below

<UserControl x:Class="SilverlightApplication2.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" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White">
        
<sdk:DataGrid AutoGenerateColumns="True" Height="221" HorizontalAlignment="Left" Margin="0,67,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="388" />
        <TextBlock FontSize="20" Foreground="Green" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="Silverlight Data Grid Demo" VerticalAlignment="Top" Width="356" FontWeight="Bold" FontStretch="Condensed" TextWrapping="Wrap" />

    </Grid>
</UserControl>



  . Add a class called  Customers with the following properties,

   Public Class Customers        Public Property custID() As Integer
        End Property
        Public Property Name() As String
        End Property
        Public Property DOB() As DateTime
        End Property
        Public Property MemberSince() As DateTime
        End Property
        Public ReadOnly Property emailID() As String
        Get 
        }
        End Get
        End Property
 End Class


  .Fill  Customers List   with samples

Private  Sub FillData()
            custList.Add(New Customers 
            {
            custID=1, DOB=New DateTime(1973,12,12), emailID="p_pathi2020@yahoo.com", MemberSince=New DateTime(2000,12,12), Name="Peter hans" 
            }
)
            custList.Add(New Customers 
            {
            custID = 2, DOB = New DateTime(1970, 12, 12), emailID = "sam@yahoo.com", MemberSince = New DateTime(2000, 12, 12), Name = "sam benegal" 
            }
)
            custList.Add(New Customers 
            {
            custID = 3, DOB = New DateTime(1983, 12, 12), emailID = "paul@yahoo.com", MemberSince = New DateTime(2000, 12, 12), Name = "Paul hons" 
            }
)
            custList.Add(New Customers 
            {
            custID = 4, DOB = New DateTime(1993, 12, 12), emailID = "pari@yahoo.com", MemberSince = New DateTime(2000, 12, 12), Name = "whiteman pari" 
            }
)
            custList.Add(New Customers 
            {
            custID = 5, DOB = New DateTime(1988, 12, 12), emailID = "pron@yahoo.com", MemberSince = New DateTime(2000, 12, 12), Name = "Porn star" 
            }
)
End Sub

.Bind DataGird to Customer List

       Dim custList As List<Customers> =  New List<Customers>()         Private Function MainPage() As Public
            InitializeComponent()
            Me.Loaded += New RoutedEventHandler(MainPage_Loaded)
        End Function

        Private  Sub MainPage_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
            FillData()

            dataGrid1.ItemsSource = custList
        End Sub


.Here is the Output