Showing posts with label Silverlight. Show all posts
Showing posts with label Silverlight. Show all posts

Tuesday, October 20, 2009

Silverlight Web Services deployment

One of the usual issues a newbie developer has with silverlight is with the webservice deployment. Everything would work fine when the services are developed along with the silverlight application but it won't work when it gets deployed to the target server.


The usual reason for this is the url references of the application won't be updated when the deployment is done. In order to make sure that this issue doesn't repeat every time, we can invoke the web services in the silverlight app in such a way that it never needs updating the urls.


A sample snippet of how to do this is as below. We use the Application.Current.Host.Source.AbsoluteUri variable which holds the value of the abolute path of the uri being accessed.



int index = Application.Current.Host.Source.AbsoluteUri.IndexOf(Application.Current.Host.Source.AbsolutePath);
String myCurrentHostUrl = Application.Current.Host.Source.AbsoluteUri.Remove(index + 1);

myCurrentHostUrl contains the value of the website where I am hosting this. Now I can invoke my webservice with this url.



BasicHttpBinding basicHttp = new BasicHttpBinding();
EndpointAddress endPoint = new EndpointAddress(myCurrentHostUrl + @"WebServices/MyWebService.svc");
MyWebServiceClient client = new MyWebServiceClient(basicHttp, endPoint);

We can simply put this code in a reusable function and keep using this as and when needed. Hope this helps.

Monday, April 13, 2009

Dynamically creating a DIV control in Silverlight

By now everyone would have gotten a clear idea that HtmlPage, HtmlDocument along with HtmlElement is the way to display a div item in silverlight pages. Now here are few samples to create some controls dynamically from a silverlight page using Html Dom bridge.
For those who wonder what is the difference between a Html Silverlight Dom bridge and HTML Overlay, Html overlay needs the windowless parameter to be set and gives the rendering job to the browser, but Html Silverlight Dom model won't.
There is an excellent FAQ article by erikreitan on the Html and Java script in silverlight http://blogs.msdn.com/erikreitan/archive/2008/12/02/silverlight-html-bridge-faq.aspx. Take a look at this article when you get some time.

HtmlDocument doc = HtmlPage.Document;
HtmlElement dynamicDiv = doc.CreateElement("div");
dynamicDiv.SetAttribute("id", System.Guid.NewGuid().ToString());
dynamicDiv.SetStyleAttribute("height", "20px");
dynamicDiv.SetStyleAttribute("width", "800px");
dynamicDiv.SetProperty("innerhtml", "A small sample of dynamically added div from silverlight");
doc.Body.AppendChild(dynamicDiv);

Remember to include the 'System.Windows.Browser' namespace for this code to compile.

Friday, April 10, 2009

Report Viewer for Silverlight 2

Silverlight platform has aroused interest in developing Line of Business Apps for a lot of people. But Microsoft has not given any Reporting control features with its release of silverlight. This is sort of a difficult balance that developers have to take in terms of giving a rich UI with support for .net programming.

Neither any popular Microsoft Platform Controls vendors have come up with any innovative ideas. Perpetuum soft has a solution, but I am not convinced at the solution as it asks for us to write code and create a dataset for displaying reports. For me ideally the reporting platform should take care of all the data plumbing, formatting, paging, printing etc., Also I wanted to use Microsoft SQL Server reports in Remote mode to be shown in the silverlight platform.

Currently as I see there is only one way of doing these reports. Create your reports definition files in Sql 2005 or 2008 and then use an aspx page to load them. A short reference for the code snippet. It is better to place this in the page_load event of the aspx page.

And currently there are 2 ways to display the aspx pages (which host the Report viewer control) in silverlight.

1. Use the div parameter in combination with javascript to display the control.


ReportParameter[] parm = new ReportParameter[1];
parm[0] = new ReportParameter("id",1);
ReportViewer1.ShowCredentialPrompts = false;
ReportViewer1.ServerReport.ReportServerUrl = "Replace with Report Server Url";
ReportViewer1.ServerReport.ReportPath = "Replace with Report Path Name";
ReportViewer1.ServerReport.SetParameters(parm);
ReportViewer1.ServerReport.Refresh();


This can use a Html Host control like Html Host Using IFrame or the c1HtmlHost provided by ComponentOne as well.

