Sunday, January 17, 2010

Slide Show in Silverlight


When my friends come and ask me how to start with Silverlight, I always point them to http://silverlight.net/ But when they ask me to give them some kind of a task so that they can have hands on, then I always tell them to make a simple slide show. Slide show is a thing which is very easy and which can be made equally complex. I find that from the making of this simple show to its conversion to a complex carousel, we get to learn Silverlight and in turn gain confidence over it.


For a beginner it’s always good to start with some static images put in some layout element, when we explore further to see what will be the best container for a stack of images we in turn explore different layouts. Then to make things look better and to add a Silverlight touch to it, I tell them to add little animations on mouse over and out events. Then I tell them to add few buttons and control the slide show using them. By now they ask me how they can do the entire thing dynamically. Then a series of events and changes are done on the same old slide show and in the end a wonderful carousel is made. If you are a beginner in Silverlight then I would suggest you to start learning it by making a slide show. People have made thousands of slide shows but each has a different touch. Here is my version for you to start with.


In this I am locally maintaining an XML that has links to images of some cute dogs. I am reading this xml and then displaying them in the age old filmstrip fashion. To read the xml I have used Linq. The slide show is controlled by a pair of forward and backward buttons.







So, now when everything is all set, why don’t you Download Source Code and get started!

Sunday, January 10, 2010

Reading xml from a SharePoint server

Every now and then we have to send and receive data through an xml or an RSS feed. Some of these xml files can be kept somewhere at the server or can be kept locally. If the xml is stored at a different location then you have to write a web service that would call it and put a Client access policy there. I had a requirement to read an xml file stored at a sharepoint server. Here is how I have done it without web services.
List<string> itemDetailsList = new List<string>();
 
List<string> itemTitleList = new List<string>();
 
List<string> itemSourceList = new List<string>();
 
private XNamespace z = "#RowsetSchema";
 
public MainPage()
 
{
 
InitializeComponent();
 
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
 
}
 
void MainPage_Loaded(object sender, RoutedEventArgs e)
 
{
 
//this xml path will be kept at a SharePoint server and the uri will have the address of the SharePoint Server.
 
Uri absUrl = new Uri("http://yourSite/_vti_bin/owssvr.dll?Cmd=Display&List=%7BCA37%2D7F%2D408CBF6%2D059D&XMLDATA=TRUE", UriKind.RelativeOrAbsolute);
 
WebClient xmlClient = new WebClient();
 
xmlClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xmlClient_DownloadStringCompleted);
 
xmlClient.DownloadStringAsync(absUrl);
 
}
 

 
void xmlClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 
{
 

 
if (e.Error == null)
 
{
 
XDocument doc = XDocument.Parse(e.Result.ToString());
 
var docNode = from item in doc.Descendants(z + "row")
 
select new
 
{
 
ItemTitle = item.Attribute("ows_NameOrTitle") == null ? string.Empty : item.Attribute("ows_NameOrTitle").Value,
 
ItemDetails = item.Attribute("ows_Details") == null ? string.Empty : item.Attribute("ows_Details").Value,
 
ItemSource = item.Attribute("ows_RequiredField") == null ? string.Empty : item.Attribute("ows_RequiredField").Value
 
};
 
foreach (var itemContent in docNode)
 
{
 
itemTitleList.Add(itemContent.ItemTitle);
 
itemDetailsList.Add(itemContent.ItemDetails);
 
itemSourceList.Add(itemContent.ItemSource);
 
}
 
}
 
else
 
{
 
MessageBox.Show("error while reading from the server");
 
}
 
}

Sunday, December 20, 2009

Preloader in Silverlight

Preloaders are those special and small animations which makes the user still stay at your page, when data is retrieved and when there is nothing to be displayed. These small packets of animation can be simple and at the same time can be very creative. Preloaders can actually show how creative or how funny or how professional your website or application is.They actually does add lots of XP's to your app.

You can check this site for some really funny and creative Flash based preloders . Here is one such simple and very common preloader. You may add this as a seperate xap in your project or just copy the xaml into your project. Keep watching this space for more such preloaders.
 Download source code here.

Monday, November 16, 2009

Connecting JQuery/javascript and Silverlight

