Debugging WCF Service from Silverlight: The Breakpoint will not currently be hit at WCF Service error

Assumption

  1. Binding configuration at WCF has debugging enabled
  2. Cross domain problem has been take care of since WCF and Service is running on different servers.
  3. Visual studio is running in administrator credentials or credentials having enough permission to debug on server.

While working today I came across a requirement to debug WCF Service from Silverlight and it took me one hour to find the solution, I had above three assumptions met and I was not able to debug WCF Service from Silverlight.

I had architecture of solution as below,

clip_image001

There is nothing unusual in above architecture. I had Silverlight, Web Application and WCF as part of the same solution. Problems came when I tried to debug WCF service from Silverlight. I was getting below information at breakpoint in the service side and I was never able to hit the service while debugging.

clip_image002

I binged lot but did not get quiet good solution suggesting solving this. Eventually I found it very simple way to solve this.

Follow steps as below to hit the breakpoint in the service ,

Set web application as Startup project

clip_image003

Put breakpoint on Xaml.cs and run Silverlight application and once hitting breakpoint on XAML page stop for a while

clip_image005

While breakpoint on XAML is in hit select Tool from the menu and choose Attach to Process option

clip_image006

And then attach WCF host server.

clip_image008

Once after attaching WCF host server you should able to hit the breakpoint in WCF Service from Silverlight.

I hope this post was useful. Thanks for reading.

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

 

Fetching selected value from List Box in Silverlight

Let us say you have a list box as below. You have a requirement that on click of button fetch value of the same row button belongs to.

For example if you are clicking second cross, you should able to fetch value Pinal, SqlServer , 500 from the list box.

clip_image001

In above list box

  • There is a button (cross image) in each item.
  • Text blocks bind with data.
  • List box is bind to the collection.

XAML of list box is as below,

<ListBox x:Name="lstData" Margin="5,7,6,15">
<ListBox.ItemTemplate>
<DataTemplate >
<Grid x:Name="TopGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Margin="5,5,5,5" Click="Button_Click">
<Button.Template >
<ControlTemplate >
<Image Source="delete.png" VerticalAlignment="Center"   Height="30" Width="30"/>
</ControlTemplate>
</Button.Template>
</Button>
<Grid x:Name="nestedGrid" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}" />
<StackPanel Grid.Row="1" Orientation="Horizontal">
<TextBlock Text="{Binding Interest}"  Style="{StaticResource PhoneTextSubtleStyle}" />
<TextBlock Text="{Binding Totalposts}" Style="{StaticResource PhoneTextAccentStyle}"/>
</StackPanel>
</Grid>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>

&nbsp;

Item source of list box is set to List of Bloggers.

image

Bloggers class is as below,

Note: Make sure you are calling OnNotifyPropertyChanged() after seeting the value of the property [Edited]


public class Bloggers : INotifyPropertyChanged
{
private string name;
public string Name
{
get
{
return name;
}
set
{
NotifyPropertyChanged("Name");
name = value;
}
}

private string interest;
public string Interest
{
get
{
return interest;
}
set
{
NotifyPropertyChanged("Interest");
interest = value;
}
}

private int  id;
public int  Id
{
get
{
return id;
}
set
{
NotifyPropertyChanged("Id");
id = value;
}
}

private int  totalposts;
public int Totalposts
{
get
{
return totalposts;
}
set
{
NotifyPropertyChanged("Totalposts");
totalposts = value;
}
}

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

#endregion

&nbsp;

}

&nbsp;

Now on click event of button if you want to fetch particular list item then first take data context as blogger

clip_image002

Then fetch list box item as below,

clip_image004

Now you would able to use data as below

clip_image005

On click event of button you need to write code as below to fetch particular item list value.


private void Button_Click(object sender, RoutedEventArgs e)
{

Bloggers data = (sender as Button).DataContext as Bloggers;
ListBoxItem bloggerToDeleteFromListBox = this.lstData.ItemContainerGenerator.ContainerFromItem(data)
as ListBoxItem;
var Name = data.Name
}

In this way you can fetch the value of particular list item. I hope this post was useful. Thanks for reading J

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Creating Deep Zoom Images through c# code

