How to use Bing Maps In Windows 7 Phone

by Naveen 27. July 2010 05:12

Download Sample Project (41.34 kb)

using bing maps in Windows 7 phone

Some of the cool applications on smart phones are developed to help present information to the user based on their geo locations. And lot of time it involves using maps. Since Windows 7 Phone development platform is based on Silverlight, use of Bing Maps Silverlight Control comes as a natural choice. But so far there is not a official release of the control specific to Windows 7 Phone. Good news is that since Windows 7 Phone SDK is built on top of Silverlight 3 platform, you can use current release of Bing Maps Control for Silverlight with a small caveat. In this post I will discuss how to use Bing Maps in Windows 7 Phone.

First thing first. You will need to make sure that you all the tools needed for Bing Maps development. I have explained this in my earlier post Using Bing Maps In Silverlight 4. The steps to use Bing Maps Silverlight Control are exactly the same as in your conventional Silverlight application development.

How to use Bing Maps in Windows 7 Phone

  • Create Windows 7 Phone project in Visual Studio 2010
  • Add reference to following assemblies in your project from location where you installed Bing Maps SDK.
    • Microsoft.Maps.MapControl
    • Microsoft.Maps.MapControl.Common

    Now compile the project to make sure that the reference to Bing Maps are correctly included. This is where you will hit the first road block. You will get a compile time error.

    error CS0234: The type or namespace name 'Maps' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
    The primary reference "Microsoft.Maps.MapControl" could not be resolved because it has an indirect dependency on the framework assembly "System.Windows.Browser, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e" which could not be resolved in the currently targeted framework. "Silverlight,Version=v4.0,Profile=WindowsPhone". To resolve this problem, either remove the reference "Microsoft.Maps.MapControl" or retarget your application to a framework version which contains "System.Windows.Browser, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e".

    Here is little piece of information you will need to know and is very important. As per Silverlight documentation for Windows 7 Phone namespace System.Windows.Browser is not supported on the device. Good news is that you can add reference to this assembly from the folder where your Silverlight assemblies are installed by Visual Studio. For example in my case the location is C:\Program Files\Microsoft Silverlight\4.0.50524.0\System.Windows.Browser.dll. Adding reference to this assembly does not mean that you can actually use all the APIs from this namespace. If you will try, you will get run time errors. Remember that this namespace is not supported in Windows 7 Phone platform. Now compile the project again and you should be good to go.

  • Now implement the code that will fetch data that needs to be used to render locations on Bing Maps. In previous post How to use WCF in Windows 7 Phone, I described use of WCF. In the sample project attached with the post, I am using WCF service to get geo locations that I want to plot on Bing Maps on Windows 7 Phone.

As I mentioned in previous posts about Windows 7 Phone development, you can cut and paste code from your regular Silverlight application in Windows 7 Phone application and it will work as long as you are not using any APIs that is not supported on Windows 7 Phone.

Give your advice to big bosses and make money

Views: 701

Tags: ,

Bing Map | Silverlight | Windows 7 Phone

How to use Silverlight Toolkit themes

by Naveen 14. July 2010 13:51

When you are working on a rich user interface application, the most important thing that you need to figure out is how you can make your user interface appealing and intutive. As developer you can put together the back end plumbing to fetch the data and wire it to the user interface. But its the design part that can be tricky at times. You try to figure out color schemes and layout details of your pages and controls to make it appealing to your users.

Silverlight Toolkit provides more than a dozen themes that you can choose to implment your user interface look and feel. Some time you find that one theme may not fit all the needs. Well, tool kit does not stop you from mixing the themes as well. In this post I will show simple steps on how to use Themes from Silverlight Toolkit.

Install Silverlight Toolkit

If you are reading this post then there is good chance that you already know what silverlight toolkit is and you have already installed it. But for sake of completion, I will provide the link from where you can download latest toolkit.

Download Silverlight Toolkit From CodePlex

Add Assembly Reference

Add reference to theme assemblies as per your need. Each theme is contained in with in its own assembly. You can add reference to all or what you need. For example I wanted to add Shiny Red and Rain Purple themes to my project. So I have added reference to those assemblies only. Following screen shot how the references look like in my project.

Add Theme From Toolbox

Adding a theme to your page is as simple as dropping a control from the toolbox. If you look under Silverlight Controls node in Toolbox, you will find the controls as shown in the snapshot below. Pick the one that you want to use and drop in on your Silverlight page surface. You will see a code snippet as shown below appear on your page's XAML.


<shinyRedTheme:ShinyRedTheme>
 <Grid x:Name="LayoutRoot">
  <ScrollViewer x:Name="PageScrollViewer" Style="{StaticResource PageScrollViewerStyle}">
   <StackPanel x:Name="ContentStackPanel">
    <toolkit:RainierPurpleTheme Height="50" Name="rainierPurpleTheme1" Width="100">
     <Button x:Name="ClickItButton" Content="Click Me!" Width="Auto"></Button>
    </toolkit:RainierPurpleTheme>
   </StackPanel>
  </ScrollViewer>
 </Grid>
</shinyRedTheme:ShinyRedTheme>

The tag prefix toolkit and shinyRedTheme are ones that need to be defined at top of your page with other namespace declaration. When you drop a theme from toolbox on the page, the declaration gets added at top of the page automatically. Here is what it looks like in my project.


xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"

shinyRedTheme is namespace declaration that I added manually.

Add Controls

One you have dropped a theme on the page, you can add your UI controls inside that theme's container and all the controls with in that block will have that theme applied to it.

Mix Themes On Silverlight Page

If your UI needs to more than one themes and needs to be nested, there is nothing special you will need to do. Simple drag and drop another theme inside one theme and you are good to go. Following image shows rainier purple theme nested inside shiny red theme. And the XAML code snippet above reflects it as well.

I hope this gives you a good starting point on how to use themes from silverlight toolkit.

Give your advice to big bosses and make money

Views: 297

Tags:

Silverlight

Break point not hitting in Silverlight - Enable Silverlight Debugging in ASP.Net Project

by Naveen 13. July 2010 13:25

Recently when I was debugging one of my Silverlight projects, I was not hitting break points inside my Silverlight code. Debugging has been working fine on that project. My initial reaction was that my recent changes to the control probably did not update XAP file in my ASP.Net project and I was trying to debug against old executable. I tried to manually take care of that part but I was still not hitting break point. ThenI realized that I had upgraded my project from VS2008 to VS2010. So I took a look at properties of my web project. It turned out that Silverlight debugging code disabled in the project. I turned in on and everything was perfectly fine after that and was hitting all break points inside Silverlight code. Following snapshot shows the setting in Project Properties > Web tab.

Give your advice to big bosses and make money

Views: 580

Tags:

Silverlight

How to add tool tip to Pushpin in Bing Map Silverlight control

by Naveen 13. July 2010 05:40

Download Sample Projects (188.73 kb)

bing maps silverlight control

Some time back I wrote about using Bing Maps Silverlight control. Recently I was developing an application for a client using Bing Maps silverlight control and realized that there have been some changes since I last wrote about it. So this series of posts is focused on some of the following topics.

  • How to use Bing Maps Silverlight control?
  • How to add push pins or location markers on Bing Maps?
  • How to add tool tip to push pin or location on Bing Map?
  • How to use WCF in silverlight application?
  • How to use Bing Maps web service in Silverlight application?
  • .... and more...

