Silverlight

Must-have Tools on Windows – Part 2 of 2

March 7, 2012 CSharp, Open Source, Silverlight, Windows Phone , , , ,

Every technologist has his favourite list of developer tools, applications and OS which they believe are indispensible and without them they would not be able to develop anything.  With time and changing focus, this list keeps changing.  Here’s my list of tools that I think you as a developer should have on your laptop.

Most of them are Open-Source or Freeware as I promote using Open-Source (and donating them) than buying products at premium price.  So it is possible that many excellent products have not made it to my list!

Must have Tools on Windows – Part 1 of 2 – Visit here

 

Source Control and Versioning (contd)

 

I would like to continue with the last section on Source Control of Part 1 of this article. 

Until the announcement of TFS “Express”, I was preferred using SubVersion and Mercurial but with I think TFS Express will be a game changer.  It would be an ideal source control system for teams smaller in size.  But until Microsoft launches it officially, I would continue with Subversion and Mercurial

Windows Shell TortoiseSVN for Subversion and TortoiseHG for Mercurial

Visual Studio PluginAnkhSVN for Subversion and VisualHG for Mercurial

Defect Management CollabNet allows collaboration of SVN repository with defect management tools such as JIRA, HP Quality Centre, and many more.  You can use it with Visual Studio or Eclipse as a plugin

 

Microsoft .NET development tools (contd)

 

SharpDevelop – If you don’t want to use Visual Studio Express editions then you can give a try to SharpDevelop.

CoffeeScript Compiler – If you are building Web Applications and are not familiar/used to writing JavaScript (or jQuery), you should give a try to CoffeeScript.  You can create complex JavaScript files easily using CoffeeScript and its compiler.

Storm – Other than SoapUI, Storm is a perfect tool to test cross-platform Web Services.

CruiseControl – There are several continuous integration software available in the market, but truly CruiseControl is the leader due to some obvious reasons (read: free, no-cost, no-royalty).  You can download the CCTray to get real-time build status of your projects.

SilverlightSpy – I have tried the Free-Edition and I must admit – If you are a Silverlight or Windows Phone developer (or designer), you must download and use this tool.

Tombstoning for Windows Phone – Tombstoning is a an undocumented yet a required feature of every Windows Phone application.  This library is the easiest way to manage tombstoning.

Nuget – If you are a .NET developer, having Nuget and Nuget Package Explorer are an absolute necessary tools.  You can explore various open-source frameworks/tools/packages available in the market

CInject – CInject is my contribution to Open-Source fraternity.  CInject allows code injection into any managed assembly without disassembling and recompiling it. It eases the inevitable task of injecting any code in single or multiple methods in one or many assemblies to intercept code for almost any purpose.  Read more here

StyleCop – StyleCop analyses C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project. StyleCop has also been integrated into many third-party development tools.

 

Database and Tools

 

MySQL – Almost all my blogging websites use MySQL as a backend.  It is light, fast, free and is most commonly available with all Website hosting packages.

Microsoft SQL 2008 Express and Compact – The express edition of SQL 2008 is really good unless you need over 4GB of data storage

Sterling – NoSQL database for Silverlight and Windows Phone platforms

Neo4j Community Edition – A graph-based, high performing, NoSQL database that is now widely accepted in several organizations

MongoDB – A document-storage based, scalable, high-performance NoSQL database

HeidiSQL – HeidiSQL is a lightweight, Windows based interface for managing MySQL and Microsoft SQL databases. It enables you to browse and edit data, create and edit tables, views, procedures, triggers and scheduled events. Also, you can export structure and data either to SQL file, clipboard or to other servers.

 

Other Windows Tools

 

Audacity – A perfect sound/video editor for your webcasts and recordings.  It can convert your audio files into various formats.

HyperCam – Screen activity and voice recorder that is an ideal for recording your webcasts.

FlashGet – An ad-free and fast download manager, FlashGet supports HTTP, HTTPS, FTP downloads

BullzipPDF – A PDF printer is something every person (not just a developer) would dream of.  Bullzip is one of the best PDF printers that allows you to print, merge, apply watermarks, encrypt with password and many more features.

