Silverlight 2 – Best Practices – I

For the past 6 months, I have been working on Performance and Memory Analysis for few projects, that became critical when developers chose not to adhere to the best practices.  Teams have started calling me ‘Dr. Perf’ as I board the ship to diagnose the applications – web and windows.  So here I go with one of the most looked after topic ‘Best Practices for Silverlight 2.’  Wherever required, I would direct you to appropriate sites, books and links to have a further read.

 

Design Considerations

 

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 than using 3rd party controls.

 

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.

 

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.

Punit Ganshani

Continue reading » · Rating: · Written on: 07-09-09 · 8 Comments »

ASP.NET Best Practices

This has been pending since long. People have been requesting this information and I’ve not been able to find time to write on Best Practices. And this fine day, finally I pen this down.

I hope this helps to you.  These best practices are direct-from-real-world i.e. noted down as observations from live projects.

String Concatenation

Use of StringBuilder is preferred over String.Concat or use of operator ‘+’

It is observed that when number of strings to be concatenated is greater than 3, StringBuilder does it much faster than String.Concat. For lesser number of strings, String.Concat can also be used.

Avoid round trips to server

  • Usage of Ajax UpdatePanel is preferred to avoid full postback to the server.
  • Client side scripts for validations should be used.
  • Check Page.IsPostBack at Page Load to ensure that only page initialization logic is performed when a page is loaded the first time and not in response to client postbacks.

ViewState & HiddenFields

  • ViewState is valid only for postback of same pages – as data is passed to client & returned in a hidden field
  • Keep minimal data in ViewState – higher the data, slower the system
  • Disable ViewState at PageLevel using EnableViewState

Session Variables

  • Not more than 20 session variables should exist in application context.
  • Keep Session TimeOut
  • Disable Session State, if you are not using in particular Page/Application.

Server.Transfer vs Response.Redirect

  • Use Server.Transfer to redirect between pages of same application.
  • Use Response.Redirect to redirect to external page or when new context needs to be started.

Use DataReader for data binding

  • If application does not demand caching, DataReader can be used. Use DataReader to retrieve data & then load it in a DataSet
  • Don’t pass this DataSet across layers. Pass custom serialize-able entities across layers.

Grid Pagination at SQL end

  • Pagination logic can be written @ SQL end, than writing it at Grid level.
  • Send Page Number, number of records to Stored Procedure to retrieve records from DB
  • Sorting should also be implemented @ DB.
  • Check for SQL Injection.

Close resources

  • Close the connections when not in use – improves security & enhances the performance.
  • Such closures should be done in finally block

Optimize loops

  • Avoid foreach – use for, while loops
    foreach degrades the performance. It is better to use for loop instead of a foreach
  • While deleting records/rows from a collection, iterate backward (counter=Max to 1). This will avoid Stack Overflow exceptions
  • Avoid try-catch in for loops – it degrades performance.

Variable Initialization @ right place

  • Initializing variable @ start & using it at a later stage will cause many PUSH/POP operations. Hence initialize variables at right place.
  • Integer variables need not to be initialized to ZERO. They are automatically initialized; String variables need to be initialized explicitly.

Use Fiddler to intercept HTTP requests.

  • Use Fiddler to intercept the HTTP requests and to know which request is consuming more time.
  • Also find out the exceptions caused during each HTTP request.

URL Rewriting

  • For URLs that have confidential information, it is advisable to implement URL Rewriters.
  • URLs should be consistent

Caching Mechanism

  • Cache static content for longer period – use high value for Expires property
  • Use Friendly folder structure – content\images\header.gif, etc.
  • Minimize use of SSL as SSL is not cached
  • Use IIS HTTP Headers to configure static caching.

Application Settings

  • Content-Length should be fixed. This keeps the connection open for limited time & closes automatically when the content length is greater than declared one.
  • Encrypt connection strings on server.
  • Make sure all the reference DLLs are present in GAC
  • Disable tracing and debugging
    Set <deployment retail=”true” /> in machine.config file – it forces debug to be false, disables output tracing, and redirects to custom error page rather than the actual error page.

Progressive UI

  • Progressive UI enables fast & smooth surfing – load/visible the DIV tags only when required.

Web Services

  • Prevent overloading of web services through DoS (Denial of Service) attacks. Check if it is the First time visit, or repeated visit for the same function from same IP.
  • Use trusted SQL connections in Web Services
  • Make sure there are asynchronous calls to web services

Exception Handling

  • Log the exceptions & display appropriate message to user.
  • Define a base class say : MyException
  • This class should have following information for display to user
    • What Happened
    • What has been affected
    • What actions to do
    • Support Information
  • This class should have following information for logging purpose
    • Server Name
    • Instance id
    • User Id
    • Call Stack
    • Assembly Name & Version
    • Exception Source, Type & Message
  • Redirect as per the Error-Level
  • Application Level: Catch errors in global.asax in Application_Error function.
  • Page Level: Use Page_Error function to log errors.

Deployment – IIS

  • Create separate application pool for your site
  • Use App_Offline.htm file. This will help you take your application offline by displaying user friendly message while fixing issues.
  • Automate the build process for
    • Development
    • Production environments
  • Make sure application is not built in DEBUG mode.
  • Load test application.
Continue reading » · Rating: · Written on: 03-10-09 · No Comments »