How to use Bing Maps Silverlight control?

As I discussed in my previous post that first you need to make sure that you have all the necessary tools on your development machine. So here is some content from previous post.

Set up development enviroment

Before you can start developing your silverlight application using Bing Map Silverlight control, you will need to do following things.

  • Create a developer account at Bing portal
  • As part of registration process, you will also be required to a credential key that is used with each request that you send to Bing web service to access data.
  • Download Bing Map Control SDK and install on your development machine

Create or Update Project

I will recommend reading on Creating a Basic Application Using the Silverlight Map Control. There have been some namespace changes as well as assembly name changes since last version of the control. Therefore it is important to follow the latest article about assembly and namespace references. Following snapshot shows the references of BingMaps control assemblies that you are going to need in your project.

bing maps assemblies

Add Pushpin to Map Control

As I mentioned in my previous post about BingMaps control, the control is a container that can host other child windows. Pushpin is nothing but another control that you add to the map control itself. So you add a map layer to the map and then add Pushpin controls to this map layer. Following code snippet from the sample shows how push pin were added.


void AddMapPushPin(ByteBlocksActivityService.GeoLocation loc)
{
Pushpin pin = new Pushpin();
Location pinLocation = new Location() 
  { Longitude = loc.Longitude, Latitude = loc.Latitude };
pin.Location = pinLocation;
GetLocationDetails(pin);
_mapLayer.AddChild(pin, pinLocation, PositionOrigin.BottomRight);
}

You may be wondering what is GeoLocation parameter to this method. This is one of the objects that I defined in my data service. I will discuss more about how to use WCF in silverlight application in subseuent posts. You can see it is pretty straight forward to add push pin to Bing Map control. You can provide your own image to be used as push pin as well. For me the standard image provided by the map control itself did the job.

Add title to Pushpin

A blank push pin is not going to provide much of information to the users. So it will be helpful if we could display some text on it as well. Depending on image used for displaying push pin, you will have very limited space. So you have to keep the title short so that it fits. This text could be some abbreviation.

You will use Content property of Pushpin control to set text to be displyed on the pushpin as shown in the code below.


pin.Content = address.CountryRegion;

Add Tool tip to Pushpin

push pin tool tip

As i mentioned above, a blank Pushpin does not provide much of information to your users. And there is not much you can display in Content. As with any visual controls, Tooltip is one of the best ways to convey information to users. This is where you can get really creative about displaying details about location or pushpin to your user. For this post, I will keep this display of tool tip to displaying address corresponding to the pin location.

bing maps push pin tool tip

As I mentioned earlier that Pushpin is nothing but another UIElement or control hosted inside Map control. So you can use TooltipService to add tool tip to Pushpin. Following code snippet shows how I added address as tool tip to Pushpin


var tooltipText = "Unkown";
if (e.Result.Results.Count != 0)
{
 var address = e.Result.Results[0].Address;
 tooltipText = address.FormattedAddress;
 pin.Content = address.CountryRegion;
}
System.Windows.Controls.ToolTipService.SetToolTip(pin, tooltipText);

I got address for the given location using ReverseGeoCode service from Bing Maps SOAP Services. I will discuss this in detail when I discuss about how to use Bing Maps SOAP Services in Silverlight applications.

Sample Project

You can download the sample project to play with maps. Remember that you will need to get your own Bing Maps Developer key from Microsoft to use the control.

Give your advice to big bosses and make money

Views: 795

Tags: ,

Bing Map | Silverlight | WCF

The non-generic method 'Microsoft.Practices.Unity.IUnityContainer.Resolve cannot be used with type arguments

by Naveen 30. June 2010 18:08

I was working on introducing Unity Framework for Silverlight in one of my older Silverlight applications. I was trying to use Resolve to get hold of singleton instance of one of my objects. I kept getting following compile time error.

error CS0308: The non-generic method 'Microsoft.Practices.Unity.IUnityContainer.Resolve(System.Type, string, params Microsoft.Practices.Unity.ResolverOverride[])' cannot be used with type arguments

There was nothing wrong with the code that I had to call Resolve method. After doing dance for more than an hour with everything I could try, I finally figured out the problem and kicked myself. I never added using declaration for Unity namespace in the class where I was using the code. After adding following line, everything was normal in my world.

using Microsoft.Practices.Unity;
Give your advice to big bosses and make money

Views: 763

Tags:

.Net | C# | Silverlight

Silverlight Grid Layout and Star Sizing

by Naveen 27. April 2010 04:35

When you are building an User Interface, the biggest challenge you face is how to layout your controls to present the data in the best possible way to the user. Yes, style and skins are important too but at the end it all depends on how you layout the controls. And root of all the layout is some container that you use. In Silverlight you have choice of using one of the following containers to create a layout for your application or control.

  • Canvas
  • Grid
  • StackPanel

Unless you are developing some application that requires precise placement of controls based on exact position coordinates and things like that, most of us end up with Grid as container for all other controls. Therefore it is important that you understand how Grid layout works.

See an example

Following XAML snippet and picture shows layout of example that I created.


<Grid x:Name="LayoutRoot" Background="{StaticResource app_background}" 
	ShowGridLines="True">
 <Grid.RowDefinitions>
  <RowDefinition Height="40"></RowDefinition>
  <RowDefinition Height="*"></RowDefinition>
  <RowDefinition Height="2*"></RowDefinition>
  <RowDefinition Height="20"></RowDefinition>
 </Grid.RowDefinitions>
 <Grid.ColumnDefinitions>
  <ColumnDefinition Width="Auto"></ColumnDefinition>
  <ColumnDefinition Width="*"></ColumnDefinition>
  <ColumnDefinition Width="3*"></ColumnDefinition>
 </Grid.ColumnDefinitions>
 <Button Content="Communicate" Height="23" HorizontalAlignment="Left" 
  Margin="0" Name="button1" VerticalAlignment="Top" Width="Auto" 
  Click="OnCommunicate" />
</Grid>

silverlight grid layout

The intention of this layout is to create a grid with 4 rows and 3 columns. I will explain other concepts about layout in the rest of the post.

Defining Rows and Columns

Grid layout is like any other grids. It has rows and columns. Use of RowDefinitions and ColumnDefinitions tags provide you a way to specify how many rows and columns you want in the grid and how you would like to size them. You do not have to specify these explicitly. If you do not specify these dimensions, the framework will automaticall insert the controls into Column 0 and row 0 for you. And it will size the content in these columns based on Auto size.

Specify Height and Width