HandBrake – HandBrake is multiplatform, multithreaded video transcoder

PortableApps – Carry your favourite applications on a portable or a cloud drive and make it work on any PC, any make.

FreeMind – FreeMind is a premier free mind-mapping software written in Java. The recent development has hopefully turned it into high productivity tool.

myTracker – myTracker is a time-tracking application.  The inevitable, effort-driven process of tracking time and analyzing is eased by this small-memory-footprint application.  The application generates reports in Microsoft Excel (.xls) format and provides pie charts and bar graphs depicting time usage, utilization.

Eraser – Eraser is an advanced security tool for Windows which allows you to completely remove sensitive data from your hard drive by overwriting it several times with carefully selected patterns.

PureText – Have you ever copied some text from a web page or a document and then wanted to paste it as simple text into another application without getting all the formatting from the original source? PureText makes this simple by adding a new Windows hot-key (default is WINDOWS+V) that allows you to paste text to any application without formatting.

EaseUS Partition Manager Home Edition – Free Partition Magic alternative, free hard drive partition manager and disk management utility for Windows 7 SP1 and dual boot Windows 7 and Windows 8 users.

CrucibleWDS is a free Windows imaging / deployment / cloning program. It supports cloning Windows XP, Vista, and 7. A free Ghost alternative. Free Ghost software. Supports unicast and multicast. Can be used with 1 computer or 1000’s. Uses a simple web interface to deploy clients, clients can also be imaged directly from a boot menu by selecting an image from a pxe menu.

 

So in case you believe there is any Free / Open-Source tool that has been missed in my list, post it in the comments.  I will be happy to include it in my list!

Silverlight Best Practices (Part 4 of 4)

November 25, 2011 CSharp, Silverlight, Visual Studio , , ,

This is in continuation to my previous post Silverlight Best Practices – III, where the focus was what should be and what should not be done while developing a Silverlight Application. It was purely from a developer’s perspective.  In this post, we would consider designing the ‘Data Access Layer’

Designing Data Access Layer

In most of the web applications, data access layer comprises of 3 components:

  • Utilities – that help in accessing data components. Example, converters and alike
  • Data components – core components that access the data sources
  • Service Agents – this is an additional layer (proxies) over the services that are called from DAL. Mostly done to bring an additional isolation, entity mapping, or service-specific conversions.

Here, we will concentrate on ‘Data Components’ as the other two components are relatively easier to design and readily available as well or tools can generate them too. 

Managing Connections

Which connection remains open/closed should be monitored by a single interface. All calls should be redirected to a single function which would manage opening, closing of a connection and its timeout.  Connections can be cached for smallest duration of time to increase performance – however, security should of sensitive information like hostname, password should be taken care of as well.

The application should also take care that the fan-out does not reach.  This will ensure that no user gets a timeout error.

Design should enable switching between two replicas of data sources. This is most important during maintenance shutdown, or release of a newer version of application, or when database crashes. 

Exception Handling

DAL should ideally handle all exceptions and should not crash in any scenario; however all CRUD operations MUST be handled by DAL.

Exceptions concerning data access (data source unavailable, timeout, etc) should be handled by DAL; while other business related errors should be returned in an Error object in a serialized format.

Profile for best performance

In Internet applications DAL is the most accessed-by, making it prone to crashes and security risks.  Profiling of DAL is must to gauge the impact of high number of concurrent users.  Also, in such scenario DAL should be prevented against attacks from hackers.  Any other source of access should be give least privilege and only the web application should be at a higher privilege.

Consider using Batch Processes to reduce round-trip to database server.

Managing data

