Blog Stats
  • Posts - 59
  • Articles - 0
  • Comments - 27
  • Trackbacks - 0

 

Tuesday, November 29, 2011

Windows Azure: Caching


I was poking around today and found this great article on caching: http://www.cloudcomputingdevelopment.net/cache-management-with-windows-azure/

Caching is a great way to boost application performance and keep down overhead on a database or file system. Its also great when you have say 3 web roles as shown in this articles Figure 2 that can share the same cache. If one of the roles goes offline then the cache is still there and can be used.

You can change out your asp.net caching to use this pretty easy. Its pretty cool.

There’s a sample that’s mentioned in the article that shows how to use this. You can download the cache here.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

SL: Showcase


One of the sites I go to frequently is www.silverlight.net/showcase. Theres always new stuff showing up here and it gives me tons of ideas.

The business section is also awesome because it has tons of samples of great applications that should really jog your brain for ideas.

One of the great things about SL and WPF is how we can break the mold of application design and come up with truly great new applications for our   users. That’s one are where the showcase can help to get new ideas on things you can do.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

SL: Silverlight 5


Check out this new demo from MIX11.

http://code.msdn.microsoft.com/silverlight/3D-Housebuilder-demo-from-def4af04

SL 5 is the next big step for great apps in SL. This new release is adding more features to an already great technology.  You can find out more about this release at http://www.microsoft.com/silverlight/future/ .

I particularly like the new features for business applications such as the next text improvements and making the combo box type ahead right out of the box. Plus there are more enhancements for databinding too.  And the list goes on and on with features such as performance and “trusted application”.

Where is Sl 5 now? its in Release Candidate now so the final bits should not be far down the road.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Monday, November 28, 2011

WPF: Thriple


I was poking around today and found this cool 3D library from the great Josh Smith. You can get the source here:

http://thriple.codeplex.com/

Its got some pretty cool stuff there. Se the Panel3D_Demo project to startup and run it. Then you can play around with the sample shown below:

 

image

 

Its pretty cool stuff.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Windows 8: SL and HTML


I  was just pointed to comment on my friend Andrew Brust’s blog about Silverlight versus HTML 5. Andrews blog is here:

http://geekswithblogs.net/andrewbrust/archive/2011/11/23/windows-8-will-be-here-tomorrow-but-should-silverlight-be.aspx#600915

You can get another idea from another friend of mine Billy Hollis here:

http://geekswithblogs.net/jalexander/archive/2011/04/09/the-eternal-battle-rich-v.-reachhellip--guest-blogger-billy-hollis.aspx

The commenter is raving about HTML 5 and how that’s the future and SL is not. Well, my reaction is “hogwash”.

Sure, HTML 5 is important and does some interesting stuff. Checkout what Bing.com is doing with it on some days and you can see.

But to say that XAML is dead is nuts.

I have been wrapping up bugs on a cross browser version of an application for awhile now. Whats the state of cross browser today? Well, better than a few years ago but far from perfect.  Each browser vendor interprets the specs in a little different way and you must account for them. The worst offender for major browsers? Apple and its Safari.  I had to make more changes for it than any other.

Whats that got to do with XAML and SL/WPF?  Well, you write your SL code once and it runs in all browsers that support it, no changes. ipad does not? Well, they should be taken to court and forced too just like MS and others have been in the past for locking out competitors.

Line of business applications? Write them in SL or WPF or both.  Use the power of XAML witch far out reaches html in any flavor and move on.

We do need HTML 5 but its not a panacea nor will it replace all other technologies.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Friday, November 11, 2011

Windows Azure AppFabric: ServiceBus Queue WPF Sample


The latest version of the AppFabric ServiceBus now has support for queues and topics. Today I will show you a bit about using queues and also talk about some of the best practices in using them. If you are just getting started, you can check out this site for more info on Windows Azure.

One of the 1st things I thought if when Azure was announced back when was how we handle fault tolerance. Web sites hosted in Azure are no much of an issue unless they are using SQL Azure and then you must account for potential fault or latency issues. Today I want to talk a bit about ServiceBus and how to handle fault tolerance.  And theres stuff like connecting to the servicebus and so on you have to take care of.

To demonstrate some of the things you can do, let me walk through this sample WPF app that I am posting for you to download.

To start off, the application is going to need things like the servicenamespace, issuer details and so forth to make everything work.  To facilitate this I created settings in the wpf app for all of these items. Then I mapped a static class to them and set the values when the program loads like so:

StaticElements.ServiceNamespace = Convert.ToString(Properties.Settings.Default["ServiceNamespace"]);
StaticElements.IssuerName = Convert.ToString(Properties.Settings.Default["IssuerName"]);
StaticElements.IssuerKey = Convert.ToString(Properties.Settings.Default["IssuerKey"]);
StaticElements.QueueName = Convert.ToString(Properties.Settings.Default["QueueName"]);

 

Now I can get to each of these elements plus some other common values or instances directly from the StaticElements class.

Now, lets look at the application.  The application looks like this when it starts:

 

image

The blue graphic represents the queue we are going to use.  The next figure shows the form after items were added and the queue stats were updated . You can see how the queue has grown:

