European Silverlight 4 & Silverlight 5 Hosting BLOG

BLOG about Silverlight 5 Hosting and Its Techologies - Dedicated to European Windows Hosting Customer

European Silverlight Hosting - Amsterdam :: Working with Isolated Storage in Silverlight

clock November 29, 2012 07:46 by author Scott

Isolated storage gives you access to a small segment of hard-disk space, with certain limitations. For example we don't know exactly where our files are being stored. We also can't read the files left by another Silverlight application or recorded for another user. In essence, isolated storage provides carefully restricted, tamperproof file access for applications that need to store permanent information in the local PC, so that information can be retrieved the next time the user runs the application.

How it works:

Isolated storage provides a virtual file system that lets you write data to a small, user-specific and application-specific slot of space. There's no way to know beforehand exactly where the data will be written, and the default space limit is a mere 1 MB (although you can request that the user grant you more).

Is it similar to browser Cookie?

  1. Essentially, isolated storage is the Silverlight equivalent of persistent cookies in an ordinary web page. It allows small bits of information to be stored in a dedicated location that has specific controls in place to prevent malicious attacks.
     
  2. Isolated storage is persistent–unlike the browser cache, it never expires, and it's not removed if the user chooses to explicitly delete temporary Internet files.
     
  3. Isolated storage isn't a good storage place for important documents, because they're never backed up, are easily deleted, and can be even more easily lost.
     
  4. Isolated storage is intended to be a limited-size storage location for data, not a handcrafted replacement for HTTP Caching.


Scope of Isolated Storage:


With isolated storage, a unique storage location is created for every combination of user and application. In other words, the same computer can have multiple isolated storage locations for the same application, assuming each one is for a different user. Similarly, the same user can have multiple isolated storage locations, one for each Silverlight application. Isolated storage isn't affected by browser, so a Windows user switching from Internet Explorer to Firefox will get the same isolated storage location in both browsers.

What all can we store in an Isolated Storage: Good choices include user-specific details, user preferences, and information about recent user actions. Isolated storage is also great temporary storage.

So now we are ready to create a application which will demonstrate how it works.

Step 1: Create a Silverlight Application project and name it IsolatedStorage.

Step 2: Now we will try to understand how to write data and read data from these storages Medias. We will also see if we want to increase the space on the handdisk; how can we do that as well.

So we created a simple xmal like this:

<Grid x:Name="LayoutRoot"  Margin="10"  Background="WhiteSmoke" Width="340" Height="200" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>         

        </Grid.RowDefinitions>

            <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" ></ColumnDefinition>
            <ColumnDefinition Width="Auto" ></ColumnDefinition>           

        </Grid.ColumnDefinitions>

            <TextBlock Text="Enter Your Name" Margin="3" Padding="5" HorizontalAlignment="Left" 
                       VerticalAlignment="Center" Grid.Row="0" Grid.Column="0">               
           
</TextBlock>

            <TextBox x:Name="txtname" Margin="3" Padding="5"
                        HorizontalAlignment="Left" VerticalAlignment="Center"
                        Grid.Row="0" Grid.Column="1" Height="30" Width="200" ></TextBox>          

            <Grid Grid.Column="1" Grid.Row="1"  Margin="5" >
                <Grid.RowDefinitions>
                    <RowDefinition Height="50" ></RowDefinition>
                    <RowDefinition ></RowDefinition>
                    <RowDefinition ></RowDefinition>
            </Grid.RowDefinitions>

                <Grid.ColumnDefinitions>
                    <ColumnDefinition ></ColumnDefinition>
                    <ColumnDefinition ></ColumnDefinition>
                </Grid.ColumnDefinitions>

            <Button x:Name="btnWrite"  Margin="5" Padding="5" Width="90" Height="30"
                    Content="Click to Write" HorizontalAlignment="Center" VerticalAlignment="Top"
                    Click="btnWrite_Click">
            </Button>

            <Button x:Name="btnRead"  Margin="5" Padding="5" Width="90" Height="30"
                    Content="Click to Read"
                    HorizontalAlignment="Center" VerticalAlignment="Top" Click="btnRead_Click"
                    Grid.Row="0" Grid.Column="1">
            </Button>

            <Button x:Name="btnSize"  Padding="5" Width="180" Height="30"
                    Content="Click to Increase Disk Storage Space"
                     HorizontalAlignment="Center" VerticalAlignment="Top"
                    Click="btnSize_Click" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
            </Button>

            <TextBlock x:Name="lblData" Margin="5"  HorizontalAlignment="Center" VerticalAlignment="Top"                       
                    Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"></TextBlock>

        </Grid>