In this quick post, I will show you the creation of deep zoom images from Image in Azure BLOB. You may come with a requirement where you need to create deep zoom images using code. If you need deep zoom images for Pivot Viewer you can very much create it using several tools available. However you may have to create deep zoom images using code in some scenario. I am going to share code snippet for the same.

Very first you need to include DeepZoomTools dll as a reference in your project.

Add namespace

clip_image001

Next you need to create Container and set the basic properties as below,

clip_image003

Next create list of images you want to convert as deep zoom image. For purpose of this post, I am taking only one image. That image is in Azure Blob. So for that I am giving URL of the Image saved in azure Blob. You can choose image from local storage as well.

clip_image005

In last step you need to create deep zoom images using the create method of CollectorCreator

clip_image006

For reference full source code is as below,


protected void Button1_Click(object sender, EventArgs e)
{

string directoryToSaveDeepZoomImages = "D:\\abc";

CollectionCreator collectionCreator = new CollectionCreator();
collectionCreator.TileSize = 256;
collectionCreator.TileFormat = Microsoft.DeepZoomTools.ImageFormat.Png;
collectionCreator.ImageQuality = 1.0;
collectionCreator.TileOverlap = 0;

List<Microsoft.DeepZoomTools.Image> images =
new List<Microsoft.DeepZoomTools.Image>();
images.Add(new Microsoft.DeepZoomTools.Image("azuerbloburlforimage"));

collectionCreator.Create(images, directoryToSaveDeepZoomImages);
}

&nbsp;

In this way you can create deep zoom images. I hope this post was useful. Thanks for reading  Smile

 

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Upload Image from Silverlight to Azure BLOB using WCF

Working with Azure Blob is very common task you must be doing. Sometime you may come with requirement to upload an image from Silverlight client to Azure BLOB. In this post I am trying to help you in achieving this.

In this post I will show you below three stuffs.

  1. Uploading Image to Azure BOLB
  2. Abstracting BLOB upload code in WCF service
  3. Using WCF Service in Silverlight client to upload the image.

Expected Output

image

Flow of application

Step 1: On click event of Button File Dialog will open

Step 2: User will select Image and on selection Image will get uploaded in Azure Blob.

Step 3: On successful uploading URI of image will be returned from the service. Source property of Image control would be set to the returned URL.

Creating Service

Service Contract will have an function expose as operation contract as below,


[ServiceContract]
public interface IBLOBImageUpload

{

[OperationContract]
string UploadImage(byte[] Image);

}

Service is implemented as below,

  • We are creating a new GUID to set as file name of the image
  • Converting input byte array to stream
  • Calling a function to upload stream to blob
  • And returning URL of uploaded image
public string  UploadImage(byte[] Image)
{
string rowKeynFileName = Guid.NewGuid().ToString();
System.IO.Stream stream = new System.IO.MemoryStream(Image);
string imageUri= UploadImageinBlob(stream, rowKeynFileName );
return imageUri;

}

Function to upload Image in BLOB is as below

  • It is taking stream as input to upload
  • It is taking filename to be given to upload image
  •  DataConnectionString is connection string to Azure storage.
  •  urlContainer is name of the public container
  • Creating blob name by appending .jpg extension
  • Returning URL of uploaded image.

public string UploadImageinBlob(Stream Streams,string FileName)
{
CloudStorageAccount account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("urContainer");
string uniqueBlobName = string.Format("{0}.jpg", FileName);
CloudBlob blob = container.GetBlobReference(uniqueBlobName);
blob.Properties.ContentType = "image\\jpeg";
Streams.Seek(0, SeekOrigin.Begin);
blob.UploadFromStream(Streams);
string url = blob.Uri.OriginalString;
Streams.Close();
return url;

}

Configuring Service EndPoint

There are many points you need to put in mind while configuring the service end point.

  • Change maxReceivedMessageSize to 2147483647
  • Change maxBufferSize to 2147483647
  • Change maxArrayLength to 2147483647
  • Change maxBytePerRead to 2147483647
  • Change maxDepth to 2147483647
  • Change maxTableCharCount to 2147483647
  • Change maxStringContentLength to 2147483647
  • In Service behavior change data contract serliazer max object graph value to 2147483647

<system.serviceModel>

<bindings>

<basicHttpBinding>

<binding name="ServicesBinding"