One of the common problems seen in many projects while doing profiling exercises is degraded performance due to improper data handling.  So let us see some important guidelines:-

  • If the system involves lot of documents and image storing – prefer to store them in BLOB, than on a file system
  • Avoid Outer Joins wherever possible
  • Use of cursors should not be preferred – use in-memory temporary tables instead.
  • Open connections as late as possible.
  • Use XML pameters for bulk inserts or updates – this will save execution time.
  • Use parameterized SQL statements and typed parameters to mitigate security issues and reduce the chance of SQL injection attacks succeeding.
  • Do not use string concatenation to build dynamic queries in the data layer.
  • Use typed parameters as input values to the procedure and output parameters to return single values.
  • Use optimistic concurrency with non-volatile data to mitigate the cost of locking data in the database

 

Dynamic Queries or Stored Procedure

 

  1. For a small footprint application with lesser clients and few business rules, prefer Dynamic Queries. IF NO, STEP 2
  2. Larger application, multiple clients – abstraction can be at
    1. Database level in Stored Proc – minimal code changes
    2. DAL using patterns  – best till the schema does not change, can be debugged
    3. DAL using ORM – best till the schema does not change, can be debugged

 

ADO.NET Services

I would suggest a very good tutorial on MSDN. Click here to read through.

This concludes the series of best practices articles on Silverlight. Thanks for reading them through!


Silverlight Best Practices (Part 2 of 4)

November 16, 2011 Silverlight, Visual Studio , , ,

This is in continuation to my previous post Silverlight Best Practices – I, where I talked about Design Considerations.  These design considerations were a bird’s view and the posts to come will explain these in detail.  In this post, I shall deal with the Business Layer, its components, steps to design these components, and design considerations.  This post can be considered not just for Silverlight Applications, but for other Web Applications as well.

Business Layer

 

Let us take on the parts of the business layer for those who are newbie

  1. Application Façade – layer that combines multiple business operations into single message based operation
  2. Business Components – Business Rules & Validations
  3. Entities – Used to pass data between business components
  4. Business Workflow – Multi-step and/or long-running business process

Design Considerations

 

Before you jump into designing of business layer, it is advisable to do these

 

  1. Identify ACTORS or CONSUMERS
  2. How these ACTORS will communicate to your business layer.
    1.  Concurrency needs to be addressed for access to STATIC data.
    2.  Long-running transactions should not LOCK the data.
  3. SECURITY requirements for business layer
    1.  Apply AUTHENTICATION wherever required.
    2. Use SSO where appropriate.
  4.  VALIDATION and EXCEPTION HANDLING strategies
    1. DONOT RELY on validations at presentation layer – reuse the VALIDATION logic.
    2. Should NOT reveal sensitive information to the end user.
    3.  Should NOT use exceptions for application logic.
    4.  Log SUFFICIENT detail from exceptions.

Authentication & Authorization Module Design

Authentication is not a mandate requirement and should be done if the Business Layer is to be used by several clients.  An easier said – public web services need authentication, but an application oriented service does not.

Consider IP filtering to restrict hacks and unauthorized usage or to have access only through the presentation layer.

For business decisions –role based or claim based authorization needs to be implemented.

Impersonation can screw-up your performance. So prefer avoiding it.

Business Components & Entities

Keep them light and encapsulated.  Do not mix data access logic and business logic. Break them into two assemblies. Volatile business rules ought to be kept in rules engine (Workflow, DROOLS.NET, etc)

Use ONLY CUSTOM objects as Business Entities, even if it means encapsulating only a string object.

Choose between the three patterns while designing these entities-

  • Table Module Pattern – this is typically used when database tables can represent entities.  This model is suited for large database applications or applications that use LINQ to SQL.
  • Domain Module Patter – this pattern is widely used for stateful application that has complex business rules.
  • XML – this is used for relatively smaller applications.

Serialize your objects if it requires passing between network boundaries.


Caching and Concurrency

Appropriate caching mechanism can speed up your performance by leaps and bounds by avoiding duplicate processing.  To avoid client delays, caching should be a background process.

Cache the data (non-sensitive ONLY) in a ready-to-use format.  In other words, data taken from cache should not necessarily require processing before use.  Caching resources should avoid locks due to threading.

Use connection based transactions to access single data source. Which means – a rollback should let you get back to previous state. When a rollback or commit cannot be applied (for processes that are long-running), then compensating methods should be in place. 