I had a requirement to send few parameters to silverlight from aspx
page. One of the option I had was to send the parameters as initparams, but initparams
are visible in the page source. Another one was to send the parameters using
JQuery or simple javascript. To go with approach, there is a problem. The problem is not with writing a javascript but
is to send parameters to the silverlight function or to call a javascript function
from silverlight.
To use JQuery we need to add a small javascript file to your
project. Once it is done the rest of the things become very easy. You can
get the
JQuery file here.

Calling Silverlight function from JQuery functionCalling Silverlight
function from JQuery function

A function in silverlight cannot be understood by a jquery function directly.
But we can always make it understand a silverlight function using a simple
[ScriptableMember] tag which indicates that a particular function or
event is accessible to a javascript function. We can add it on a function or
event in silverlight like this  

namespaceJQuerySLinteraction
{   
   public partial class MainPage : UserControl
   {
      string time;
      publicMainPage( )   
     {
        InitializeComponent( ); 
       HtmlPage.RegisterScriptableObject("MainPage", this);    
     }     
     [ScriptableMember]

     public void GetTime( )
     {
        time = DateTime.Now.ToShortTimeString( );
        time_txt.Text = time;
     }
   }
 }
...and in the aspx page you first need to give an id to your silverlight objcet
tag. In the example I have given the id as SLinteractionXapMarker.
You will have to add the source of the .js file which you downloaded to support
the JQery and make your work easier and efficient. The code with the id and
source of js would look like this..
<head>
<script src="../Scripts/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="silverlightControlHost">
<object data="data:application/x-silverlight-2," id="SLinteractionXapMarker" type="application/x-silverlight-2"
width="100%" height="100%">
<param name="source" value="ClientBin/JQuerySLinteraction.xap" />
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="3.0.40624.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration: none">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight"
style="border-style: none" />
</a>
</object>
<iframe  id="_sl_historyFrame"  style="visibility: hidden;  height: 0px;  width: 0px;
 border: 0px"></iframe>
</body>


now to call the JQuery or to trigger an event we will make a hyperlink, and on click of that we will call the JQuery that will in turn call the silverlight function
. We will write a small script that would be called on this hyperlink's
click.

<head>
<script language="javascript" type="text/javascript">          
$(function() { $("#_time").click(callGetTimeFunc); });
function callGetTimeFunc() {
document.getElementById("SLinteractionXapMarker").Content.MainPage.GetTime();
}
</script>
</head>
<a id="_time" href="default.aspx">Get Time</a>
Note that the #_time is identifying which hyperlink is clicked. The
SLinteractionXapMarker is identifying
which xap has to be addressed, MainPage
is with which we have registered the scriptable object. We can pass any
parameters as well in this way.
Happy Coding!

Sunday, November 1, 2009

Create a simple DeepZoom sample application

A really great feature added by microsoft to interact with images and create amazing zooming applications is Deep Zoom. In short, Deep Zoom provides the ability to interactively view high-resolution images. You can zoom in and out of images rapidly without affecting the performance of your application. Deep Zoom enables
smooth loading and panning by serving up multi-resolution images and using spring animations. With its help we can create amazing web experience.
Some of the best examples would be hard rock memorablia, Deep Zoom Pix

How to Create the simplest Deep Zoom application
  1. Install Deep Zoom Composer .
  2. After installation create a new project. Go to File -> New project. A new project will be created with a .dzprj extension.
  3. Collect few good quality pictures.
  4. Start importing it in your project by clicking the add image button.
  5. Prepare a storyboard in your mind. By storyboard I mean how you would like your application to react on mouse events.
  6. Start positioning and composing the images by clicking on the compose tab.
  7. Select an image which would serve as your base image. For example, if I want to make an application similar to Google Earth, then I will take the satellite image of the world as my base image.
  8. Drag and drop the base image into the storyboard area and make it  fit to screen.
  9. Add rest of the images on to the base image and reduce their size, till it looks like small yellow lense on your base image.
  10. Add more images and do the same.
  11. Your deep zoom application is ready to be exported!!
  12. Export it and keep zoomin!!!
     

Friday, October 16, 2009

Create Glow effect in Silverlight