This solution now can support all features needed for a reporting platform. But obviously using windowless property to show the Html in the browser leaves the browser to manage your silverlight app and has an impact on performance.

2. And the second option is write your own reporting solution. I am not good at it yet :).

Please contact me if you have better ideas of doing a solution for reporting in silverlight. Will be glad to hear those.

Saturday, March 28, 2009

Html Host control in Silverlight

The revised and latest version of this control can be found at revised silverlight htmlhost.

It is generally a problem in silverlight to use the HTML content. First and foremost problem is the trouble with setting the position of the control based on the silverlight page we are creating. Also it is really clunky to write the code to read and write your div details by accessing the HTML DOM objects.

Ofcourse Silverlight exposes these HTML DOM objects in the System.Windows.Browser namespace by the classes like HTMLDocument, HTMLElement, HTMLPage etc., These classes provide functions like CreateElement, which can create the controls we want. I've used this function to create the IFRAME which I finally position properly on the page using some properties exposed.

This is a clean way of using the HTML IFrame in your code. Feel free to use the source and add more functionality. If you think your new functionality may be useful to someone else, pls let me know by dropping an email to muthu.v (@) g mail dot com.

How the Html Host control was built:

This creates a DIV inside the HTMLPage.Document.Body and adds an IFRAME object to the DIV control. This uses the classes like HtmlDocument, HtmlElement, HtmlPage for creating these and adds them to the HTML Document object. This has been tested to work fine in IE8 and FireFox. If any of you find any issues and fixes, pls let me know I'll fix and upload again. That will be useful to our programming community.

I've not added much of design time support. So after adding the control, you need to call a function InitControl() for this to be rendered. Also positioning of the control can be done by using the properties HtmlControlTop and HtmlControlLeft properties. Width and Height are exposed as "Width" and "Height" only.
How to use the Html Host control:
  1. Create a new Silverlight application or add a new Silverlight User Control (page) into your existing application.
  2. Reference the FreeHtmlHost.dll in the project.
  3. Add the namespace reference to the silverlight user control on the top like this.

    xmlns:cust="clr-namespace:FreeHtmlHost;assembly=FreeHtmlHost"

  4. Add the control in the location you want like this. Adjust the position of the controls according to your needs.

    <cust:FreeHtmlHost x:Name="customHost" Width="620" HtmlControlTop="50" HtmlControlLeft="30" Height="500" NavigationUrl="http://www.microsoft.com"/>


  5. Call the customHost.InitControl(); function in the Page load event of the control or the constructor of your Page.xaml.cs file after the 'InitializeComponent()' function.
The isWindowless property determines whether the HTML is displayed on top of silverlight. If set to true, the HTML controls behind the silverlight plugin are displayed and if false, the silverlight is displayed on top of HTML. This must be set to true while using this HTML host control.

There is another option of background=transparent which makes the background of the plugin to invisible. This option should be avoided as this might hit the performance of the app. We need not worry about this property for using this control. Leave it to its default.

There is another property enableHTMLAccess property which provides a layer of security to specify whether the silverlight code should access HTML DOM or not. This is by default set to true even if you don't use it.

Download Source:

You can download the Visual Studio 2008 control source file at FreeHtmlHost source.

The sample code using this library can be found at Sample Project.

Wednesday, March 18, 2009

How to create a simple pushpin as a placemarker for DeepEarth in Silverlight?

The DeepEarth Maps in codeplex is a very brilliant work and can support a lot of map types with different providers like Yahoo, Open Street Maps, Blue Marble (except Google for now) in silverlight. I am a fan of this work.

They also have sample source code to create custom push pins. These are like the markers in the javascript version of google and yahoo maps. These are controls derived from a base class called PointBase which derives from DependencyObject at the deep base levels. Finally it overrides a function called OnApplyTemplate where it really does the work of showing the data/controls. This article does not intend to explain those concepts though.

Problem:
The sample project they have contains support for Pins which can show JPEG or other items in their styles and ability to show descriptions etc., which is great. But recently I had a requirement just to show the text of a village name for example. The existing sample controls did not fit my needs. So I had to write a simple control on my own. Hope this helps some one else as well.

Anyway here you go!!

Solution:
We need to take care of 2 things. The first is to define a style in App.xaml and the second is to write the control code.

The control name that I used is "PlaceMarkerPin". You can rename it if you like something else.