Step 3: Now come to Code Behind and write handler for btnWrite_Click.

Also add this Isolated storage namespace.

using System.IO.IsolatedStorage;

private void btnWrite_Click(object sender, RoutedEventArgs e)
        {
            // Write to isolated storage.
            try
            {               
                //this gives you exactly what you want: an application-specific, user-specific
                //location where you can store data.

               IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();

                 //If we would have used
                //IsolatedStorageFile.GetUserStoreForSite ,
                //then a storage site that's accessible to all the Silverlight applications on the same website domain.
                using (IsolatedStorageFileStream fs = store.CreateFile("data.txt"))
                {
                    StreamWriter sw = new StreamWriter(fs);                  
                    sw.Write(txtname.Text);                  
                    sw.Close();
                }
                txtname.Text = string.Empty;

            }
            catch
            {

            }
        }


Let us concentrate on this line.

IsolatedStorageFile
store = IsolatedStorageFile.GetUserStoreForApplication();

Silverlight creates isolated stores automatically. To interact with an isolated store, you use the IsolatedStorageFile class. You get the IsolatedStorageFile object for the current user and application by calling the static IsolatedStorageFile.GetUserStoreForApplication() method, as shown here:

Step 4: Press F5 and test write and read buttons.

Step 5: Now let's concentrate on how disk storage works. Initially, each Silverlight application gets 1 MB of space in it's isolated store. You can examine the IsolatedStorageFile.AvailableFreeSpace property to find out how much free space remains. If your application needs more space, you can use an option: the IsolatedStorageFile IncreaseQuotaTo() method.

We must request a value that's higher than the current quota. Otherwise, you'll receive an exception. That means you can't use the IncreaseQuotaTo() method to ensure that there's a certain level of free space.

If everything goes well, you will be presented with something such as shown in the figure below.

 



European Silverlight 5 Hosting - Amsterdam :: Working with Observable Collections in Silverlight 5

clock November 15, 2012 09:49 by author Scott

Observable Collections are great to preserve the latest data in data controls without having to rebind data to the data controls. In this article we will explore how we can work with Observable Collections in Silverlight 5.

Silverlight – A Quick Look

Silverlight is a browser plug-in that promotes a collaborative development environment of rich online media content that enables developers and designers alike to integrate multimedia and graphics into web pages within the context of the managed environment. Over the past few years, Silverlight, formerly known as Windows Presentation Foundation Everywhere (WPF/E), has become popular worldwide for developing the next generation of cross-browser, cross-platform Rich Internet Applications (RIAs).

Observable Collections

The generic List<T> represents a strongly typed list of elements or a CLR or non-CLR type. When we bind data to a DataControl in ASP.NET using such a list, the data in the data bound control is up to date with the data in the list. However, when the data in the list changes, the data control has to be re-bound to reflect the changes. In other words, we have to rebind the data in the list (now the list contains updated data) to reflect the change. This problem is solved in using ObservableCollection<T>. This collection is capable of providing notifications of items added/deleted/edited through the INotifyCollectionChanged interface. The INotifyCollectionChanged interface has an event called PropertyChanged, which is fired when a property value is changed.

ObservableCollection is a generic dynamic data structure that has the ability to send notifications when items are added, removed or when the collection is refreshed. The MSDN states: "Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed." Reference: http://msdn.microsoft.com/en-us/library/ms668604.aspx

The ObservableCollection class is shown below:

[SerializableAttribute]
public class ObservableCollection<T> : Collection<T>,
            INotifyCollectionChanged, INotifyPropertyChanged


You can instantiate an Observable collection as shown in the code snippet below:

using System.Collections.ObjectModel;
ObservableCollection<Product> products = new ObservableCollection<Product>();

Consider the following class:

public class Contact
    {
        private string firstName;
        private string lastName;
        private string address; 

        public Contact(string firstName, string lastName, string address)
        {
            this.firstName = firstName;
            this.lastName = lastName;
            this.address = address;
        } 

        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        } 

        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        } 

        public string Address
        {
            get { return address; }
            set { address = value; }
        }
    }

The following class creates an Observable Collection out of the Contact class:

public class EmployeeList : ObservableCollection<Contact>
    {
        public EmployeeList()
            : base()
        {
            Add(new Contact("Joydip", "Kanjilal", "Hyderabad"));
            Add(new Contact("Debanjan", "Banerjee", "Kolkata"));
            Add(new Contact("Shaik", "Tajuddin","Hyderabad"));
            Add(new Contact("Firdous", "Khan", "Hyderabad"));
        }
    }

You can now use the Observable Collection you have created to bind data to a Silverlight Data Grid. Here is how the mark-up code would look:

<Grid x:Name="LayoutRoot" Background="White">
        <sdk:DataGrid x:Name="dgData" Grid.Row="2" AutoGenerateColumns="True"  ItemsSource="{Binding Source}" >

        </sdk:DataGrid>
    </Grid>

And, here's the code you would write to bind data to the DataGrid control named dgData:

public partial class MainPage : UserControl
    {
        EmployeeList empList = new EmployeeList();

        public MainPage()
        {
            InitializeComponent();          

            dgData.ItemsSource = empList;

        }
    }

To ensure that the DataGrid is refreshed if any item in the collection is changed, we should take advantage of the PropertyChangedEventHandler event handler. The NotifyPropertyChange event handler would be automatically called whenever the list is changed.

public partial class MainPage : UserControl
    {
        EmployeeList empList = new EmployeeList();

        public MainPage()
        {
            InitializeComponent();          
            dgData.ItemsSource = empList;

        }

        public EmployeeList Data
        {

            get { return empList; }

            set
            {

                empList = value;

                NotifyPropertyChange("empList");

            }

        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChange(string propertyName)
        {

            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

        }
    }

Summary

In this article we discussed how we can work with Observable Collections in Silverlight 5. We explored Observable Collections, why they are helpful and how we can bind data to data controls in Silverlight using Observable Collections. Happy reading!

 



European WCF 4.5 Hosting - Amsterdam :: WCF 4.5 ChannelFactory Caching

clock October 19, 2012 10:59 by author Scott

Today I explain what ChannelFactory caching in the WCF 4.5 framework is. With the help of this new feature in .NET we can cache the service instance. Microsoft has introduced a new property for the ClientBase<T> class; the property name is CacheSetting. We can set the cachesetting with the help of the CacheSetting enum.

Here are the values of the Enum:

Name

Description

System.ServiceModel.CacheSetting.AlwaysOn

All instances of Client will use the same channel factory.

System.ServiceModel.CacheSetting.AlwaysOff

All instances of the Client would use different channel factories. This is useful when each endpoint has different security requirements and it makes no sense to cache.

System.ServiceModel.CacheSetting.Default

All instances of Client would use the same channel factory except instance #4. Instance #4 would use a channel factory that is created specifically for its use. This setting would work for scenarios where a particular endpoint needs different security settings from the other endpoints of the same ChannelFactory type (in this case IService).


Here is sample code for the Default CacheSetting:


class Program
    {
        static void Main(string[] args)
        {
             ClientBase<IService1>.CacheSetting = System.ServiceModel.CacheSetting.Default;
             using (ServiceReference1.Service1Client client = new Service1Client()) {


             }
        }
}


Here is sample code for the AlwaysOn CacheSetting:


static void Main(string[] args)

{

  ClientBase<IService1>.CacheSetting = System.ServiceModel.CacheSetting.AlwaysOn;

using (ServiceReference1.Service1Client client = new Service1Client()) {

   }
}


Here is sample code for the AlwaysOff CacheSetting:

static void Main(string[] args)
{
   ClientBase<IService1>.CacheSetting = System.ServiceModel.CacheSetting.AlwaysOff;


   using (ServiceReference1.Service1Client client = new Service1Client()) {

   }
}

 

 



European WCF 4.5 Hosting - Amsterdam :: Implementing WebSockets in WCF 4.5

clock October 15, 2012 06:59 by author Scott

Web Services have one great virtue: they're completely interoperable. They also have one great failing: in order to be interoperable, Web Services use a set of technologies that are guaranteed to give you, at best, adequate performance. Fortunately, WCF 4.5 has a solution: support for WebSockets.

Ever since Web Services appeared, developers have been trying to make them run faster. REST and JSON can be seen as a way of speeding things up by reducing the overhead in the messaging format used by Web Services. However, even with REST and JSON you're still moving and parsing text, which is the bulkiest and slowest data transfer mechanism; you'd get better performance if you could move binary data around. And REST and JSON don't tackle another reason for why Web Services give poor performance: HTTP, the network protocol used by Web Services. There are slower protocols than HTTP around, but no one is using them.


But performance isn't the only issue that using HTTP creates: HTTP in Web Services is tied to a request/response cycle. The reason Ajax applications make all their requests asynchronously is because if you call a service that takes a long time to complete, your request has to wait for that response before you can get your result.


On top of that, if your service has something else to tell your client after that initial response (an ongoing set of updates, for instance), then either your client has to make repeated polling calls to the service to get the result (another performance burden) or, in a non-Ajax application, you have to set up a complementary Web Service that the service can call with the updates.


A far better arrangement would be for the client to submit its request in a "fire and forget" kind of arrangement and then for the service to call back to the client when it has the data (and keep calling back if there are updates to send).


WebSockets addresses all of those issues, while still being an industry standard and therefore interoperable (confusions in vendor's implementations of the standard may interfere). In fact, your browser probably already supports WebSockets.


For most processing, WebSockets uses TCP to communicate, giving you the benefit of a faster protocol. WebSockets also supports sending both binary (for speed) and text (for interoperability). But in many ways, the best part of WebSockets is that it supports two-way communication: The client can call the service just to open communication; and after that, the service can call the client whenever it has information to share. And WCF 4.5 provides support for WebSockets.


So in the next few columns, I'm going to look at WebSockets in WCF 4.5. I'll look at the two ways you can implement WebSockets (one complicated and flexible, one simpler and less flexible) and create client a JavaScript client. Along the way I'll also discuss some of the issues you should consider in creating a WebSocket application.


Configuring the Server

One warning: You may not be able to use the code in this series, yet. As I write this (April 2012), WebSockets is only supported on Windows 8 (I worked on the 64-bit
beta ISO for Windows 8 Server); even then, you'll need to configure Windows 8 to support WebSockets.

To configure Windows 8, in Server Manager, from the Manage menu, run the Add Server Roles and Features wizard. In the Wizard, you'll need to add the Web Server (IIS) role. After that, under Features, select ASP.NET 4.5 (if it isn't already selected) and, under Web Services, select HTTP Activation. Finally, under Web Services (IIS)/Role Services, select WebSockets. After finishinb the Wizard, select Local Server and set IIS Enhanced Security Configuration to off.


To work with WCF 4.5, you'll need
Visual Studio 11 (again, in beta, as I write this). The first time you run it, Visual Studio 11 will probably offer to download an update; if so, take the update (I took the update and I won't guarantee that the following code will work without it).

Second warning: This may be a frustrating set of columns if you're reading them as soon as I post them. I've got a fair amount of ground to cover so, in this column, I'll only be setting up to write the code that a WebSocket service requires. But hang tough; the next column will have the code and subsequent columns will show you how to build the clients and provide an alternative way to build a WebSocket service.


Building the Service

I did my testing with a WCF Service Application Project. To take advantage of IIS's support for WebSockets that I'd just finished configuring, I went to the Web tab of my Project Properties and unchecked the Use IIS Express option so that I was testing with the "real" IIS.


Once you've set up your server and project, the first step in creating your WebSocket service is to define two interfaces: one with a single method that accepts requests from clients and another interface with a single method to send results.


For the first interface, I'll define a method that accepts an Order Id (I call the method OrderStatusById method and the interface IRequestOrderStatusUpdates). In the ServiceContract attribute on the interface that accepts requests, you need to use the attribute's CallbackContract to specify the second interface (the one with the method used to send data back to the client is ISendOrderStatus in this example). The method must accept a Message as its only input parameter and the method's OperationContract attribute must set its IsOneWay property to True and its Action property to an asterisk.


The result for my Order status example looks like this:


<ServiceContract(CallbackContract:=GetType(ISendOrderStatus))>
Public Interface IRequestOrderStatusUpdate

  <OperationContract(IsOneWay:=True, Action:="*")>
  Sub OrderStatusByID(OrderStatusMessage  As Channels.Message)

End Interface


The definition for the return method is similar, except that you don't need any special specifications for the ServiceContract attribute. I've called my method SendOrderStatus:


<ServiceContract()>
Public Interface ISendOrderStatus

  <OperationContract(IsOneWay:=True, Action:="*")>
  Sub SendOrderStatus(OrderStatusMessage  As Channels.Message)

End Interface


At this point you're ready to write the code for these methods, which I'll look at in my next column (the column after that will look at building a client).

 



HostForLIFE.eu now supports Windows Server 2012 Hosting Platform in European Data Center

clock October 1, 2012 08:06 by author Scott

Microsoft has just officially released the highly anticipated Windows Server 2012. The newly released server operating system offers a number of features that can be utilized to benefit developers, resellers and businesses. As a premier European Windows and ASP.NET hosting provider that follow the developments of Microsoft products, HostForLIFE.eu proudly announces the support of Windows Server 2012 Hosting Platform in the world-class Amsterdam (The Netherlands) data center.

“We know that our customers are always looking for new technologies and the latest Microsoft product. With the launch of Windows Server 2012, we believe that anyone can take advantage of all the improvements available in this platform”, said Manager of HostForLIFE.eu, Kevin Joseph. “The focus on high availability, scalability, and virtualization has made this one of the most important releases of Windows Server to date. We have been working closely with Microsoft throughout the pre-release development cycle of the platform to both drive the direction of the product and ensure our team is ready to support Server 2012 solutions. We couldn’t be more excited and confident in the solutions now available to our clients with Windows Server 2012.”


With our Windows Server 2012 Hosting Platform, customers have an access directly to all the newest technologies and frameworks, such as ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, Silverlight 5 Hosting, WebMatrix Hosting, Visual Studio Lightswitch Hosting and SQL 2012 Hosting. All these technologies/frameworks are integrated properly on our world-class Control Panel. The package is offered from just €2.45/month and we believe that this is the most affordable, features-rich Windows and ASP.NET Hosting package in European market.


HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see
http://www.microsoft.com/web/hosting/HostingProvider/Details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.

For more information about our service, please visit
http://www.hostforlife.eu.

About HostForLIFE.eu:


HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


Our number one goal is constant uptime. Our data center uses cutting edge technology, processes, and equipment. We have one of the best up time reputations in the industry.


Our second goal is providing excellent customer service. Our technical management structure is headed by professionals who have been in the industry since its inception. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European Silverlight 5 Hosting - Amsterdam :: Markup Extensions in Silverlight 5

clock September 28, 2012 09:03 by author Scott

Another cool feature available in Silverlight 5 is markup extensions. The idea behind the feature is ability to allow developers to supply values to XAML parser at the time it parses visual tree. In other words, once parser finds a markup extension in XAML, it will create an instance of it, set any properties that the extension might have, then call ProvideValue method that will return a value of the type that the property that markup extension supports expects. For example, I am writing a markup extension to supply an ICommand to the button, my XAML would looks like the following:

      <Button Content="Save" HorizontalAlignment="Left"  
             Grid.Row="4" Grid.Column="0"
             Command="{ext:CommandMarkupExtension
                 ViewModel={Binding ElementName=LayoutRoot, Path=DataContext},
                 ExecuteMethodName=Run,
                 CanExecuteMethodName=CanRun}"/>


So, in this example for markup extension I am writing a command extension. As you can see in the XAML above, my extension takes three parameters: ViewModel to invoke, execute and can execute method names. This way I can de-clutter my view model by removing all the command instantiation code, and just write the two methods I need. The code in this extension is very easy – just a handful of dependency properties and interface implementation for IMarkupExtension:

using System;

using System.Windows;

using System.Windows.Input;

using System.Xaml;


namespace SL5Features.Extensions

{

  public class CommandMarkupExtension : FrameworkElement, IMarkupExtension<ICommand>
  {

    public Object ViewModel
    {
      get { return (Object)GetValue(ViewModelProperty); }
      set { SetValue(ViewModelProperty, value); }
    }

    public static readonly DependencyProperty ViewModelProperty =
        DependencyProperty.Register(
        "ViewModel", typeof(Object),
        typeof(CommandMarkupExtension),
        new PropertyMetadata(null));

    public string ExecuteMethodName
    {
      get { return (string)GetValue(ExecuteMethodNameProperty); }
      set { SetValue(ExecuteMethodNameProperty, value); }
    }
    public static readonly DependencyProperty ExecuteMethodNameProperty =
        DependencyProperty.Register(
        "ExecuteMethodName",
        typeof(string),
        typeof(CommandMarkupExtension),
        new PropertyMetadata(null));


    public string CanExecuteMethodName
    {
      get { return (string)GetValue(CanExecuteMethodNameProperty); }
      set { SetValue(CanExecuteMethodNameProperty, value); }
    }

    public static readonly DependencyProperty CanExecuteMethodNameProperty =
        DependencyProperty.Register(
        "CanExecuteMethodName",
        typeof(string),
        typeof(CommandMarkupExtension),
        new PropertyMetadata(null));

    public ICommand ProvideValue(IServiceProvider serviceProvider)
    {
      ReflectionCommand command =
        new ReflectionCommand(ViewModel, ExecuteMethodName, CanExecuteMethodName);
      return command;
    }
  }
}

To support the extension I need to write a command object that would actually implement ICommand. This class is pretty trivial, so I am not commenting it much:


using System;

using System.Reflection;

using System.Windows;

using System.Windows.Input;  


namespace SL5Features.Extensions

{

  public class ReflectionCommand : ICommand
  {

    private MethodInfo canExecuteMethod = null;
    private MethodInfo executeMethod = null;
    private object viewModel = null;

    private ReflectionCommand() {


    public ReflectionCommand(
      object viewModel,
      string executeMethodName,
      string canExecuteMethodName)
    {
      this.viewModel = viewModel;
      Type type = viewModel.GetType();
      if (!string.IsNullOrEmpty(canExecuteMethodName))
      {
        this.canExecuteMethod = type.GetMethod(canExecuteMethodName);
      }
      this.executeMethod = type.GetMethod(executeMethodName);
    }

    public void Execute(object parameter)
    {
      executeMethod.Invoke(viewModel, new[] { parameter });
    }

    public bool CanExecute(object parameter)
    {
      if (viewModel != null && canExecuteMethod != null)
      {
        return (bool)canExecuteMethod.Invoke(viewModel, new[] { parameter });
      }
      else
      {
        return true;
      }
    }



    public event EventHandler CanExecuteChanged;

    public void RaiseCanExecuteChanged()
    {
      if (CanExecuteChanged != null)
      {
        CanExecuteChanged(this, EventArgs.Empty);
      }
    }

  }
}

So, far it is pretty easy. Now, all I have to do is add Run and CanRun method on my view model that my command will invoke:

using SL5Features.Models;
using System.Windows;

namespace SL5Features.ViewModels

{
  public class PersonViewModel : ViewModelBase<Person
  {
    public PersonViewModel()
    {
      Model = new Person() { FirstName = "Sergey", LastName = "Barskiy" };
    }

    public void Run(object parameter)
    {
      MessageBox.Show("Run")
    }
    public bool CanRun(object parameter
    {
      return true;
    }
  }
}


Hopefully, I demonstrated the power of markup extension for you. The goal of using them to me is reduction of the amount of code elsewhere in the system, since you will obviously have to write more XAML. Of course, I am sure Blend 5 will support mark up extensions, so potentially you can just drag my extension on top of the button and setup a few properties in properties window. You will also see a number of demos where an extension is used to support localization, which seems pretty intuitive use of the feature. Bottom line is: I love getting new features that make my job easier by allowing me to write less code and re-use more of the code written.

 



European WCF 4.5 Hosting - Amsterdam :: IntelliSense for WCF Config file .NET 4.5

clock September 4, 2012 07:09 by author Scott

Now Visual studio 2011 is giving IntelliSense for WCF config files (App.config, Web.config). It is really good for .NET developer, previously when we developed WCF application; Application development is easy rather than configuration. Now in VS 2011 gives us IntelliSense in the Config file. Even we can also map contract.

In previous version of Visual Studio we did configuration via "
Edit WCF Configuration" wizard

In the below image we can set endpoint binding.




In the below image we can set service contract.


 



European Silverlight 5 Hosting - Amsterdam :: Creating a Silverlight 5 Static Markup Extension

clock August 28, 2012 10:00 by author Scott

If you have done any WPF application development I am sure you have used and fallen in love with the Static markup extension. If you’re are not familiar with it, the Static markup extension allows you to reference static fields and properties in your XAML markup.

For example; let’s assume we have a class with the following static field defined:


public class Common

 {
     public static string StaticText = "This is text from a static property";
 }

We can use this field in our WPF application as follows:

<Grid>

     <TextBlock Text="{x:Static ext:Common.StaticText}" />
 </Grid>



NOTE: “ext” is a namespace that has been defined to instruct the XAML parser where to find our static field.

Pretty cool right? Unfortunately if you are also doing any Silverlight development you will soon find that this wonderful and useful extension does NOT exist in Silverlight. Luckily for us in Silverlight 5 we were given the ability to write our own custom markup extensions. This can be done using either the
IMarkupExtension or the abstract MarkupExtension class.

Now it’s time to create our own Static markup extension. I want to point out that there is a naming convention when creating custom markup extensions. The convention is as follows; ExtensionNameExtension. The name of the extension is followed by Extension. This is very similar to how you create attributes. You won’t actually be using the suffix when define them in XAML.

Let’s start by creating a new class called StaticExtension. The StaticExtension class should derive from the MarkupExtension abstract class. You will need to implement the abstract ProvideValue method. The code I used for the Static markup extension is as follows.

/// <summary>
 ///  Class for Xaml markup extension for static field and property references.
 /// </summary>
public class StaticExtension : MarkupExtension
 {
     /// <summary>
     ///  The static field or property represented by a string.  This string is
     ///  of the format Prefix:ClassName.FieldOrPropertyName.  The Prefix is
    ///  optional, and refers to the XML prefix in a Xaml file.
     /// </summary>
    private string _member;
     public string Member
     {
         get { return _member; }
         set
         {
             if (value == null)
             {
                 throw new ArgumentNullException("Member");
             }
             _member = value;
         }
     }

    /// <summary>
     ///  Return an object that should be set on the targetObject's targetProperty
    ///  for this markup extension.  For a StaticExtension this is a static field
    ///  or property value.
     /// </summary>
    /// <param name="serviceProvider">Object that can provide services for the markup extension.
     /// <returns>
     ///  The object to set on this property.
     /// </returns>
    public override object ProvideValue(IServiceProvider serviceProvider)
     {
         if (_member == null)
             throw new InvalidOperationException("member cannot be null");

        // Validate the _member
        int dotIndex = _member.IndexOf('.');
         if (dotIndex < 0)
             throw new ArgumentException("dotIndex");

        // Pull out the type substring (this will include any XML prefix, e.g. "av:Button")
        string typeString = _member.Substring(0, dotIndex);
         if (typeString == string.Empty)
             throw new ArgumentException("typeString");

        // Get the IXamlTypeResolver from the service provider
         IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
         if (xamlTypeResolver == null)
             throw new ArgumentException("xamlTypeResolver");

        // Use the type resolver to get a Type instance
        Type type = xamlTypeResolver.Resolve(typeString);

        // Get the member name substring
         string fieldString = _member.Substring(dotIndex + 1, _member.Length – dotIndex – 1);
         if (fieldString == string.Empty)
             throw new ArgumentException("fieldString");

        // Use the built-in parser for enum types
         if (type.IsEnum)
         {
             return Enum.Parse(type, fieldString, true);
         }

        // For other types, reflect
        bool found = false;
         object value = null;

        object fieldOrProp = type.GetField(fieldString, BindingFlags.Public |                                                         BindingFlags.FlattenHierarchy | BindingFlags.Static);
         if (fieldOrProp == null)
         {
             fieldOrProp = type.GetProperty(fieldString, BindingFlags.Public
|                                                         BindingFlags.FlattenHierarchy | BindingFlags.Static);
             if (fieldOrProp is PropertyInfo)
             {
                 value = ((PropertyInfo)fieldOrProp).GetValue(null, null);
                 found = true;
             }
         }
         else if (fieldOrProp is FieldInfo)
         {
             value = ((FieldInfo)fieldOrProp).GetValue(null);
             found = true;
         }

        if (found)
             return value;
         else
             throw new ArgumentException("not found");
     }
 }

Now all I need to do is add a namespace to my Silverlight view and then use it in XAML as follows:

<Grid x:Name="LayoutRoot" Background="White">

     <TextBlock Text="{ext:Static Member=ext:Common.StaticText}" />
 </Grid>



That’s it! I will definitely be using this quite often. I would like to mention that unlike in WPF where you don’t have to specify the “Member” property explicitly, in Silveright you have to explicitly set the Member property. This is because there is not a
ConstructorArgument attribute in Silverlight. So until then you will need to have a little extra text in your markup syntax.



European Silverlight 5 Hosting - Amsterdam :: Breakpoints on Xaml in Silverlight 5

clock July 13, 2012 09:45 by author Scott

Silverlight 5 Beta brings the enormously useful ability to set a break point in your Xaml where you have a data binding. This can greatly simplify debugging and fixing binding issues.



To see this, create a new Silverlight 5 project and set up the Xaml to have 5 rows and 2 columns. Place the title in the first row (spanning both columns) and prompts in the next 4 rows. The prompts are


- FullName

- Address
- Phone
- Email

Add four TextBlocks in the second column to display the values that will correspond to these prompts. The Xaml for the four prompts looks like this:


<TextBlock
    Grid.Column="1"
    Grid.Row="1"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding FullName}" />
<TextBlock
    Grid.Column="1"
    Grid.Row="2"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding Address}" />
<TextBlock
    Grid.Column="1"
    Grid.Row="3"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding PhoneNumber}" />