maxReceivedMessageSize="2147483647"

maxBufferSize="2147483647">

<readerQuotas

maxArrayLength="2147483647"

maxBytesPerRead="2147483647"

maxDepth="2147483647"

maxNameTableCharCount="2147483647"

maxStringContentLength="2147483647" />

</binding>

</basicHttpBinding>

</bindings>

<services>
<service name="Service.BLOBImageUpload" behaviorConfiguration="ServiceData.Service1Behavior">

<endpoint address="" binding="basicHttpBinding" contract=" Service.IBLOBImageUpload " bindingConfiguration ="ServicesBinding" />

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name ="ServiceData.Service1Behavior">

<serviceMetadata httpGetEnabled="true"/>

<serviceDebug includeExceptionDetailInFaults="false"/>

<dataContractSerializer maxItemsInObjectGraph ="2147483647"/>

</behavior>

</serviceBehaviors>

</behaviors>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

</system.serviceModel>

&nbsp;

Now your service is written. You can choose service to host anywhere you want.

Creating UI

I have kept UI as sweet and simple as possible. There is just a button and image control. On click of button FileDialogBOX will open and user can select an image to upload. After successful uploading, URL of uploaded image in Azure blob will be returned and that will be set as source of Image control


<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>

<RowDefinition Height="100" />
<RowDefinition Height="*" />

</Grid.RowDefinitions>

<Button x:Name="btn" Height="100" Width="100" Click="btn_Click" Content="Upload Image" />
<Image Grid.Row="1" x:Name="img" Height="auto" Width="auto" />
</Grid>

&nbsp;

Calling Service

You need to make a normal service call

  • On click event of the button opening the file dialog
  • Converting stream to byte array
  • Passing byte array as input to the function.
  • GetImageSource function is converting given string URL as image source to be set as source of image control

public partial class MainPage : UserControl
{

public OpenFileDialog fileDialog = null;
public MainPage()
{
InitializeComponent();
}

private void btn_Click(object sender, RoutedEventArgs e)
{
Stream strm;
byte[] buffer = null; ;
fileDialog = new OpenFileDialog();
fileDialog.Multiselect = false;
fileDialog.Filter = "All Files|*.*";
bool? retval = fileDialog.ShowDialog();
if (retval != null && retval == true)
{
strm = fileDialog.File.OpenRead();
buffer = new byte[strm.Length];
strm.Read(buffer, 0, (int)strm.Length);
}

BLOBImageUploadClient proxy = new BLOBImageUploadClient ();

proxy.UploadImageAsync(buffer);
proxy.UploadImageAsync += new EventHandler<UploadImageCompletedEventArgs>(proxy_UploadImageCompleted);
}

void proxy_UploadImageCompleted (object sender, UploadImageCompletedEventArgs e)
{

img.Source = GetImageSource(e.Result.ToString());
}

private ImageSource GetImageSource(string fileName)
{
return new BitmapImage(new Uri(fileName, UriKind.Absolute));
}

}
}

&nbsp;

This is what all you need to do as far as coding is concern. Yes you may need to put clientacccesspolicy.xml at the root location of server where you are hosting WCF service to avoid cross domain problem.

I hope this post was useful. Thanks for reading Smile

If you find my blogs useful you may like to,

Follow me on twitter http://twitter.com/debug_mode

Like Facebook page of this blog http://www.facebook.com/DebugMode.Net

If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Silverlight 5 Multi Column and Linked Text

If you are designer of text and love to play around text formatting’s, then you would love to use Multi Columns and Link text in Rich Text Box. This feature gives your ability to display overflowed content in next box or column rather than using scroll bar to read through all the content.

While working with RichText Box you had option that If paragraphs and text is more than height and width of RichText Box you show then using scroll bars. Now in Silverlight 5, you can link overflowed content to next column or box.

If you link text in multi columns, you will get expected output as below,

image

All columns [You may say box as well] all linked to each other. You can put boxes as you want. In above case three boxes are in three different columns, if you want you can put Column2 and Column 3 in same columns.

If you have a RichTextBox like below and this may be having many contents.

image

Now you want to link this RichText Box with RichTextOverFlow such that overflow content will be displayed in next box.

image

It can be done as below,

image