It every designer's requirement to have three basic effects,
1. Drop shadow effect.
2. Glow effect.
3. Blur effect.
but Silverlight 3 doesn't have glow effect directly. But the good news is that we can create it indirectly!!!
Lets see how it can be done:
1. Create a normal button or any component and style it as you want.
2. Add Drop shadow effect ot it.
3. Set the depth of the shadow to 0.
Thats it!!! Your glow effect is ready!



To achieve this you just need to do a small adjustment in your blend,



Tuesday, October 6, 2009

Styling a Text Block


Now a days everybody is bored with age old white contemporary text block!!!Lets make something good!
Here is the TextBlock with a button


This Text block has a button at its end though! I will be posting the code for that button in my next post.
Here is the code:
<Style x:Key="BookmarkTxt" TargetType="TextBox">
           <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Background" Value="#FFFFFFFF"/>
            <Setter Property="Foreground" Value="#FF000000"/>
            <Setter Property="Padding" Value="2"/>
            <Setter Property="BorderBrush">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="#FFA3AEB9" Offset="0"/>
                        <GradientStop Color="#FF8399A9" Offset="0.375"/>
                        <GradientStop Color="#FF718597" Offset="0.375"/>
                        <GradientStop Color="#FF617584" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TextBox">
                        <Grid x:Name="RootElement">
                            <vsm:VisualStateManager.VisualStateGroups>
                                <vsm:VisualStateGroup x:Name="CommonStates">
                                    <vsm:VisualState x:Name="Normal"/>
                                    <vsm:VisualState x:Name="MouseOver">
                                        <Storyboard>
                                            <ColorAnimationUsingKeyFrames Storyboard.TargetName="MouseOverBorder" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)">
                                                <SplineColorKeyFrame KeyTime="0" Value="#FF000000"/>
                                            </ColorAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="Opacity">
                                                <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
                                                <SplineColorKeyFrame KeyTime="00:00:00" Value="#FF333333"/>
                                            </ColorAnimationUsingKeyFrames>
                                            <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)">
                                                <SplineColorKeyFrame KeyTime="00:00:00" Value="#FF45494D"/>
                                            </ColorAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name="ReadOnly">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="ReadOnlyVisualElement" Storyboard.TargetProperty="Opacity">
                                                <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)">
                                                <SplineColorKeyFrame KeyTime="00:00:00" Value="#FF45494D"/>
                                            </ColorAnimationUsingKeyFrames>
                                            <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
                                                <SplineColorKeyFrame KeyTime="00:00:00" Value="#FF262626"/>
                                            </ColorAnimationUsingKeyFrames>
                                            <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="ReadOnlyVisualElement" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
                                                <SplineColorKeyFrame KeyTime="00:00:00" Value="#00333333"/>
                                            </ColorAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                </vsm:VisualStateGroup>
                                <vsm:VisualStateGroup x:Name="FocusStates">
                                    <vsm:VisualState x:Name="Focused">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity">
                                                <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name="Unfocused">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity">
                                                <SplineDoubleKeyFrame KeyTime="0" Value="0"/>
                                            </DoubleAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                </vsm:VisualStateGroup>
                            </vsm:VisualStateManager.VisualStateGroups>
                            <Border x:Name="Border" Opacity="1" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4,4,4,4" Background="#FF242424" BorderBrush="#FF45494D">
                                <Grid>
                                    <Border x:Name="ReadOnlyVisualElement" Opacity="0" Background="#72F7F7F7" CornerRadius="4,4,4,4"/>
                                    <Border x:Name="MouseOverBorder" BorderBrush="Transparent" BorderThickness="1">
                                        <ScrollViewer x:Name="ContentElement" BorderThickness="0" IsTabStop="False" Padding="{TemplateBinding Padding}" BorderBrush="#FF525252"/>
                                    </Border>
                                </Grid>
                            </Border>
                            <Border x:Name="DisabledVisualElement" IsHitTestVisible="False" Opacity="0" Background="#A5F7F7F7" BorderBrush="#A5F7F7F7" BorderThickness="{TemplateBinding BorderThickness}"/>
                            <Border Margin="1" x:Name="FocusVisualElement" IsHitTestVisible="False" Opacity="0" BorderThickness="{TemplateBinding BorderThickness}"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>