As you can see in the XAML code above, I have specified height of rows using Height property and width using Width property on rows and column definition. You can there are different ways to specify these dimensions.

  • Auto: What this option means is that you want Silverlight framework to extend height or width dimension to fit the content. In the example above, you can see that I added a button to Row=0,Column=0. I specified fixed height of 40 for first row but I have set width of first column to Auto. This allows my first column to be as wide as it need to fit the button. If you do not set these dimension properties to any value, then Auto is default value that these take.
  • * or Star: This option is also called Star Sizing. This value is something that some people get confused with. This is more like specifying a dimension in "%" terms but more advanced. What this * means is that it wants Silverlight framework to allocate remaining space in proportion to number of STARS. Remaining is key to this option. This remaining is the space left after layout has accomodated FIXED and AUTO dimensions.

    Lets look at the example above for RowDefinitions. I have specified first row to be fixed height of 40, fourth row as fixed height of 20. Then second row as * and third row as 2*. Lets assume that total height of our grid is 400. So what this means is:

    • Row 0: 40 px
    • Row 3: 20 px

    Now we have (400 - 60)=340px left. This remaining height is to be divided between Row 1 and Row 2 as per Start Sizing set. We have 1 * for Row 1 and 2 * for Row 2. These values means is of the remaing 340 px left to be allocated, give 1/3 to Row 1 and 2/3 to Row 2. So as per this at the end we have:

    • Row 0: 40 px
    • Row 1: (340/3)= 113 px
    • Row 2: (340*2/3)= 226 px
    • Row 3: 20 px

Based on this information, you should be able to figure out how sizing will work for width in columns. You can see flexible and convenient is to use Star Sizing. It provides a lot of control on how to dynamically size layouts proportionally. B

Give your advice to big bosses and make money

Views: 1488

Tags: ,

Silverlight

Silverlight Error - Failed to assign to property 'System.Windows.ResourceDictionary.Source'

by Naveen 16. April 2010 07:37

When you add resource dictionary files aka style files, you may run into following errors.


{System.Windows.Markup.XamlParseException: Failed to assign to property 
 'System.Windows.ResourceDictionary.Source'. [Line: 8 Position: 32]
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at SilverLayout.App.InitializeComponent()
   at SilverLayout.App..ctor()}

As the error indicates that there is something wrong related to Source property of ResourceDictionary object. Following example shows XAML snippet from my App.xaml file where I was trying to add a resource dictionary.


<Application.Resources>
 <ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
   <ResourceDictionary Source="Assets\LayoutStyles.xaml">
  <ResourceDictionary.MergedDictionaries>
 <ResourceDictionary>
<Application.Resources>

If you look at the code snippet there does not seem to be anything wrong with it. But I have marked part of it with RED. Yes, I accidently used BACK SLASH (\) in the path. Parser did not like that while resolving path to that dictionary file. To fix this problem I just has to switch to using FORWARD SLASH (/)


<Application.Resources>
 <ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
   <ResourceDictionary Source="Assets/LayoutStyles.xaml">
  <ResourceDictionary.MergedDictionaries>
 <ResourceDictionary>
<Application.Resources>

Give your advice to big bosses and make money

Views: 2007

Tags:

Silverlight

Silverlight WCF Error - Custom tool warning: The type 'System.Collections.ObjectModel.ObservableCollection`1' could not be found

by Naveen 16. April 2010 04:59

While developing a Silverlight applicatio, I ran into the following error when I tried to add service reference to one of my WCF services.

Custom tool warning: The type 'System.Collections.ObjectModel.ObservableCollection`1' could not be found

This was really strange because I had the reference to this WCF earlier and I was not running into any issues. I made some service contract interface changes so I had to update the reference in my silverlight application as well. For a moment I thought that the new DataContract and DataMember that I added into the service contract may have something to do with it. I had added a new property to my DataContract which was an enumeration. So I removed that from the contract. I still kept getting the same error.

After fighting with it for an hour or so, I decided to use the ultimate solution that I happen to use for most Microsoft products. I closed the solution and shut down instance of Visual Studio. And then restarted Visual Studio and loaded my projects. Now I added Service Reference to same WCF service and no errors. It seems that there is some bug or something in Visual Studio's reference generation tool that triggers when there is significant change in your service's contracts.

Bottom line is that if you run into similar errors with WCF Service Reference tool, first try this wonderful solution of restarting Visual Studio and reloading your project.

Give your advice to big bosses and make money

Views: 1273

Tags: ,

Silverlight | WCF

WCF Error - Could not find endpoint element with name and contract in the ServiceModel client configuration section

by Naveen 30. March 2010 14:23

This week I had to work on an old Silverlight and WCF application. So I had to make this Silverlight 3.0 application consume a WCF service that is used to perform search in Amazon.com database. This post is about first WCF error I ran into when my silverlight application tried to call into my WCF web service. And I realized this is a very common issue lot of developers run into when developing a Silverlight application that consumes WCF service.