---------------------------------------------------------------------------------------------
App.xaml:

<Style x:Key="PlaceMarkerStyle" TargetType="MyControls:PlaceMarkerPin">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="MyControls:PlaceMarkerPin">
<Grid>
<TextBlock x:Name="DisplayTitle" Text=" " TextAlignment="Center" Foreground="Black" FontSize="12" FontWeight="Bold" />
</Grid>

</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

---------------------------------------------------------------------------------------------

Now if you really look at it we have only one control TextBlock named as "DisplayTitle" in the above style and this is the only item displayed. You can change the Font styles, alignment etc., to your liking.

Now to the control code

---------------------------------------------------------------------------------------------
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Input;
using DeepEarth.Geometry;

namespace YourNameSpace
{
public class PlaceMarkerPin : PointBase
{
private string _title;

public string Title
{
get { return _title; }
set { _title = value; }
}

public PlaceMarkerPin()
{
}


#region Balloon Functions

#endregion

public override void OnApplyTemplate()
{
TextBlock tbDisplayTitle = (TextBlock)GetTemplateChild("DisplayTitle");

bool designTime = (HtmlPage.IsEnabled == false);
if (designTime == false)
{
tbDisplayTitle.Text = _title;
_IsLoaded = true;
ForceMeasure();
Layer.UpdateChildLocation(this);
}
}

void tbDisplayTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
CaptureMouse();
}
}
}
---------------------------------------------------------------------------------------------

The following is the codesnippet for adding it to the DeepEarth map layer. This assumes that we already have a layer created.
---------------------------------------------------------------------------------------------
Point point = new Point(loc.Longitude, loc.Latitude);
var pin = new PlaceMarkerPin() { Point = point, Style = (Application.Current.Resources["PlaceMarkerStyle"] as Style) };
pin.Title = loc.CustomLocationName;
customlayer.Add(pin);
---------------------------------------------------------------------------------------------

This also is a very short example to actually understand how the pins in DeepEarth Maps work. One can now add more controls and styles to make it better if a need arises.

Saturday, January 10, 2009

Silverlight Datagrid find row number

Silverlight 2.0 datagrid has rich UI features giving very impressive look and feel. I am trying to add to a list of difficult to find tricks which might be helpful to others. I could not obviously find these while I did the google search, so I am writing this now.

Adding a button column to Silverlight Grid:


<data:datagrid name="gridCustomers" autogeneratecolumns="False" headersvisibility="All" gridlinesvisibility="All" isreadonly="True" rowbackground="Cornsilk" alternatingrowbackground="LemonChiffon"
ColumnWidth="85" RowHeight="30" CanUserResizeColumns="False" Canvas.Top="603" Canvas.Left="16" Width="1072" Height="120" SelectionMode="Single" >
<data:datagrid.columns>
<data:datagridtextcolumn header="Id" binding="{Binding id}">
<data:datagridtextcolumn header="Location Name" binding="{Binding Name}">

<data:datagridtemplatecolumn header="Edit">
<data:datagridtemplatecolumn.celltemplate>
<datatemplate>
<button content="Edit" margin="4" tag="{Binding customlocationid}" click="datagridEditRow_Click"></button>
</datatemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
<data:datagridtemplatecolumn header="">
<data:datagridtemplatecolumn.celltemplate>
<datatemplate>
<button content="Delete" margin="4" tag="{Binding customlocationid}" click="datagridDeleteRow_Click"></button>
</datatemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>


The above code gives the WPF markup for the grid. See the bold font for the Templated Column definitions for the "Edit" and "Delete" buttons.

Finding the row numbers:
  Now our button click event handlers datagridEditRow_Click and datagridDeleteRow_Click will need to know the row numbers when they are clicked. 

  We cannot use the gridCustomers.SelectedItem for this. The reason is, a click on the button won't automatically select the row. So we have to use the following code.
        private void datagridEditRow_Click(object sender, RoutedEventArgs e)
        {
            Button btnSender = (Button)e.OriginalSource;
            int dgridrow = DataGridRow.GetRowContainingElement(btnSender).GetIndex();
            gridLocations.SelectedIndex = dgridrow;
      }

 The above code will automatically get us the row number and we can use it to find the data in the row or may be select that row by setting the selectedindex property.