Logging and Audit Mechanism

Logging and Auditing cannot be compromised at an enterprise level application.  It can open doors to threats without getting noticed.  Auditing, if generated at granular level, can let us know precise time, IP, location of resource access.

One can use Enterprise Library or any other component to implement logging mechanism – but it needs to be centralized.   However unexpected failure of this centralized block should not cause stop the business functionalities.

Workflows

 

Windows Workflow is a great-gift by Microsoft to the technologies. Workflows – state machine or sequential – should be initiated on a separate thread for long-running process.  Faulty conditions should be handled as exceptions. 

Deployment

Towards the end, an incorrect deployment will surely not deliver excellent results. Use TCP protocol and SSL to support remote business layer in a safe manner.

 

The next to come in this series will be a post on what not to do in Silverlight while developing an application. This will focus on best practices that a developer needs to take care of.

 

Silverlight Best Practices (Part 3 of 4)

November 10, 2011 Silverlight, Visual Studio , , ,

[Republished after additions]

This is in continuation to my previous post Silverlight Best Practices – II, where I talked about Business Layer Design Considerations.  This post, the area of concentration, will be a list of to-do’s while developing a Silverlight Application.

Development Tactics and Practices

Defacing Errors

One of the regular application development exercise is debugging and debugging errors in Silverlight applications can be really tough job if your default browser is Chrome. I’m not sure whether there is problem with Chrome, or with Silverlight IDE, or something else – but until today, the breakpoint will not be hit in Chrome. Hence, prefer using Internet Explorer.

Using Team Foundation Servers (TFS)

Silverlight developers often struggle setting up a source-safe (read TFS) within a team. To enable TFS, install VS 2010 and Silverlight Tools on Team Build Server machine.

First-class rule

Ideally, for a file Page.xaml, the first class definition in the Page.xaml.cs should be Page class.  This otherwise has known issues related to code refactoring.

Locally defined StaticResource fails to load

When a StaticResource object is both defined and referenced inside the same element, the Preview Window will fail to load with an error “The type StaticResource was not found.”

Hence, it is advisable to keep Static Resources in App.xaml file. This also helps usage of these resources across the modules in the application.

Share a Brush than copying it

Instead of defining Brush in XAML, define it as StaticResouce and reference it. This creates only one instance and then reuses it.

A Generic TODO list