This is very nice feature you can use to create multicolumn content. For your reference source code of output, I shown earlier is given blow,


<UserControl x:Class="SilverlightApplication9.MainPage"
xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation"></a>"
xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>"
xmlns:d="<a href="http://schemas.microsoft.com/expression/blend/2008"></a>"
xmlns:mc="<a href="http://schemas.openxmlformats.org/markup-compatibility/2006"></a>"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White">
<RichTextBlock x:Name="FirstBox"
HorizontalAlignment="Left"
Width="100"

OverflowContentTarget="{Binding ElementName=SecondBox}"
Margin="33,0,0,0">
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
<Paragraph>what we are going to do with our attitude does matter ...</Paragraph>
<Paragraph>what we are going to do with our attitude does matter.</Paragraph>
</RichTextBlock>
<RichTextBlockOverflow  x:Name="SecondBox" HorizontalAlignment="Right"
Width="100"
OverflowContentTarget="{Binding ElementName=ThirdBox}"
Margin="0,0,45,250">

</RichTextBlockOverflow>
<RichTextBlockOverflow x:Name="ThirdBox"
HorizontalAlignment="Right"
Width="100"
Margin="0,0,194,195">
</RichTextBlockOverflow>
</Grid>
</UserControl>

I hope this post was useful. Thanks for reading Smile

If you find my blogs useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of this blog http://www.facebook.com/DebugMode.Net

If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Charts in Windows Phone 7

Today morning I got a call from SQL Server Guru  Pinal Dave and conversation was as below.

image

 

image

 

image

 

So, I started working on this. I decided to go ahead with hard coded data as below,

 


public class Bloggers
    {
        public string Name { get; set; }
        public double Posts { get; set; }
    }


And function returning data is,

 


public static List<Bloggers> GetMembers()
        {
            List<Bloggers> lstMembers = new List<Bloggers>
                                        {
                                            new Bloggers
                                            {
                                                 Name ="Pinal",
                                                 Posts = 2000

                                            },
                                            new Bloggers
                                            {

                                                 Name ="Debugmode",
                                                 Posts = 400
                                            },

                                             new Bloggers
                                            {

                                                 Name ="Koiarala",
                                                 Posts = 1000


                                            },
                                              new Bloggers
                                            {

                                                 Name ="Mahesh",
                                                 Posts = 1500


                                            },


                                        };
            return lstMembers;
        }



image

 


<Grid x:Name="LayoutRoot">
        <controls:Panorama Title="Bloggers">

            <!--Panorama item one-->
            <controls:PanoramaItem Header="Series Chart">
                <Grid>
                    <charting:Chart x:Name="seriesChart" Background="Black">
                        <charting:ColumnSeries Background="Black" />
                    </charting:Chart>
                </Grid>
            </controls:PanoramaItem>

            <!--Panorama item two-->
            <controls:PanoramaItem Header="Pie Chart">
                <Grid>
                    <charting:Chart x:Name="pieChart"></charting:Chart>
                </Grid>
            </controls:PanoramaItem>
            <!--Panorama item three-->
            <controls:PanoramaItem Header="Scatter Chart">
                <Grid>
                    <charting:Chart x:Name="scatterChart"></charting:Chart>
                </Grid>
            </controls:PanoramaItem>
        </controls:Panorama>
    </Grid>




 

To add chart control on XAML, I added namespace on XAML as below ,

 


 xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;
assembly=System.Windows.Controls.DataVisualization.Toolkit"


And on code behind as below,

 


using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.DataVisualization.Charting;
using System.Windows.Data;


Creating Column Series


ColumnSeries series = new ColumnSeries();
            seriesChart.Series.Add(series);
            series.SetBinding(ColumnSeries.ItemsSourceProperty, new Binding());
            series.ItemsSource =  GetMembers();
            series.DependentValuePath = "Posts";
            series.IndependentValuePath = "Name";



There is nothing to get confused in above code. It is creating a Column Series and adding to the chart in the first panorama item. Expected output would be as below ,

image

 

Creating Pie Series



PieSeries pieSeries = new PieSeries();
            pieChart.Series.Add(pieSeries);
            pieSeries.SetBinding(PieSeries.ItemsSourceProperty, new Binding());
            pieSeries.ItemsSource = Model.Factory.GetMembers();
            pieSeries.DependentValuePath = "Posts";
            pieSeries.IndependentValuePath = "Name";