{System.InvalidOperationException: Could not find endpoint element with name 
'BasicEndPoint' and contract 'ProductSearchService.IAmazonSearchService' 
in the ServiceModel client configuration section. This might be because no 
configuration file was found for your application, or because no endpoint 
element matching this name could be found in the client element....

The error provided me some starting point to start my diagnosis. Here are the steps that i followed and approached the solution.

Check WCF Configuration File On Client

When you choose Add Service Reference option in Visual Studio to add a WCF service reference to your Silverlight application, it will add a WCF client configuration file ServiceReferences.ClientConfig in your project. Open that file to check if it does have correct WCF configuration entries. Well, in my case, for some reason Visual Studio choked and added an empty ServiceReferences.ClientConfig file. So I manually added the configuration entried to create a WCF proxy.


<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicEndPoint" maxBufferSize="2147483647" 
           maxReceivedMessageSize="2147483647">
          <security mode="None" />
        </binding>
        <binding name="BasicHttpBinding_IAmazonSearchService" 
            maxBufferSize="2147483647"
          maxReceivedMessageSize="2147483647">
          <security mode="None" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost/ProductsSearch/AmazonSearchService.svc"
        binding="basicHttpBinding" 
        bindingConfiguration="BasicHttpBinding_IAmazonSearchService"
        contract="ProductSearchService.IAmazonSearchService" 
        name="BasicHttpBinding_IAmazonSearchService" />
    </client>
  </system.serviceModel>
</configuration>

After populating configuration, I still kept getting the same when my Silverlight application tried to connect to WCF service. So I moved to next end point of this equation that was server side WCF service.

Silverlight Supports basicHttpBinding and not wsHttpBinding

I quickly checked the service implementation code and did not find anything wrong. There was nothing to check much because my one method in service was returning statically constructed list. So at this point I did not have to worry about diagnosing any issues with Amazon.com web service itself.

Now I opened web.config file to look for configuration entries for my WCF configuration. Oh well, there was something obviously wrong. Notice binding value in endpoint configuration. It is set to wsHttpBinding


<system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="ProductsSearch.AmazonSearchServiceBehavior">
     <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
     </serviceBehaviors>
    </behaviors>
   <services>
    <service behaviorConfiguration="ProductsSearch.AmazonSearchServiceBehavior" 
     name="ProductsSearch.AmazonSearchService">
      <endpoint address="" binding="wsHttpBinding" 
       contract="ProductsSearch.IAmazonSearchService">
        <identity>
         <dns value="localhost"/>
        </identity>
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
  </services>
</system.serviceModel>

Change the endpoint configuration to use basicHttpBinding. Recompile the service and go back to Silverlight project. Right click on the service reference and choose the option to update it. And now compile Silverlight project.

It worked!

Yes, that did work. So if you are working with a Silverlight 3.0 application that is going to consume a WCF service, make sure that:

  • Your WCF service is configured to use basicHttpBinding
  • Your client side WCF configuration file has correct information about the binding etc.
  • And if you are calling the client proxy constructor by name, then you do have correct name for your endpoint in client configuration file.
Give your advice to big bosses and make money

Views: 2678

Tags: ,

.Net | Silverlight | WCF

Error adding reference to assembly downloaded from internet

by Naveen 17. March 2010 12:03

If you download a .Net assembly from internet and then add reference to it in your .Net project, you will run into the following compile time error. This happens when you do it in VS2010 and using .Net 4.0 framework. The reason behind this is described in description of <loadFromRemoteSources> in MSDN documentation.


The "ValidateXaml" task failed unexpectedly.
System.IO.FileLoadException: Could not load file or assembly 'file:///C:\Projects\xyz.dll'
or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515
File name: 'file:///C:\Projects\xyz.dll' ---> System.NotSupportedException: An attempt was
made to load an assembly from a network location which would have caused the assembly to be
sandboxed in previous versions of the .NET Framework. This release of the .NET Framework
does not enable CAS policy by default, so this load may be dangerous. If this load is not
intended to sandbox the assembly, please enable the loadFromRemoteSources switch.
See http://go.microsoft.com/fwlink/?LinkId=155569 
for more information.
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName,
 String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, 
StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection,
Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, 
Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, 
 Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, 
Evidence assemblySecurity, StackCrawlMark& stackMark, 
Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, 
Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, 
Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at Microsoft.Silverlight.Build.Tasks.ValidateXaml.XamlValidator.Execute(ITask task)
   at Microsoft.Silverlight.Build.Tasks.ValidateXaml.XamlValidator.Execute(ITask task)
   at Microsoft.Silverlight.Build.Tasks.ValidateXaml.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.
Execute()

Solution

Just right click on that assembly and click on Unblock button in bottom right of the dialog box. That should take care of this error.

Give your advice to big bosses and make money

Views: 1028

Tags:

.Net | Silverlight

Silverlight Error - Invalid or malformed application: Check manifest

by Naveen 17. March 2010 05:18

I was working on development of a Silverlight control. The development was mostly converting an existing application to use new SL framework. When I tried to debug the application, I got hard exception thrown at me.

Invalid or malformed application: Check manifest

So I decided to look at AppManifest.xaml file that gets packed in XAP package. The way to do that is as follows:

  • In ClientBin folder of web application rename your .xap file to .zip file
  • Open this renamed ZIP file to extract the contents. There you will find your AppManifest.xaml file
  • Open this AppManifest.xaml file in editor to examine the entries. This will contain what all is going to be packaged for your Silverlight application

I was not expecting anything wrong with this manifest file or the contents of the package itself. After some digging around I realized that I had changed default namespace of Silverlight application project and changed namespaces of all classes to match that as well. But I never changed the entry point of the application in project settings. So I brought up the properties dialog box for the project and fixed the Startup Object value and everything went to normal.

Give your advice to big bosses and make money

Views: 1883

Tags:

Silverlight

How to use HttpWebRequest to send POST request to another web server in Silverlight?

by Naveen 10. March 2010 10:14

Download Sample Projects (114.64 kb)

Quite some time back I wrote about How to use HttpWebRequest to send POST request to another web server in ASP.Net applications. Now that a lot of silverlight applications are being developed, we have similar need to post data from silverlight applications. The concept is exactly the same that I used in ASP.Net. But there is little difference. Silverlight does not allow blocking synchronous requests. All web requests are asynchronous. That means we have little bit more book keeping to do and manage the thread contexts etc. to make sure that then requests complete and we need to do any UI work in call back methods, we stay in correct thread context.

To keep example simple, I am going to post two values to destination URL using POST method. In the attached project, on Slots.xaml page, I have added a simple button Submit Data. And in the event handler of this button, I initiated request to submit data to Default page of sample web application. The event handler for the click looks as below.


private void SubmitData_Click(object sender, RoutedEventArgs e)
{
 // Prepare web request...
 HttpWebRequest myRequest =
 (HttpWebRequest)WebRequest.Create("http://localhost/SilverGridWeb/Default.aspx");
 myRequest.Method = "POST";
 myRequest.ContentType = "application/x-www-form-urlencoded";
 myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}

This code is pretty much same as what I had in ASP.Net application. There is one difference. Instead of calling GetRequestStream method, you will need to call BeginGetRequestStream. This will initiate an asynchronous request. There are two parameters that are passed to this method. First is the callback method that needs to be called when this method completes. Second parameter is any object that you want to pass to callback method. So here I have passed my HttpWebRequest object itself.

Now lets look at what is this callback method GetRequestStreamCallback. I copied the function from Microsoft documentation itself and made some changes to fit my needs.


private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
 HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
 System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
 string strId = "My Id";
 string strName = "My Name";
 string postData = "userid=" + strId;
 postData += ("&username=" + strName);
 byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
 // Write to the request stream.
 postStream.Write(byteArray, 0, postData.Length);
 postStream.Close();
 // Start the asynchronous operation to get the response
 request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

You can see that in callback method, I grabbed the request object that was passed as state to the method call. Then I constructed data that I need to pass with the request that needed to be sent as POST. And then made another async call BeginGetResponse to submit the data and get the response.

Now lets look at what is this callback method for response.


private void GetResponseCallback(IAsyncResult asynchronousResult)
{
 HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
 HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
 Stream streamResponse = response.GetResponseStream();
 StreamReader streamRead = new StreamReader(streamResponse);
 string responseString = streamRead.ReadToEnd();
 // Close the stream object
 streamResponse.Close();
 streamRead.Close();
 // Release the HttpWebResponse
 response.Close();
 Action<string> act = new Action<string>(DisplayResponse);
 this.Dispatcher.BeginInvoke(act, responseString);
}

void DisplayResponse(string msg)
{
 GainersText.Text = msg;
}

Again I passed original HttpWebRequest object to the call method as state. In the call back method, you can grab the request object and then call EndGetResponse to get the resonse stream.

Thread Context and Invalid cross-thread access error

You will notice that in GetResponseCallback method I have called BeginInvoke method on Dispatcher thread. This is very important if you are planning on doing any UI manipulation in the call back methods. The call back methods are invoked on a thread that are separate from the UI thread that initiated the request. So if you try to access any UI element in this callback you will get the following exception thrown.


An unhandled exception ('Unhandled Error in Silverlight Application 
Code: 4004    
Category: ManagedRuntimeError       
Message: System.UnauthorizedAccessException: Invalid cross-thread access.
   at MS.Internal.XcpImports.CheckThread()
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, 
   Boolean allowReadOnlySet, Boolean isSetByStyle, Boolean isSetByBuiltInStyle,
   PropertyInvalidationReason reason)
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value)
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Controls.TextBlock.set_Text(String value)
   at SilverGrid.Views.Stocks.GetResponseCallback(IAsyncResult asynchronousResult)
   at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassd.
    <InvokeGetResponseCallback>b__b(Object state2)
   at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, 
   ContextCallback callback, Object state)
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal
   (_ThreadPoolWaitCallback tpWaitCallBack)
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)     
') occurred in iexplore.exe [7532].