<TextBlock
    Grid.Column="1"
    Grid.Row="4"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding Email}" />

To make this work, of course, we need a class and an instance to bind to. Begin by creating a new class, Person,


public class Person

{

    public string FullName { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}

In MainPage.xaml.cs create an instance of Person, and set that instance to be the data context for the bindings,


public MainPage()
{
    InitializeComponent();
    var per = new Person()
    {
        FullName = "Jesse Liberty",
        Address = "100 Main Street, Boston, MA",
        Email = "[email protected]",
        Phone = "617-555-1212"
    };
    this.DataContext = per;
}

When you run this you’ll find that three of the four bindings work well, but the phone number is not displayed. Set a break point in the Xaml folder on the binding for the PhoneNumber and run the application. When you hit the break point examine the locals window as shown in the illustration to the below.



Note that there is an error message. By clicking on the message you can open a text reader for the entire error message, as shown in the next figure to the below.




The error message indicates that there is no property PhoneNumber in the type Person, and sure enough, a quick check of the code shows that the property is just
Phone.

Change the binding from PhoneNumber to Phone and the program works as expected.



European Silverlight 5 Hosting - Amsterdam :: How to Design RichTextBox in Silverlight 5

clock June 29, 2012 08:54 by author Scott

In this article, I am going to explain how to design a RichTextBox in Silverlight. This example also demonstrates the RichTextBox control as well. It is easy to formatt a Silverlight RichTextBox at design time through XAML. In this example I have used an image to illustrate the example clearly.

<UserControl x:Class="SilverlightApplication3.MainPage"
                  xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
                  xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
                  xmlns:d=http://schemas.microsoft.com/expression/blend/2008
                  xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
                     mc:Ignorable="d"
                  d:DesignHeight="300" d:DesignWidth="400" DataContext="{Binding}">