Expected output is as below,

image

 

Creating Scatter Series


ScatterSeries scatterSeries = new ScatterSeries();
scatterChart.Series.Add(scatterSeries);
scatterSeries.SetBinding(ScatterSeries.ItemsSourceProperty, new Binding());
scatterSeries.ItemsSource = Model.Factory.GetMembers();
scatterSeries.DependentValuePath = "Posts";
scatterSeries.IndependentValuePath = "Name";


Expected Output is as below,

image

 

image

 

Nested ListBox binding in Silverlight and Windows Phone 7

While creating an application I came across a requirement when I had to put a listbox inside a list box and then I had bind that nested listbox dynamically.

For example say, entity class called Roles as below,



    public class Roles
    {
        public string RollName { get; set; }
    }


And you are using Role class in another entity class called Subscription as property


  public class Subscription
    {
        public string SubscriptionName { get; set; }
        public List<Roles> lstRoles { get; set; }
    }


We need to achieve,

image

There is function to return Data to bind to nested list box as below,



List<Subscription> GetDataToBind()
        {
           List<Subscription> lstSubscriptions = new List<Subscription>
                                                {
                                                   new Subscription
                                                   {
                                                       SubscriptionName ="Susbcription1",
                                                       lstRoles = new List<Roles>
                                                       {
                                                            new Roles
                                                            {
                                                                RollName = "Role1"
                                                            },
                                                             new Roles
                                                            {
                                                                RollName = "Role2"
                                                            },
                                                             new Roles
                                                            {
                                                                RollName = "Role3"
                                                            }
                                                       }
                                                   },
                                                   new Subscription
                                                   {
                                                   SubscriptionName ="Susbcription2",
                                                       lstRoles = new List<Roles>
                                                       {
                                                            new Roles
                                                            {
                                                                RollName = "Role1"
                                                            },
                                                             new Roles
                                                            {
                                                                RollName = "Role2"
                                                            },
                                                             new Roles
                                                            {
                                                                RollName = "Role3"
                                                            }
                                                       }
                                                   }
                                                };
           return lstSubscriptions;

        }


As of now we are ready with

  1. Entity class
  2. Data source

image

And there is one more property in of generic list type in entity class. To bind that you need to set item source of internal list box as binding.

image

Final XAML will be as below,



<ListBox Height="646" HorizontalAlignment="Left" Margin="6,19,0,0" Name="listBox1" VerticalAlignment="Top" Width="444" >

                <ListBox.ItemTemplate>
                    <DataTemplate>
                    <Grid x:Name="grdListItem" Width="440">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="201*"/>
                            <ColumnDefinition Width="239*" />
                        </Grid.ColumnDefinitions>
                            <Image Source="AzureLogo.png" Height="100" Width="100" Grid.Column="0" />
                            <TextBlock x:Name="txtSubscription" Grid.Column="1" Height="100" Margin="6,0" Text="{Binding SubscriptionName}" />

                        <ListBox x:Name="lstWebRoles" Grid.Column="1" Margin="10,0,0,0" ItemsSource="{Binding lstRoles}" >
                                <ListBox.ItemTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Vertical" >
                                    <TextBlock x:Name="txtRoles" Height="80" Width="220" Text="{Binding RollName}" />
                                </StackPanel>
                                  </DataTemplate>
                                 </ListBox.ItemTemplate>
                           </ListBox>

                    </Grid>
                    </DataTemplate>
                    </ListBox.ItemTemplate>
            </ListBox>



Eventually put item source of external list box as,



public MainPage()
        {
            InitializeComponent();
            listBox1.ItemsSource = GetDataToBind();
        }

In this post we discussed binding of nested listbox in Silverlight. I hope this post was useful. Thanks for reading.  Smile

Learn WCF RIA Service: Day 3

Learn WCF RIA Service: Day 1

Learn WCF RIA Service: Day 2

Overview of Domain Service Class

On day 2 we ran through creating our first line of business application using RIA services. We did not look deeper much into generated classes. Today we will take a step back and examine Domain Service class. Better understanding on Domain Service class would give us more efficiency to create, share and focus on application logic in between presentation layer and middle layer.