Therefore it is important that from the callback method, you invoke an action request on Dispatcher thread of UI.

Give your advice to big bosses and make money

Views: 3585

Tags:

Silverlight

Silverlight Cross Domain Web Service Access Error - This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place

by Naveen 9. March 2010 08:37

Here is some error that most of Silverlight developers run into at some point.


An error occurred while trying to make a request to URI 
'http://nave-pc/SilverGridWeb/GridDataService.asmx'.
This could be due to attempting to access a service in a cross-domain way 
without a proper cross-domain policy in place, or a policy that is unsuitable 
for SOAP services. You may need to contact the owner of the service to publish 
a cross-domain policy file and to ensure it allows SOAP-related 
HTTP headers to be sent. This error may also be caused by using internal types 
in the web service proxy without using the InternalsVisibleToAttribute attribute. 
Please see the inner exception for more details.

I had developed cross-domain access web services for Silverlight in the past and all work like a charm. This morning I ran into this issue again while developing a new web service for a new Silverlight application. I knew that I needed to add CrossDomain.xml or ClientAccessPolicy.xml at root of my web application. So I copied those files from existing application to this new one. To my surprise it did not resolve the issue. I tried all kind of tricks and options but nothing seemed to help. Finally I decided to look at Silverlight documentation and see if there is anything new that has been done for Silverlight 3. Last time I did this was for a Silverlight 2.0 application. I could not find anything different in the description of what needed to be done. But then there was something in the sample XML file content for these files that caught my eye and looked different that what I had.


<allow-from http-request-headers="SOAPAction" >

Notice the underlined section. Previously the value in the allowed headers used to be *. Well, that does not seem to work any more. So I replaced it and everything worked fine.

There are some other important points I am going to discuss in this post. A lot of users do not seem to be clear where these cross domain policy files should be placed.

Location of CrossDomain.xml and ClientAccessPolicy.xml

As the documentation states, these should be placed at the root of the application. Although the statement is very clear but it causes lot of confusion about what is root? There are two ways you create a site in IIS, Virtual Directory and Web Application. So if you have a web site foo.com created as a web site in IIS, then the folder containing the content of this site is root of the application. So your policy files go in that folder. If you have created a virtual directory Bar under this web site where your web service is hosted, then the root of the site is still foo.com and not foo.com/bar. To verify it, open IIS log of your application and look for entries for Crossdomain.xml and ClientAccessPolicy.xml. From those entries you can figure out where those files should be located. If the caller is not finding those files, then you should 404 errors in your log file. For example here are entries from my log file.


1.17.30.170 GET /clientaccesspolicy.xml - 80 - 1.17.30.162  404 0 2 1
1.17.30.170 GET /crossdomain.xml - 80 - 1.17.30.162 404 0 2 1

This is very important. If you are hosting your web service in a web application that is created as a virtual directory in Default Web Site then you need to copy these files in wwwroot folder or whatver folder is configured to be default folder for your IIS installation. Copying policy files in your virtual directory is not going to help. You can also verify the location by looking at traffic in fiddler for your web service access.

Content for CrossDomain.xml and ClientAccessPolicy.xml

I have copied the content of these two files below. These files work for me on my my servers for cross domain access from silverlight.

ClientAccessPolicy.xml


<?xml version="1.0" encoding="utf-8"?>
<access-policy>
	<cross-domain-access>
		<policy>
			<allow-from http-request-headers="SOAPAction ">
				<domain uri="*"/>
			</allow-from>
			<grant-to>
				<resource path="/" include-subpaths="true"/>
			</grant-to>
		</policy>
	</cross-domain-access>
</access-policy>

CrossDomain.xml


<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
	<allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
</cross-domain-policy>

Give your advice to big bosses and make money

Views: 2025

Tags: , ,

Silverlight | WCF | Web Service

How to display custom tool tips in Silverlight Charts?

by Naveen 3. March 2010 11:49
custom tool tip in silverlight charts

Download Sample Projects (28.22 kb)

In my previous post, How to set silverlight column chart style programatically", I discussed one of the customizations of chart styles. In this post I will discuss one more customization of Silverlight charts rendering. This is about customizing display of Tooltip display on charts. If you look at default tool tip display, they are limited to displaying some combination of Independent and Dependent value. In some cases, that information is sufficient. But you may have cases where you want your tool tips to be verbose to convey more information about the data point that was used to render that point or column etc.

Template is the key

First and foremost concept that you will need to understand is how a chart actually gets rendered. Who decided the layout of various components of a chart display. Like any other Silverlight control, its the control template that defines how to chart is going to be rendered. So to customize the dispplay of Silverlight control, you can create a new template or take the default template and make modifications to it to come up with your own display scheme. Now you are asking from where can you get the default template for various chart types. The answer to it is Silverlight Toolkit source code. If you look in Charting/DataPoint folder of Controls.DataVisualization.Toolkit project, you will find template files for all chart types.

Customize Tooltip For Chart

Let us get started. For this discussion I picked Column type chart. Here are the steps that I followed to create a new template file for my column charts.

  • Add a new resource dictionary file in your project. In sample project I added ColumnChartStyle.xaml file under Assets folder.
  • Open ColumnDataPoint.xaml file from DataPoint folder from tool kit source. Copy the content of this file into your resource file.
  • Make sure that you change the build action of your resource file to Resource from Page
  • Assign a key to your style as shown below. You can pick any unique name. You are going to use the key when we apply this new template and style to our column charts.
    
    <Style TargetType="charting:ColumnDataPoint" x:Key="ByteBlocksColumns">
    
    
  • Open the XAML file where you have added chart that you want to display. In the sample project, it is in Home.xaml. And then assign DataPointStyle property to point to the static resource that we created from default implementation of ColumnDataPoint. And make sure that you use the key name that you used in the resource file. Following snippet shows how I did it in sample project.

    
    <chartingToolkit:Chart Title="Fruit Supply and Demand" 
       x:Name="FruitChart" 
       Width="500" 
       Height="350">
     <chartingToolkit:Chart.Series>
      <chartingToolkit:ColumnSeries
    		DataPointStyle="{StaticResource ByteBlocksColumns}"
            Title="Fruit Supply"
            IndependentValueBinding="{Binding Name}"
            DependentValueBinding="{Binding Supply}"/>
      </chartingToolkit:Chart.Series>
    </chartingToolkit:Chart>
    
    

Now you should be able to compile and run your project. We have not done any customization of tool tip yet. At this point you should be able to run the project with default template.

TooltipService and Tooltip

If you look near bottom of ColumnChartStyle.xaml file, you will find following snippet of code.


<ToolTipService.ToolTip>
 <ContentControl Content="{TemplateBinding FormattedDependentValue}"/>
</ToolTipService.ToolTip>

This is default implementation of how and what is displayed in tool tip. So you can see that by default only DependentValue is displayed. So this is the place where you will need to make changes to customize the display of tooltip for chart. If you are only interested in making some minor changes like adding some static text or adding display of dependent value as well, you can make a change as below.