image

To add an item to the queue, click the Add Order button which displays the following dialog:

image

After you fill in the form and press OK, the order is published to the ServiceBus queue and the form closes.

The application also allows you to read the queued items by clicking the Process Orders button. As you can see below, the form shows the queued items in a list and the  queue has disappeared as its now empty.

image

In real practice we normally would use a Windows Service or some other automated process to subscribe to the queue and pull items from it.

I created a class named ServiceBusQueueHelper that has the core queue features we need. There are three public methods:

* GetOrCreateQueue – Gets an instance of the queue description if the queue exists. if not, it creates the queue and returns a description instance.

* SendMessageToQueue = This method takes an order instance and sends it to the queue. The call to the queue is wrapped in the ExecuteAction method from the Transient Fault Tolerance Framework and handles all the retry logic for the queue send process.

* GetOrderFromQueue – Grabs an order from the queue and returns a typed order from the queue. It also marks the message complete so the queue can remove it.

 

Now lets turn to the WPF window code (MainWindow.xaml.cs). The constructor contains the 4 lines shown about to setup the static variables and to perform other initialization tasks.

The next few lines setup certain features we need for the ServiceBus:

TokenProvider credentials = TokenProvider.CreateSharedSecretTokenProvider(StaticElements.IssuerName, StaticElements.IssuerKey);
Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", StaticElements.ServiceNamespace, string.Empty);
StaticElements.CurrentNamespaceManager = new NamespaceManager(serviceUri, credentials);
StaticElements.CurrentMessagingFactory = MessagingFactory.Create(serviceUri, credentials);

The next two lines update the queue name label and also set the timer to 20 seconds.

            QueueNameLabel.Content = StaticElements.QueueName;
            _timer.Interval = TimeSpan.FromSeconds(20);
           

Next I call the UpdateQueueStats to initialize the UI for the queue:
            UpdateQueueStats();

            _timer.Tick += new EventHandler(delegate(object s, EventArgs a)       
                 {
                     UpdateQueueStats();
                 });
            _timer.Start();
        }

The UpdateQueueStats method shown below. You can see that it uses the GetOrCreateQueue method mentioned earlier to grab the queue description, then it can get the MessageCount property.

        private void UpdateQueueStats()
        {
            _queueDescription = _serviceBusQueueHelper.GetOrCreateQueue();
            QueueCountLabel.Content = "(" + _queueDescription.MessageCount + ")";
            long count = _queueDescription.MessageCount;
            long queueWidth = count * 20;
            QueueRectangle.Width = queueWidth;
            QueueTickCount += 1;
            TickCountlabel.Content = QueueTickCount.ToString();
        }

 

The ReadQueueItemsButton_Click event handler calls the GetOrderFromQueue method and adds the order to the listbox.

If you look at the SendQueueMessageController, you can see the SendMessage method that sends an order to the queue. Its pretty simple as it just creates a new CustomerOrderEntity instance,fills it and then passes it to the SendMessageToQueue.

As you can see, all of our interaction with the queue is done through the helper class (ServiceBusQueueHelper).

Now lets dig into the helper class. First, before you create anything like this, download the Transient Fault Handling Framework. Microsoft provides this free and they also provide the C# source. Theres a great article that shows how to use this framework with ServiceBus.

I included the entire ServiceBusQueueHelper class in List 1.

Notice the using statements for TransientFaultHandling:

using Microsoft.AzureCAT.Samples.TransientFaultHandling;
using Microsoft.AzureCAT.Samples.TransientFaultHandling.ServiceBus;

The SendMessageToQueue in Listing 1 shows how to use the async send features of ServiceBus with them wrapped in the Transient Fault Handling Framework.  It is not much different than plain old ServiceBus calls but it sure makes it easy to have the fault tolerance added almost for free.

The GetOrderFromQueue uses the standard synchronous methods to access the queue. The best practices article walks through using the async approach for a receive operation also.  Notice that this method makes a call to Receive to get the message then makes a call to GetBody to get a new strongly typed instance of CustomerOrderEntity to return.

Listing 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AzureCAT.Samples.TransientFaultHandling;
using Microsoft.AzureCAT.Samples.TransientFaultHandling.ServiceBus;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System.Xml.Serialization;
using System.Diagnostics;
namespace WPFServicebusPublishSubscribeSample
{
    class ServiceBusQueueHelper
    {
        RetryPolicy currentPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(RetryPolicy.DefaultClientRetryCount);
        QueueClient currentQueueClient;
        public QueueDescription GetOrCreateQueue()
        {           
            QueueDescription queue = null;
            bool createNew = false;

            try
            {
                // First, let's see if a queue with the specified name already exists.
                queue = currentPolicy.ExecuteAction<QueueDescription>(() => { return StaticElements.CurrentNamespaceManager.GetQueue(StaticElements.QueueName); });

                createNew = (queue == null);
            }
            catch (MessagingEntityNotFoundException)
            {
                // Looks like the queue does not exist. We should create a new one.
                createNew = true;
            }

            // If a queue with the specified name doesn't exist, it will be auto-created.
            if (createNew)
            {
                try
                {
                    var newqueue = new QueueDescription(StaticElements.QueueName);

                    queue = currentPolicy.ExecuteAction<QueueDescription>(() => { return StaticElements.CurrentNamespaceManager.CreateQueue(newqueue); });
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    // A queue under the same name was already created by someone else,
                    // perhaps by another instance. Let's just use it.
                    queue = currentPolicy.ExecuteAction<QueueDescription>(() => { return StaticElements.CurrentNamespaceManager.GetQueue(StaticElements.QueueName); });
                }
            }

            currentQueueClient = StaticElements.CurrentMessagingFactory.CreateQueueClient(StaticElements.QueueName);

            return queue;
        }

