Dec
5

Making a payment provider for Tea Commerce

Making a payment provider for Tea Commerce

When making an e-commerce system one of the key points, is often the ability for customers to pay online with credit card or others online payment services. Tea Commerce comes with a couple of pre-installed payment providers, but one of the great things is if you need to use a payment provider that isn’t given to you out of the box – it’s really simple to make you own. It’s as simple as inherit from a single .Net class and implement some metods and that’s it!

APaymentProvider

APaymentProvider is an abstract class, in the TeaCommerce.Payment.dll, all payment providers in Tea Commerce needs to inherit from, to be able to process payments through the Tea Commerce API and admin interface. When your payment provider inherits from APaymentProvider you will have to implement 6 different methods and a property – each explained below
All methods that returns a valid PaymentCallbackInfo will change the order’s transaction information.

FormPostUrl

You need to implement this property as it tells Tea Commerce what url to post the payment request to when the customer makes it to the payment step.

string FormPostUrl { get { return "http://www.teacommerce.dk"; } }

GenerateForm

When webshop customers is ready to go to the payment step – and the front-end developer call TeaCommerce.goToPayment() in our javascript API – Tea Commerce will see what payment method the customer selected, and based on the related payment provider, Tea Commerce generates a form and post it to the FromPostUrl. Return a dictionary containing the name/value pairs that builds up the form
Summary

Dictionary<string, string> GenerateForm( string orderName, string currencyISOCode, decimal amount, string defaultContinueUrl, string defaultCancelUrl, string defaultCallBackUrl, Dictionary<string, string> settings );

Example

Dictionary<string, string> GenerateForm( string orderName, string currencyISOCode, decimal amount, string defaultContinueUrl, string defaultCancelUrl, string defaultCallBackUrl, Dictionary<string, string> settings ){
  Dictionary<string, string> nameValues = new Dictionary<string, string>();
  nameValues.Add( "provider", "TeaCommerce" );
  nameValues.Add( "secretKey", "Expect simplicity" );
  return nameValues;
}

ProcessCallback

This method is called when Tea Commerce recieves a callback from the payment gateway. You need to process the request and tell Tea Commerce if the callback is valid

PaymentCallbackInfo ProcessCallback( HttpRequest request, Dictionary<string, string> settings );

GetStatus

For Tea Commerce to show the newest information about a transaction, this method is called when the webshop owner views an order in the admin.

PaymentCallbackInfo GetStatus( string transactionId, Dictionary<string, string> settings );

CapturePayment

Called when capturing the transaction from the Tea Commerce admin

PaymentCallbackInfo CapturePayment( string transactionId, string currencyISOCode, decimal amount, Dictionary<string, string> settings );

RefundPayment

Called when refunding the transaction from the Tea Commerce admin

PaymentCallbackInfo RefundPayment( string transactionId, string currencyISOCode, decimal amount, Dictionary<string, string> settings );

CancelPayment

Called when cancelling the transaction from the Tea Commerce admin

PaymentCallbackInfo CancelPayment( string transactionId, Dictionary<string, string> settings );

Helper methods

To make it much easier for your to make a payment provider for Tea Commerce, we have implemented some generic used methods in the APaymentProvider base class for you to use

MakePostRequest

These methods makes a post request for you and returns the response as a string.

string MakePostRequest( string url, Dictionary<string, string> inputFields );
string MakePostRequest( string url, string request );

GenerateContinueUrl

For Tea Commerce to work correctly, you need to use this method when generating a continue url. This methods makes a wrapper for your url, which force the continue url to be returned to Tea Commerce and process the request from the payment gateway before returning to your specified continue url.

string GenerateContinueUrl( string finalContinueUrl );

GenerateCancelUrl

This one works just like the GenerateContinueUrl method, just for the cancel url.

string GenerateCancelUrl( string finalCancelUrl );

GetMD5Hash

Some payment gateways use a MD5 hash as a security mechanism and this method makes it easy to generate one.

string GetMD5Hash( string input );

Extra properties

There is some extra properties for you to control in the APaymentProvider

//Return true to finalize the order as soon as the customer accepts the payment terms
bool AutoFinalize { get { return false; } }