<ToolTipService.ToolTip>
 <StackPanel Orientation="Horizonal">
 <ContentControl Content="{TemplateBinding FormattedDependentValue}"/>
 <TextBlock Text="-" />
  <ContentControl Content="{TemplateBinding FormattedIndependentValue}"/>
 </StackPanel Orientation="Horizonal">
</ToolTipService.ToolTip>

Customizing Tooltip Display at run time

In the sample project, I have implemented a use case where I want to create tool tip display at run time. What this means is that content of tool tip is being constructed based on some input from the existing data that is bound to that column. So in the template I am going to make some changes as shown below.


<ToolTipService.ToolTip>
<StackPanel Orientation="Horizontal">
<ContentControl Content="{Binding Id, Converter={StaticResource FruitConverter}}"/>
</StackPanel>
</ToolTipService.ToolTip>

In the snippet above you will see use of two things. One is that I am binding the content to the actual data object that was used to render that point. Second is use of converter. I am passing "Id" of the object as parameter to the converter. And in the converter I do some mock query to get more data. Following code shows how I constructed text of tool tip.


public class FruitSupplyToolTipConverter : IValueConverter
{
 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
  return GetToolTip(int.Parse(value.ToString()));
 }

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

 object GetToolTip(int id)
 {
  var supply = MockData.FruitSupply.GetSupply();
  var query = from item in supply where item.Id == id select item;
  var items = query.ToList();
  if (items.Count == 0)
  {
   return string.Empty;
  }
  return CreateToolTip(items[0]);
 }

 object CreateToolTip(FruitSupply supply)
 {
  var panel = new StackPanel();
  panel.Orientation = Orientation.Vertical;
  var tipTextBlock = new TextBlock();
  tipTextBlock.Inlines.Add(new Run { Text = supply.Name });
  tipTextBlock.Inlines.Add(new LineBreak());
  tipTextBlock.Inlines.Add(new Run { Text = string.Format("Supply: {0}", supply.Supply)});
  tipTextBlock.Inlines.Add(new LineBreak());
  panel.Children.Add(tipTextBlock);
  var hlink = new HyperlinkButton();
  hlink.Content = "For more informattion Goto http://www.ByteBlocks.com";
  hlink.NavigateUri = new Uri("http://www.byteblocks.com");
  panel.Children.Add(hlink);
  return panel;
  }
}

You could argue that instead of going to the extent of using converter to build a tool tip text, I could have added another property to data object that contains the text and then bind tool tip to that property. That would have worked perfectly as well. But for demonstrating how you can construct tool tip text based on some other pieces of data or if tool tip content changes rapidly with time as well, then you need to access it at run time.

I hope this should give you good starting point to go nuts on more nifty tool tips.

Give your advice to big bosses and make money

Views: 2723

Tags: , ,

Charting | Silverlight

How to add paging to DataGrid in Silverlight

by Naveen 24. February 2010 10:23

Download Sample Project (367.89 kb)

paging in silverlight datagrid

In one of my previous posts How to use DataGrid in Silverlight I showed a very simple usage where data grid was bound to a list of products. Now let us take one more step in customizing use of this data grid. When I executed my method to get list of products from AdventureWorks database, it returned me about 1000 records. And then datagrid was bound to that list, i got a huge page with grid showing all the records. I am sure at this point you are looking for way to add some kind of paging to your data grid so that user can navigate the list easily.

Silverlight has a control named DataPager that comes in very handy to add paging functionality to any control that you use to display lists. From the name is it obvious that this control is a pager. Following XAML shows how I added paging functionality to my datagrid.


<StackPanel x:Name="ContentStackPanel" Orientation="Vertical">
 <TextBlock x:Name="HeaderText" Style="{StaticResource HeaderTextStyle}" 
     Text="Products"/>
  <data:DataPager x:Name="ProductsPager" 
    PageSize="10" 
    DisplayMode="Numeric" 
    AutoEllipsis="True" 
    HorizontalAlignment="Left" />
  <data:DataGrid x:Name="ProductsGrid">
   <data:DataGrid.Columns>
   <data:DataGridTemplateColumn>
   <data:DataGridTemplateColumn.CellTemplate>
   <DataTemplate>
   <StackPanel>
   <Button x:Name="UpdateButton" Content="Update" 
     Click="UpdateButton_Click"></Button>
   </StackPanel>
   </DataTemplate>
   </data:DataGridTemplateColumn.CellTemplate>
   </data:DataGridTemplateColumn>
   </data:DataGrid.Columns>
   </data:DataGrid>
</StackPanel>

You can read more about different ways to customize the display of datapager from the documentation. For this discussion you can see that I have set PageSize, DisplayMode, AutoEipsis and HorizontalAlignment properties of pager and the screen shot shows how it looks. I will talk more about customization of DataPager in detail in next post. For now I just want to keep it to simple use.

PageViewCollection

This is the collection object that drives the functionality for DataPager. In general you need a collection that implements IPagedViewCollection interface. No, you do not have to do any more implementation to get DataPager to work. We already have list of products obtained from previous web service call. You can simply wrap that list into PagedViewCollection object and set it as Source for DataPager object. And then set the source for DataGrid as this PagedViewCollection object and we are all set to go. Following code shows simple change I made in code from previous sample project.


void GetProductsCompleted(object sender, GetProductsCompletedEventArgs e)
{
 _products = e.Result;
 if (null != _products)
 {
  _pagedProductsView = new PagedCollectionView(_products);
  ProductsPager.Source = _pagedProductsView;
  ProductsGrid.ItemsSource = _pagedProductsView;
 }
}

Add References

PagedViewCollection is defined in System.Windows.Data assembly. So you will need to add reference to this assembly in your Silverlight project and then add using directive for the namespace in your source code to refer to the classes in this namespace and assembly.

Adding Paging to DataGrid in Silverlight is as easy as that.

Give your advice to big bosses and make money

Views: 2110

Tags: ,

DataGrid | Silverlight

How to add buttons to Silverlight DataGrid?

by Naveen 11. February 2010 15:36

Download Sample Project

In the previous post How to use Silverlight DataGrid I discussed simple use of DataGrid in Silverlight application. Now it is time to start putting together implementation that we have from day to day to applications. One of the tasks that you may come across is that you need to add buttons to each row in the DataGrid and then handle click events for those buttons. In the previous post I mentioned use of DataGridTemplateColumn to provide custom rendering of columns in the grid. So to add button(s) to your column, you will use the template column and then provide Button control to add them to each row. Following snippet shows how it looks like in my sample application.


<data:DataGrid x:Name="ProductsGrid">
 <data:DataGrid.Columns>
  <data:DataGridTemplateColumn>
  <data:DataGridTemplateColumn.CellTemplate>
   <DataTemplate>
    <StackPanel>
     <Button x:Name="UpdateButton" Content="Update" 
        Click="UpdateButton_Click"></Button>
    </StackPanel>
   </DataTemplate>
  </data:DataGridTemplateColumn.CellTemplate>
 </data:DataGridTemplateColumn>
 </data:DataGrid.Columns>
</data:DataGrid>

Handling Click Event For Button In DataGrid