This is more of a compilation of single-liners that aptly fit in the TODO list of a Silverlight developer.

  • Naming Convention – Casing:
    • Pascal Casing and not Camel Casing is preferred (unlike in C#). myButton is wrong in Silverlight though it is correct in C#. The correct version is MyButton.
    • Use x:Name instead of Name as x:Name is generic and can be used for all elements.
  • Indentation:
    • Place first attribute in-line with the element name like.

<StackPanel  DockPanel.Dock=”Top” Orientation=”Horizontal”>

  • Choose a StaticResource over DynamicResource. For further read, click here
  • Resources should be placed at one location, preferably at Application Level in App.xaml file. This will avoid reloading of resources over and again when objects are created and destroyed.
  • SnapsToDevicePixels – Using graphic objects can appear nice on some monitors, while it may fade on others.  It is preferred to use a Style resource in such scenarios. For more read, click here
  • Define a definite folder structure before starting application development
    • Services – to have WCF service references
    • Images – to store application images and videos
    • Resources – platform specific APIs
    • Data – to store XML, text files
  • Remove the Object Handlers when not in use.  Not removing object handlers may keep the object alive, which may degrade the performance. RegisterClassHandler is called on every instance of object creation, which may cause performance problems
  • Frozen objects over Non-frozen:
    • Frozen objects occupy lesser memory space and are fast in execution.
    • Consider the example on MSDN–  Prefer VirtualizingStackPanel (40mSec) over a simple StackPanel (takes 3000mSec for same UI) to speed up the execution time.
    • Avoid using a TextBlock in FlowDocument
    • Since Label.Content property is slow in execution, TextBlock.Text should be used. (This is one reason why Label is not a part of Silverlight framework, and it is part of WPF)
    • Show underline in Hyperlink only on MouseOver events.  TextDecoration is performance intensive.
    • Bind an IList to an object, not an IEnumerable to avoid an automatic wrapper creation.  This will enhance your performance.
  • Proper node at proper place:
    • While the tree is developed, there can be two approaches – bottom-up or top-down. A top-down approach is 10 times faster. This is because when a node is added or removed from the logical tree, property invalidations are raised on the node’s parent and all its children.

Best practices generally evolve as a result of implementations and errors/observations. So this post remains unconcluded for the users to add in their inputs and make it extensive guide. Keep adding to it

Note: The next in this series is the Data Access Layer Guidelines.

Silverlight Best Practices (Part 1 of 4)

November 9, 2011 Silverlight, Visual Studio , , ,

I have been working on Designing and Development of Rich UI applications on Silverlight, and Windows Phone platforms and high performing applications as middleware components for Trading Applications.  One of the biggest issues I have seen is non-adherence to standards causing slowness in applications, or a red-mark in Audits due to mis-fit of technology stack. To help developers decide whether to opt for Silverlight and when designing what should be taken care of, this series of articles are written.  Wherever required, I would direct you to appropriate sites, books and links to have a further read to avoid duplicacy of text on two websites. 

 

 

This article has been edited and republished on demand.

Silverlight – yes or no?

This decision is very vital decision as you are pressing your money, time and your resources behind application development. Choose Silverlight only when

  1. Your clients hardware/software supports RIAs
  2. A good network bandwidth to download XAP components
  3. Sections that have more visualizations than that provided by HTML and ASP.NET markups
  4. High-streaming of video/audio is required.
  5. Best for single-screen applications; but can be extended to multi-screens.

Where not to choose Silverlight? Say NO when

  1. Pages are highly complex
  2. Multi-page user interfaces
  3. Browser specific programming is required (though you actually can do it, you must prefer not to use platform-specific-APIs)

Design your application such a way that plug-in installation is non-interruptive 

Data Accessibility

Accessing business logic directly from a Silverlight Application is not advisable.  It is better to encapsulate such logic in Web Services (read: WCF services), just like any other Web Application.  For security reasons, do not put highly sensitive unencrypted business logic on the client. Transferring logic to UI-layer (Silverlight) is preferred only when the performance is a huge hit, but this is done as a trade-off between performance and security.  Put your business validation/rules in a separate assembly so that it can updated independently when rules change.

Data store (DB, XML, etc), obviously, will be accessed through these services.  Do not attempt to use local client databases.  Minimize number of round-trips by filtering data at server rather than client end. 

Accessing local resources of client machine (in client-server arch) will be possible in limits only. So define the scalability of application and request appropriate space from user for your application. Avoid unhandled exceptions by checking if Storage Space is sufficient or not. The .NET cryptography APIs are available in Silverlight and should be utilized when storing and communicating sensitive data to the server if not already encrypted using another mechanism.

Application Performance Methods

 

Use appropriate methodologies to boost the application performance.  Ensure that your application has a lightweight foot-print so that users don’t spend too much time in downloading XAP file.  Initially load only code stubs which can lazy-load other modules.  Prefer using inbuilt RIA controls or trusted 3rd party controls offered by Telerik, Infragistics, Visifire, etc.

Cache your business logic and divide your modules very intelligently. Cache objects that not likely to change during a session.

Validate the data before call is given to Web Services. This will reduce the number of trips and make the system more responsive.  If validation logic is too large, consider putting it into a separate assembly. 

Communication

Prefer allocating data pull calls to background worker processes or in separate threads.  If your web service is slow in response, make sure that you keep polling it regularly (say every 5 minutes in a separate thread) to retrieve data.  Long-running processes should be executed in a separate thread to avoid blocking of UI.

Ensure that cross-domain configuration is done aptly to have communication with services hosted in other domains.  Consider using Sockets over Web Services when high-amount of information needs to be pushed/pulled to/from server. Example: Rich gaming sites, Stock-trading sites, etc.

Check out alternatives such as Nirvana for light weight push mechanism

 

Exception Handling & Logging


Using Exception Handling to control business logic is not advisable.  Catch internal exceptions and decide an appropriate exception propagation strategy – bubbling up to boundary layers.  Provide appropriate notification services for critical errors.

Logging component in Silverlight has several limitations. Hence, log errors at client-end and transfer them to server. If using services to implement logging, consider the increased overhead. The added overhead may also change message behavior on the server thus making it harder to use logging to troubleshoot message timing issues.

Mobility

Check if the plug-in has reduced functionalities for Mobile devices or the same.  If required, incorporate device specific features to improve user experience. Re-examine UI layout using simulators for a smaller screen size.  

Deployment

 

Design several modules (XAP-files) instead of a single-large XAP-file, so that individual modules can be downloaded and cached as and when required.  This will also ensure extensibility and modularity in the architecture.  Prefer to have a separate Web Application Server and a Database Server.  A Web Farm can be configured to improve response time.  However, cross domain policies should be implemented and tested. To avoid hardware failures, clustering should be done.

Version your components and label them in Source-Safe.

Provide Internet and Intranet links to manually download and install the plug-in if automatic installation cannot be done.

Ensure that your DLLs are obfuscated before deployed to any server.

Well, that’s for the first time. I’ll add more to this soon.. Please add in your expertise by commenting to this blog.

Creating Page Transitions in Windows Phone

July 3, 2011 CSharp, Visual Studio, Windows Phone , , ,

Creating page transitions is not difficult at all when you have Silverlight Toolkit available in market.  So follow the steps written below

Step 1: Using Silverlight Toolkit

So first download the latest copy of Silverlight Toolkit and follow the steps belowAdd a reference of Microsoft.Phone.Controls.Toolkit in your application

Step 2: Modify App.xaml.cs

Next modify App.xaml.cs to enable loading a page with transitions instead of a normal page.

Find out,  this line

[sourcecode language=’c#’]

RootFrame = new PhoneApplicationFrame();
[/sourcecode]

This has to be replaced by

[sourcecode language=’c#’] RootFrame = new Microsoft.Phone.Controls.TransitionFrame();
[/sourcecode]

Step 3: Apply transitions to page

Add the XML name space for toolkit in your page first if it is not already presented:
[sourcecode language=’c#’] xmlns:toolkit=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit”
[/sourcecode]

Now, add appropriate transition to your page (not as a resource).  Few samples are as shown below:

Example 1: Rotate pages when loading and exiting

[sourcecode language=’xml’]



















[/sourcecode]

Example 2: Turnstile motion when loading and exiting

[sourcecode language=’xml’]



















[/sourcecode]

Step 4: You are done!

Execute your application and see the page transitions working fine!

C# Html Sanitizer for Xaml

May 14, 2011 CSharp, Silverlight, Visual Studio, Windows Phone, WPF , , , ,

One of the converters that my application developerChannel uses is HtmlSanitizer.  The purpose of this converter is to remove the HTML formatting from a HTML-rich text.

Step One: Define the converter

[sourcecode language=’c#’]

public class HtmlSanitizer : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return HtmlSanitizer.Convert(value as string);
}

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

public static string Convert(string input)
{

// Remove HTML tags and empty newlines and spaces
string returnString = Regex.Replace(input, “< .*?>“, “”);
returnString = Regex.Replace(returnString, @”n+s+”, “nn”);

// Decode HTML entities
returnString = HttpUtility.HtmlDecode(returnString);

return returnString;
}

}

[/sourcecode]

Step Two: Define converter in XAML

In the XAML file, define

[sourcecode language=’xml’] [/sourcecode]

Step Three: Use the converter in XAML controls

[sourcecode language=’xml’]

Silverlight Interview Questions – I

Hello folks,

Marching forward, I will post a series of Interview Questions on Silverlight.  This will cover questions at each level – easy, intermediate and advanced.  And I am sure, other sites & users would post these on many other sites too 🙂

So keep watching this space. Some questions below to start with

Level: Developer

  • What is the role of Silverlight Plugin in the Silverlight Application Life-Cycle?
  • What does the keyword ‘type’ signify in the Silverlight Hosting page.[sourcecode language=’xml’]
    [/sourcecode]
  • You have developed an application on Silverlight 2, will it execute on Silverlight 4 platform? Is vice-versa true?
  • Your organization has blocked download of any software from Internet and you want to deploy your Silverlight Application as Intranet Application.  The users do not have Silverlight plugin installed on their machine; however you have the installable.  How do you plan to deploy your application? Will you change the application code to fit this requirement or change the organization policy?
  • Your Silverlight application faces some technical errors while it is executed. Where will you write your code to get notification of these errors?
  • Can any Silverlight Application be viewed on Linux? Or a specific installation is required?
  • Assume your host page defines the background as White[sourcecode language=’xml’] [/sourcecode]

    while your MainPage.xaml (that loads initially) defines background as ‘Gray’

    [sourcecode language=’xml’]
    [/sourcecode]

    What will be the color of the background?

  • I have two actors to a Silverlight Application – Employee and Customer. The default page (default.html) should always open Customer view; whereas viewemployee.html should open Employee view.How would you implement this?
  • What is significance of initParams in
    [sourcecode language=’xml’] [/sourcecode]
  • Customizing Splash Screen in Silverlight

    Customizing Splash Screen (a screen that loads before the Silverlight application loads) requires some development effort in the host application (could be HTML/ASPX/any other application).

    Creating SplashScreen.xaml

    First, we create a XAML file – say SplashScreen.xaml file which displays two things – a progress bar and a textblock that displays ‘% completed’

    [sourcecode language=’xml’]

    http://schemas.microsoft.com/client/2007”
            xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml“>
      
         
            movementBar” Fill=”Gray” Height=”28″ Margin=”101,20″>
             
               
                  progressText” HorizontalAlignment=”Center” Text=”0% downloaded …”>
       

    [/sourcecode]

    Here, we have a baseBackground (that forms background) that is Black in color and small bar that will move ‘movementBar‘ which is Gray in color.

    As the page downloads the data, movementBarTransform needs to be changed, so that the movementBar appears as if it is increasing. And simultaneously, progressText should display the % downloaded.

    Modifying host file

    Now let’s modify the host file that loads the Silverlight Application.

    [sourcecode language=’xml’]

                      
       http://go.microsoft.com/fwlink/?LinkId=108181” alt=”Get Microsoft Silverlight” style=”border-style: none”/>
       
      

    [/sourcecode]

    The most important line that calls a JS function ‘onSourceDownloadProgressChanged’ when some part (bytes) of the XAP is downloaded is:

    [sourcecode language=’xml’]

     [/sourcecode]

    Adding JS in hosting file

    [sourcecode language=’js’]

    function onSourceDownloadProgressChanged(sender, eventArgs)
            {
           
             sender.findName(“progressText”).Text = Math.round((eventArgs.progress * 100)) + “% downloaded …”;        
             sender.findName(“movementBarTransform”).ScaleX = eventArgs.progress;        
            }

    [/sourcecode]

    This code snippet calculates the percentage of XAP file downloaded and displays it in the textbox.  It also increases the ScaleX property of ScaleTransform of movementBar as per the progress.

    Testing the Splash Screen

    Now, add some heavy sized ZIP file in the Silverlight application so that your XAP file becomes atleast 5 MB and try to execute the application. 

    What you would see is a new custom Splash Screen

    ClientAccessPolicy Sample

    Recently I have delivered a 4-day training session on Silverlight 4 and many participants asked for a sample ClientAccessPolicy.xml file. So this is for those who want it 🙂

    [sourcecode language=’xml’]



     
             
           
         

         
           
         

       
     

    [/sourcecode]

    Just change the “*” to “*.xyz.com” to restrict permissions to request originating from xyz.com

    [sourcecode language=’xml’]

    [/sourcecode]

    Happy creating of WCF services for Silverlight & Flash..

    Follow on Feedly