//Add extra attributes to the genereated form element in GenerateForm()
string FormAttributes { get { return @"name=\""ePay\"" target=\""ePay_window\"" id=\""ePay\"""; } }

//If a method is specified - Tea Commerce will call it instead of posting the form when goToPayment is called
string SubmitJavascriptFunction { get { return @"open_ePay_window();"; } }

//These properties tells Tea Commerce if the specific action is possible with your payment provider
bool AllowsGetStatus { get { return true; } }
bool AllowsCapturePayment { get { return true; } }
bool AllowsRefundPayment { get { return true; } }
bool AllowsCancelPayment { get { return true; } }

PaymentCallbackInfo

This is the object almost every APaymentProvider method returns. The object should contain information about the response from the payment provider. When returning this object, if it’s valid, it will be used to change the order’s current transaction information

/// <summary>
/// Payment callback info
/// </summary>
///<param name="orderName">Name of the order</param>
///<param name="amount">Amount of the order</param>
///<param name="state">State of the order</param>
///<param name="transactionId">Id of the transaction</param>
///<param name="paymentStatus">The new payment status for the order to have</param>
PaymentCallbackInfo( string orderName, decimal amount, string state, string transactionId, PaymentStatus paymentStatus );

/// <summary>
/// Used to tell Tea Commerce an error occured in the payment provider
/// </summary>
///<param name="errorMessage">Message to show in Tea Commerce</param> 
PaymentCallbackInfo( string errorMessage );
Nov
2

Tea Commerce – XSLT extensions

Tea Commerce – XSLT extensions

Tea Commerce offers a lot of nice XSLT extension to be used in Umbraco. In this post i will walk you through the different extension, but because the xml output can be quite large for some of the methods i won’t go into details about the output. You can just do a simple <xsl:copy-of select=”teacommerce:method” /> to see the xml output

GetOrderXml

Returns the current order – if no order is present in the cart the order output is empty

<xsl:variable name="order" select="teacommerce:GetOrderXml()"/>
<xsl:if test="$order/@id != ''">
  <xsl:value-of select="$order/@name" />
  <xsl:for-each select="$order/orderLine">
    <xsl:value-of select="properties/productName" />
  </xsl:for-each>
</xsl:if>

Output example

WEB-5
Apple Speakers
Podspeaker MicroPod

GetFinalizedOrderXml

Returns the finalized order – is to be used in the shopping cart’s last step after the order is finalized

<xsl:variable name="order" select="teacommerce:GetFinalizedOrderXml()/@totalQuantity"/>

Output example

5

GetSpecificOrderXml

Returns the order with the specified id – is made to be used for testing and is also used in the default implementation of Tea Commerce – TeaCommerce/teaCommerceAdminOrder.xslt

<xsl:variable name="order" select="teacommerce:GetSpecificOrderXml( '11' )/@name"/>

Output example

WEB-11

GetFinalizedOrdersXml

Returns all finalized orders – can be used in many different cases, its just your imagination that is the limit

<xsl:for-each select="teacommerce:GetFinalizedOrdersXml()/order">
  <xsl:value-of select="@name" />
</xsl:for-each>

Output example

WEB-1
WEB-2
WEB-3

GetFinalizedOrdersXmlForMember

Returns all finalized orders for a specific member

<xsl:for-each select="teacommerce:GetFinalizedOrdersXmlForMember( umbraco.library:GetCurrentMember()/@id )/order">
  <xsl:value-of select="@name" /> - <xsl:value-of select="@totalPriceFormatted" />
</xsl:for-each>

Output example

WEB-7 - $250.00
WEB-9 - $349.00

GetCountries

Returns all countries

<xsl:for-each select="teacommerce:GetCountries()/country">
  <xsl:value-of select="@name" />
</xsl:for-each>

Output example

United States
Denmark

GetCurrencies

Returns all currencies

<xsl:for-each select="teacommerce:GetCurrencies()/currency">
  <xsl:value-of select="@ISOCode" />
</xsl:for-each>

Output example

USD
DKK
EUR

GetShippingMethods

Returns possible shipping methods for the current selected country

<xsl:for-each select="teacommerce:GetShippingMethods()/shipping">
  <xsl:value-of select="@name" /> - <xsl:value-of select="@feeFormatted" />
</xsl:for-each>

Output example

Pick up - kr. 0,00
FedEx - kr. 100,00

GetPaymentMethods

Returns possible payment methods for the current selected country

<xsl:for-each select="teacommerce:GetPaymentMethods()/payment">
  <xsl:value-of select="@name" /> - <xsl:value-of select="@fee" />
</xsl:for-each>

Output example

VISA - 10,00
Account Transfer - 0,00

GetCurrentCountry

Returns the currently selected country. I no specific country has been selected through the javascript API, the default country is returned

<xsl:variable name="currentCountry" select="teacommerce:GetCurrentCountry()" />
<xsl:if test="$currentCountry/@id ='2'">
  <xsl:value-of select="@name" />
</xsl:if>

Output example

United States

GetCurrentCurrency

Returns the currently selected currency. I no specific currency has been selected through the javascript API, current currency fallback to the default country’s currency

<xsl:variable name="currentCurrency" select="teacommerce:GetCurrentCurrency()" />
<xsl:value-of select="@cultureName" />

Output example

da-DK

FormatPrice

Formats a price with a currency symbol, based on current currency’s culture

<xsl:variable name="order" select="teacommerce:GetOrderXml()"/>
<xsl:value-of select="teacommerce:FormatPrice( $order/@totalPrice )" />

Output example

kr. 1395,00

FormatPriceNoSymbol

Formats a price without a currency symbol, based on current currency’s culture

<xsl:variable name="order" select="teacommerce:GetOrderXml()"/>
<xsl:value-of select="teacommerce:FormatPriceNoSymbol( $order/@totalPrice )" />

Output example

1395,00

FormatPriceWithSpecificCulture

Formats a decimal price with a currency symbol, based on the specified culture

<xsl:variable name="order" select="teacommerce:GetOrderXml()"/>
<xsl:value-of select="teacommerce:FormatPriceWithSpecificCulture( $order/@totalPrice, 'en-US' )" />

Output example

$249.00

FormatPriceNoSymbolWithSpecificCulture

Formats a decimal price without a currency symbol, based on the specified culture

<xsl:variable name="order" select="teacommerce:GetOrderXml()"/>
<xsl:value-of select="teacommerce:FormatPriceNoSymbolWithSpecificCulture( $order/@totalPrice, 'en-US' )" />

Output example

249.00
Nov
21

I installed Tea Commerce – what’s next

I installed Tea Commerce – what’s next

**Update**

Since we launched Tea Commerce back in November 2010 much has happened. We have launched a starter kits that you can install – its a complete Umbraco/Tea Commerce site so you can quickly and easily get started with an Umbraco ecommerce solution.

Getting started

So you downloaded the latest version of Tea Commerce and installed it – now what to do? In this blog post i will walk you though a very simple setup of a web shop on top of a umbraco runway install. The web shop will sell four products and the shop will be an american shop with USD as the currency. So lets start.

The initial setup of Tea Commerce

Country

Lets start by setting up the “United States” as a country. Make it the default country – as this is the country we “expect” customers to shop from and based on that we can calculate the prices from the country VAT. ( The selected VAT group in my example is 0% as we doesn’t need to calculate VAT in this simple setup )

Currency

With Tea Commerce comes 3 standard currencies – DKK, EUR and USD. Let me explain the different properties of a Currency.
- ISO code – used to passed along to payment providers and can be used in the UI
- Price field – this is the property alias for where to find the USD price on a product node from Umbraco
- Culture name – is used to format the currency

E-mail template

For the shop to send a confirmation e-mail to the customer and the shop owner we have to setup the e-mail settings. These properties should be pretty basic to setup
Remember – if you want to send email you will have to specify the smtp in your web.config

Products

Defining the product document type

One of the great thing about Umbraco is the possibility to create almost anything with document types and it’s properties. Of course Tea Commerce is build with this in mind, so all you products/product categories etc. you will create as your familiar Umbraco document types. For my demo i have only made a product document type as it’s enough to show how to do it.

Let me walk you though the properties:
- Product name – is used in the standard teaCommerceAdminOrder.xslt and teaCommerceEmailTemplate.xslt to output the product name ( this is for setups with product variants – for simple setups you could use nodeName in the XSLT files instead of productName )
- Product number – again used in the standard XSLT files
- Image – What to say :)
- Product price USD – this is the USD price field that we specified earlier for the USD currency

Display the products

Now we need to create some products and display them. Lets create a XSLT file and matching macro to output the products. To display the products i have created a text page “Products” and 4 products below it. Below is the XSLT and screenshots of the products in Umbraco and when displayed at the website.

<xsl:for-each select="$currentPage/Product [@isDoc]">
  <div>
    <h3><xsl:value-of select="@nodeName"/></h3>
    <xsl:if test="./image != ''">
      <img src="{umbraco.library:GetMedia(./image, false)/umbracoFile}" style="float: none; padding: 0;" />
    </xsl:if>
    <span><xsl:value-of select="productPriceUSD"/></span>
    <a href="#" class="productAddToCart" nodeid="{./@id}">Add to cart</a>
  </div>
</xsl:for-each>

Adding order lines the cart

Configure order line properties to copy

Next step is to have the different products added to a cart. Before we make the javascript to do this, we have to go back to the “General settings” for Tea Commerce. When we add order lines to the cart, Tea Commerce need to know which properties to copy from the product node – as these properties can we used in the email template and the admin interface. These properties is configured in the “Order line property aliases” field. In the standard admin and email XSLT i know that “productName” and “productNumber” is used so I specify these two.

Adding order lines with javascript

Tea Commerce has an extensive javascript API to do a lot of the shop functionality through /base calls – but in this post i will only touch about three of the API methods – to read more about the javascript API, please read my colleague Rune’s blog.
Before we can do anything through javascript we need to have some script references in the head section – i have created a script file “default.js” where i will implement the javascript necessary to run my specific web shop.

<script type="text/javascript" src="/scripts/TeaCommerce/teaCommerce.js"></script>
<script type="text/javascript" src="/scripts/default.js"></script>

default.js

/* When we add product to cart */
jQuery(".productAddToCart").live("click", function () {
  var nodeId = jQuery(this).attr('nodeid');

  /* Add orderline is called using the Tea Commerce javascript API */
  TeaCommerce.addOrderLine(nodeId, 1, false);
    
  return false;
});

Now when i click the “Add to cart” the product is added as an order line to my cart – BUT at the moment the content of the cart isn’t displayed – lets do that as the next thing

Building a mini cart

Before making my mini cart XSLT macro, I will make my checkout pages as i need to link to them in my minicart, so i created a “Cart” page with two subpages – “Personal information – Step 01″ and “Order confirmation – Step 02″.
Next step is to create the mini cart XSLT and insert the macro in my text page template so the customer can see what is in his cart. In my demo setup i haven’t used a lot of nifty javascript so the customer has to refresh with F5 to get the mini cart to display the newly items added to the cart :)

<xsl:variable name="order" select="teacommerce:GetOrderXml()"/>

<xsl:if test="$order/@id != ''">
  <div>
    <h2>Mini cart</h2>
    <xsl:for-each select="$order/orderLine">
      <div><xsl:value-of select="./properties/nodeName"/> - <xsl:value-of select="./@totalPriceFormattedNoSymbol"/></div>
    </xsl:for-each>
    Total: <xsl:value-of select="$order/@totalPriceFormattedNoSymbol"/>
    <a href="/cart/personal-information-step-01.aspx">Checkout</a>
  </div>
</xsl:if>

Building the checkout – step 1

Now that the customer has order lines in his cart – he want to go through the checkout flow. In the mini cart there is a “Checkout” link that will take the customer to step 1 of the checkout flow.

Personal information form

For step 1 i have created an XSLT macro and inserted it on the step 01 page. This step will let the customer fill in some information needed to ship the products to him.

<xsl:variable name="order" select="teacommerce:GetOrderXml()"/>

<xsl:if test="$order/@id != ''">
  <div id="personalInformation">
    <span>Company:</span><input type="text" id="company" /><br/><br/>
    <span>First name:</span><input type="text" id="firstName" /><br/><br/>
    <span>Last name:</span><input type="text" id="lastName" /><br/><br/>
    <span>Email:</span><input type="text" id="email" /><br/><br/>
    <span>Street address:</span><input type="text" id="streetAddress" /><br/><br/>
    <span>Zip code:</span><input type="text" id="zipCode" /><br/><br/>
    <span>City</span><input type="text" id="city" /><br/>
    <a id="confirmOrder" href="#">Confirm order</a>
  </div>
</xsl:if>

Order properties

Order properties is a property bag in the Tea Commerce API, which means that there is no limit to what you can add as order properties.
Important To give the ability to search orders by customer name and to send email to the customer, Tea Commerce needs to know the order property names of these three. This can be configured in “General settings” in the Tea Commerce custom section. Please specify the order property names – as default values the system uses “firstName”, “lastName” and “email”.

Confirm order

Before we can click the “Confirm order” in this demo setup and go to the next step we need to specify the “Default continue URL” in “General settings”. Tea Commerce will redirect to this URL when a payment provider ( a payment method uses a payment provider ) makes a positive feedback about a payment. In my demo shop i will use the “Account” payment method that uses the default Tea Commerce payment provider.

Now that we have specified these things we are ready to create the javascript that will do the magic. The javascript is hooked up to the “Confirm order” click event, and when its clicked these things happens:
- Build a an array with the information to save as order properties and send it to the server
- Set the payment method to “Account” ( id = 2 )
- Go to payment – the default payment provider in Tea Commerce – will finalize the order, send a confirmation email and redirect to the “Default continue URL” ( this is the step 2 page in my demo )

/* The confirm order step of the cart */
jQuery('a#confirmOrder').live("click", function () {
  var personalInformation = jQuery("#personalInformation");

  /* We fetch the information from the form and creates
    an object that can be sent to the server as a form
    POST submit */
  var formObj = {
    "company": personalInformation.find("#company").val(),
    "firstName": personalInformation.find("#firstName").val(),
    "lastName": personalInformation.find("#lastName").val(),
    "email": personalInformation.find("#email").val(),
    "streetAddress": personalInformation.find("#streetAddress").val(),
    "zipCode": personalInformation.find("#zipCode").val(),
    "city": personalInformation.find("#city").val()
  };

  /* The properties is sent to the server with a syncronous call
    This way we lock the UI and can redirect the user.*/
  TeaCommerce.updateOrderProperties(formObj, false);
  TeaCommerce.setPaymentMethod(2, false);
  TeaCommerce.goToPayment();
  return false;
});

Building the checkout – step 2

Now that the customer has recieved his email, the order will be finalized and his cart is empty again. But to show exactly what the customer bought, I have a confirmation page that will display the personal information entered in the previous step and his order lines.

<xsl:variable name="order" select="teacommerce:GetFinalizedOrderXml()"/>
  
<xsl:if test="$order/@id != ''">
  <div>
    <span>First name:</span><xsl:value-of select="$order/properties/firstName"/><br/>
    <span>Last name:</span><xsl:value-of select="$order/properties/lastName"/><br/>
    <span>Email:</span><xsl:value-of select="$order/properties/email"/><br/>
    <span>Street address:</span><xsl:value-of select="$order/properties/streetAddress"/><br/>
    <span>Zip code:</span><xsl:value-of select="$order/properties/zipCode"/><br/>
    <span>City:</span><xsl:value-of select="$order/properties/city"/><br/>
    
	<h2>Orderlines</h2>
    <xsl:for-each select="$order/orderLine">
      <div><xsl:value-of select="./properties/nodeName"/> - <xsl:value-of select="./@totalPriceFormattedNoSymbol"/></div>
    </xsl:for-each>
    Total: <xsl:value-of select="$order/@totalPriceFormattedNoSymbol"/>
  </div>
</xsl:if>

The end

Thats it – I have created a simply web shop and hope that you got the basic knowledge to begin setup your own web shop in Umbraco, using Tea Commerce. Please ask any questions regarding this basic demo shop or tell me what you would like to see in my next blog post – where I will dive deeper into what is possible with Tea Commerce

Nov
7

Tea Commerce – the new eCommerce for umbraco

Tea Commerce – the new eCommerce for umbraco

The birth of Tea Commerce

It all started on Sept. 23, 2010 to umbraco meetup in Copenhagen with my colleague Rune Grønkjær and four others from the great danish Umbraco community. The evening’s most discussed topic was ecommerce systems – what systems exist today, advantages / disadvantages, which situations fits the various systems and are there alternatives to the systems we use today.

There were both talking about uCommerce, super simple webshop, simplecartjs and simple ecommerce solutions developed for specific cases. As the conversation went on, it soon became clear that among the participants we would agreed the lack of a low budget ecommerce system for Umbraco, but still flexible and having the functionality necessary to operate an online store.

On the way home from Copenhagen, we could not help but think of how such a system should work and how to be developed, and during the trip we laid the first bricks for the new ecommerce system for Umbraco – Tea Commerce

Focus points

Tea Commerce has been developed with two main focus points, compared to the people who ultimately use the system to implement webshops – low cost and simple implementation. The price has been a really great focus point throughout the entire development, which has meant that we thought out the system more simple than other ecommerce systems – but without losing the essential functionalities.

The implementation process of Tea Commerce is incredibly simple, because the whole system is integrated into Umbraco and when you know Umbraco you quick get the touch of Tea Commerce. Many ecommerce systems offer a whole lot of different options so the system can be used in all possible situations, but often ends confusing the developers and end users with all the different options and possibilities. To avoid this in Tea Commerce, we have cut away some functionalities which are often not used or are incredibly complex to use. This of course means that Tea Commerce can not be used in all situations, but by having focus on the primary functions I think most webshops can be build untop of Tea Commerce and as the big prize the system is incredibly easy to implement and use.

Price Structure

Now for one of the very important points – the price. As promised, we have placed great emphasis on price and this means that a site license for will cost: 249 USD ex. VAT – Introduction price rest of 2010

With such a low price, it is possible to implement Tea Commerce in even very small projects with a limited budget, while the system is so flexible that it can easily be used for large ecommerce solutions that require a more custom setup.

Integration scenarios

To give an idea of how flexible Tea Commerce is, I will give two fictitious examples of customers who want a webshop and how these could be implemented in Tea Commerce.

Scenario 1 – simple ecommerce solution

In the first senarie we have a customer who has just started his business up and want to try the online market – but have a low budget. Its products consist of 10 different posters, and they want a new website to sell these through where there is a shopping cart and online payment. These functions are the core of every ecommerce system and of course Tea Commerce have these features out of the box. With the included JavaScript API and integrated payment providers its super simple to implement and the price makes Tea Commerce the perfect choice for a shop with a low budget.

Scenario 2 – advanced ecommerce solution

The second senarie could be a larger company that has hundreds of products, product variants and want the possibility for customers to choose gift wrapping for their purchase. As products and product variants is controlled by Umbraco document types it makes Tea Commerce incredibly flexible and allows almost anything is possible – just as you know it from Umbraco. Gift wrapping options could be created as nodes in Umbraco and be outputted in the basket process via XSLT, and through the javascript API it’s really easy to add custom fields to an order or to add gift wrapping as an order line.

A more technical point of view

If you want a more technical approach to Tea Commerce, I would recommend you to read my colleague Rune’s blog post that goes more into technical details about how Tea Commerce work – from the frontend, through the server and into the data layer.

The next few weeks

Over the next week, my colleague Rune and I will blog about the development of Tea Commerce, all the possibilities in the system and how you can use Tea Commerce to build your next ecommerce solution. If you want a live review of the system and look at some of the technical possibilities of it, you’re more than welcome to come to Umbraco UK Festival – Copenhagen where we’ve got 30 minutes to present the product and to take on questions.

We hope to have a version ready of Tea Commerce we can share with developers in the next couple of weeks so you can try it out. Follow our blogs/twitter the next few weeks for more information and as always you’re more than welcome to ask questions or make a comment.

Oct
1

Developing “Insert flash” for umbraco

Developing “Insert flash” for umbraco

My previous blog post talked about how easy it was to insert flash in umbraco with my “Insert Flash” macro. In this post I will go into more depth and talk about the technology behind the module and provide an example of how the XSLT easily can be reused to insert Flash in your own XSLT macro.

The techinal part

To give a better understanding of what happens in the XSLT, I’ll devide the code up and explain each part of it.

The variables explained

trueFileURL: Finds a URL to the flash element, either via a media item from umbraco’s media section or via a typed URL
finalFileURL: Concats the “trueFileURL” variable with any enclosed url parameters
finalCssId: Uses the optional enclosed “cssId”, and if not present, the XSLT will use a C# helper method to generate an auto id – so there may be added an infinite number of flash elements on the same page, without having to specify a “cssId” to each of them

    <xsl:variable name="trueFileURL">
      <xsl:choose>
        <xsl:when test="$mediaFile != ''">
          <xsl:value-of select="$mediaFile/data[@alias = 'umbracoFile']"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$fileURL"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

    <xsl:variable name="finalFileURL">
      <xsl:choose>
        <xsl:when test="$urlParameters != ''">
          <xsl:value-of select="concat($trueFileURL, $urlParameters)"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$trueFileURL"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

    <xsl:variable name="finalCssId">
      <xsl:choose>
        <xsl:when test="string($cssId) != ''">
          <xsl:value-of select="$cssId"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="concat( 'ts-', randomTools:GetRandom() )"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

Calling the template

We now have all the necessary information we need to insert a flash element through the “insertFlash” template.

    <xsl:call-template name="insertFlash">
      <xsl:with-param name="finalFileURL" select="$finalFileURL" />
      <xsl:with-param name="width" select="$width" />
      <xsl:with-param name="height" select="$height" />
      <xsl:with-param name="finalCssId" select="$finalCssId" />
    </xsl:call-template>

Where the true “magic” happens

We have reached the area where the flash element gets embedded. To embed the flash content i use swfobject, so i dont need to handle tart part – i just need to parse it the necessary parameters.

REMEMBER to remove the script reference to swfobject in the XSLT file and paste it instead into your HTML head section, so you don’t have a script reference for each flash element you insert through the macro

<xsl:template name="insertFlash">
  <xsl:param name="finalFileURL"/>
  <xsl:param name="width"/>
  <xsl:param name="height"/>
  <xsl:param name="finalCssId"/>

  <div id="{$finalCssId}">
    <xsl:text> </xsl:text>
  </div>

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js">
    <xsl:text> </xsl:text>
  </script>

  <script type="text/javascript">
    <![CDATA[
    var flashvars = {};
    var params = {};
    var attributes = {};

    var path = "]]><xsl:value-of select="$finalFileURL" /><![CDATA[";
    var cssId = "]]><xsl:value-of select="$finalCssId" /><![CDATA[";
    var width = "]]><xsl:value-of select="$width" /><![CDATA[";
    var height = "]]><xsl:value-of select="$height" /><![CDATA[";

    swfobject.embedSWF( path, cssId, width, height, "9.0.0", false, flashvars, params, attributes);
    ]]>
  </script>

</xsl:template>

Reuse the XSLT to easy insert flash in you own XLST macro’s

It’s easy to reuse the “insertFlash” XSLT template in your own XSLT macro. The only thing you need to do is to import the insertFlash.xslt file in the top of your XSLT, and call the “insertFlash” template with your parameters. Below is an example:

<xsl:include href="insertFlash.xslt"/>

<xsl:template match="/">
  <div id="flashContent"></div>

  <xsl:call-template name="insertFlash">
    <xsl:with-param name="finalFileURL" select="$currentPage/data[@alias = 'flashFile']" />
    <xsl:with-param name="width" select="200" />
    <xsl:with-param name="height" select="100" />
    <xsl:with-param name="finalCssId" select="flashContent" />
  </xsl:call-template>
</xsl:template>

Next time

Stay tuned for my next blog post where I will explain how to enable your XSLT to support both the umbraco 4.0 and 4.5 xml schema

The complete XSLT

<xsl:template match="/">

  <xsl:variable name="mediaFile" select="/macro/mediaFile/*"/>
  <xsl:variable name="fileURL" select="/macro/fileURL"/>
  <xsl:variable name="width" select="/macro/flashWidth"/>
  <xsl:variable name="height" select="/macro/flashHeight"/>
  <xsl:variable name="cssId" select="/macro/cssId"/>
  <xsl:variable name="urlParameters" select="/macro/urlParameters"/>

  <xsl:if test="$mediaFile != '' or $fileURL != ''">
    <xsl:variable name="trueFileURL">
      <xsl:choose>
        <xsl:when test="$mediaFile != ''">
          <xsl:value-of select="$mediaFile/data[@alias = 'umbracoFile']"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$fileURL"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

    <xsl:variable name="finalFileURL">
      <xsl:choose>
        <xsl:when test="$urlParameters != ''">
          <xsl:value-of select="concat($trueFileURL, $urlParameters)"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$trueFileURL"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

    <xsl:variable name="finalCssId">
      <xsl:choose>
        <xsl:when test="string($cssId) != ''">
          <xsl:value-of select="$cssId"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="concat( 'ts-', randomTools:GetRandom() )"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

    <xsl:call-template name="insertFlash">
      <xsl:with-param name="finalFileURL" select="$finalFileURL" />
      <xsl:with-param name="width" select="$width" />
      <xsl:with-param name="height" select="$height" />
      <xsl:with-param name="finalCssId" select="$finalCssId" />
    </xsl:call-template>

  </xsl:if>

</xsl:template>

<xsl:template name="insertFlash">
  <xsl:param name="finalFileURL"/>
  <xsl:param name="width"/>
  <xsl:param name="height"/>
  <xsl:param name="finalCssId"/>

  <div id="{$finalCssId}">
    <xsl:text> </xsl:text>
  </div>

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js">
    <xsl:text> </xsl:text>
  </script>

  <script type="text/javascript">
    <![CDATA[
    var flashvars = {};
    var params = {};
    var attributes = {};

    var path = "]]><xsl:value-of select="$finalFileURL" /><![CDATA[";
    var cssId = "]]><xsl:value-of select="$finalCssId" /><![CDATA[";
    var width = "]]><xsl:value-of select="$width" /><![CDATA[";
    var height = "]]><xsl:value-of select="$height" /><![CDATA[";

    swfobject.embedSWF( path, cssId, width, height, "9.0.0", false, flashvars, params, attributes);
    ]]>
  </script>

</xsl:template>

<msxml:script language="c#" implements-prefix="randomTools">
  <msxml:assembly href="../bin/umbraco.dll"/>
  <![CDATA[
    //Basic idea from http://our.umbraco.org/wiki/reference/xslt/snippets/getting-a-series-of-unique-random-numbers

    /// <summary>
    /// Gets a random integer that falls between the specified limits
    /// </summary>
    /// <returns>A random integer</returns>
    public static int GetRandom() {
      Random r = umbraco.library.GetRandom();
      int returnedNumber = 0;
      lock (r) {
        returnedNumber = r.Next();
      }
      return returnedNumber;
    }
  ]]>
</msxml:script>
Sep
7

Insert flash in umbraco – the easy way

Insert flash in umbraco – the easy way

Back in December 2009, I was looking for an easy way to insert flash content into Umbraco. I fell upon an already existing module, but it could not all the things I wanted and as the developer I am, I chose to develop my own flash module for Umbraco in XSLT.

Using the module

First of all you need to download the “Insert flash” module for umbraco and install it to your umbraco powered website. The module will install a macro named “Insert flash” that you can both use in your templates or in the rich text editor.

When inserting the macro you will see a screen like the one below, and when you have filled the parameters as you like, your flash content is now ready to be displayed on your website.

Inserting flash in umbraco

The parameters explained

  • Flash file – Pick a swf file from the media section to display
  • Url to file – Or type URL to the swf file to insert
    ( At least 1 of these is required )
  • Width – Width of the flash ( Pixels, Required )
  • Height – Height of the flash ( Pixels, Required )
  • Css id – An id of a html element to replace with the flash content ( Optional )
  • Url parameters – Parameters to send by Url to the flash. ( Optional )

Note about the module

This module automatically inserts a script reference to swfobject hosted by Google to enable insertion of the flash. To not have this script reference inserted every time you use the macro, move it to your template in the “head” section and remove it from the XSLT file.

Next time

Stay tuned for the next blog post, where I will dive into the xslt behind the module and the possibilities of reusing the xslt in your own xslt.