As you can see from the XAML above, I just added handling of Click event on Button control. And in the codebehind provided implementation for it.


private void UpdateButton_Click(object sender, RoutedEventArgs e)
{
 var ctl = e.OriginalSource as Button;
 if (null != ctl)
 {
  var product = ctl.DataContext as Product;
  if (null != product)
  {
   var msg = string.Format("{0}, {1}, {2}", 
      product.ProductID, product.Name, product.ListPrice);
   MessageBox.Show(msg);
  }
 }
}

Accessing Data Associated With Row In DataGrid

When user clicks on the button in datagrid row, the method gets called. Next question you have is how do you access the data associated with the row on which button was clicked. It is very straight forward. When DataGrid rendering takes place, each control in the row is bound to DataContext. This DataContext is the data that was used to render that row. So you simple look at DataContext property of Button control that raised the event and got the actual data object used for that row.

I think this should give you a good starting point on how to add buttons or some other controls in DataGrid rows and how to access data for them as well. In next post I will discuss more of customization of Silverlight DataGrid.

Give your advice to big bosses and make money

Views: 2099

Tags: ,

DataGrid | Silverlight

How to use DataGrid in Silverlight

by Naveen 5. February 2010 06:58
DataGrid is one of the most important control when it comes to displaying tabular kind of data. We all implement rendering of such data in some of table format. Developers who has been using ASP.Net are very familiar with controls like DataGrid and GridView. Good news is that there is equivalent DataGrid control for Silverlight as well. And for most part it is used the same way as you do in ASP.Net but with different syntax and different way of customizing display of it. In this post I am going to show a very plain and simple use of DataGrid control in Silverlight and then in subsequent posts I will build on top of this post to show some more advanced uses of DataGrid control.

Silverlight Tool Kit

You may already know this and already has it on your development machine, but I will mention it for sake of completness. You are going to need Silverlight Toolkit to use DataGrid. Yes, the control is not part of core Silverlight. Microsoft has developed it as part of the tool kit that has lot of usefull controls. You can read more about this tool kit and controls on the site. For now, down the toolkit and install it on your machine.

Reference assemblies

In your Silverlight project, you will need to add reference to System.Windows.Controls.Data assembly. This is the assembly where DataGrid control is defined. Now you can include DataGrid control on your XAML file. If you tried to add mark up like below on your page, you are going to get error telling you that DataGrid is not recoganized.


<DataGrid x:Name="MyGrid" />

You have to treat DataGrid control like a UserControl in ASP.Net where you have to specify a tag prefix and assembly on top of your page to indicate use of that control. In Silverllight you do this my including xml namespace tag for that silverlight control. In my case I have the following xmlns entry on my XAML file.


xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

This tells the application that I am going to use prefix data for the controls that are present in assembly System.Windows.Controls.Data. Based on this you can now add the following like of mark up on XAML file to include DataGrid on your page.


<data:DataGrid 
  x:Name="CommentsGrid" 
  Height="300" 
  AutoGenerateColumns="True" 
  IsReadOnly="True">
</data:Grid>

Attach To Data Source

Now that we have included DataGrid control on the page, we need to attach it to some data source to show some results. Very much like ASP.Net, you will attach an enumeration to this control. The difference is that here it is done through property name ItemSource. Following line of code shows how it is done for silverlight DataGrid control.


List<Comment> unmoderatedComments = new List<Comment>();

void BindGrid()
{
 CommentsGrid.ItemsSource = unmoderatedComments;
}

As you can see that DataGrid is bound to a List of Comment objects. So far so good, very much like your ASP.Net DataGrid or GridView.

Columns to Display

In the mark of DataGrid above, I have explcitly set AutoGenerateColumn property to true. This actually is default value. What this means is that when DataGrid is bound to the collection, it will generate column for each data field or property for the objects in the collection and display them. Thsi is same behavior you see in ASP.Net data grid.

Explcitly specifying Columns

When you are dealing with some real application most of the time you control the columns you want to display and how you want to display them. Silverlight DataGrid does allow you to do so. Fisrt, you will set AutoGenerateColumns property to false. Following mark up shows how you will specify the columns that you want to display.


<data:DataGrid x:Name="CommentsGrid" Height="300" 
  AutoGenerateColumns="False" IsReadOnly="True">
 <data:DataGrid.CellStyle>
  <Style TargetType="data:DataGridCell">
  <Setter Property="VerticalAlignment" Value="Top"></Setter>
  </Style>
 </data:DataGrid.CellStyle>
 <data:DataGrid.Columns>
  <data:DataGridTextColumn Header="Comment Date" 
    Binding="{Binding CommentDate}"></data:DataGridTextColumn>
  <data:DataGridTextColumn Header="Comment Text" Binding="{Binding Text}">
  <data:DataGridTextColumn.ElementStyle>
  <Style TargetType="TextBlock">
   <Setter Property="TextWrapping" Value="Wrap"/>
  </Style>
  </data:DataGridTextColumn.ElementStyle>
 </data:DataGridTextColumn>
 <data:DataGridTemplateColumn>
  <data:DataGridTemplateColumn.CellTemplate>
   <DataTemplate>
    <StackPanel Orientation="Horizontal">
     <Button x:Name="ApprovedButton" Content="Approved" 
       Click="ApprovedButton_Click" Height="30" Margin="3"></Button>
     <Button x:Name="DeleteButton" Content="Delete" 
        Click="DeleteButton_Click" Height="30" Margin="3"></Button>
     <Button x:Name="SpamButton" Content="Mark Spam" 
       Click="SpamButton_Click" Height="30" Margin="3"></Button>
   </StackPanel>
   </DataTemplate>
  </data:DataGridTemplateColumn.CellTemplate>
 </data:DataGridTemplateColumn>
 </data:DataGrid.Columns>
</data:DataGrid>

You will need to add Columns section under your DataGrid control definition and then specify each column that you would want to display. And to bind the column to particular property or field, you will use Binding property. For this post I am going to keep the dicussion to simple binding of the column to property of the object. I will discuss more advanced use in subsequent posts. You can see it is very similar to how you are used to doing things in ASP.Net.

And to accomodate more customized view of the column, you will use DataGridTemplateColumn where you can layout the template of the view of that column. This is also similar to template column in ASP.Net.

More...

For this post I am going to leave this discussion to this simple display of data. I will be discussing more about use of Silverlight DataGrid in subsequent posts. This post should get you started with use of it now.

Give your advice to big bosses and make money

Views: 1886

Tags: ,

DataGrid | Silverlight

How to hide navigation controls on Bing Map Silverlight control

by Naveen 7. January 2010 17:25

Default rendering of Bing Map Silverlight Control displays few of the in-built controls like Copyright, Scale, Navigation, Logo etc. If you are not interested in displaying any of these controls, you can simply hide it by setting their visibility. Following code snippet shows how to hide these navigation controls.


void SetMapForgroundMembers()
{
 UserLocationsMap.NavigationVisibility = System.Windows.Visibility.Collapsed;
 UserLocationsMap.LogoVisibility = Visibility.Collapsed;
 UserLocationsMap.CopyrightVisibility = System.Windows.Visibility.Collapsed;
 UserLocationsMap.ScaleVisibility = System.Windows.Visibility.Collapsed;
}		}