If you go ahead and open solution explorer of project we created on day 2, you will get two projects, one Silverlight and other hosting web project there.

image

If you remember we added Domain Service class to the web project and we enabled metadata for domain services as well. Due to that you are seeing there is a metadata.cs class in solution explorer.

Open SchoolRIAService.cs and first thing you would notice would be as in below image.

image

  1. Attribute EnableClientAccess tells this domain class would be visible to the presentation layer residing at client side.
  2. The class is derived from LinqToEntitiesDomainService. This is generic abstract class and it is part of WCF RIA Service framework.
  3. Generic class is taking data model class as input to create domain service.

Next you move further in the class you will find different CRUD methods for different entities from data model. If you have four entities in data model then you will have 16 methods here. For each entity there would be four methods.

Below four methods would perform CRUD operation for Course entity.

image

In this way you will find CRUD methods for other entities like Departments, OnlineCourses etc

If you remember at time of creating Domain Service class, we checked the check box against entities class to enable editing.

image

Besides different generated methods you can plug application logic in this Domain Service class. You can modify existing application logic also for example modifying logic behind GetCourse() method.

I will conclude day 3 with assumption that by now you have an overview of Domain Service Class.

See you on day 4 Smile

Learn WCF RIA Service: Day 2

Learn WCF RIA Service: Day 1

Building a simple line of business Application using RIA Services

Last day we had enough of theory on RIA Services. Today let us get our hand dirty and launch visual studio. We will keep it simple and easy in flow since it is our first exercise.

Essentially we will fetch data from Person table and bind it to grid view on Silverlight page. Flow diagram of the application we are going to make would be as below diagram.

image

Building Silverlight Application

Start with creating a Silverlight application.

image

Next you will get prompted to choose

  1. Web site to host Silverlight application
  2. Select Silverlight target version

And if you have WCF RIA services installed then you will get a check box to instruct Silverlight whether you want to enable WCF RIA Service for this particular Silverlight application or not ? You want to enable WCF RIA service so check the checkbox Enable WCF RIA Services.

image

We have instructed Silverlight application while creating that we want RIA Service enabled and next we need to create Data Model to be exposed and share data through this model in between presentation layer and middle layer.

Building Data Model

To create data model right click on web project [project with extension .web] and choose option add new item from context menu.

image

Next from Data tab you need to choose ADO.Net Entity Model template. We are going to use ADO.Net Entity Model ORM to create data model. ADO.Net Entity Model creates model with extension edmx. Change name of created edmx file to SchoolModel.edmx.

image

After clicking on add button, you will be prompted to choose the source of data model. Either you can create empty data model or choose a database as a source to create data model. We are going to choose School database residing on my local server as a source of data model. So select Generate from database option and click on next button

image

Now you will be prompted to choose database object. If school database is not listed in drop down then you can create a New Connection else you can choose from the dropdown. Let us proceed with creating a new connection

On clicking of New Connection button, you will be prompted with dialog box to specify database connection properties. Specify different values as of below image and click on Test Connection. After getting successful message click on Ok button.

image

In Data connection dialog box if you want you can change the name of connection setting in web.confg. However I am leaving the default name.

image

Click on next button to get last dialog box to conclude data model creation. Here you need to choose database objects you want to put as mart of data model. You can have tables, views, and stored procedures from database as part of data model. I am selecting all tables and stored procedures as part of data model. If you want you can change namespace name but for sake of simplicity at this point leave everything else as default.

image

On click on Finish button you will get data model created and you will get data model file open in designer surface. Here you can notice mapped between the entities.

image

In solution explorer you will find SchoolModel.edmx file has been added under the web project.

clip_image001

Building Domain Service

To create data model right click on web project [project with extension .web] and choose option add new item from context menu.

image

Next from Web tab you need to choose Domain Service class template. Change name to SchoolRIAService.cs and click on Add button.

image

In next dialog box go ahead and

  1. Select DataContext or ObjectContext class from the dropdown. You will get SchoolEntities context class in drop down value to choose.
  2. You can edit Domain Service class name. For simplicity leave it as it is.
  3. You have check box to specify Enable Client Access. Check this check box.
  4. You have check box to specify whether you want to expose ODATA Endpoint. For this time uncheck it.
  5. You will get all the entities from the context class listed. You can choose from them to be exposed as RIA Service. I am selecting all the entities and enabling all entities for edit.
  6. Check the box generates associated class for metadata.