              <Grid x:Name="LayoutRoot" Background="White" Height="450" Width="550">
                      <RichTextBox HorizontalAlignment="Left" Margin="10,12,0,0" Name="contentBox" VerticalAlignment="Top" Height="330" Width="390" IsReadOnly="True" Background="#FFFFFF69">
                    <Paragraph FontFamily="Arial" FontSize="12" TextAlignment="Justify">
                   This photograph shows a
                <Run Text=" blue hills " FontStyle="Italic" FontWeight="ExtraBold" /> belongs to the
                <Run Text=" high " Foreground="blue" FontWeight="ExtraBold"/> graphic photography. High graphic photography requires a     great deal of precision.
                <LineBreak/>
                <InlineUIContainer>
                    <Image Height="143" HorizontalAlignment="Left" Margin="144,82,0,0" Name="images" Stretch="Uniform" VerticalAlignment="Top" Width="196" Source="/SilverlightApplication3;component/Images/Blue%20hills.jpg" />
                </InlineUIContainer>
                <LineBreak/>
                <LineBreak/> |
          </Paragraph>
        </RichTextBox>
    </Grid>
</UserControl>

Now I am going to explain the code so that it can be easily understood. It creates a RichTextBox, with some text and an image. To place and format the text, I first use the Paragraph element, then the Run element. Note that the Paragraph element also has a Foreground property but which I have not used here. In this I use the Run element which is useful to format text. The RichTextBox control also allows you to add elements of type Bold, Underline etc.The Run element derives from the Inline element, an Inline cannot be used directly within a RichTextBox control, however, you can use the Run element.


The LineBreak element is used to introduce line breaks.

The Image is placed inside the InlineUIContainer.

InlineUIContainer: A mandatory child element that is used to place an Image in the RichTextBox control.

You can have as many Paragraph and Run elements as you want, in a RichTextBox control. Using a combination of Paragraph and Run elements, you can format the text in various ways.

The output of the above application is shown below:



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in