Give your advice to big bosses and make money

Views: 2563

Tags: ,

Silverlight

How to use Bing Map Silverlight Control and add push pins for location markers

by Naveen 6. January 2010 07:35
Bing map silverlight control sdk

In one of my earlier posts Convert IP Addresss To Geo Location, I discussed how you can query a web service or database to get geo-location of that internet service provider. Now what do you do with that geo-location or spatial information. For one of the current Data Visualization projects I am working on, I had to show these locations on the map as well. The application is a Silverlight application so obvious choice was to find a control or component that I could drop in silverlight. And you pretty much have the answer, Use Bing Map Silverlight Control.

In this post I am going to discuss some of the following topics.

  • How to use Bing Silverlight Map Control?
  • How to add push pins to bing map?
  • How to add legends or some text to Silverlight Bing Map?
  • How to add regular silverlight controls on Bing Map control?

The documentation for Bing Map Silverlight control is still maturing and lacks lot of details. So most of the discussion in this post is based on personal experience and conversations I had through news groups and forums.

Set up development enviroment

Before you can start developing your silverlight application using Bing Map Silverlight control, you will need to do following things.

  • Create a developer account at Bing portal
  • As part of registration process, you will also be required to a credential key that is used with each request that you send to Bing web service to access data.
  • Download Bing Map Control SDK and install on your development machine.

Create Project and lets roll

Microsoft has provided a good walk through on Creating a Basic Application Using the Silverlight Map Control. I will strongly recomment going through it if its first time for you in Bing Map development.

Adding PushPin to Bing Map

Now that you have a vanilla implementation of map showing in your application. Next I want to add indicztors on the map to show location of internet service providers for which I have geo corodinates. There are few ways you can do. The most basic thing that you need to keep in mind is that Bing Map control is like any other silverlight control and can act as a container for other silverlight control. That means that I can just draw any shapes or objects at given corodinates. Well, you got it. Bing Map SDK provides some of these indicator controls out of the box. And one of them is PushPin. So what you need to do is crate instances of PushPin objects, set their longitude and latitude and add them as children of map control. Following code snippet shows how I added a collection of PushPin objects to my map control.

foreach(var loc in locations)
{
	var pp = new Pushpin() 
	  {Location = new Location(loc.Latitude, loc.Longitude)};
	UserLocationsMap.Children.Add(pp);
}

Adding DataGrid to Bing Map

Next task I had to do was to provide some summary of the data on the map itself. More precisely, I wanted to show how many service provides from each country I have in my database. For demo purposes I just needed to show name and count. I decided to add a DataGrid to map to show this data. Later on I am going to handle click events in this grid to have some interaction with the map as well. Since I already knew where I wanted to place the grid and what columns needed to be shown, I could just add this through XAML file itself. Following XAML snippet from the application shows how I have added a text block and data grid to Bing Map control as children.


<m:Map CredentialsProvider="xxxxxxxxxx" Name="UserLocationsMap">
 <m:Map.Children>
  <o:ShadowText x:Name="MapTitleText" ForegroundTop="Black" ForegroundBottom="Orange"
      Text="ISP Locations" FontFamily="Verdana" FontSize="24"
      HorizontalAlignment="Left" Margin="20,75,50,10"/>
	<StackPanel x:Name="CountryListPanel" Margin="20,250,50,10" Orientation="Vertical">
	 <data:DataGrid x:Name="CountryCountGrid" Width="150" Height="250"
	   AutoGenerateColumns="False" HorizontalAlignment="Left">
	  <data:DataGrid.Columns>
	   <data:DataGridTextColumn Header="Country" Width="SizeToHeader" Binding="{Binding Name}" />
	   <data:DataGridTextColumn Header="Count" Width="SizeToHeader" Binding="{Binding Count}" />
	  </data:DataGrid.Columns>
	 </data:DataGrid>
	</StackPanel>
	</m:Map.Children>
</m:Map>

Postioning on Map control

This is something you will have to play very close attention to. There is a difference between how controls or objects placed on map control. You must have noticed that when I added PushPin to map, I used longitude and latitude to position them on the map. But when I added DataGrid and ShadowText controls, I used Margin to control the placement. Most of the indiccator or layer objects that are provided in Bing Map SDK use gro-location values (longitude and latitude) to place object. But when you add regular silverlight controls on map, then you will control the position using Margin relative to origin of map control.

Give your advice to big bosses and make money

Views: 5379

Tags: ,

Bing Map | Silverlight

How to set silverlight column chart style programatically

by Naveen 4. January 2010 14:31

Let me wish a happy new year to all our blog readers.

This is first post of year 2010 and I decided to write my favorite topic of all times, Data Analysis and Visualization. These days I am working on a Silverlight application that involves very extensive use of charts for data visualization. And I use charting controls provided by Microsoft in Silverlight tool kit.

There are lot of examples available out there that shows you how to use these controls and how to style them. When it comes to styling and things like that, majority of the examples are focused around modifying control template or modifying styles in XAML file itself. Lot of time you make decisions about the type of chart and style of chart at run time based on data that needs to be visualized.

In this post I am going to focus on following tasks:

  • How to add a chart series programatically
  • How to set style of chart series programtically
  • How to set colors of columns in silveright charts programtically

Following image shows you a multi-series column chart. It shows three types of values at different intervals. One of the driving factor behind adding the column series was that I did not know how many different types of values are going to be returned in the data. So I could not simply add X number of ColumnSeries on XAML to say that I need to draw multi-series column chart with 3 points or things like that.

silverlight multiseries column chart

Following code snippet shows how I added column series in the main chart controls and how I specified different colors of the bars that are going to represent each type of data point.


foreach(LatencyColumnPlotData plotData in _latencyDataValues.ColumnPlotValues)
{
var series = new ColumnSeries();
var style = new Style(typeof (ColumnDataPoint));
SolidColorBrush bgBrush = (idx==1) ? 
    new SolidColorBrush(Colors.Blue) : 
    new SolidColorBrush(Colors.Orange);
var setterBg = new Setter(ColumnDataPoint.BackgroundProperty, bgBrush);
style.Setters.Add(setterBg);
series.DataPointStyle = style;
series.ItemsSource = plotData.DependentValues;
series.IndependentValueBinding = null;
series.Title = (idx == 1) ? "Average" : "Current";
idx++;
latencyChart.Series.Add(series);
}

var thresholdSeries = new ColumnSeries();
thresholdSeries.IndependentValueBinding = null;
thresholdSeries.ItemsSource = _latencyDataValues.ThresholdLatencyValues;
thresholdSeries.Title = "Threshold";
var bg = 
   new Setter(ColumnDataPoint.BackgroundProperty, new SolidColorBrush(Colors.Green));
var bgStyle = new Style(typeof(ColumnDataPoint));
bgStyle.Setters.Add(bg);
thresholdSeries.DataPointStyle = bgStyle;
latencyChart.Series.Add(thresholdSeries);

Give your advice to big bosses and make money

Views: 3855

Tags: , ,

Silverlight

Powered by BlogEngine.NET 1.5.1.7
Theme by Naveen Kohli

By Categories