Scholar Open Source Project

Scholar is now up on Codeplex. Scholar is a new open source project that will provide a starting point for developers to create distributed data processing such as the SETI@home project. It will use Azure to enable scalability and allow independent developers to get started without needed there own data centres. It's hoped that eventually it might be used to enable large medical and scientific data to be processed.

http://scholar.codeplex.com/

SHARE:

Developing a Windows 7 Phone App That Connects To Azure (a quick overview)

Installing

Download and install VS 2010 RC (phone tools below don't currently work with RTM ver of VS 2010):

http://www.microsoft.com/downloads/details.aspx?FamilyID=301c97f3-aecf-42ca-966a-b8d7304f40b0&displaylang=en

Download and install vs 2010 express for windows phone ctp:

http://www.microsoft.com/express/Downloads/#2010-Visual-Phone

 

Developing

Open VS 2010 RC

New --> Project

Double Click Enable Windows Azure Tools and follow instructions to install Azure tools ( once install starts you will  have to quit VS2010)

 

 

Reopen VS2010

Create new proj Cloud --> Windows Azure Cloud Service


Add WCF Service Web Role

R click Service1 Refactor --> Rename to HelloWorldService

R Click definition for Iservice1 Refactor --> Rename to IHelloWorldService

Change interface and service class to:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WCFServiceWebRole1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IHelloWorldService
    {

        [OperationContract]
        string SayHello(string name);     

    }
}





using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WCFServiceWebRole1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class HelloWorldService : IHelloWorldService
    {

        public string SayHello(string name)
        {
            return String.Format("Hello {0}.", name);
        }

    }
}




Add a Windows Phone Application project to the solution.