image

Click on OK button and give a second to examine web project in solution explorer. You will find three classes added there. We will examine and talk more on these classes in coming days. Today we are just going to see there uses at the presentation layer in Silverlight project.

image

Using Domain Service in Presentation layer or Silverlight client

You have,

  1. Created data model
  2. Create domain service

Now build the web project and add below namespace on MainPage.xaml.cs file.

image

After adding namespaces open MainPage.xaml and drag and drop a data grid on that. Give name of the data grid as grdRIADataGrid. Xaml would be as below,

MainPage.Xaml


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

    <Grid x:Name="LayoutRoot" Background="White">
    <sdk:DataGrid x:Name="grdRIADataGrid" />
    </Grid>
</UserControl>

At this point designing of page has been completed. You need to bind data from person table to data grid. For that

1. Create instance of domain service class

clip_image001[5]

2. Load all people to the context of client side proxy

clip_image003

3. Fetch the entities from loaded list of entities and bind as item source of data grid

clip_image004

Code behind would look like as below,

MainPage.xaml.cs


using System.Windows.Controls;
using DemoDay2.Web;
using System.ServiceModel.DomainServices.Client;
namespace DemoDay2
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            SchoolRIAContext proxy = new SchoolRIAContext();
            LoadOperation<Person> loadPerson = proxy.Load(proxy.GetPeopleQuery());
            grdRIADataGrid.ItemsSource = loadPerson.Entities ;
        }
    }
}

Now you run Silverlight project and in data grid you will get the entire person from school database using RIA Service.

clip_image002

Today we followed a simple path and fetched data from database and bind to data grid on at Silverlight client using RIA Service. We have not gone deeper into different aspect of context class. We will discuss then in further days. I will conclude day two with assumption that by now you know,

  1. Why WCF RIA?
  2. Creating simple line of business application using RIA Services

See you on day 3 Smile

Learn WCF RIA Service: Day 1

Working with JavaScript in Silverlight 4.0

In this post I will show you calling of Javascript function from Silverlight. It is very simple and straight forward.

Assume you have a JavaScript function on aspx page as below,

SilverlightTestPage.aspx


<script type="text/javascript" language="javascript" >
         function callmeonPageLoad() {
             alert("Hello Javascript from Silvertlight");
         }
    </script>


You want to call this Javascript function on page load of the Silverlight page then you will have to add namespace

clip_image001

And in the constructor of the page call it as below,

MainPage.xaml.cs


using System.Windows.Controls;
using System.Windows.Browser;

namespace SilverlightApplication7
{
   [ScriptableType]
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            HtmlPage.RegisterScriptableObject("MainPage", this);
            HtmlPage.Window.Invoke("callmeonPageLoad");

        }
    }
}


If you notice above code you would find that MainPage is attributed with ScriptableType.

clip_image002

On running Silverlight application you will be getting output as below,

clip_image004

On your XAML if you have textbox like below,

clip_image005

You want to access and change value of textbox txtName in Javascript then it too is very simple. Create a function Javascript as below,

SilverlightTestPage.aspx


 <script type="text/javascript">
        function UpdatingTextBoxValue(sender)
        {

            var txtBlockFromSL = sender.FindName("txtName");
            alert(txtBlockFromSL.text);
            txtBlockFromSL.Text = "Salsa ";
            alert(txtBlockFromSL.Text);


        }
</script>



txtName is name of the Silverlight text box.

And on the page load on aspx page add a param

clip_image001[5]

If you have a function in managed code and you want to access that from javacript .Assume you have function as below,

MainPage.xaml.cs



  [ScriptableMember]
       public void SilverLightFunction(string txtToUPdate)
        {
            txtName.Text = txtToUPdate;
        }





You can call this function from JavaScript as below,


 <script type="text/javascript">
        function UpdatingTextBoxValue(sender)
        {


            var host = sender.GetHost();
            host.content.MainPage.SilverLightFunction("Dhananjay");


        }
</script>



This was all about various ways to work with Silverlight and JavaScript. I hope this post was useful. Thanks for reading.