        public void SendMessageToQueue(CustomerOrderEntity Order)
        {
            BrokeredMessage msg = null;
            GetOrCreateQueue();
            // Use a retry policy to execute the Send action in an asynchronous and reliable fashion.
            currentPolicy.ExecuteAction
            (
                (cb) =>
                {
                    // A new BrokeredMessage instance must be created each time we send it. Reusing the original BrokeredMessage instance may not
                    // work as the state of its BodyStream cannot be guaranteed to be readable from the beginning.
                    msg = new BrokeredMessage(Order);

                    // Send the event asynchronously.
                    currentQueueClient.BeginSend(msg, cb, null);
                },
                (ar) =>
                {
                    try
                    {
                        // Complete the asynchronous operation.
                        // This may throw an exception that will be handled internally by the retry policy.
                        currentQueueClient.EndSend(ar);
                    }
                    finally
                    {
                        // Ensure that any resources allocated by a BrokeredMessage instance are released.
                        if (msg != null)
                        {
                            msg.Dispose();
                            msg = null;
                        }
                    }
                },
                (ex) =>
                {
                    // Always dispose the BrokeredMessage instance even if the send
                    // operation has completed unsuccessfully.
                    if (msg != null)
                    {
                        msg.Dispose();
                        msg = null;
                    }

                    // Always log exceptions.
                    Trace.TraceError(ex.Message);
                }
            );
        }

       
        public CustomerOrderEntity GetOrderFromQueue()
        {
            CustomerOrderEntity Order = new CustomerOrderEntity();
            QueueClient myQueueClient = StaticElements.CurrentMessagingFactory.CreateQueueClient(StaticElements.QueueName, ReceiveMode.PeekLock);
            BrokeredMessage message;
            ServiceBusQueueHelper serviceBusQueueHelper = new ServiceBusQueueHelper();
            QueueDescription queueDescription;
            queueDescription = serviceBusQueueHelper.GetOrCreateQueue();

            if (queueDescription.MessageCount > 0)
            {
                message = myQueueClient.Receive(TimeSpan.FromSeconds(90));

                if (message != null)
                {
                    try
                    {
                        Order = message.GetBody<CustomerOrderEntity>();

                        message.Complete();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    throw new Exception("Did not receive the messages");
                }
            }
            return Order;
        }
    }
}

I will post a link to the download demo in a separate post soon.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Friday, November 04, 2011

.Net: Action type


This type is a delegate and is pretty cool. It can contain a method with one parameter and no  return value. You can read a bit more here: http://msdn.microsoft.com/en-us/library/018hxwa8.aspx

This type is used Transient Fault Tolerance Framework in some of the ExecuteAction methods. For instance, the following signature allows you to call ExecuteAction and pass in 3 anonymous methods:

public abstract void ExecuteAction(Action<AsyncCallback> action, Action<IAsyncResult> callback, Action<Exception> faultHandler);

You can see an example of calling this method in this article: http://msdn.microsoft.com/en-us/library/hh545245(v=VS.103).aspx

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Azure: Fault Tolerance for apps


Check out the Fault Tolerance Framework:

http://windowsazurecat.com/2011/02/transient-fault-handling-framework/

This is really sweet. You can download the source code, then open it in VS and build it. Then plug into your app to get fault tolerance for SQL Azure, Windows Azure storage, Service Bus and Caching Service.

Once you have it built and referenced in your project, it only takes a few minutes to plumb your application to use it.

Next week (hopefully) I will post a new WPF app that uses ServiceBus and shows hot so use the features with best practices such as async operations and using the fault tolerance framework.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Monday, October 31, 2011

MVC 3.0: Ipad access–Button Value Attribute


Another issue I found was the use of the Value attribute on Submit buttons. This is handy because you can change the Value attribute depending on the action and then pick up the button with its Name attribute in a controller method.

Enter the ipad safari browser. Apparently this browser does not pickup the value attribute value and put it in the request variables. It just comes to the controller method as empty.

The solution was to create a hidden input field and set it. Then pick it up as a parameter to the controller method. Works like  a charm.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

MVC 3.0: Ipad access–ID vs Name


I have been working for months on converting an ASP classic app to MVC 3. This new version needs to run on FF and Ipad Safari.

one of the things we found was the user of just the Name attribute for controls such as input and so forth. This works fine in IE and some other browsers. But Safari chokes on this. The solution is to make the Name and the ID the same and then all the browsers are happy.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
 

 

Copyright © xamlnotes