Create a user interface that looks similar to this (notice how the UI elements are pre-styled to the Win 7 phone look and feel codename 'Metro':



Here's where it gets a bit messy. VS2010 RC phone app project doesn't have an Add Service Reference, so: Save All, then r click Service1.svc --> Preview In Browser, then copy the URL - leave IE open

Open VS 2010 Express, open the solution (there might be some errors, but click ok to them), when the solution opens, add service reference to the Windows Mobile application and paste the URL into the add service box and click ok. Save all and close VS 2010 Express.

Go back to VS 2010 RC and click reload solution if you get prompted.

Now we can double click our button to go to the code behind and type:


        private void button1_Click(object sender, RoutedEventArgs e)
        {
            ServiceReference1.HelloWorldServiceClient proxy = new ServiceReference1.HelloWorldServiceClient();

            // declare callback as statement lambda
            proxy.SayHelloCompleted += (s2, e2) =>
            {
                txtGreeting.Text = e2.Result;
            };

            // call 'Azure' service
            proxy.SayHelloAsync(txtName.Text);

        }

Now hit f5 and wait for the Windows Phone Emulator to start (it may take a little time...) then if u click on the button a keyboard will pop up:



Type you name then click the Say Hello button, you should then see the "Hello ...." result displayed that was returned from the Azure service:


It's pretty amazing that a sole developer can now create a worldwide Win 7 phone app which connects to scalable set of services in Azure all from within VS2010.

SHARE:

Global.asax Application_Error "File does not exist" Exception

This can sometime also manifest as a "Session state is not available in this context" exception. If you get either of these in your Application_Error event where you are using Response.Redirect and you have breakpoints set, simply remove the breakpoints and test again.

SHARE:

Failed to encrypt the section [name] using provider RsaProtectedConfigurationProvider. Error message from the provider: Object already exists.

If you're running aspnet_regiis to encrypt a section in your web.config, e.g.

 aspnet_regiis -pef mytestsection .

(assuming your current directory contains the web.config and the section is called 'mytestsection')

And you get a message ...   Object already exists  trying running the Visual Studio command prompt as an administrator.

SHARE:

Modify And Save an EF EntityDataSource Bound Entity From Code Behind

If you're using databound controls (e.g. FormView) and binding them to an EntityDataSource you might want to be able to modify (and save) the underlying entity from code. For example, if you have a Question entity bound to a FormView via an EntityDataSource you might want a button to allow the use to vote up or down the question (like StackOverflow for example). To be able to do this without extra trips to the database, the first thing we need to do is get hold of the EF ObjectContext that the EntityDataSource is using.

        // Context that we can use for code-behind operations
        ObjectContext questionObjectContext = null;


        protected void QuestionEntityDataSource_ContextCreated(object sender, EntityDataSourceContextCreatedEventArgs e)
        {
            questionObjectContext = e.Context;
        }

When the QuestionEntityDataSource creates it's context, we take a reference to it in our private field questionObjectContext.

Now in the button click we can up-vote the question:

 

        protected void btnVoteUp_Click(object sender, EventArgs e)
        {
            // force a databind to ensure we have a DataItem in the FormView        
            FormView1.DataBind();

            // Get the actual entity represented by the FormView
            Question questionToUpdate = FormView1.DataItem.WrappedEntity<Question>();

            // Vote-up
            questionToUpdate.VoteScore++;
           
            // using our 'copy' of the EntityDataSource ObjectContext, save the changes
            questionObjectContext.SaveChanges(true);
           
            // Force rebind of FormView to ensure newest data displayed
            FormView1.DataBind();                     
        }

This method feels like a bit of a hack, but ideally you would provide a client-side AJAX version, only if JavaScript is disabled on the client do we use this server-side up-vote.

SHARE:

Introduction To jTemplates - A jQuery and JavaScript Template Engine

jTemplates is a great lightweight template engine for jQuery and JavaScript. It allows you to process data (e.g. JSON data returned from an AJAX call) and feed it ito a template definition rather than manually building your html elements.

jTemplates supports foreach, for, if..elseif..else constructs in additional to parameters, nested templates etc.

The example below defines a template to display a list of orders and for each order the list of items that belong to that order. It shows how nested foreach can be used. The project documentation goes into more detail.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="js/jquery-jtemplates0.7.8.js" type="text/javascript"></script>
   
    <title>jTemplates Demo</title>
   
    <script type="text/javascript" language="javascript">
        // define some sample data orders
        var sampleOrder1 = {
            orderID: 'OR0001',
            orderItems: [
                { product: 'Apple', quantity: 23 },
                { product: 'Kiwi', quantity: 13 },
                { product: 'Orange', quantity: 2 },
                { product: 'Mango', quantity: 99 }
            ]
        }
        var sampleOrder2 = {
            orderID: 'OR0002',

            orderItems: [
                { product: 'Pear', quantity: 2 },
                { product: 'Mango', quantity: 400 }
            ]
        }

        // define a list of (2) sample orders
        var sampleOrdersList = {
            orders : [sampleOrder1, sampleOrder2]       
        }

        // When the DOM is ready apply the jTemplate
        $(document).ready(function() {
            // Tell jTemplates we want the div with the ID of renderedContentWillGoHere
            // to be filled with the templated
            $('#renderedContentWillGoHere').setTemplate($('#ordersListTemplateDefinition').html());

            // Combine the data in sampleOrdersList with the templateand render
            $('#renderedContentWillGoHere').processTemplate(sampleOrdersList.orders);
        });
   
    </script>
   
   
   
   
    <script type="text/html" id="ordersListTemplateDefinition">
   
        <!-- iterate over all the orders that were passed in as data
             and as each order is processed we give it an alias of currentOrder -->
        {#foreach $T as currentOrder}
   
            <!-- Output the orderID for the currentOrder we are iterating -->
            <h1> Order ID: {$T.currentOrder.orderID} </h1>
           
           
            <!-- Now we have a nested loop where we output the orderItems for the currentOrder -->
            <h4>Order Items</h4>           
            <ul>
                {#foreach $T.currentOrder.orderItems as currentOrderItem}
                    <li>{$T.currentOrderItem.product} {$T.currentOrderItem.quantity}</li>
                {#/for}
            </ul>           
           
        {#/for}
       
    </script>
       
</head>

<body>
    <div id="renderedContentWillGoHere"></div>
</body>

</html>

SHARE:

Auto Expanding Div Columns (when floated div has no set size)

Usually 2 divs side-by-side (e.g. left menu and main content) will have the left div floated left with set size, the 2nd div also float with a left margin equal to the width of the left div.

When the left div has no set size (for example if it will contain an image of unknown width) you can still float it left, but instead of floating the 'main content' div, you can set overflow: hidden; in its CSS style (real implementation via external .css).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title></title>
</head>
<body>   
    <div style="float: left">           
        <div style="width:200px; height:200px; background-color: Fuchsia"></div>        
    </div>

    <div style="overflow: hidden">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus commodo sodales faucibus. Aenean ante nunc, porta nec lacinia dignissim, eleifend ut quam. Duis quam elit, condimentum ac hendrerit et, sodales semper arcu. Phasellus justo urna, porta quis vestibulum non, fringilla non est. Sed vestibulum bibendum feugiat. Vivamus porttitor justo at sem egestas ultricies vitae et mi. Ut mattis ante sed dui viverra vel scelerisque felis bibendum. Proin nec sapien id orci egestas eleifend. Sed facilisis erat in urna ullamcorper et suscipit urna luctus. Phasellus cursus consequat odio eget auctor. Curabitur eu ante nec lacus ultrices tristique.</p>
    </div>
</body>
</html>
 

SHARE:

Disable Grey Border On Focus Selected Anchor <a> Elements

When an <a> element is selected the browser can add a grey focus border around, the CSS outline:none; can be use to prevent it on standards browsers, for IE (except IE 8 when not in compatibility mode) adding the (non-standard) hidefocus="hidefocus" attribute to the <a> element seems to work. (Unsure what older versions of IE support this.) http://help.dottoro.com/lhgdtcso.php

SHARE:

Accessing Entity Framework Entities In EntityDataSource Data-Bound Controls

If using ASP.NET EntityDataSource and databound controls you may need to access the actual entity object being represented in the control, e.g. a data row in a table or a single entity in a FormView. The actual entity is not readily available however as it is automatically wrapped in a System.Web.UI.WebControls.EntityDataSourceWrapper which is not accessible. The extension method below allows you to gain access to the strongly typed, underlying entity. It is based on the article by Diego Vega which explains the wrapping behaviour in more detail. 

 /// <summary>
/// Gets the actual EF entity object that is being wrapped and databound.
/// </summary>
/// <example>
/// Advert ad = myFormView.DataItem.WrappedEntity<Advert>();
/// (where myFormView is databound to EntityDataSource returning Advert entity)
/// </example>
static class WrappedEFEntityExtensions
{
    public static TEntity WrappedEntity<TEntity>(this object dataItem) where TEntity : class
    {
        var entity = dataItem as TEntity;

        if (entity != null)
            return entity;

        var typeDescriptor = dataItem as ICustomTypeDescriptor;

        if (typeDescriptor != null)
            return (TEntity)typeDescriptor.GetPropertyOwner(null);

        return null;
    }
}

SHARE: