Phuong's profilePhuong's spacePhotosBlogLists Tools Help

Blog


    May 13

    Creating a Silverlight Custom Control - The Basics

    Reference: http://www.silverlightshow.net/items/Creating-a-Silverlight-Custom-Control-The-Basics.aspx

    + Add to SilverlightShow Favorites

    15 comments   /   posted by Emil Stoychev on Jun 16, 2008

    (23 votes)

    Tags: Custom Controls , Styling , Templating , VSM , Emil Stoychev

    Categories: Tutorials , QuickStarts

    Introduction

    This articles focuses on the process of creating a Custom Control in Silverlight 2. It describes the basics of what you need to build a styleable control with custom logic that can be used in Silverlight applications. The article shows a sample(part) of implementing a LinkLabel control that recognizes URIs in a given text and displays them as links instead of as plain text.

    Overview
    Don't Miss

    The control model in Silverlight 2 offers creating UserControls and Custom Controls. UserControls enable encapsulation of a specific logic. They are used in scenarios where you want to reuse XAML and/or logic in multiple places or build a sophisticated page with smaller chunks(the UserControls). However, in other scenarios you may need a custom logic to be built in the control and this control to allow designers customize easily its look. You need a way to modify the control visuals without having to modify the control logic. This is where the Custom Controls comes in handy. In Silverlight they derive from the Control class and specify a default style for the way they will look like.

    To get started create a Silverlight Class Library project in VisualStudio 2008. This will generate just a single .cs file. Lets take a sample implementation of a LinkLabel control.

       1: public class LinkLabel : Control
       2: {
       3: ...
       4: }

    Ok, the first step is to define a default look for this control. A file called generic.xaml contains the UI of your custom controls. It should be placed in a "themes" directory inside your project. Add a new item of type XML File in your project in the "themes" directory and name it generic.xaml. By default when you add a new file the Build Action is set to Silverlight page. But the platform look for the generic.xaml as a Resource file. Therefore you need to change the default behavior:

    1. Open the Properties window of the file.
    2. Change the Build Action to Resource.
    3. Clear the Custom Tool value.

    generic.xaml.build.action

    In the generic.xaml add a ResourceDictionary element where you will put all the resources.

       1: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       2: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
       3: ...
       4: </ResourceDictionary>

    The next step is to add the default style for the control. Start by including the XML namespace of the assembly.

       1: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       2: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       3: xmlns:local="clr-namespace:CompletIT.Windows.Controls;assembly=LinkLabel">
       4: 
       5:     <!-- Default style for CompletIT.Windows.Controls.LinkLabel -->
       6:     <Style TargetType="local:LinkLabel">
       7:         <Setter Property="Template">
       8:             <Setter.Value>
       9:                 <ControlTemplate TargetType="local:LinkLabel">
      10:                     <StackPanel x:Name="LayoutRoot">
      11:                         <ContentPresenter   />
      12:                     </StackPanel>
      13:                 </ControlTemplate>
      14:             </Setter.Value>
      15:         </Setter>
      16:     </Style>
      17: </ResourceDictionary>

    In this code snippet you see a Style element just like the one you might have already used in your Silverlight applications. You may also notice that there is no x:Key attribute - you don't need it because when the platform looks for the default style of the control it just examines the TargetType. To specify the control's look set the Template property and add a ControlTemplate. This is where you can define the full appearance of the control.

    With the release of the VisualStateManager in Beta 2 it is important to point that this style is also the place where you can define the state parts of your control. This is not the main focus of this article so I won't get deep in it. For more information on this topic you can read Parts & States Model with VisualStateManager and watch Creating Rich, Dynamic User Interfaces with Silverlight 2 by Karen Corby.

    Ok, enough of XAML. Lets see what's needed in the code.

    Start with creating a constructor and set the FrameworkElement.DefaultStyleKey - type that should be used to look up the built-in style - to the Type of the control.

       1: public LinkLabel()
       2:     : base()
       3: {
       4:     DefaultStyleKey = typeof( LinkLabel );
       5: }

    Then, define all the custom properties of the control. Most of the properties in the framework are of DependencyProperty type. If you want a particular property of your control to be template-bindable, data-bindable or styleable,  you need to define it as a DependencyProperty. For the LinkLabel control lets just add a Text property.

       1: public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
       2:             "Text",
       3:             typeof( string ),
       4:             typeof( LinkLabel ),
       5:             new PropertyMetadata( new PropertyChangedCallback( OnTextChanged ) ) );
       6: 
       7: public string Text
       8: {
       9:     get
      10:     {
      11:         return ( string )this.GetValue( TextProperty );
      12:     }
      13: 
      14:     set
      15:     {
      16:         base.SetValue( TextProperty, value );
      17:     }
      18: }

    As you can see on line 5 a new PropertyChangedCallback is added that will be called when the text is changed. This is not needed for all controls. We will walk through the implementation of the OnTextChanged method in a second. Do the same for all properties your control needs.

    One last step before proceeding to the control logic code. The StackPanel we use for a "built-in" style in the generic.xaml is still not accessible from the code file. To assign it to a member variable create a private field of type StackPanel and override the OnApplyTemplate method like this:

       1: public override void OnApplyTemplate()
       2: {
       3:     this.layoutRoot = this.GetTemplateChild( "LayoutRoot" ) as StackPanel;
       4:     Debug.Assert( this.layoutRoot != null, "LayoutRoot is null" );
       5: 
       6:     base.OnApplyTemplate();
       7: }

    As you see in the above code we call this.GetTemplateChild(childName) to retrieve the element from the visual tree.

    That's it. From there on you should write the custom logic needed by your control to act as you want. For our LinkLabel sample we need to process the entered text by replacing all URIs with links. To achieve this we need to define a new method (ProcessText()) that should be called (1) from the OnApplyTemplate event and (2) from the OnTextChanged event. I'll skip the implementation of the ProcessText method here as I'll blog about the full implementation of the LinkLabel control later this week and will provide the source code and a sample usage.

       1: private static void OnTextChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
       2: {
       3:     LinkLabel linkLabel = d as LinkLabel;
       4:     Debug.Assert( linkLabel != null, "LaytouRoot is null" );
       5: 
       6:     linkLabel.ProcessText();
       7: }
    Conclusion

    Building a Custom Control in Silverlight can be tricky sometimes, but that really depends on the complexity the control requires. Silverlight really gives the freedom to create whatever your imagination can born and push it to the highest level. You are able to build beautiful controls that can be easily customized by designers on their own. You are sure that the designer won't brake your logic while making the fascinate look of the control. With the new VisualStateManager and the "Parts and States Model" you can easily define complex UI while keeping the designer's ability to style it. This is another quite a big and interesting topic that I'll try to cover in future posts.

    Stay tuned to see the LinkLabel control. I'll provide a link in this article too.

    Update
    Check out the LinkLabel control here.

    References

    Styling and Templating Overview on MSDN
    Creating a Templatable Control on MSDN
    Creating Rich, Dynamic User Interfaces with Silverlight 2 by Karen Corby
    Parts & States Model with VisualStateManager by Karen Corby

    April 21

    Ý trí vững vàng tình cảm mênh mang

    Gió cuốn đi những tháng năm dài đằng đẵng
    Tình vẫn còn mà người chẳng thấy đâu
    Hận trời xanh vô tình nhắm mắt
    Chẳng chịu nghe, chịu hỏi, chịu trông
    Mặc cho giông tố cuốn đi tình yêu chân thật
    Khiến ta cuồng si, khiến nàng đau khổ
    Mang trên vai gánh nặng tương tư
    Người anh hùng vương vấn bởi nặng chữ tình
    Nếu suốt đời bôn ba lặn lội
    Mà không giữ đựơc người ki trỉ hồng nhan
    Thì dù cho có nắm cả giang sơn
    Vẫn cảm thấy xót xa ân hận
    Muốn tỏ mặt anh tài: lòng muốn khóc mắt cũng không rơi lệ
    Rượu cạn rồi lại ngập nỗi nhớ thương
    Điều khó nhất trên đời là làm một trang nam tử
    Ý chí vững vàng mà tình cảm mênh mang

    Ngày tháng cũ mịt mờ như trong mộng
    Người thân yêu xa mãi tận chân trời
    Thế gian này phản phúc biết bao nhiêu
    Sao người nỡ quên đi tất cả
    Tình yêu đầu ngây thơ chân thật
    Có thể nào sống lại với ta
    Như biển sâu khiến tình ta đau đớn
    Tháng năm trôi mái tóc đã điểm sương
    Đừng chờ đợi tháng năm quay đầu lại
    Dứt không được hình ảnh trong tâm khảm
    Đừng bỏ đi hạnh phúc của ngày mai
    Đời cô tịch là điều cam go nhất
    Dứt không ra nỗi đau khổ tình đời
    Đừng nhẫn nại vì mối tình xưa nữa
    Hoa nở xuân về mà người đã ra đi
    Để tim ta vấn vương bụi trần thế...

    March 23

    WS-Eventing for WCF (Indigo)

    http://69.10.233.10/KB/WCF/WSEventing.aspx

    Contents

    Note: This article was written by .NET Framework 3.0 (RTM)

    Introduction

    Event-driven async distributed architecture requires a common interaction pattern for transmitting a workflow state across a service boundary. The Web Service Eventing (WS-Eventing) represents a SOAP-based specification for pub/sub communications patterns. These enable decoupling of an event source from its consumer, based on the event interest known as a subscription. The WS-Eventing specification was created by IBM, BEA Systems, TIBCO Software, Sun Microsystems, Computer Associates and Microsoft. On March 15, 2006 it was submitted to W3C (HP, IBM, Intel and Microsoft) for Web Service Standards. More details about that can be found here.

    The Web Service Standards introduced a few new specifications on the top of the WS-Eventing such as WS-EventingNotification and WS-ResourceTransfer. These new WS-* specs can standardize an interaction of the WS-Eventing in the Service Oriented Architecture (SOA), e.g. using a WS-ResourceTransfer for subscription storage and WS-EventingNotification for delivering a notification message to the event sink. Note that these specs are new and therefore they are not publicly available yet. This article describes a design, implementation and usage of the WS-Eventing spec in the foundation level with a capability for future extensions using the above mentioned new specs.

    Concept and design implementation

    In order to better understand the concept of the Eventing notifications system and message exchange pattern, let's start with a simple notification case that is shown in the following figure:

    In the above picture, I am assuming that some endpoints would like to be notified from the place where some situation (event) occurred. The place where the situation occurred is called in the WS-Eventing spec and is referred to as as Event Source, the initiator (producer) of the message. The message is called the Event Message because the message is related to some event situation. The Event Message is sent to the service that is waiting for this event situation, the Event Sink. The Event Sink is described by Address, Binding and Contract (ABC), known as ServiceEndpoint, and of course by a behavior. However, that's the local subjective of each Event Sink.

    Now, the upcoming question would be, "How does the Event Source knows about the Event Sink and delivery mechanism?" The minimum requirement is to know a base address of the Event Sink. In order to obtain binding information of the Event Sink endpoint, we can use a WS-MEX (Web Service MetadataExchange) message pattern. In addition, the Event Source needs to know how to deliver an Event Message to the destination sink service. This delivery mechanism is called in the WS-Eventing as Delivery Mode.

    Based on the above analysis, the Event Source needs some metadata for the message producer to properly generate an Event Message for each situation. This metadata related to the Event Sink interest is known as Subscriptions. Subscriptions, based on the event situation, can be organized by the event topic related to the application-specific Event Source, for example: weather, stock market, magazine, etc.

    One more thing: each event situation represents some event value -- i.e. DataContract between the Event Sink and Event Source -- that can be used as a condition by Event Sink interest for delivering a notification message. This pattern can be defined in the Subscription using the Filter element. Note that the WS-Eventing specification does not constrain notifications and it depends on the Contract only. Basically, any SOAP-based message can be an Event Message. However, if the Event Sink requires some additional application-specific header blocks, the subscription will be held. This topic will be described later on this article.

    Event source

    The Event Source hides many WS-Eventing features. Let's look at them in detail. We know that the logical connectivity (interest) between the Event Sink and its Source is defined (abstracted) in the resource called Subscription. For a message exchange pattern with an Event Sink, the Event Source contains a message producer (service) that relays on one or more Event Topics. This producer (Notification Manager) encapsulated the Event Sink from the Event Source. The following picture shows its position in the Event Source:

    Let's assume that somehow we stored our subscriptions in the Event Storage. This could be done administratively (manually) or programmatically using DAL layer or WS-Transfer service. In addition, the Notification Manager is able to query the Event Storage for Subscription based on the Event Topic. The Subscription is stored in the Storage as a resource with a resource descriptor. The following code snippet shows an example of the Subscription and its descriptor:

    Collapse Copy Code

    <ResourceDescriptor>
      <Name>Subscription for weather report</Name>
      <Key>uuid:770b3a90-27c8-419e-94ae-301313d52793</Key>
      <Topic>weather:report.storm</Topic>
      <Expires>2007-05-22T05:58:14.4838Z</Expires>
      <Created>2006-05-22T06:35:57.7556Z</Created>
      <Updated/>
    </ResourceDescriptor>
    
    
    <wse:Subscription>  
      <wse:Delivery wse:Mode=
        "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push">
        <wse:NotifyTo>
          <a:Address>net.tcp://localhost:33333/OnStormWarning</Address>
          <a:ReferenceParameters xmlns="http://www.w3.org/2005/08/addressing">
            <MySubscription xmlns="urn:MyNamespace">1234567890</MySubscription>
          </a:ReferenceParameters>
        </wse:NotifyTo>
      </wse:Delivery>
      <wse:EndTo>
        <a:Address>net.tcp://localhost:44444/Admin</Address>
        <a:ReferenceParameters>
          <MySubscription xmlns="urn:MyNamespace">1234567890</MySubscription>
        </a:ReferenceParameters>
      </wse:EndTo>
      <wse:Expires>2007-05-22T05:58:14.4838368Z</wse:Expires>
      <wse:Filter xmlns:ow="http://www.example.org/oceanwatch">
         //ow:WindReport/ow:Speed <= 65
      </wse:Filter>
    </wse:Subscription>

    The above Subscription example contains major metadata, the delivery pattern knowledge base for the Notification Manager Service. It represents an Event Sink interest. When a situation in the Event Source has occurred, the specific event topic is delivered to the Notification Manager service based on the internal connectivity knowledge base. The process in the service starts to query all ResourceDescriptors in the Event Storage related to this event topic, for example: weather:report.storm. Walking through this Subscription collection, the service looks for the Filter. It will execute its expression on the situation value (a message payload). When the filtering is passed, the Delivery element starts processing based on the delivery mode.

    In our example, the delivery mode is this, where the Event Message is forced to push it to the sink in the fire & forget (async) manner. The service dispatcher will initiate an output channel destination for NotifyTo EndpointAddress. Note that the NotifyTo's ReferenceParameters will be added in the message header and delivered to the sink without any modification (loosely coupled correlation info between the sink and subscription). The above Subscription contains additional information such as EndTo EndpointAddress, which is useful for delivering a notification message about the Event Source status (disable, shutdown, etc.). Also, it is possible to add additional information to Subscription, such as Subscription Policy, binding key, etc.

    Note:

    The Event Message is delivered to the Event Sink based on the ABC description. In the WS-Eventing for Web Service, the binding uses BasicHttpBinding (Soap 1.1). What about the other bindings, for instance tcp, msmq, namepipe, etc?. How does the Event Source knows about the binding of the specific Event Sink? Or how about the scalability, when the Event Source needs to deliver a notification message to a thousand sinks?

    The WS-Eventing specification didn't specify any of these questions. Some of them will require additional information to be added to the subscription or the use of another WS-* spec to obtain it. For example, WS-MetadataExchange enables one to get the Event Sink's metadata for creating a proxy. Certainly, this part of the Notification Manager must necessarily be customized based on the application requirements. This article describes how to implement a basic Event Message push delivering.

    Based on the above description, you could have a fundamental question. Where is the WS-Eventing spec pattern and can the Event Source send messages to the Event Sink based on Data and Operation Contracts? Well, that is the right question. WS-Eventing didn't specify anything about the Event Notification message, just a Push (fire&forget) delivery mode. It appears that the Notification Manager is doing router work based on the Subscription without the knowledge of the event situation. That's correct.

    For example: The Event Sink can send a Subscription by e-mail (or FedEx), and then administrator will manually add (subscribe) it into the Event Storage, which will activate the Event Sink for its notification interest. This off-line subscribing process is used by many applications in private pub/sub notification systems. It is the first step for incremental development of WS-Eventing based on the 3 actors such as Event Source, Subscription/Notification Manager and Event Sink.

    ………

    March 16

    Developing Custom Controls in Silverlight 2

    Ref: http://geekswithblogs.net/Silverlight2/archive/2008/10/31/developing-custom-controls-in-silverlight-2.aspx
    Introduction

    Creating custom controls is not as difficult as they actually appear, but before we go creating custom controls lets first look at the difference between Custom Controls (CC) and Custom User-Controls (CU).

    Simply put Custom Controls (CC) are skinable, themable and reusable controls that once created can be used by simply loading the assembly in any project, where are Custom User-Controls are user controls that can be reused but they can't be skinned or themed. Technically they are both difference Custom Controls inherits from (System.Windows.Controls) Controls whereas User Controls inherits from (System.Windows.Controls.UserControl) UserControl. All controls that are used in Silverlight (eg., Button, TextBlock, TextBox) and UserControl is also a Control.

    Lets just start by creating a custom control and we can discuss the technicalities where they arise. I'll do this in both C# and VB.NET.

    Note: This was my first custom control I built on Silverlight 2 about couple of weeks ago, and I wrote this blog last week as well. I wanted to first introduce concepts like binding and dependency properties before I publish this, but since Microsoft have released Silverlight Toolkit and included NumericUpDown, this is purely academic now. But do enjoy and learn how to create Custom Controls. But the basic concepts are still going to follow.

    Developing a Custom Control

    In this example we'll create a custom control for NumericUpDown. Its a very simple control that can be easily built, I'll be using Microsoft Visual Studio 2008 and Microsoft Expression Blend 2 (SP1), we don't really need Expression Blend but sometimes it saves time using Expression Blend.

    First, we'll set up and prepare to built a custom control and to test it.

    1. Setup:

    In Visual Studio Start a new Project with Silverlight Application Template and name it (I named it Silverlight Control Library), then select ASP.NET Web Application Project for testing.

    2008-10-25_141920 2008-10-25_141938

    Now the project for testing is ready and we need a new Silverlight Class Library Template project within the solution, so add new project and Name it (I named it Controls), this is where we'll be building our custom controls, by default you'll have a Class1.vb or Class1.cs file in the project delete the file, and add a new folder and rename it "themes" (The name of this folder is important, so keep it like it is). 

    2008-10-25_142351 2008-10-25_142446 2008-10-25_142514

    Now add an empty xaml file in that folder and name it "generic.xaml" (Again the name is important), add the following XAML tags in the the xaml file, this is the basic shell we'll always need in building custom controls.

    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows">
        <Style>
            
        </Style>
    </ResourceDictionary>

    It is very important that you remember to make the generic.xaml build action as Resource, this is to make sure that the template is packed in the same assembly as the control otherwise the template wont be available.

    2008-10-25_210935

    Add another folder and name it "NumericUpDown", this is where we'll be building our custom control.

    2008-10-25_142528 2008-10-25_142541 2008-10-25_142558

    2: Preparing

    Now that the setup is complete we can start building the control but first we need to focus and gather facts about the custom control.

    1. Is a Numeric Only TextBox with 2 buttons for increasing and decreasing the value.
    2. Will have a Minimum and Maximum, along with an actual Value.
    3. TextBox should only take numeric input along with Up/Down buttons
    4. Optionally control can be made to use only Up/Down instead of directly entering the value in the TextBox.
    5. When the value is changed, the control will raise an event to notify anyone listening, with its own EventArgs.
    6. The Control should allow access and Binding on basic properties like IsEnabled, Foreground, Font Size etc.

    3: Building

    First, we'll add a Class file in "NumericUpDown" folder and name it "NumericBox", this will be the name of the control, but like I explained before all controls should inherit from Control, second you'll have to tell the compiler where default style for the control is, in order to do this we'll set the DefaultStyleKey value, so in constructor.

    C#

    public class NumericBox: Control
       {
           public NumericBox()
           {
               DefaultStyleKey = typeof(NumericBox);
           }
       }

    VB.NET

    Public Class NumericBox
        Inherits Control
    
        Public Sub New()
            DefaultStyleKey = GetType(NumericBox)
        End Sub
    
    End Class

    Now the constructor will look for default style in generic.xaml (under themes folder) for any style referencing to current assembly. 

    Now we'll expose some properties externally for anyone to bind, you should be aware that any external property you want to bind to the control should be a DependencyProperty, any property (Attached Property / Dependency Property) can be binded but the property that it is binding to should be a DependencyProperty, so to keep this control bindable we'll have to expose Dependency Properties, If you have problem following this, leave a message and I'll try to explain DependencyProperty in detail.

    Now, we already know that we need to expose three properties Minimum, Maximum and Value, in order for us to able to check if the values entered are valid we'll check them every time the any property is changed by using PropertyChangedCallback. (We'll implement Property Callbacks later)

    C#

    #region Dependency Properties
           public int Minimum
           {
               get { return (int)GetValue(MinimumProperty); }
               set { SetValue(MinimumProperty, value); }
           }
    
           public static readonly DependencyProperty MinimumProperty =
               DependencyProperty.Register("Minimum", typeof(int), typeof(NumericBox), 
               new PropertyMetadata(0, new PropertyChangedCallback(MinimumChanged)));
    
           private static void MinimumChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
           {
    
           }
    
           public int Maximum
           {
               get { return (int)GetValue(MaximumProperty); }
               set { SetValue(MaximumProperty, value); }
           }
    
           public static readonly DependencyProperty MaximumProperty =
               DependencyProperty.Register("Maximum", typeof(int), typeof(NumericBox), 
               new PropertyMetadata(10, new PropertyChangedCallback(MaximumChanged)));
    
           private static void MaximumChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
           {
    
           }
    
           public int Value
           {
               get { return (int)GetValue(ValueProperty); }
               set { SetValue(ValueProperty, value); }
           }
    
           public static readonly DependencyProperty ValueProperty =
               DependencyProperty.Register("Value", typeof(int), typeof(NumericBox),
               new PropertyMetadata(0, new PropertyChangedCallback(ValueChanged)));
    
           private static void ValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
           {
    
           }
    
    #endregion

    VB.NET

    #Region "Dependency Properties"
    
        Public Property Minimum()
            Get
                Return GetValue(MinimumProperty)
            End Get
            Set(ByVal value)
                SetValue(MinimumProperty, value)
            End Set
        End Property
    
        Public Shared MinimumProperty As DependencyProperty = _
        DependencyProperty.Register("Minimum", GetType(Integer), GetType(NumericBox), _
                                New PropertyMetadata(0, New PropertyChangedCallback(AddressOf MinimumValueChanged)))
    
        Private Shared Sub MinimumValueChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    
        End Sub
    
        Public Property Maximum()
            Get
                Return GetValue(MaximumProperty)
            End Get
            Set(ByVal value)
                SetValue(MaximumProperty, value)
            End Set
        End Property
    
        Public Shared MaximumProperty As DependencyProperty = _
        DependencyProperty.Register("Maximum", GetType(Integer), GetType(NumericBox), _
                                    New PropertyMetadata(10, New PropertyChangedCallback(AddressOf MaximumValueChanged)))
    
        Private Shared Sub MaximumValueChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    
        End Sub
    
        Public Property Value()
            Get
                Return GetValue(ValueProperty)
            End Get
            Set(ByVal value)
                SetValue(ValueProperty, value)
            End Set
        End Property
    
        Public Shared ValueProperty As DependencyProperty = _
        DependencyProperty.Register("Value", GetType(Integer), GetType(NumericBox), _
                                    New PropertyMetadata(0, New PropertyChangedCallback(AddressOf ValueChanged)))
    
        Private Shared Sub ValueChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    
    
        End Sub
    
    #End Region

    Now we have three Dependency Properties exposed, we are setting the default values here but its a good practice to also set them in Style, so we'll go to generic.xaml (after compiling the project) and add a reference to current assembly and then add them to the style.

    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
        xmlns:local="clr-namespace:Controls.NumericUpDown;assembly=Controls.NumericUpDown">
        
            <Style TargetType="local:NumericBox">
                <Setter Property="Minimum"  Value="0"/>
                <Setter Property="Maximum" Value="10"/>
                <Setter Property="Value" Value="0"/>
            </Style>
    </ResourceDictionary>
        

    Now that you understand how to expose properties, we'll first finish the job with Dependency Properties by validating the values.

    C#

    private static void MinimumChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        NumericBox NB = sender as NumericBox;
    
        int val = (int)e.NewValue;
    
        if (NB == null)
            return;
    
        if (val > NB.Maximum)
            NB.Minimum = (int)e.OldValue;
    
        if (NB.Value < val)
            NB.Value = val;
    }
    
    private static void MaximumChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        NumericBox NB = sender as NumericBox;
    
        int val = (int)e.NewValue;
    
        if (NB == null)
            return;
    
        if (val < NB.Minimum)
            NB.Maximum = (int)e.OldValue;
    }
    
    private static void ValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        NumericBox NB = sender as NumericBox;
        int val = (int)e.NewValue;
        if (NB == null)
            return;
    
        if (val < NB.Minimum)
        {
            NB.Value = NB.Minimum;
            NB._ValueChanged = false;
            return;
        }
    
        if (val > NB.Maximum)
        {
            NB.Value = NB.Maximum;
            NB._ValueChanged = false;
            return;
        }
        NB._ValueChanged = true;    
    }

    VB.NET

    Private Shared Sub MinimumValueChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    
        Dim NB As NumericBox = CType(sender, NumericBox)
        Dim Val As Integer = CType(e.NewValue, Integer)
    
        If NB Is Nothing Then Return
    
        If Val >= NB.Maximum Then NB.Minimum = CType(e.OldValue, Integer)
    
        If Val > NB.Value Then NB.Value = Val
    
    End Sub
    
    Private Shared Sub MaximumValueChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    
        Dim NB As NumericBox = CType(sender, NumericBox)
        Dim Val As Integer = CType(e.NewValue, Integer)
    
        If NB Is Nothing Then Return
    
        If Val <= NB.Minimum Then NB.Maximum = CType(e.OldValue, Integer)
    
        If Val < NB.Value Then NB.Value = Val
    
    End Sub
    
    Private Shared Sub ValueChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    
        Dim NB As NumericBox = CType(sender, NumericBox)
        Dim Val As Integer = CType(e.NewValue, Integer)
    
        If NB Is Nothing Then Return
    
        If Val < NB.Minimum Then
            NB.Value = NB.Minimum
            NB._ValueUpdated = False
            Return
        End If
    
        If Val > NB.Maximum Then
            NB.Value = NB.Maximum
            NB._ValueUpdated = False
            Return
        End If
    
        NB._ValueUpdated = True
    End Sub

    Now that basic logic is in place we'll finish with the basic structure, for this we need to define template in generic.xaml to provide the building blocks of the control (i.e., the look and feel of the control).

    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
        xmlns:local="clr-namespace:Controls.NumericUpDown;assembly=Controls.NumericUpDown">
        
            <Style TargetType="local:NumericBox">
                <Setter Property="Minimum"  Value="0"/>
                <Setter Property="Maximum" Value="10"/>
                <Setter Property="Value" Value="1"/>
                <Setter Property="Template">
                    <Setter.Value>
                      <ControlTemplate TargetType="local:NumericBox">
                           <Grid>
                              <Grid.ColumnDefinitions>
                                  <ColumnDefinition Width="3*"/>
                                   <ColumnDefinition Width="*"/>
                               </Grid.ColumnDefinitions>
                             <TextBox x:Name="NumericTextBox"  Grid.Column="0" Grid.ColumnSpan="2" IsTabStop="True"
                                      IsEnabled="{TemplateBinding IsEnabled}" 
                                      Foreground="{TemplateBinding Foreground}"
                                      Background="{TemplateBinding Background}"
                                      Visibility="{TemplateBinding Visibility}"
                                      Text="{TemplateBinding Value}"
                                      />
                             <Grid Grid.Column="1">
                                 <Grid.RowDefinitions>
                                     <RowDefinition/>
                                     <RowDefinition/>
                                 </Grid.RowDefinitions>
                                 <Button x:Name="ValUp" Grid.Row="0" Margin="0,1,1,0" IsTabStop="False"
                                      IsEnabled="{TemplateBinding IsEnabled}"
                                      Background="{TemplateBinding Background}"
                                      Visibility="{TemplateBinding Visibility}"
                                      >
                                     <Path Fill="{TemplateBinding Foreground}" 
                                           Data="F1 M 4.81721,-3.05176e-005L 9.63441,8.3436L 2.49481e-006,8.3436L 4.81721,-3.05176e-005 Z "/>
                                 </Button>
                                 <Button x:Name="ValDown" Grid.Row="1" Margin="0,0,1,1" IsTabStop="False"
                                         IsEnabled="{TemplateBinding IsEnabled}"
                                         Background="{TemplateBinding Background}"
                                         Visibility="{TemplateBinding Visibility}"
                                         >
                                     <Path Fill="{TemplateBinding Foreground}" 
                                           Data="F1 M 4.81721,8.34363L 9.63441,0L 2.49481e-006,0L 4.81721,8.34363 Z "/>
                                 </Button>
                             </Grid>
                         </Grid>
                        </ControlTemplate>
                 </Setter.Value>
            </Setter>
        </Style>
    </ResourceDictionary>
       

    Note that we have binded all external properties to both the TextBox or Buttons, and pay attention that the Buttons and the TextBox have names, we use these names in our control class to access these objects to access events associated with them, if for some reason the names in the control templates change (user defined template/Skinned template), the whole control will fall apart, and there is no simple way to deal with it (we can deal with this by accessing the root element and checking its children, but that is a different story)

    Now we have to access four events, TextBox.TextChanged, TextBox.KeyDown, ButtonUp.Click and ButtonDown.Click to do this we'll overload/override "OnApplyTemplate" Method, it has to be noted that you can't access the template from constructor, even though we set the DefaultKeyStyle in constructor so the only way to safely access the objects and capture events is to do it when the template is applied, you can get a child from the template using "GetTemplateChild" method.

    C#

    private TextBox TBxNum;
    private Button ButUp;
    private Button ButDw;
    
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    
        TBxNum = base.GetTemplateChild("NumericTextBox") as TextBox;
        ButUp = base.GetTemplateChild("ValUp") as Button;
        ButDw = base.GetTemplateChild("ValDown") as Button;
    
        if (TBxNum == null)
            return;
    
        if (ButUp == null)
            return;
    
        if (ButDw == null)
            return;
    
        TBxNum.TextChanged += new TextChangedEventHandler(TBxNum_TextChanged);
        TBxNum.KeyDown += new KeyEventHandler(TBxNum_KeyDown);
        ButUp.Click += new RoutedEventHandler(ButUp_Click);
        ButDw.Click += new RoutedEventHandler(ButDw_Click);
    }

    VB.NET

    Private TBxNum As TextBox
    Private ButUp As Button
    Private ButDw As Button
    
    
    Public Overloads Overrides Sub OnApplyTemplate()
        MyBase.OnApplyTemplate()
    
        TBxNum = CType(MyBase.GetTemplateChild("NumericTextBox"), TextBox)
        ButUp = CType(MyBase.GetTemplateChild("ValUp"), Button)
        ButDw = CType(MyBase.GetTemplateChild("ValDown"), Button)
    
        If TBxNum Is Nothing Then Return
    
        If ButUp Is Nothing Then Return
    
        If ButDw Is Nothing Then Return
    
        AddHandler TBxNum.TextChanged, AddressOf TBxNum_TextChanged
        AddHandler TBxNum.KeyDown, AddressOf TBxNum_KeyDown
        AddHandler ButUp.Click, AddressOf ButUp_Click
        AddHandler ButDw.Click, AddressOf ButDw_Click
    End Sub

    We need to capture Button.Click events to Up/Down the Value, but we are defining TextBox.KeyDown event to restrict the entry of non-numeric keys in the text box, and we'll update Value when the Value is typed in the TextBox, thats why we are capturing the TextBox.TextChanged Event, although we are already restricting the keyboard entry I still prefer to check if the Value entered in the TextBox is a number, and we can update the Value in one procedure.

    C#

    void TBxNum_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (Single.IsNaN(System.Convert.ToSingle(TBxNum.Text)))
            throw new NotFiniteNumberException(TBxNum.Text);
        else
           UpdateValue((int)System.Convert.ToInt64(TBxNum.Text));
    }
    
    void TBxNum_KeyDown(object sender, KeyEventArgs e)
    {
        if (((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Back))
            e.Handled = false;
        else
        {
            e.Handled = true;
        }
    }
    
    void ButUp_Click(object sender, RoutedEventArgs e)
    {
        UpdateValue(Value + 1);
    }
    
    void ButDw_Click(object sender, RoutedEventArgs e)
    {
        UpdateValue(Value - 1);
    }
    
    void UpdateValue(int val)
    {
        _ValueChanged  = false;
        Value=int;
        if(_ValueChanged) 
        {
            TBxNum.Text = Value.ToString();
        }
    }

    VB.NET

    Private Sub TBxNum_TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)
        If (Single.IsNaN(System.Convert.ToSingle(TBxNum.Text))) Then
            Throw New NotFiniteNumberException(TBxNum.Text)
        Else
            UpdateValue(CType(TBxNum.Text, Integer))
        End If
    End Sub
    
    Private Sub TBxNum_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
        If ((e.Key >= Key.D0 And e.Key <= Key.D9) OrElse (e.Key >= Key.NumPad0 And e.Key <= Key.NumPad9) _
            OrElse e.Key = Key.Back) Then e.Handled = False Else e.Handled = True
    End Sub
    
    Private Sub ButUp_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        UpdateValue(Value + 1)
    End Sub
    
    Private Sub ButDw_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        UpdateValue(Value - 1)
    End Sub
    
    Private Sub UpdateValue(ByVal val As Integer)
        _ValueUpdated = False
        Value = val
        If _ValueUpdated Then
            TBxNum.Text = val
        End If
    End Sub

    Now the control is up and ready for testing(don't forget to add reference to this assembly), you can make any changes to the source code as you see it fit, the only thing left is to raise an event when the value changes in case anyone is listening. For this we'll build a custom EventArgs to pass the changed value.

    So add another file in the folder and name it "NumericBoxChangedArgs.cs" or "NumericBoxChangedArgs.vb"  as shown below.

    2008-10-26_092756

    Now, the NumericBoxChangedArgs class inheirts EventArgs and have a readonly property and a constructor to set the Value changed, it also have a delegate event handler with NumbericBoxChangedArgs signature.

    C#

    public delegate NumericBoxChangedHandler(object sender, NumericBoxChangedArgs e);
    
    public class NumericBoxChangedArgs : EventArgs
    {
        private readonly int _Value;
    
        public NumericBoxChangedArgs(int val)
        {
            _Value = val;
        }
    
        public int Value
        {
            get
            {
                return _Value;
            }
        }
    }

    VB.NET

    Namespace NumericUpDown
        Public Delegate Sub NumericBoxChangedHandler(ByVal sender As Object, ByVal e As NumericBoxChangedArgs)
    
        Public Class NumericBoxChangedArgs
            Inherits EventArgs
    
            Private ReadOnly _val As Integer
    
            Public Sub New(ByVal val As Integer)
                _val = val
            End Sub
    
            Public ReadOnly Property Value() As Integer
                Get
                    Return _val
                End Get
            End Property
    
        End Class
    End Namespace

    Now we just declare the delegate locally and raise event in it in UpdateValue procedure.

    C#

    public event NumericBoxChangedHandler NumericBoxChanged;
    
    void UpdateValue(int val)
    {
        _ValueChanged  = false;
        Value=int;
        if(_ValueChanged) 
        {
            TBxNum.Text = Value.ToString();
            NumericBoxChangedArgs NArgs = new NumericBoxChangedArgs(Value);
            NumericBoxChanged(this, NArgs);
        }
    }

    VB.NET

    Public Event NumericBoxChanged As NumericBoxChangedHandler
    
    Private Sub UpdateValue(ByVal val As Integer)
        _ValueUpdated = False
        Value = val
        If _ValueUpdated Then
            TBxNum.Text = Value
            Dim NArgs As New NumericBoxChangedArgs(Value)
            RaiseEvent NumericBoxChanged(Me, NArgs)
        End If
    End Sub

    All the points mentioned while preparing the control are now achieved (I have added couple of more Dependency Properties to the source code (IncrementStep, IncrementOnly). Our Custom Numeric Up/Down Box is now complete, you can download the source code for this custom control below, if you make any modifications to the source code, please let me know.

    Licence

    Creative Commons License
    Silverlight NumericUpDown Control by Imran Shaik is licensed under a Creative Commons Attribution-Non-Commercial-Share Alike 2.0 UK: England & Wales License.
    Based on a work at www.geekswithblogs.net.

    Download Source Code/Binary

    Version 1.0 (Both VB.NET & C#)

    March 11

    Nine Silverlight 2 Features Not to Be Missed

    Reference: http://www.devx.com/RIA/Article/37982/7184

    Buttons and DataGrids get all the press, but Microsoft Silverlight 2 Beta 1 has more than new controls. Here are nine less-visible, "long-tail" technologies in the current beta, one of which may be the key to your next Silverlight application. 

    by Steve Apiki
    May 21, 2008

    Everybody likes buttons—everybody needs buttons—so it's not surprising that the premier of buttons and other visual controls in Microsoft® Silverlight™ 2.0 Beta 1 was the subject of headlines. Not everybody's Silverlight application will need to manipulate the DOM, or use local storage, or fetch data from a web service. But if you're building such an application, you may be more excited about these and other critical, but less visible, technologies in Beta 1. In this article we'll get right into nine Silverlight 2 Beta 1 technologies that belong in every developer's bag of tricks. Then we'll zoom in a little closer with a demo application that's built on a sampling of these features.

    1. HTML DOM Integration
    For Silverlight applications that are deployed as a control or element of a larger Ajax application, tight integration between Silverlight and the HTML DOM means no bump between Silverlight and its hosting page, and a better user experience. The number one use case for DOM integration before Beta 1 may well have been gaining access to HTML controls, but now that we've got Silverlight native equivalents we can move on to enhance page integration.

    In Beta 1, you can do virtually everything related to the DOM from managed code. You can:

    • Manipulate elements in the DOM from .NET code
    • Install C# event handlers for DOM events
    • Call JavaScript functions in the hosting page
    • Have JavaScript functions in the hosting page call you

    The key to making this work is the HtmlPage class in System.Windows.Browser. HtmlPage has a Document member that you can use to get access to DOM elements using functions such as GetElementById(). Once you've got the element, you can set its attributes or hook in events using the HtmlElement.AttachEvent() API.

    2. JSON Serialization
    Silverlight 2 Beta 1 applications can use the new .NET 3.5 DataContractJsonSerializer to serialize .NET objects to JSON. In our example project, below, we'll use this class to serialize our object for local storage. Since the representation is JSON, you can also use this technology to deserialize JSON strings from a web server or web service into C# objects on the client.

    As we'll see in the sample, you need to set DataContract and DataMember attributes to mark a class as serializable and call out the members to be serialized (and optionally set the serialization name). These attributes give you control over how your object is serialized, allowing you, for example, to safely serialize a class that contains both an encrypted string (serialize) and its decrypted representation (don't serialize).

    3. Styles and Templates
    In the Silverlight control model there's complete separation between control functionality and control appearance. The only thing that's intrinsic about a button is its functionality; that is, it fires a click event when clicked. The appearance of the button and how that appearance changes for various states can be lightly or fully customized using Styles and ControlTemplates. It's important that these customizations are expressed and applied in XAML, not in code, keeping them in the realm of the designer and not the developer.

    Styles are set through Style resources that are targeted at specific control types and allow you to control the visible properties of that type:

    <Style TargetType="TextBlock" x:Key="TextBlockStyle">
                < Setter Property="FontSize" Value="12"/>
                <Setter Property="Margin" Value="5"/>
            </Style>

    You can then apply the style ("TextBlockStyle") to TextBlocks within the application.

    Templates provide much deeper customization, giving you control over the XAML that defines the control's visible content. We can't go into any depth on control templates here, but Scott Guthrie's blog entry on the topic is a great place to learn more.

    4. Local Storage
    Isolated Storage gives your Silverlight application access to storage resources on the client. It's "isolated" because the store is partitioned per application, meaning no other applications can access files in your storage. On the other hand, your application (application defined by its URL) always gets the same storage, even if it's run in a different browser.

    Prior to Beta 1, Silverlight local storage was cleared along with the browser cache. In Beta 1, local storage is independent of the cache, but the virtual file system presented by Isolated Storage still lives in the user's file system and can be deleted at any time. That makes local storage suitable for application settings, for caching, and for other locally-relevant but expendable data.

    Beta 1 also lowers the per-domain quota of local storage to 100 KB (down from 1 MB). However, you can now ask the user for permission to increase your quota (the user can still say no) using the TryIncreaseQuotaTo() API.

    5. Databinding
    Silverlight now supports two-way, one-way, and one-time databinding between visible controls and classes in code that represent application logic. One-way and one-time databinding are for read-only controls. Two way databinding lets the user make changes that automatically update classes in the model. You can also bind visual controls to static XAML resources, and indirectly to other visual controls, but I'll focus on making the binding in C# code here.

    In XAML, you mark a control property for binding like so:

    <TextBox x:Name="FontFamily" Text="{Binding FontFamily, Mode=TwoWay}"
    Style="{StaticResource TextBoxStyle}" Grid.Row="0" Grid.Column="1"/>

    This statement links the Text property of the FontFamily TextBox to an object's FontFamily member.

    To be used for binding, an object must implement INotifyPropertyChanged:

    public class Prefs : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged; 

    And then you can bind an instance of Prefs to the textbox by setting the textbox's DataContext to that instance:

    FontFamily.DataContext = prefs; 

    We'll explore this a little further in the sample application later in the article.

    6. Generics
    One of the best parts of Silverlight 2 development is access to a substantial subset of the .NET 3.5 Framework and the CLR. The CLR supports generics, classes and methods that are written to work with types that aren't known until runtime. Generics allow you to write flexible classes and methods without losing the benefits of strong typing.

    The most obvious application of generics is generic collection classes, where a common collection class (e.g., List) can be used to hold items of different types. The Silverlight .NET framework includes a full complement of generic collection classes that you can use in your applications.

    7. ItemsControls
    An ItemsControl is a UI element that displays a list of data objects. Doesn't sound like much, but the power of the ItemsControl is the flexibility that this simple mission provides. The ItemsControl can display the items of any enumerable collection, and it can display it in any fashion you like, all set up through the declarative magic of templates.

    Generally, you'll use an ItemsControl by setting its ItemsSource property to a collection of objects that you manage in code. A simple way to control how each item looks is to set the ItemsControl's DisplayMemberPath to the item property to display. But for complete customization, you can instead set the ItemControl's ItemTemplate property to a DataTemplate resource. The DataTemplate functions much like a ControlTemplate, but instead of being applied to a control the DataTemplate is instead bound to each item in the collection for display:

    <DataTemplate x:Key="ItemsControlDataTemplate">
                <TextBlock Text="{Binding TextMember}"/>
            </DataTemplate >

    In addition to templating each data item, you can also supply an ItemsPanelTemplate which defines the item layout in the ItemControl.

    8. Layout Management
    Along with its new controls, Beta 1 provides flexible layout management derived from the layout management system of WPF. To position controls within your application, you use one of three types of layout controls:

    • Canvas: Provides absolute positioning and controls don't change position with changes in container size.
    • StackPanel: Stacks controls in a single column or row, vertically or horizontally, and sets control position based on container size.
    • Grid: A tabular layout. Container position is specified according to row and column within the grid.

    In the sample application below, we used a Grid panel as the container for the TextBoxes and other controls.

    9. WebClient
    Silverlight applications can consume data from REST web services using the WebClient object. In fact, if you want to get media as a stream or need to process plain text or xml data, WebClient is your best choice as it can get anything you need from a web server. The coolest thing about WebClient is that it can operate asynchronously, pulling down data in the background without blocking the UI thread. When the download is complete, WebClient fires an event to let you know that the data is available.

    Putting It in Practice
    Now it is time to see some of these technologies in action. I built an example "HTML font preferences" application that lets you make some minor tweaks to the DOM of its containing page, and then uses isolated storage to persist those tweaks between browser runs. Along the way, this example also makes use of JSON serialization, control styles, grid layouts, and two-way databinding.

    Figure 1. The sample Silverlight application sits at the top of an HTML page and lets you make changes to the body font that persist between runs.

    The font prefs application is hosted at the top of a web page, the rest of which is filled with sample text and images. It includes two text box controls and a check box that let you specify some font attributes. When you click the "Apply" button, those font style attributes are applied to the HTML body. When you click "Save," the font family, font size, and font weight preferences are serialized and saved to isolated storage. From that point on, the page uses the specified styles whenever it's loaded.

    Figure 2. The font prefs application up close.

    With a Silverlight project, Visual Studio automatically generates a test HTML page to host your Silverlight control for debugging. I used a copy of that generated HTML as a starting point for my page. Then I moved the container for the Silverlight control to the top of the page and added some test content to the body. Finally, I added the HTML host page to the project and set up Visual Studio to launch that page rather than the one it generates.

    For our sample, we want to store the user's preferences for font family, font size, and font weight. We'll get those from the user using three controls, two TextBoxes and one CheckBox. We define these controls, along with the Apply and Save buttons, in the application's main XAML file, Page.xaml. Here is the first TextBlock and TextBox pair, used for Font Family:

    <TextBlock x:Name="FontFamilyLabel" Text="Font Family" Style="{StaticResource
    TextBlockStyle}" Grid.Row="0" Grid.Column="0"/>
    <TextBox x:Name="FontFamily" Text="{Binding FontFamily, Mode=TwoWay}"
    Style="{StaticResource TextBoxStyle}" Grid.Row="0" Grid.Column="1"/>

    There are a few items to note in this little snippet. First, all of these items are contained within a grid layout panel, and we've set the position for our controls using the Grid.Row and Grid.Column attributes. Second, we've applied separate style resources to the TextBlock and TextBox. These styles set FontSize and Margin properties, and are defined at the application level (in app.xaml) so they can be made available to all controls.

    <Application.Resources>
            <Style TargetType="TextBox" x:Key="TextBoxStyle">
                <Setter Property="FontSize" Value="12"/>
                <Setter Property="Margin" Value="5"/>
            </Style>
            <Style TargetType="TextBlock" x:Key="TextBlockStyle">
                <Setter Property="FontSize" Value="12"/>
                <Setter Property="Margin" Value="5"/>
            </Style>
        </Application.Resources>

    Finally, we've prepared the TextBox for databinding by specifying that its Text property will be bound to the FontFamily property of the object we'll use for a data context. We've specified two-way binding because we need the user to be able to modify our preferences object (the default binding mode is OneWay).

    Now we need to build that preferences object. This will be an instance of a class that has the data properties we need (FontFamily, FontSize, and Bold) and which implements INotifyPropertyChanged. Here is the Prefs class, with only one member property shown for clarity:

    public class Prefs : INotifyPropertyChanged
        {
            public string FontFamily
            {
                Get { return _fontFamily; }
                set
                {
                    _fontFamily = value;
                    OnPropertyChanged("FontFamily");
                }
            }
            private string _fontFamily = "Times";
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected virtual void OnPropertyChanged(string propertyName)
            {
               If (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }

    When FontFamily is set, it fires a PropertyChanged event which notifies bound controls of the change.

    Now we have to hook up the prefs object with the controls. This is done by setting the DataContext for these controls to our prefs instance. Because DataContexts are inherited, we can set the DataContext of the containing grid instead of setting it for each control:

    LayoutRoot.DataContext = prefs; 

    This binds all of the controls within the LayoutRoot grid to our prefs object.

    When the user clicks the Apply button, we want to take the font style information in our prefs object and apply it to the DOM of the containing HTML page. The HtmlPage object makes this pretty simple. Here is the ApplyPrefs function that is called when the button is clicked (from Page.xaml):

    private void ApplyPrefs()
        {
            HtmlElement body = HtmlPage.Document.GetElementsByTagName("body")[0];
    
            body.SetStyleAttribute("fontFamily", prefs.FontFamily);
            body.SetStyleAttribute("fontSize", prefs.FontSize);
            body.SetStyleAttribute("fontWeight", prefs.Bold ? "bold" : "normal");
        }

    We find the body element using GetElementsByTagName and then apply the styles to the element using SetStyleAttribute.

    When the user clicks the Save button, we'll use what we've learned about JSON serialization and local storage to persist these preferences to a file on the client. Recall that we can't serialize the Prefs calls using the data contract serializer until we set the data contract attributes. The Prefs class itself gets a DataContract attribute, and each property that we want to serialize gets a DataMember attribute:

     [DataContract]
        public class Prefs : INotifyPropertyChanged
        {
            [DataMember]
            public string FontFamily
    Now we're ready to take a look at the function we use to actually store the prefs object.
    private void StorePrefs()
        {
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream stream = file.CreateFile(storageLocation);
    
            DataContractJsonSerializer serializer = new 
    DataContractJsonSerializer(typeof(Prefs));
            serializer.WriteObject(stream, prefs);
    
            stream.Flush();
            stream.Close();
        }

    Here, storageLocation is a string, the name of the file we want to create in the isolated storage file system. We create the file, and then use the DataContractJsonSerializer to serialize the object as JSON to the file stream.

    Finally, we'll add a little more to Page_Loaded so that the HTML page gets the last saved font style every time you load the page:

    void Page_Loaded(object sender, RoutedEventArgs e)
        {
            LoadPrefs();
            ApplyPrefs();
    
            LayoutRoot.DataContext = prefs;
        }

    LoadPrefs() is the counterpart to StorePrefs, a member function that deserializes the prefs object from local storage.

    The nine technologies we've seen here may not make many headlines, but they help to make Silverlight an increasingly rich and functional client platform. Some, like layout panels, will be used in every Silverlight app. Others, like WebClient, may be less frequently used, but when you need it, there's no substitute. Don't forget these features as you build your next Silverlight application.

    February 11

    Using the GridSplitter control with Silverlight 2

    Reference: http://www.dotnetcurry.com/ShowArticle.aspx?ID=223&AspxAutoDetectCookieSupport=1

        In web applications, we often come across a requirement where we have to resize and redistribute space in our controls container. In such cases GridSplitter is a very useful control.

    GridSplitter is a control which allows us to change space between rows and columns of a Silverlight Grid Control at runtime. Using this control, we can change the Height and Width of the Grid rows and columns at run time. That means we will also be able to resize controls in specific cells of that Grid.

    The controls can be resized both horizontally as well as vertically. To do so, we have to set the Horizontal Alignment and Vertical alignment property of the GridSplitter. This control can be used to show several windows which are split and that can be resized to view the content.

    The Grid control is required for using Grid splitter.

    In this sample we will place two splitter controls on a Page, one horizontally and the other vertically. We will then place some controls inside different cells of the Grid so that we can demonstrate what happens when we resize rows/columns using the GridSplitter Control. We will also see a few properties of the Splitter Control.

    Step 1: Open Visual Studio 2008 > File > New Project > Select the language (C# or VB.NET) > Select ‘Silverlight’ in the Project Types > from the templates, select ‘Silverlight Application’.

    Step 2: Type a name (GridSplitterSample) and location for the project and click ok (see Figure below). Choose the first option ‘Add a new Web to the solution for hosting the control’ and the project type as ‘Web Site’ and click OK. You will see that two projects are created: GridSplitterSampleWeb and GridSplitterSample.

    New Project

    Step 3: Add a Xaml Reference to System.Windows.Controls assembly. This assembly is required for referring to the GridSplitter Control. Also note that the width and height is not set on the UserControl.

    <UserControl x:Class="GridSplitterSample.Page"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:basics="clr-namespace:System.Windows.Controls;

    assembly=System.Windows.Controls">

    In order to add a System.Windows.Controls reference to your project, in your Solution Explorer right click ‘References’ in the GridSplitterSample project > Add Reference > Choose ‘System.Windows.Controls’ from the .NET tab.

    Note: In Silverlight Beta 2 the splitter was in System.Windows.Controls.Extended assembly. In the final release, it is now in the System.Windows.Controls assembly as System.Windows.Controls.Extended.dll was renamed to System.Windows.Controls.dll.

    Step 4: Now add 5 Rows and 5 Columns to Grid. Remember that a Grid is required for using GridSplitter Control.

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

    <Grid.RowDefinitions>

    <RowDefinition  Height="200"/>

    <RowDefinition Height="200"/>

    <RowDefinition Height="200"/>

    <RowDefinition Height="200"/>

    <RowDefinition Height="200"/>

    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>

    <ColumnDefinition Width="180"/>

    <ColumnDefinition Width="180"/>

    <ColumnDefinition Width="180"/>

    <ColumnDefinition Width="180"/>

    <ColumnDefinition Width="180"/>

    </Grid.ColumnDefinitions>

    </Grid>

    Step 5: We will now add 2 GridSplitter controls; one for horizontal splitting and one for vertical splitting.

    ... </Grid.ColumnDefinitions>

    <basics:GridSplitter  Height="200" Grid.Row="0" Grid.Column="3"  VerticalAlignment="Stretch" HorizontalAlignment="Left" Background="Coral" Width="5">

    </basics:GridSplitter>

    <basics:GridSplitter  Background="BlanchedAlmond"  Width="1400" Grid.Row="1" Grid.ColumnSpan="5"  VerticalAlignment="Top" HorizontalAlignment="Stretch" Height="5">

    </basics:GridSplitter>

    Here in the 1st Splitter, we are setting the Grid.Row = 0 and Grid.Column = 3 which means that our Splitter will be in the 3rd Column and 0th row. In the second splitter, we set the Grid.ColumnSpan as 5, i.e. the splitter will span 5 columns and will take space of 5 Columns (very similar to the Html tables colSpan property).

    Note: In both the Splitters we are setting the VerticalAlignment and HorizontalAlignment property, which decides whether we will resize the Column or Row. If the VerticalAlignment property = Stretch, it will resize the column. If the HorizontalAlignment property = Stretch it will resize the row.

    We have set Height and Width, otherwise by default it will be 0 Height and 0 Width.

    Grid Splitter

    Step 6: We will now add a few visual elements and will place them in different rows and columns of the Grid in order to see the GridSplitter effect.

    The entire markup after adding the visual elements will look like this:

    <UserControl x:Class="GridSplitterSample.Page"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls">

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

    <Grid.RowDefinitions>

    <RowDefinition  Height="200"/>

    <RowDefinition Height="200"/>

    <RowDefinition Height="200"/>

    <RowDefinition Height="200"/>

    <RowDefinition Height="200"/>

    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>

    <ColumnDefinition Width="180"/>

    <ColumnDefinition Width="180"/>

    <ColumnDefinition Width="180"/>

    <ColumnDefinition Width="180"/>

    <ColumnDefinition Width="180"/>

    </Grid.ColumnDefinitions>

    <basics:GridSplitter  Height="200" Grid.Row="0" Grid.Column="3"  VerticalAlignment="Stretch" HorizontalAlignment="Left" Background="Coral" Width="5">

    </basics:GridSplitter>

    <basics:GridSplitter  Background="BlanchedAlmond"  Width="1400" Grid.Row="1" Grid.ColumnSpan="5"  VerticalAlignment="Top" HorizontalAlignment="Stretch" Height="5">

    </basics:GridSplitter>

    <Rectangle Height="100" Fill="Aqua" Grid.Row="0" Grid.Column="0"></Rectangle>

    <Rectangle Height="70" Width="75" Fill="DarkBlue" Grid.Row="1" Grid.Column="2"></Rectangle>

    <Rectangle Height="70" Fill="AliceBlue" Grid.Row="1" Grid.Column="1"></Rectangle>

    <Ellipse Height="100" Width="100" Grid.Row="0" Grid.Column="2" Fill="Beige"></Ellipse>

    <Ellipse Height="100" Width="100" Grid.Row="0" Grid.Column="3" Fill="CadetBlue" Margin="0,0,0,0"></Ellipse>

    </Grid>

    </UserControl>

    Grid Splitter

    Once you run the application now, you will find that you can resize the rows and columns. A sample resizing would look similar to the following:

    Grid Splitter

    We can see that without writing a single line of code, we could easily resize columns and rows of Grid Control.

    How do I add a Silverlight GridSplitter Programmatically?

    If you need to add a GridSplitter programmatically, use this code. The code adds a vertical splitter.

    C#

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Net;

    using System.Windows;

    using System.Windows.Controls;

    using System.Windows.Documents;

    using System.Windows.Input;

    using System.Windows.Media;

    using System.Windows.Media.Animation;

    using System.Windows.Shapes;

    namespace GridSplitterSample

    {

    public partial class Page : UserControl

        {

    public Page()

            {

                InitializeComponent();

    GridSplitter grdSplitter = new GridSplitter();

                grdSplitter.Background = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));

                grdSplitter.Width = 5;

                grdSplitter.Height = 200;

                grdSplitter.VerticalAlignment = VerticalAlignment.Stretch;

                LayoutRoot.Children.Add(grdSplitter);

    //Setting Column and Row attached Property

                grdSplitter.SetValue(Grid.RowProperty, 1);

                grdSplitter.SetValue(Grid.ColumnProperty, 1);

            }

        }

    }

    VB.NET

    Imports System

    Imports System.Collections.Generic

    Imports System.Linq

    Imports System.Net

    Imports System.Windows

    Imports System.Windows.Controls

    Imports System.Windows.Documents

    Imports System.Windows.Input

    Imports System.Windows.Media

    Imports System.Windows.Media.Animation

    Imports System.Windows.Shapes

    Namespace GridSplitterSample

    Partial Public Class Page

    Inherits UserControl

    Public Sub New()

                      InitializeComponent()

    Dim grdSplitter As New GridSplitter()

                      grdSplitter.Background = New SolidColorBrush(Color.FromArgb(255, 0, 0, 0))

                      grdSplitter.Width = 5

                      grdSplitter.Height = 200

                      grdSplitter.VerticalAlignment = VerticalAlignment.Stretch

                      LayoutRoot.Children.Add(grdSplitter)

    'Setting Column and Row attached Property

                      grdSplitter.SetValue(Grid.RowProperty, 1)

                      grdSplitter.SetValue(Grid.ColumnProperty, 1)

    End Sub

    End Class

    End Namespace

    Grid Splitter

    References:

    http://msdn.microsoft.com/en-us/library/system.windows.controls.gridsplitter(VS.95).aspx

    http://msdn.microsoft.com/en-us/library/cc278070(VS.95).aspx

    So that was the GridSplitter control for you. Run the sample and experience how you can use the GridSplitter to redistribute space. I hope this article was useful and I thank you for viewing it.

    If you liked the article, Subscribe to the RSS Feed.

    Harsh Bardhan (MCTS) has developed IT solutions with a diverse background in server side and client side development. He is currently working with SymphonyServices as a Software developer. Harsh continues to be an integral part of open forums on cutting-edge technology like Silverlight, including the .NET Framework and Web Services. Harsh has expertise with many Microsoft technologies, including .NET, LINQ, WCF Service, Silverlight and a strong background in SQLServer.

    Similar Posts
    Create a Simple Progress Bar Control In Silverlight 2
    Load and Play a Video File at Runtime using Silverlight 2 Beta 2
    Step By Step - Using Silverlight to Access a WCF Service Hosted In a Console Application
    DataBinding in Silverlight - Change property of a Silverlight UI Control at runtime based on another UI Control
    How to Navigate and Pass Values between Pages using Silverlight 2 Beta 2
    Selecting and Displaying Images and Text Files from a Client Machine using Silverlight 2
    Load and Play Media Files at Runtime using Silverlight 2

    February 08

    Chapter 10 — Improving Web Services Performance

    Reference: http://msdn.microsoft.com/en-us/library/ms998562.aspx

    Improving .NET Application Performance and Scalability

    J.D. Meier, Srinath Vasireddy, Ashish Babbar, and Alex Mackman
    Microsoft Corporation

    May 2004

    Summary: This chapter focuses on design guidelines and techniques, such as state management, asynchronous invocation, serialization, threading, to help you develop efficient Web services. This chapter also presents a formula for reducing thread contention and HTTP connections to increase the throughput for your Web services.

    Contents

    Objectives
    Overview
    How to Use This Chapter
    Architecture
    Prescriptive Guidance for Web Services, Enterprise Services, and .NET Remoting
    Performance and Scalability Issues
    Design Considerations
    Implementation Considerations
    Connections
    Threading
    One-Way (Fire-and-Forget) Communication
    Asynchronous Web Methods
    Asynchronous Invocation
    Timeouts
    WebMethods
    Serialization
    Caching
    State Management
    Bulk Data Transfer
    Attachments
    COM Interop
    Measuring and Analyzing Web Services Performance
    Web Service Enhancements
    Summary
    Additional Resources

    Objectives

    • Identify top Web services performance issues.
    • Design scalable Web services that meet your performance objectives.
    • Improve serialization performance.
    • Configure the HTTP runtime for optimum performance.
    • Improve threading efficiency.
    • Evaluate and choose the most appropriate caching mechanism.
    • Decide when to maintain state.
    • Evaluate and choose the most appropriate bulk data transfer mechanism.

    Overview

    Services are the ideal communication medium for distributed applications. You should build all of your services using Web services and then, if necessary, use Enterprise Services or Microsoft® .NET remoting within the boundaries of your service implementation. For example, you might need to use Enterprise Services for distributed transaction support or object pooling.

    Web services are ideal for cross-platform communication in heterogeneous environments because of their use of open standards such as XML and Simple Object Access Protocol (SOAP). However, even in a closed environment where both client and server systems use the .NET Framework, ease of deployment and maintenance make Web services a very attractive approach.

    This chapter begins by examining the architecture of ASP.NET Web services, and then explains the anatomy of a Web services request from both the client and server-side perspectives. You need a solid understanding of both client and server to help you identify and address typical Web services performance issues. An understanding of Web services architecture will also help you when you configure the HTTP runtime to optimize Web services performance. The chapter then presents a set of important Web services design considerations, followed by a series of sections that address the top Web services performance issues.

    How to Use This Chapter

    To get the most out of this chapter:

    • Jump to topics or read from beginning to end. The main headings in this chapter help you to locate the topics that interest you. Alternatively, you can read the chapter from beginning to end to gain a thorough appreciation of performance and scalability design issues.
    • Use the checklist. Use "Checklist: Web Services Performance" in the "Checklists" section of this guide to quickly view and evaluate the guidelines presented in this chapter.
    • Use the "Architecture" section of this chapter to learn how Web services work. By understanding Web services architecture, you can make better design and implementation choices.
    • Use the "Design Considerations" section of this chapter. This section helps you to understand the higher-level decisions that affect implementation choices for Web services code.
    • Read Chapter 6, "Improving ASP.NET Performance" Many of the performance optimizations described in Chapter 6, "Improving ASP.NET Performance" — such as tuning the thread pool and designing and implementing efficient caching — also apply to ASP.NET Web services development.
    • Read Chapter 13, "Code Review: .NET Application Performance" See the "Web Services" section of Chapter 13 for specific guidance.
    • Measure your application performance. Read the "Web Services" and ".NET Framework Technologies" sections of Chapter 15, "Measuring .NET Application Performance" to learn about key metrics that you can use to measure application performance. It is important that you are able to measure application performance so that you can target performance issues accurately.
    • Test your application performance. Read Chapter 16, "Testing .NET Application Performance" to learn how to apply performance testing to your application. It is important that you apply a coherent testing process and that you are able to analyze the results.
    • Tune your application performance. Read the "Web Services" section of Chapter 17, "Tuning .NET Application Performance" to learn how to resolve performance issues identified through the use of tuning metrics.


    February 06

    BlackBerry được đẻ ra ở TQ như thế nào?=))

    Lấy từ tinhte.com
    Nguồn cội chiếc máy của tôi
    Đợt vừa rồi mình có đi china ngao du chơi. Mình quyết tâm tìm hiểu về BB ở đất nước pro này. Và đc biết như sau:
    + Ở đây họ nhập Main BB rác theo cân từ US
    + Vỏ thì khỏi phải bàn rồi


    Click this bar to view the full image.

    Click the image to open in full size.
    Có vô vàn những cái main kiểu như thế này đc làm lại
    Sau khi nhập xong, họ rửa sạch sẽ, dồn linh kiện sống lại 1 main -> test ok là xong 1 con. Con nào mà chết Flash thì thay 1 con Flash mới có sẵn đầy nhan nhản ở china vào. Họ dùng 1 mạch nạp, chép hết data từ Flash sống có trong main rác sang con mới. Vậy là đc 1 con Flash copy y chang rồi đóng vào thế là đc 1 con máy mới với imei và PIN trùng với con Flash kia.
    Tới đây thì mọi người cũng đã hiểu đc vì sao lại trùng PIN và trùng imei rồi nhé.


    Click this bar to view the full image.

    Click the image to open in full size.


    máy sau khi dựng lại thì có ở khắp nơi
    Riêng nói về phần hộp máy thì họ làm hộp theo 1 style chung mà a c e đã biết. Hoặc họ mua luôn hộp bên us về. Cái hộp giấy đó thật ra cũng chẳng nói lên đc điều j. Click the image to open in full size.
    Về code unlock thì rất hay. Phải nói là china có 1 nền công nghiệp điện tử rất cao và tay nghề, trình độ rất giỏi. Code mà mọi người vẫn gọi là code unlock thì có j đâu. Chỉ là 1 chuỗi mã số đc nhúng sẵn vào Flash để mở máy chứ ko phải là mở mạng. Mạng thì nó vẫn là GSM bt như bao đt khác rồi đâu có bị trói buộc trong 1 band tần số của các nhà cung cấp dịch vụ mạng ở US hay các nước khác nữa. Cái code đó cũng đc làm rất kỹ lưỡng. Cũng có 16 số nhưng đối với mạng của AT&T hay Tmobile. Cái hay là có lẽ họ cũng ko nghĩ tới là mạng khác như:
    - T-mobile us, att: code unlock đều có 16 con con số cho dòng BB
    - dòng HTC, T-mobile Wing, dash, shadow chỉ có 8 con con số
    - Rogers/Fido, T-mobile UK: 8 con số
    - Vodafone UK: 16 con số
    hay các mạng khác nữa hoặc họ cũng biết but chỉ cần code mở là mọi người cũng ko để ý tới và tin là hàng zin nguyên bản. Những cái code đó thì thường chỉ dùng cho đc máy đó thôi và đc đi kèm sẵn. Nếu mình đi mua code khác thì thường là code not found bởi làm j có code cho imei đó mà mua. But có con thì do là Flash trên main mua bên kia về nó vẫn sống thì vẫn đc. Đây gọi là hàng china xịn Click the image to open in full size.
    Cái đó là mua bên China. China cụ thể là Thẩm Quyến còn sell buôn rất hay và tránh đc thuế má nữa. Đó là bán rời main với vỏ ra. Người mình sang mua hoặc nó chuyển sang bằng cách riêng của nó. Rồi mình tự dựng lên 1 con máy mới long lanh chạy phè phè.


    Click this bar to view the full image.

    Click the image to open in full size.


    Một cửa hàng ở china với những tem imei - pin dán la liệt khắp nơi
    Về giá của máy thì bán kiểu j cũng đc hết (rẻ mà) vì thế mà 3tr 6 1 em Cuver 8320 người bán vẫn lời kha khá (cái này tế nhị lắm tớ ko nói đâu Click the image to open in full size.)
    Về chất lượng thì ko dám mạnh mồm. Ai mà chẳng biết nó là cái j đấy Click the image to open in full size.
    Ở HN nói chung thì từ huyenmobile hay quangmobile hay nhiều nhiều cửa hàng BB khác thì 8320 đc bán là 4tr5 - 5tr - 6tr ồ hay 1 cái giá rất chi là.... Click the image to open in full size. con nào mà đc nhúng cái code để mở máy thì sell còn đc giá hơn và dễ hơn Click the image to open in full size.
    Vâng thưa a c e tinhte nói chung. Đó là những j mà mình đc chứng kiến tại china. Ko đc chụp ảnh nên mình ko có ảnh để post. Ngoài BB ra thì PPC hay nokia, SS china ăn cắp đc công nghệ nên họ làm từ a - z luôn. VN mình nhập về qua 1 cty rồi đc chế độ bảo hành từ cty đó. Hơn nữa còn có dịch vụ là làm tem giả. Tem FPT nilong 1000vnd 1 cái. Mua nhiều thì là 800d. Tem giấy thì chỉ có 500d. tem thì có 1 chú người china khoác balo sang vietnam rao tận nơi. Hàng chục tờ kích thước bằng tờ A4 với các loại tem khác nhau. Từ FPT - Petro - Viettel... có đủ cả. Hơn nữa china bảo hành cũng rất hay. Máy có bị sao chỉ cần gửi trả lại nó và nó gửi cho cái máy mới khác. Nó về lại Fix và lại xuất ra. Đơn giản chưa.Click the image to open in full size.
    Hiện nay thì lại còn pro hơn. Đó là có máy chuyên dụng để change PIN code. Cái này đã có ở VN. Cụ thể là có ở HN. Mọi người cứ nghĩ là máy trùng pin thì là hàng clone, hàng dolly. Bây h đem con trùng pin đó đi change PIN code đi thì lại thành ko trùng nữa Click the image to open in full size. ngạc nhiên chưa. Cái PIN code đó khi change thích gõ số j thì gõ Click the image to open in full size. chi phí là 300k cho 1 lần change. Tha hồ mà dùng jive talk reg bằng CC nhá Click the image to open in full size. có bị lock pin thì change pin code đi là lại ok Click the image to open in full size. đặc biệt là ko cần mở máy mới ác liệt chứ Click the image to open in full size. cái này cũng có thể đặt cho máy 1 dãy số để unlock cũng đc đó Click the image to open in full size. Các bác muốn biết địa chỉ cụ thể ko Click the image to open in full size. theo nguốn tin mà em biết thì địa chỉ ở 385 Hoàng Quốc Việt - Quận Cầu Giấy - Hà Nội. Các bác nào rỗi kiểm chứng giúp e địa chỉ này nhé.


    Click this bar to view the full image.

    Click the image to open in full size.


    Một chương trình để thay đổi thông số máy. Change Pin - imei thoải mái
    Click the image to open in full size.
    Click the image to open in full size.
    Click the image to open in full size.
    Click the image to open in full size.
    Click the image to open in full size.
    Đó là những kiến thức mà e đã biết thưa a c e. Hy vọng sẽ giúp đc mọi người phần nào.

    Làm thế nào để chọn được 1 em blackberry đẹp!

    Có mấy thứ sau bạn nên kiểm tra thật kỹ:
    1.Bàn phím:
    - Độ giơ của bàn phím, bạn thử dùng ngón tay cái đặt vào giữa bàn phím hơi ấn xuống và rê qua rê lại xem bàn phím có giơ nhiều không. Nếu là máy tốt thì không giơ đâu.
    -Sau đó bạn nên kiểm tra độ nhạy của bàn phím. Bạn nên bỏ công ấn tất cả các phím xem có phím nào bị kẹt không, bấm có nhạy không kể cả phím chức năng như phím đèn hay phím call hay phím ESC ( hông máy dưới track wheel).
    2.Track wheel:
    Bạn nên kiểm tra xem Track wheel còn nhạy không. Nếu là máy tốt thì track wheel sẽ không quá chặt và quá lỏng. Và khi cuộn track wheel thì sẽ có tiếng tack tack. Và ấn thử vào track wheel xem có nhạy không. Nếu là máy tốt thì khi bấm track wheel sẽ hơi nặng tay.
    3.Màn hình:
    Bạn nên tắt đèn màn hình và và lắc qua lắc lại, nếu máy tốt thì màn hình sẽ không bị nhiễu, hoặc có thì nhiễu rất ít không đáng kể khó nhận ra. Còn máy không tốt thì lắc nhẹ cũng nhiễu nhiều. Nhớ là phải tắt đèn mới thấy, bật đèn không thấ đâu.
    4.Chỗ cắm USB, và cable:
    Bạn nên kiểm tra xem lỗ cắm và cable USB còn tốt không, còn nhậy không, nếu không sẽ rất khó khi bạn up rom hay cài phần mềm sau này. Nếu cable và lỗ cắm còn tốt thì khi bạn cắm vào máy tính sẽ nhận ngay và trên BB sẽ có biểu tượng pin đang sạc. Nếu lỗ cắm hay cable không tốt thì kết nối sẽ không ổn định và trên BB sẽ thông báo bằng TA "máy không thể sạc pin, làm ơn kiểm tra lại nguồm cắm USB!"
    5. Sạc và pin:
    Để kiểm tra sạc và pin. Trước tiên bạn nên kiểm tra xem sạc và pin có logo biểu tượng của Blackberry không. cái này cũng chưa nói lên điều gì nhưng cứ phải có trước đã. Sau đó bạn cắm vào máy sạc thử 15 phút. Nếu pin xịn sạc xịn thì chỗ cục sạc sẽ mát hoặc hơi âm ấm, còn nếu pin hay sạc có vấn đề thì chỗ sạc pin sẽ nóng ran. 1 là do độ hoạt hóa của pin kém, 2 là do sạc kém. Bạn nên kiểm tra pin và sạc thật kĩ.
    (Lần đầu tiên bạn nên sạc BB cho thật đầy, mỗi ngày sau bạn nên sạc từ 10 đến 15 phút, BB sẽ luôn đầy up pin, làm vậy sẽ tốt cho pin. Trích từ hướng dẫn sử dụng của BB)
    6. Loa và Mic:
    Bạn nên gọi thử để kiểm tra xem loa và mic của máy còn rõ không, bạn vặn loa to hết cỡ nếu nghe tiếng vẫn trong và ấm thì không vấn đề, nhưng nếu loa rè hoặc không rõ, hay người bên kia không nghe thấy bạn nói thì nên đổi máy khác là vừa.
    7. Nhạc chuông và rung;
    Bạn chọn Profile rồi tạo một profile mới. Sau đó kiểm tra xem nhạc chuông và máy rung có tốt không. Một số máy bị hỏn rung không thể rung. Thông thường nếu là máy tốt thì khi bạn để rung rồi để lên mặt bàn, máy sẽ bị xê dịch.
    8. Kiểm tra chế độ tiết kiệm pin của máy. Bạn thử dí một cục nam châm nhỏ vào vị trí nút space, nếu màn hình tắt đi thì ổn, còn không thì chế độ tiết kiệm pin đã hỏng. Nếu bạn mua kềm bao gia hay hoslter thì có thể bỏ vào bao hay hoslter xem màn hình có tắt không, nếu không một là bao gia không có miếng nam châm hay là hỏng chế độ tiết kiệm pin. Thông thường bao gia hay hoslter thường có một miếng nam châm nhỏ đúng vị trí của nút space.
    9. Kiểm tra xem máy bắt sóng có tốt không. Mời bạn ấn Alt+N,M,L,L. Cột sóng sẽ chuyển thành số, Nếu máy bắt sóng tốt thì trong thành phố sóng khoảng từ 50-60. Cái này kiểm tra cũng hơi khó, nhưng các bác cứ thử
    10. Cái này không quan trọng lắm, chỉ dành cho bác nào khó tính thôi, đó là kiểm tra kĩ xem vỏ blackberry có bị nứt hay bị sước nhiều không, mặt nhôm (7290) có bị bong ra không, vì nhìn cái máy cũ quá cũng chán. Rồi xem xem số Imei và mã pin sau máy có trùng khít sau máy không ( cái này cũng không quan trọng lắm đâu, máy cũ mà, quan trọng là các phần trên có tốt không thôi)
    Bạn cũng nên tham khảo một số cửa hàng trước khi mua, như thế mới thấy được hàng nào chất, hàng nào không.
    Đừng tham rẻ nhá!
    Em xin lỗi các bác đã chơi BB chuyên nghiệp, khi post bài này, và nếu như bài này là thừa thì mong các bác mod xóa giùm em. Còn anh em nào thấy hữu ích thì nhớ thank em nha. Xin cảm ơn!

     

    Ref: http://www.tinhte.vn/forum/showthread.php?t=14717

    February 05

    Clog - Client Logging, Silverlight Edition

    Ref: http://www.codeproject.com/KB/silverlight/SilverlightLogging.aspx?display=PrintAll&fid=907929&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2332149

     

    Please visit the CodePlex Project Site for the latest releases and source code.

    Clog - All your log are belong to Clog.

    Contents

    Introduction

    So you've deployed your swanky new Silverlight application to test. But wait! There's a problem. Your testers tell you that it breaks when they click the orange button! They send you a multitude of screen shots, but to no avail! It appears unresolvable, and with deadlines looming, it's crunch time. With no hope in site, desperation sets in. You raise your fists in the air and exclaim "If only I could know what was happening on the client side!".

    Enter Clog.

    Ok, the previous hypothetical scenario is melodramatic, but it highlights the need for an integrated client side logging solution. Thus I decided to create Clog. Clog is a log provider system that allows you to harness your existing logging system to log client side messages to your server. It is fully customizable, can serialize and log all Exception types, and allows filtering of messages both on the client and server sides using custom or inbuilt filters, which so far consists of an IP Address Range Filter, and a Role Membership filter. In this release Clog includes an extendible Log provider system, a log4net log strategy, and a Silverlight log viewer.

    Clog Overview

    Figure: Consuming Clog from a web client application.

    This article will discuss how Clog works, how to set up Clog on both client and server, including configuration of the Silverlight Log Viewer control, an example use of the .NET provider model, and also some more advanced topics such as the Silverlight security model.

    Although this article's client side focus is primarily on a Silverlight implementation, Clog is capable of providing logging services to any .NET or web service consumer. Thus, in future articles, I intend to provide editions for WPF and ASP.NET AJAX.

    Background

    A solid server side logging system is the mainstay of most web based applications. With the advent of WPF, Silverlight, and a client side CLR, it is my view that we will see a shift in focus away from the traditional and primarily server based logging scenario, to cater to a more client centric environment.

    While Visual Studio allows us to readily debug Silverlight and WPF, without the debugger or some means of tracing client side events, we can find ourselves left in the dark. We have no built-in mechanism for logging to e.g., an event log on a client machine, and we lack an immediate feedback mechanism that could allow us to know if our client side .NET applications are behaving correctly. Clog bridges this client-server divide. We are now able to selectively capture logging events that originate from both client and server side applications.

    I recall, some years ago, my first experiences while hand coding form validation JavaScript, and trying to provide myself with client side feedback. It was, and still is, common practice to use message boxes for displaying information while scripting. It's a fairly slipshod and haphazard approach, and also potentially embarrassing if you should forget to comment out the code when you're through! Today there are one or two Ajax JavaScript client to server logging projects out there. And while they may work well with loosely typed JavaScript, they address a different need.

    There are numerous logging libraries for .NET, and many of us have come to know and rely on a particular system over time; sometimes customizing it to suit our own requirements. Clog allows us to keep our existing system, by wrapping it; allowing us to perform both client and server logging in the same manner.

    Consuming Clog

    Figure: Local and remote clients consuming Clog.

    Clog System Overview

    Clog's core component is the Orpius.Logging.dll. It provides for most of the server side functionality. Silverlight logging functionality is located in Orpius.Logging.Silverlight.dll, and auxiliary to this is the optional component Orpius.Logging.Silverlight.UI.dll, which contains the LogViewer Silverlight control. The following diagram provides a conceptual overview of some of the principle types and their interdependencies.

    Clog component diagram.

    Figure: Clog Component Diagram.

    Using Clog

    To enable Clog for client side logging we complete a two stage process. First we configure the server based project to use Clog. Then we configure our client side project to use Clog.

    Server Side Configuration

    To enable Clog on the server side, add a reference to the Orpius.Logging assembly.

    <section name="ClientLogging"
        type="Orpius.Logging.ClientLoggingConfigSection"/>

    Next, create the ClientLogging config section, as in the following excerpt.

    <ClientLogging defaultProvider="Log4NetProvider">
        <providers>
            <clear />
            <add name="Log4NetProvider"
                type="Orpius.Logging.LogStrategyProvider, Orpius.Logging"
                LogStrategy="Orpius.Logging.Log4NetStrategy,
                Orpius.Logging.Log4NetLogStrategy" />
            <add name="CustomProvider"
                type="Orpius.Logging.LogStrategyProvider, Orpius.Logging"
                LogStrategy="ExampleWebsite.SimpleLogStrategy, ExampleWebsite" />
        </providers>
        <filters>
            <add name="IPAddressRange"
                type="Orpius.Logging.Filters.IPAddressRangeFilter, Orpius.Logging"
                begin="127.0.0.0" end="127.0.0.10"/>
            <add name="RoleMembership"
                type="Orpius.Logging.Filters.RoleMembershipFilter, Orpius.Logging"
                roles="Developer, Administrator"/>
        </filters>
    </ClientLogging>

    Create a new file in your Web project called ClientLoggingService.asmx, open it and paste the following content:

    <%@ WebService Language="C#" Class="Orpius.Logging.ClientLoggingService,
        Orpius.Logging" %>

    The web service code is actually located in the Orpius.Logging.dll assembly. It is up to you to define your preferred logging method. For this demonstration we are using log4net. While configuring log4net is outside the scope of this article, you can view the example website download to see how it's done. Briefly, it requires adding an assembly reference to log4net.dll, adding a config section in the web.config, and then initialising log4net within your website. I do this by performing an arbitrary logging request when the application starts.
    N.B. If you don't initialise log4net from your website before it is used in another assembly, it won't be configured properly.

    Clog for Silverlight Configuration

    To use Clog in your Silverlight project, add a reference to the Orpius.Logging.Silverlight assembly. If you also wish to use the Silverlight Log Viewer, then add a reference to the Orpius.Logging.Silverlight.UI assembly as well.

    Writing to the Log from Silverlight

    To use Clog on the client side, within a Silverlight application, we add a reference to the Orpius.Logging.Silverlight assembly, and we use the LogManager to provide us with an ILog by calling GetLog method like so:

    static readonly ILog log = LogManager.GetLog(typeof(Page));

    The typeof(Page) argument is used to determine the name of the Log in conjunction with the URL of the page itself. This gives us a fine grained control over filtering of log requests. That is, we can control logging requests not only based on a particular Silverlight custom control or page, but also on where it has been deployed. To facilitate debugging from localhost where there is a dynamic port specified in the URL, we don't include the port number in the log name.

    Writing to the log flowchart

    Figure: Client log writing process.

    The client-side Silverlight Log dispatches log entries to the server asynchronously, as the following excerpt shows:

    void WriteLogEntryAux(LogLevel logLevel, string message, Exception exception)
    {
        ExceptionMemento memento = null;
        if (exception != null)
        {
            memento = CreateMemento(exception);
        }
    
        LogEntryData entry = new LogEntryData()
        {
            LogLevel = logLevel,
            Message = message,
            ExceptionMemento = memento,
            CodeLocation = GetLocation(),
            LogName = Name,
            ThreadName = System.Threading.Thread.CurrentThread.Name,
            ManagedThreadId =
                System.Threading.Thread.CurrentThread.ManagedThreadId,
            Url = HtmlPage.DocumentUri.ToString(),
            OccuredAt = DateTime.Now
        };
    
        OnLogEntrySendAttempt(new LogEventArgs(entry));
    
        if (ConfigurationData == null || !ConfigurationData.LogEnabled
            /* Enable enum and remove cast
             * when Silverlight supports Enum serialization. */
                || (int)entry.LogLevel < ConfigurationData.LogLevel)
        {
            return;
        }
        /* Send of the log entry to the web service. */
        LoggingService.BeginWriteEntry(entry, delegate(IAsyncResult result)
                                                  {
            OnLogEntrySent(new LogEventArgs(entry));
                                                  }, null);
    }

    Silverlight Log Viewer

    Overview

    The Log Viewer is a Silverlight control that can be placed on a Canvas to automatically monitor the LogManager. When an ILog instance receives a request to write a log message, the Log Viewer is able to display the log message. The following screen capture shows the Log Viewer receiving an outgoing log entry, while the Log4Net Viewer shows the result of the log entry, after it has been relayed to log4net.

    Browser and Log4Net Viewer

    Figure: Clog Silverlight Log Viewer with Log4Net Viewer.

    Using the Log Viewer

    To include the Log Viewer in your Silverlight application, add a reference to the Orpius.Logging.Silverlight.UI assembly, and add the following namespace definition to the root canvas on a page.

    xmlns:Orpius="clr-namespace:Orpius.Logging.Silverlight.UI;
        assembly=ClientBin/Orpius.Logging.Silverlight.UI.dll"

    Then place the LogViewer XAML element somewhere on the page.

    <Log:LogViewer x:Name="LogViewer" Canvas.Top="180" Width="640" Height="300"/>

    The number of rows displayed in the LogViewer is dependant upon the height of the control. For example, given that each row is hardwired to be 16 pixels tall, if the Height property of the LogViewer is set to 160, we can expect to see 10 rows. The width of the columns is also calculated using the declared Width of the control.

    Inside the Log Viewer

    Silverlight doesn't have many controls provided with its download yet; the viewer is constructed from the ground up.

    When a Silverlight application requests the writing of a log entry, two events may be raised by the active ILog instance. The first event, WriteRequested, happens unconditionally, and if the "Log Viewer" is in OfflineMode a log entry will be displayed immediately. The second event, LogEntrySent, is raised if the log entry is sent to the server. In this case, if the "Log Viewer" is not in OfflineMode then the log entry is displayed. Sending of the log entry depends on the ILog's ClientConfigurationData LogLevel and Enabled properties, and the requested log level.

    Log Viewer display process flowchart

    Figure: Log Viewer processing a log entry flowchart.

    Silverlight Security Model

    Silverlight does not use Code Access Security (CAS). Silverlight uses the transparency model introduced in .NET 2.0. In this model there are three levels: Transparent, Safe Critical, and Critical. In the Silverlight CLR, all code is "Transparent" by default, and, therefore, so is the user code. This is the opposite of the desktop CLR, which is "Critical" by default (.NET Security Blog). Any method decorated with a SecurityCritical attribute can't be called directly by user code because transparent code is not allowed to call "Critical" code. If "Transparent" code attempts to call "Critical" code, a MethodAccessException ensues.

    Transparent code cannot call Critical code directly.

    Figure: Transparent code cannot call Critical code directly.

    The Silverlight mscorlib contains "many" methods decorated with the SecurityCritical attribute. One such method is the System.Diagnostics.StackTrace constructor, and, unfortunately for us, this means we can't get a stack trace; preventing us from obtaining and passing on the origin of calls to the Log. It makes sense to hide stack trace information from user code, as it may reveal sensitive information. It would, however, be nice to have a "Safe Critical" method to retrieve a stack trace consisting of just user code. But I'm not holding out for that one.

    To take a look at what methods are available to our user code, fire up Reflector and replace the Framework mscorlib assembly in Reflector with the Silverlight version. As we can see, much of this assembly is a no-go-zone.

    StrackTrace class disassembled in Reflector

    Figure: StackTrace class disassembled in Reflector.

    Extending Clog

    Clog Provider Model

    "All your log are belong to Clog."

    -D. Vaughan. (See derivation)

    Clog uses ILogStrategy instances to send log entries to third-party logging systems. Included with Clog are two ILogStrategy implementations. The first is a really simple tracing strategy that serves as a basic example; the second, a log4net strategy. I hope to include more in a later release. If you happen to write one for a particular 3rd party logging system, I'd love to include it in the next release (with credit of course).

    An ILogStrategyProvider is tasked with instantiating the ILogStrategy and exposing it through its LogStrategy property. Internal to the Orpius.Logging module, there is a default implementation of an ILogStrategy that should be sufficient in most cases.

    Log Strategy provider class diagram

    Figure: ILogStrategy and ILogStrategyProvider class diagram.

    Integrating Clog with your Existing 3rd Party Logging System

    To integrate Clog with an existing logging system, implement the ILogStrategy interface, and specify the type in the provider configuration using the LogStrategy attribute, as in the following example:

    <add name="CustomProvider"
        type="Orpius.Logging.LogStrategyProvider, Orpius.Logging"
            LogStrategy="YourAssembly.Strategy, YourAssembly" />

    The ILogStrategy interface has three members. For client side logging functionality implement the void Write(IClientLogEntry logEntry); and LogLevel GetLogLevel(string logName); methods. If you plan to only use Clog for client side logging, then you can forget about the void Write(IServerLogEntry logEntry); overload (of course you will still need a default empty implementation). If, however, you wish to use Clog as a wrapper for your existing logging system, then provide an appropriate implementation for the IServerLogEntry overload as well.

    The Log Strategy determines how a log entry is written to a log. It is here that we connect our existing logging system, such as log4net, to Clog. When a log write is requested, the current Log Strategy must take the information present in the IServerLogEntry or IClientLogEntry and construct a call to the existing logging system. The LogLevel GetLogLevel(string logName); method is used to determine the threshold at which log entries are written, and it also allows us to inhibit logging on the client side if the level is higher than the requested logging level.

    This release of Clog comes with a log4net strategy (Log4NetStrategy). The following excerpt shows how the class writes a log message to log4net using a specified IClientLogEntry argument.

    public void Write(IClientLogEntry logEntry)
    {
        ILog log = defaultLog;
        if (logEntry.LogName != null)
        {
            log = LogManager.GetLogger(logEntry.LogName);
        }
    
        /* Create a Log4Net event data instance,
         and populate it with our log entry information. */
        LoggingEventData data = new LoggingEventData();
        if (logEntry.ExceptionMemento != null)
        {    /* Use the exception memento to write the message
            and stack trace etc. */
            data.ExceptionString = logEntry.ExceptionMemento.ToString();
        }
    
        data.Level = GetLog4NetLevel(logEntry.LogLevel);
        ICodeLocation location = logEntry.CodeLocation;
        if (location != null)
        {
            data.LocationInfo = new LocationInfo
                (location.ClassName, location.MethodName,
                location.FileName, location.LineNumber.ToString());
        }
    
        data.LoggerName = logEntry.LogName;
        data.Message = logEntry.Message;
        data.ThreadName = logEntry.ThreadName;
        data.TimeStamp = logEntry.OccuredAt;
        //data.Properties = logEntry.Properties;
    
        if (string.IsNullOrEmpty(logEntry.UserName))
        {    /* Populate the UserName property using the Membership provider. */
            MembershipUser user = Membership.GetUser(true);
            if (user != null)
            {
                data.UserName = user.UserName;
            }
        }
        else
        {
            data.UserName = logEntry.UserName;
        }
    
        LoggingEvent loggingEvent = new LoggingEvent(data);
        log.Logger.Log(loggingEvent);
    }
    Filters

    Clog uses server side filters to determine what log entries to discard before they are sent to the active Log Strategy. Filters are evaluated when retrieving ClientConfigurationData, and on receipt of a log write request. I have included two filters with this release. One is an IP Address range filter, which will restrict logging to an IP within a range that is defined in the provider configuration. The other is a Role Membership filter, which restricts logging to those authenticated users who have a role specified in the configuration.

    Filters class diagram

    Figure: Filter class diagram.

    The current ILogProvider evaluates each IFilter by calling the IsValid method, as the following excerpt from the IPAddressFilter class demonstrates.

    /// <summary>
    /// Restricts logging based on an IP address range.
    /// </summary>
    
    class IPAddressRangeFilter : HttpRequestFilterBase
    {
        uint begin;
        uint end;
    
        public override bool IsValid(LogEntryOrigin origin)
        {
            if (origin != LogEntryOrigin.Client || HttpRequest == null)
            {
                return true;
            }
    
            string addressValue = HttpRequest.UserHostAddress;
            return IsWithinRange(begin, addressValue, end);
        }
    
        /// <summary>
        /// Initialises the specified filter element.
        /// </summary>
        /// <param name="filtereElement">The filtere element.</param>
    
        public override void Init(FilterElement filtereElement)
        {
            begin = ToUInt(IPAddress.Parse(filtereElement.Begin));
            end = ToUInt(IPAddress.Parse(filtereElement.End));
        }
    
        static bool IsWithinRange
            (uint beginAddress, string addressValue, uint endAddress)
        {
            IPAddress address = IPAddress.Parse(addressValue);
            uint ip = ToUInt(address);
            return ip >= beginAddress && ip <= endAddress;
        }
    
        /// <summary>
        /// Converts and <see cref="IPAddress"/> to an unsigned int.
        /// </summary>
        /// <param name="ipAddress">The ip address to convert.</param>
        /// <returns>A <code>uint</code> representing
        /// the specified ipAddress.</returns>
    
        static uint ToUInt(IPAddress ipAddress)
        {
            byte[] bytes = ipAddress.GetAddressBytes();
    
            uint result = (uint)bytes[0] << 24;
            result += (uint)bytes[1] << 16;
            result += (uint)bytes[2] << 8;
            result += bytes[3];
    
            return result;
        }
    }

    Logging Exceptions the Clog Way

    When a request to log an Exception occurs client side, an ExceptionMemento is used to encapsulate the exception information so that it can be correctly serialized and sent over the wire. You may be aware that an Exception is not immediately serializable without using a binary formatter for serialization, and this is due to the IDictionary _data field. To sidestep any serialization issues, and relieve the Clog consumer from having to worry about the serializability of his or her logged exceptions, we gather what information we can from the exception into an ExceptionMemento instance. This is then sent over HTTP to our Clog web service, where it is relayed to the active Log Strategy.

    Log Entries

    ILogEntry instances encapsulate the log entry information that passes through Clog, via a remote client application or local consumer, and on to the end point; the active ILogStrategy. External consumers of Clog use the LogEntryData data type, which forms the base type for all concrete ILogEntry instances, and omits various internal properties. When a LogEntry arrives at the Clog web service, a ClientLogEntry is instantiated and decorated with the IP of the incoming request. This is then sent on to the static Log class. The following class diagram shows the ILogEntry interface and its inheritors. Concrete implementations of the various ILogEntry interfaces are internal to the Orpius.Logging project.

    Log Entry class diagram

    Figure: Log Entry class diagram.

    IServerLogEntry instances represent server side log entries, and are used when requests to write to the log originate within the same application, and most likely within the same appdomain, as the Orpius.Logging.dll component.

    IClientLogEntry instances, on the other hand, represent client side log entries. These are used when requests to write to the log originate from a remote client, such as a Silverlight Clog Log.

    Points of Interest

    JSON Serialization

    Communicating with web services from Silverlight is one of its great features. Though, at this early stage, Silverlight Alpha 1.1 does have some limitations. The first is that there is no support for enum deserialization in Silverlight. In our ClientConfigurationData class, we have a LogLevel property. This property was initially, you guessed it, a LogLevel enum type. But as I quickly discovered, Silverlight was unable to deserialize the value, and I had to resort to changing its data type to int. Mind you, serialization (not deserialization) of enums on the client (Silverlight) side works fine. We can happily send enum values to a web service, as we do with our LogEntryData. The second gotcha was revealed when, by decorating a class with the XmlElement attributes, I was unable to add a web reference from our Silverlight Logging project. For now, my best advice is to stick with simple data container classes when exposing them from web services that you intend to consume from Silverlight.

    Silverlight 1.1 Alpha and Web Services

    You may notice in our ClogLoggingService.cs that we have a return type of string on our WriteEntry method. The reason for this is that I was receiving Exceptions when calling the method when the return type was null. Changing the return type to a string fixed the problem. My attempt to use a "decimal" also failed as Silverlight 1.1 doesn't support serialization of the decimal type yet. I had intended the return type to be a log id, but on further consideration this made little sense as most 3rd party logging systems don't expose that information directly anyway. Of course this is open to customization, and I will happily listen to any requests to do it differently.

    ApplicationUnhandledException Doesn't Fire

    I had intended to handle the Silverlight WebApplication.Current.ApplicationUnhandledException in the included example Silverlight application, where I would log the Exception using Clog. Unfortunately though, the event isn't raised properly. You can find some more information about this on the Silverlight Forum.

    Future Enhancements

    • Use custom Exception to expose protected data to the ExceptionMemento
    • Add filter by log etc. to Log Viewer
    • Provide more Unit Tests for core logging functionality

    Conclusion

    This article discussed the implementation of Clog; a client server logging provider system. It showed how to set it up, including configuration of the Silverlight Log Viewer control, an example use of the .NET provider model. The article also touched on some more advanced topics such as the Silverlight security model. I intend to release "Clog WPF edition" in the coming weeks. Although Clog is still just a prototype, I believe it shows a lot of promise for becoming quite a useful tool.

    I hope you find this project useful. If so, then you may like to rate it and/or leave feedback below.

    References

    History

    • November 2007
      • First release
    • January 2008
      • Added a config attribute to disable the use of ASP.NET Membership by Clog.
      • Integrated Silverlight and WPF Editions into the same download.
      • Improved the multithreaded logging capability to prevent exceptions due to logging calls being made from non STA threads.

    February 03

    Người Nhật chọn việc và bạn đời theo... nhóm máu

    Tham khao: http://www.vnexpress.net/GL/Doi-song/2009/02/3BA0ADE7/

    Người Nhật từng xây dựng bộ phim hài "Bạn trai tôi nhóm B". Ảnh: Photobucket.

    Ở xứ sở mặt trời mọc, câu hỏi "Bạn thuộc nhóm gì?" có ý nghĩa hơn nhiều một câu xã giao thông thường: nó có thể là câu hỏi quan trọng nhất trong mọi việc, từ mai mối đến xin việc làm.

    'Nhóm', theo nghĩa của người Nhật nghĩa là nhóm máu, và không một chứng cứ khoa học nào có thể bẻ gãy được quan niệm thâm căn cố đế rằng nhóm máu nói lên tất cả.

    Trong năm 2008 vừa qua, 4 trong số 10 cuốn sách bán chạy nhất là nói về tác động của nhóm máu tới cá tính, theo nhà phân phối sách lớn nhất nước này, công ty Tohan. Nhà xuất bản sách Bungeisham cho biết seri sách này (mỗi cuốn nói về một nhóm máu như A, B, O, AB) đều bán được trên 5 triệu bản.

    Taku Kabeya, tổng biên tập của Bungeisha, cho rằng điều hấp dẫn của những cuốn sách này là chúng mang lại sự xác nhận về chân dung mỗi người: bạn đọc sẽ khám phá ra định nghĩa về nhóm máu của mình và nó giống như thể "Vâng, đúng là tôi đấy!".

    Theo mô tả của những cuốn sách này, người nhóm A rất cầu toàn nhưng hay lo lắng thái quá. Người nhóm B vui vẻ nhưng lập dị và ích kỷ. Những người nhóm máu O ham hiểu biết, rộng lượng nhưng bướng bỉnh, và AB rất có khiếu thẩm mỹ nhưng bí ẩn và không thể dự báo được.

    Tất cả những điều đó nghe có vẻ giống như lời tiên đoán, song công chúng dường như không quan tâm đến điều đó.

    Thậm chí Thủ tướng Taro Aso dường như cũng coi điều đó quan trọng đến mức tiết lộ trong tiểu sử chính thức của ông trên web. Ông thuộc nhóm A, trong khi đối thủ, người lãnh đạo của đảng đối lập, ông Ichiro Ozawa thuộc nhóm B.

    Ngày nay, các đặc điểm về nhóm máu có mặt trong cả các game và trên các "túi may mắn" - loại phụ trang ưa thích của phụ nữ. Một chương trình tivi thậm chí còn phát một phim hài về những phụ nữ tìm chồng theo nhóm máu.

    Không dừng lại ở đó. Các cơ quan mai mối hôn nhân cung cấp những xét nghiệm tương thích nhóm máu, và một vài công ty cũng quyết định tuyển dụng dựa trên chỉ số O hay A của ứng viên. Thậm chí, trẻ em ở một vài nhà trẻ được chia để nuôi theo nhóm máu.

    Và mặc dù được cảnh báo nhiều về sự vận dụng thái quá chỉ số này, song nhiều nhà tuyển dụng vẫn tiếp tục hỏi nhóm máu của ứng viên, Junichi Wadayama, một quan chức tại Bộ Y tế, Phúc lợi và Lao động cho biết.

    "Ngày càng phổ biến việc hầu hết mọi người, thậm chí cả lãnh đạo các công ty, không nhận thức được rằng việc hỏi nhóm máu có thể dẫn tới những suy xét sai lầm", Wadayama nói.

    Còn ông Satoru Kikuchi, trợ lý giáo sư tâm lý tại Đại học Shinshu cho biết, nhóm máu (được quyết định bởi các protein) chẳng có liên quan gì với nhân cách.

    "Đó chỉ đơn giản là một thứ khoa học giả tưởng", ông nói. "Ý tưởng này khuyến khích mọi người đánh giá người khác qua nhóm máu, mà không cần hiểu thực hư họ ra sao. Đó giống như chủ nghĩa phân biệt chủng tộc".

    Quả thực bản thân quan niệm về nhóm máu này cũng có nguồn gốc tồi tệ. Nó xuất phát từ những nhà tư tưởng phân biệt chủng tộc Đức quốc xã, và được chính quyền quân sự Nhật chấp thuận những năm 1930 để sàng lọc các binh lính tốt. Giả thuyết này đã bị gạt bỏ một năm sau đó và sự đam mê của mọi người với nó cũng nhạt dần.

    Nhưng giả thuyết về nhóm máu lại hồi sinh vào những năm 1970.

    January 21

    Abraham Lincoln

    Bách khoa toàn thư mở Wikipedia

    (đổi hướng từ Lincoln, Abraham)
    Bước tới: menu, tìm kiếm
    Abraham Lincoln
    Abraham Lincoln
    Thứ tự Tổng thống Hoa Kỳ thứ 16
    Nhiệm kỳ 4 tháng 3 năm 186115 tháng 4 năm 1865
    Tiền nhiệm James Buchanan
    Kế nhiệm Andrew Johnson
    Ngày sinh: 12 tháng 2 năm 1809
    Nơi sinh Hardin, Kentucky
    Ngày mất 15 tháng 4 năm 1865 (56 tuổi)
    Nơi mất Washington, D.C.
    Phu nhân Mary Todd Lincoln
    Đảng Cộng hoà
    Chữ ký Abraham Lincoln signature.JPG

    Abraham Lincoln (12 tháng 2 năm 180915 tháng 4 năm 1865), (còn được bết dến với tên Abe Lincoln, tên hiệu Honest Abe, Rail Splitter, Người giải phóng vĩ đại) là Tổng thống Hoa Kỳ thứ 16, người đã dẫn dắt nước Mỹ qua cuộc khủng hoảng lớn nhất, cuộc Nội chiến Hoa Kỳ, và người chấm dứt chế độ nô lệ tại quốc gia này. Trước khi trở thành tổng thống, Lincoln từng là một luật sư, một thành viên của Viện Dân biểu Hoa Kỳ, và một ứng cử viên không thành công vào Thượng viện Hoa Kỳ. Là một người phản đối kịch liệt sự mở rộng của chế độ nô lệHoa Kỳ, Lincoln đã giành được vị trí ứng viên tổng thống Đảng Cộng Hòa năm 1860 và sau đó được bầu làm tổng thống vào năm đó. Suốt nhiệm kì của mình, ông đã bảo toàn được Hợp Chúng Quốc Hoa Kỳ khi đánh bại những nhân vật li khai trong Nội chiến Hoa Kỳ. Ông ta đã đưa ra nhiều biện pháp, kết thúc bằng vệc bãi bỏ chế độ nô lệ, đưa ra bản Tuyên ngôn Giải phóng Nô lệ năm 1863 và dẫn tới sự thông qua việc Sửa đổi Hiến pháp Lần thứ 13.

    Lincoln đã giám sát rất chặt cuộc chiến, đặc biệt trong việc lựa chọn các tướng lĩnh đứng đầu, bao gồm Ulysses S. Grant. Các sử gia đã kết luận rằng Lincoln đã rất khéo léo giải quyết các chia rẽ trong Đảng Cộng Hòa, đưa lãnh đạo của từng phe phái và nội các và bắt họ phải hợp tác. Lincoln cũng đã giúp Hoa Kỳ tránh khỏi cuộc chiến với Vương quốc Liên hiệp Anh và Ireland vào năm 1861.

    Phe phản chiến chỉ trích ông vì từ chối nhượng bộ trong vấn đề nô lệ. Ngược lại, Những Người Cộng hòa Cấp tiến, phe giải phóng nô lệ trong Đảng Cộng hòa, chỉ trích ông vì đã tiến hành giải phóng nô lệ quá chậm. Dù gặp những trở ngại này, ông thường lôi kéo được ý kiến quần chúng nhờ những bài phát biểu thuyết phục của mình; mà Diễn văn Gettysburg là một ví dụ. Kết thúc cuộc chiến, Lincoln đã có quan điểm rất ôn hòa về tái thiết, tìm kiếm sự tái đoàn kết quốc gia thông qua một chính sách tái hòa hợp độ lượng. Vụ ám sát ông năm 1865 là vụ ám sát tổng thống Hoa Kỳ đầu tiên, làm ông trở thành một chiến sĩ tử vì đạo vì lý tưởng thống nhất quốc gia.

    Mục lục

    [ẩn]

    [sửa] Tóm tắt tiểu sử

    Lincoln thuộc mẫu người tự lập. Tự học, ông trở thành một luật sư hàng đầu tại Illinois. Ông là lãnh đạo Đảng Whig (và đã đại diện cho Đảng tại Hạ viện trong một nhiệm kỳ). Khi vấn đề về chế độ nô lệ xảy ra năm 1854, ông góp phần tạo dựng Đảng Cộng hòa mới và trở thành lãnh đạo tại Illinois. Lincoln phản đối lao động nô lệ và kiên quyết khước từ mở rộng chế độ nô lệ ra thêm trong liên bang. Những cuộc tranh luận của ông với lãnh đạo Đảng Dân chủ Stephen Douglas năm 1858 khiến ông được cả nước biết tới, và với tư cách ứng cử viên ôn hòa miền tây ông đã chiến thắng trong cuộc chạy đua vào chân ứng cử viên tổng thống năm 1860. Chiến thắng của ông trong cuộc Bầu cử tổng thống Hoa Kỳ, 1860 là giọt nước làm tràn ly đối với phương Nam, nơi bảy bang quyết định ly khai, thành lập lên Liên hiệp các bang miền Nam, và chiếm quyền kiểm soát các pháo đài cũng như tài sản khác của Hoa Kỳ bên trong biên giới của họ, tạo bước khởi đầu dẫn tới cuộc Nội chiến Mỹ.

    Lincoln thường được ca tụng vì tài năng lãnh đạo của ông trong cuộc chiến; những lời phát biểu với dân chúng, nổi tiếng nhất là Diễn văn Gettysburg, đã định nghĩa những vấn đề chiến tranh và giúp tái xác định hình ảnh của chính nước Mỹ. Ông đã chứng minh khả năng khi thay thế các tướng lĩnh kém tài bằng những người giỏi giang hơn, và cuối cùng đã tìm ra vị tướng đích thực Ulysses S. Grant. Khi lãnh đạo Đảng Cộng hòa, ông giữ mọi bè phái liên hiệp với nhau và tìm kiếm những sự ủng hộ mới từ War Democrats, thậm chí khi những kẻ thù chính trị ghê gớm nhất của ông gọi ông là độc tài tàn nhẫn. Lincoln phải đàm phán giữa những lãnh đạo phe Cấp tiến phe Ôn hòa Cộng hoà, những người thường bất đồng quan điểm về các vấn đề nô lệ. Ông đích thân chỉ huy các hoạt động chiến tranh, hợp tác chặt chẽ trong giai đoạn (1864-65) với Tướng Grant, người đã buộc lực lượng quân đội chính của tướng Robert E. Lee chấp nhận đầu hàng vào tháng 4 năm 1865.

    Khả năng lãnh đạo của ông được minh chứng rõ rệt khi ông giải quyết khôn khéo vấn đề biên giới các bang nô lệ khi cuộc chiến mới bùng phát, khi đánh bại một nỗ lực vận động nghị viện nhằm tái tổ chức lại chính phủ của ông năm 1862, khi những lời tuyên bố, những bài viết của ông giúp tập hợp và truyền cảm hứng cho dân chúng miền Bắc, khi ông góp phần làm giảm những nỗi đau thời hậu chiến trong chiến dịch tranh cử tổng thống năm 1864. Những kẻ thù chính trị chỉ trích ông đã vi phạm Hiến pháp, vượt quá quyền lực hành pháp, từ chối thỏa hiệp về vấn đề nô lệ, tuyên bố thiết quân luật, đình chỉ lệnh đình quyền giam giữ, ra lệnh bắt giữ 18.000 người đối lập gồm cả các quan chức đảng cộng hòa và các nhà xuất bản, giết hại hàng trăm nghìn binh sĩ trẻ trong cuộc chiến. Phe Cấp tiến Cộng hoà chỉ trích ông hành động quá chậm chạp khi xóa bỏ chế độ nô lệ, và không đủ cứng rắn đối với những người miền Nam đã đầu hàng.

    Lincoln nổi tiếng nhất với vai trò gìn giữ Hợp chủng quốc và chấm dứt chế độ nô lệ tại Hoa Kỳ với bản Tuyên ngôn Giải phóng và việc Sửa đổi thứ mười ba Hiến pháp Hoa Kỳ.

    Các nhà sử học đã có ý kiến rằng Lincoln có tầm ảnh hưởng lâu dài trên chính trị và các định chế xã hội Hoa Kỳ, đặc biệt đã đặt ra tiền lệ cho việc tập trung hóa quyền lực ở mức độ cao hơn vào tay chính phủ liên bang và giảm bớt quyền lực các cá nhân bên trong chính phủ liên bang.

    Lincoln hầu như dồn mọi chú ý của mình vào các vấn đề chính trị và quân sự, nhưng nhờ sự ủng hộ mạnh mẽ của ông, chính phủ đá thành lập ra hệ thống các ngân hàng quốc gia với Đạo luật Ngân hàng Quốc gia như ngày nay. Chính phủ của ông cũng đã tăng thuế để tăng nguồn thu, đặt ra luật thuế thu nhập đầu tiên, phát hành hàng trăm triệu dollar khế ước và những đồng tiền giấy đầu tiên, khuyến khích người nhập cư từ Châu Âu, khởi động dự án đường sắt liên lục địa, lập ra Bộ Nông nghiệp Hoa Kỳ, Bộ nông nghiệp, khuyến khích quyền sở hữu trang trại với Đạo luật ấp trại năm 1862, và lập ra hệ thống các trường đại học hiện đại với Đạo luật các trường Đại học Morrill Land-Grant. Trong thời gian chiến tranh, bộ Ngân khố của chính phủ đã quản lý rất hiệu quả mọi hoạt động mua bán bông tại những vùng miền Nam chiếm đóng —công việc quản lý kinh tế hiệu quả nhất của liên bang. Vùng li khai West Virginia và vùng Nevada không dân chúng được chấp nhận thành các bang mới của quốc gia làm nhằm tăng đa số Cộng hòa bên trong Thượng viện Hoa Kỳ.

    Lincoln luôn được xếp hạng là một trong số hai hay ba tổng thống vĩ đại nhất. Tầm quan trọng của ông xuất phát từ vai trò trong việc xác định các vấn đề to lớn, tổ chức và giành chiến thắng trong cuộc nội chiến, tiêu diệt chế độ nô lệ, tái định nghĩa quốc gia. Việc ông bị ám sát khiến ông trở thành một người tử vì đạo trong trái tim với hàng triệu người Mỹ.

    [sửa] Lincoln trước năm 1854

    Abraham Lincoln sinh ngày 12 tháng 2, 1809, cùng ngày sinh với Charles Darwin. Lincoln sinh ra trong một căn nhà gỗ một phòng nhỏ tại Trang trại Sinking Spring rộng 348 acre (1.4 km²) ở phía đông nam Quận Hardin, Kentucky, khi ấy còn bị coi là biên giới (nay là một phần của Quận LaRue, ở Nolin Creek, cách Hodgenville 3 dặm (5km) và là con của Thomas Lincoln cùng Nancy Hanks. Lincoln được đặt theo tên người ông đã mất, ông của Lincoln đã bị lột da đầu năm 1786 trong một cuộc tấn công của người da đỏ. Ông không có tên đệm. Cha mẹ Lincoln là những người nông dân thất học và mù chữ. Khi Lincoln đã trở nên nổi tiếng, những nhà báo và những người viết truyện đã thổi phồng sự nghèo khổ và tối tăm của ông khi ra đời. Tuy nhiên, Thomas Lincoln là một công dân khá có ảnh hưởng ở vùng nông thôn Kentucky. Ông đã mua lại Trang trại Sinking Spring vào tháng 12 năm 1808 với giá $200 tiền mặt và một khoản nợ. Trang trại này hiện được bảo tồn như một phần của Địa điểm di tích lịch sử quốc gia nơi sinh Abraham Lincoln. Cha mẹ ông theo một phái nhà thờ Baptisti, vốn đã bị trục xuất khỏi nhà thờ lớn hơn vì họ đã từ chối ủng hộ chế độ nô lệ. Từ khi còn rất nhỏ, Lincoln đã thể hiện tình cảm chống chế độ nô lệ. Tuy nhiên, ông không theo tôn giáo của cha mẹ, hay bất kỳ một tôn giáo nào khác, lúc nhỏ ông thường chế giễu tôn giáo.

    Ba năm sau khi mua trang trại, một người chủ đất trước đó đưa hồ sơ ra trước Toà án Hardin Circuit buộc gia đình Lincoln phải chuyển đi. Thomas theo đuổi vụ kiện cho tới khi ông bị xử thua năm 1815. Những chi phí kiện tụng khiến gia cảnh càng khó khăn thêm. Năm 1811, họ thuê được 30 acres (0.1 km²) trong trang trại Knob Creek rộng 230 acre (0.9 km²) cách đó vài dặm, nơi họ sẽ chuyển tới sống sau này. Nằm trong lưu vực Sông Rolling Fork, đó là một trong những nơi có đất canh tác tốt nhất vùng. Khi ấy, cha Lincoln là một thành viên được kính trọng trong cộng đồng và là một nông dân cũng như thợ mộc tài giỏi. Hồi ức sớm nhất của Lincoln bắt đầu có ở trang trại này. Năm 1815, một nguyên đơn khác tìm cách buộc gia đình Lincoln phải rời trang trại Knob Creek. Nản chí trước sự kiện tụng cũng như không được các toà án ở Kentucky bảo vệ, Thomas quyết định đi tới Indiana, nơi đã được chính phủ liên bang khảo sát, nên quyền sở hữu đất đai cũng được bảo đảm hơn. Có lẽ những giai đoạn tuổi thơ ấy đã thúc đẩy Abraham theo học trác địa và trở thành một luật sư.

    Năm 1816, khi Lincoln lên bảy, ông và cha tới Quận Spencer, Indiana; ông lý giải hành động này "một phần vì quan điểm với vấn đề nô lệ" và một phần vì những khó khăn kinh tế ở Kentucky. Năm 1818, mẹ Lincoln qua đời vì "milk sickness" ở tuổi ba tư, khi ông mới chín tuổi. Một thời gian ngắn sau đó, cha Lincoln cưới Sarah Bush Johnston. Sarah Lincoln đã dạy dỗ chú bé Lincoln như con mình. Nhiều năm sau này bà đã so sánh Lincoln với những người con riêng của mình và nói "Cả hai đều là những đứa trẻ ngoan, nhưng tôi phải nói rằng – vì cả hai đứa đều đã chết, nên Abe là đứa trẻ tuyệt nhất tôi từng thấy và hi vọng được thấy." (Lincoln, by David Herbert Donald, 1995)

    Năm 1830, sau những khó khăn kinh tế và tranh chấp đất đai ở Indiana, gia đình họ định cư trên một khu đất của chính phủ do cha Lincoln lựa chọn tại Quận Macon, Illinois. Mùa đông năm sau đặc biệt khắc nghiệt, và gia đình họ hầu như sắp phải quay trở lại Indiana. Khi cha ông tái định cư gia đình ở một khu đất gần đó vào năm sau, Lincoln khi ấy đã 22 tuổi quyết định khám phá một mình, đi canô dọc Sông Sangamon tới Quận Sangamon, Illinois, ở làng New Salem. Cuối năm ấy, được một thương gia ở New Salem là Denton Offutt thuê, cùng vài người bạn ông mang hàng hoá từ New Salem đến New Orleans bằng bè trên các con sông Sangamon, IllinoisMississippi. Trong khi ở New Orleans, có lẽ ông đã chứng kiến một phiên bán đấu giá nô lệ để lại những ấn tượng không thể gột sạch trong tâm trí trong cả cuộc đời còn lại. Dù trên thực tế ông có chứng kiến một phiên đấu giá nô lệ vào thời điểm ấy hay không, cuộc sống ở vùng nông thôn với sự hiện diện của nhiều nô lệ có lẽ cũng mang lại cho ông nhiều ví dụ tàn ác tương tự diễn ra hàng ngày.

    Thời gian theo học thực sự của ông có lẽ chỉ kéo dài 18 tháng do các giáo viên không chuyên nghiệp dạy. Trên thực tế ông là người tự học, đọc mọi cuốn sách có thể mượn được. Ông thông thạo Kinh thánh, các tác phẩm của William Shakespeare, lịch sử Anhlịch sử Mỹ, và học được phong cách trình bày giản dị trước thính giả. Ông không thích câu cá và săn bắn vì không muốn giết hại bất cứ một con vật nào kể cả để làm thực phẩm dù ông rất cao và khoẻ, ông dành nhiều thời gian đọc sách tới nỗi những người hàng xóm cho rằng ông cố tình làm vậy để tránh phải làm việc chân tay nặng nhọc. Ông giỏi dùng rìu (vì thế có tên hiệu "người xẻ gỗ"), ông cũng là một đô vật cừ.

    Abraham Lincoln thời trẻ

    [sửa] Khởi nghiệp

    Lincoln bắt đầu nghề nghiệp chính trị năm 1832 khi 23 khi chạy đua vào Quốc hội bang Illinois với tư cách thành viên Đảng Whig. Cương lĩnh tranh cử của ông là tiến hành những cải cách đường thuỷ trên Sông Sangamon với hy vọng thu hút vận tải bằng tàu hơi nước trên sông, điều này cho phép những vùng nghèo khó, dân cư thưa thớt dọc hai bên bờ sông phát triển thịnh vượng. Ông giữ chức đại uý trong một đại đội dân quân Illinois được thành lập ở New Salem trong Chiến tranh Black Hawk, dù ông chưa bao giờ tham chiến. Sau khi trúng cử ông đã viết thư cho những người bạn nói rằng ông chưa từng có "bất kỳ thành công nào đáng hài lòng như vậy trong cuộc sống."

    Ông điều hành một cửa hiệu nhỏ trong một thời gian ngắn ở New Salem, Illinois. Sau khi đọc xong tập hai bộ sách bốn tập Bình luận luật pháp Anh của Ngài William Blackstone, ông đã tự học luật và được nhận vào Hội luật gia bang Illinois năm 1837. Cùng năm ấy, ông rời tới Springfield, Illinois, và bắt đầu làm nghề luật với Stephen T. Logan. Ông trở thành một trong những luật sư thành công và được kính trọng nhất ở Illinois với con đường sự nghiệp ngày càng rộng mở. Lincoln tham gia bốn nhiệm kỳ liên tục trong Hạ viện Illinois, với tư cách đại diện Đảng Whig thuộc Quận Sangamon, bắt đầu từ năm 1834. Ông trở thành một lãnh đạo Đảng Whig trong cơ quan lập pháp. Năm 1837, lần đầu tiên ông đứng ra chống lại chế độ nô lệ tại Quốc hội Illinois, cho rằng chế độ này đã “được lập lên một cách bất công và là một chính sách tồi”. [1]

    Năm 1837 Lincoln gặp người bạn thân nhất của mình Joshua Fry Speed, họ cùng sống với nhau trong bốn năm. "...rất khó để nói rằng ông là người bạn thân duy nhất — bởi vì rõ ràng ông là người bạn cuối cùng — Lincoln từng có."(Nicolay và Hay) Khi Speed cưới vợ tháng 2 năm 1842, từ Springfield Lincoln đã viết: "Hiện tại, tôi cảm thấy ghen tị với cả hai người, các bạn sẽ dành hết sự quan tâm cho nhau, tới mức chẳng còn chút nào dành cho tôi nữa."(Tuyển chọn các bài viết của Lincoln, Basler(ed))

    Năm 1842, Lincoln viết một loạt các bức thư vô danh được đăng trên tờ Sangamo Journal, chế giễu nhân vật danh tiếng của Đảng Dân chủ và là Kiểm toán viên nhà nước James Shields. Khi Shields khám phá ra chính Lincoln là tác giả của những bức thư đó, ông đã thách đấu với Lincoln. Bởi vì Shields là người thách đấu, Lincoln được lựa chọn vũ khí và ông đã chọn loại "Kiếm kỵ binh cỡ lớn nhất." Lincoln cao, tay dài hơn nên có ưu thế rõ rệt; cuộc thách đấu đã bị hủy bỏ vào giây phút cuối cùng. [2]

    Năm 1841, Lincoln hành nghề luật cùng William Herndon, một người bạn trong Đảng Whig. Năm 1856, hai người tham gia Đảng Cộng hoà. Sau khi Lincoln chết, Herndon bắt đầu sưu tập các câu chuyện về Lincoln từ những người từng biết ông ở Illinois, và xuất bản chúng trong cuốn Lincoln của Herndon.

    [sửa] Gia đình

    Ngày 4 tháng 11, 1842, khi 33 tuổi, Lincoln cưới Mary Todd. Họ có bốn người con.

    Chỉ Robert sống được tới tuổi trưởng thành. Robert có ba con và ba cháu. Không một ai trong số cháu của ông có con, vì thế dòng dõi Lincoln chấm dứt khi Robert Beckwith (cháu trai của Lincoln) chết ngày 24 tháng 12, 1985. [3]

    [sửa] Làm chính trị tại Illinois

    Lincoln những năm 1840
    Hình ảnh của Lincoln trên đồng 5 dollar Hoa Kỳ.

    Năm 1846, Lincoln trúng cử một nhiệm kỳ Hạ viện Mỹ. Là một đảng viên trung thành của Đảng Whig, Lincoln thường coi lãnh đạo đảng Henry Clay là thần tượng chính trị của mình. Vì là thành viên lần đầu vào Hạ viện, Lincoln không có nhiều quyền lực hay ưởng hưởng tại đó. Ông đã lên tiếng chống lại cuộc chiến tranh với Mexico, mà ông coi là tham vọng giành "vinh quang quân sự - cây cầu vồng đẹp đẽ đó, xuất hiện sau những cơn mưa máu" của Tổng thống Polk. Bên cạnh cách nói hùng biện đó, ông cũng trực tiếp phản đối tuyên bố biên giới Texas của Polk. [1]

    Lincoln là một trong 82 thành viên Đảng Whig đánh bại 81 thành viên Dân chủ trong một cuộc bầu cử thủ tục tháng 1 năm 1848 về việc sửa đổi nhằm gửi ngược lại một nghị quyết thông thường cho ủy ban với những hướng dẫn để ủy ban thêm vào câu sau "...một cuộc chiến tranh không cần thiết và phi hiến đã bắt đầu bởi Tổng thống Hoa Kỳ". Việc sửa đổi được thông qua, nhưng dự luật không bao giờ được ủy ban tái đề xuất và từ đó cũng không bao giờ được bỏ phiếu thông qua lần cuối. [2].

    Lincoln đã mất một phần uy tín sau bài phát biểu quá khích trước Hạ viện. Ông tuyên bố, "Chúa trời đã quên không bảo vệ những kẻ yếu ớt và vô tội, và đã cho phép những băng đảng giết người cũng những tên quỷ sứ từ địa ngục giết hại đàn ông, phụ nữ và trẻ em, đưa rác rưởi và sự cướp bóc tới miền đất của sự công bằng". Chỉ hai tuần sau, Polk đã gửi một hiệp ước hòa bình tới Hạ viện. Không ai ở Washington có bất kỳ chú ý nào tới Lincoln, nhưng những thành viên Dân chủ đã tổ chức một cuộc phản đối tại quê hưởng ông, nơi chiến tranh được ủng hộ và nhiều người dân tình nguyện ra trận. Tại Hạt Morgan, các nghị quyết được thông qua theo chiều hướng ủng hộ chiến tranh và sự lên án đầy thịnh nộ trước "những cuộc tấn công phản nghịch của những tên du kích trong nước; những đảng mị dân;" những kẻ vu khống Tổng thống, những kẻ bảo vệ sự giết chóc tại Alamo, những kẻ phỉ báng tinh thần anh dũng tại San Jacinto. Đối tác pháp luật của Lincoln là William Herndon đã cảnh báo ông rằng sự chống đối đang tăng lên và uy tín của ông đang giảm sút không thể cứu chữa; chính Lincoln cũng thất vọng, và ông đã quyết định không ra tái tranh cử. Trong cuộc bầu cử mùa thu năm 1848 ông đã cổ vũ mạnh mẽ cho Zachary Taylor, vị tướng thành công nhưng từng bị ông tố cáo những hành động tàn ác trong tháng 1. Những cuộc tấn công của Lincoln về phía Polk sẽ lại quay trở lại trong cuộc Nội Chiến. [Beveridge 1: 428-33] Nội các đang được thành lập của Taylor trao cho Lincoln chức Thống đốc Lãnh thổ Oregon xa xôi. Chấp nhận điều này đồng nghĩa với việc chấm dứt công việc của ông tại bang Illinois đang phát triển nhanh chóng, vì thế ông đã từ chối. Lincoln quay trở lại Springfield, ông ngừng các hoạt động chính trị và quay sang kiếm sống với nghề luật sư, nghề này mang lại cho ông nhiều chuyến đi dài trên lưng ngựa từ hạt này sang hạt khác.

    [sửa] Nhiệm kỳ tổng thống (1861 - 1865)

    [sửa] Ám sát

    Ngày 14 tháng 4 năm 1865, Lincoln bị John Wilkes Booth ám sát tại Ford's Theatre, Washington, D.C.. Ông đã qua đời vào ngày hôm sau và trở thành vị tổng thống Hoa Kỳ đầu tiên bị sát hại.
    Trước:
    John Frémont
    Ứng cử viên tổng thống Đảng Cộng hòa Hoa Kỳ
    1860 (thắng cử), 1864 (thắng cử)
    Sau:
    Ulysses Grant
    Trước:
    James Buchanan
    Tổng thống Hoa Kỳ
    4 tháng 3, 186115 tháng 4, 1865
    Sau:
    Andrew Johnson

    November 13

    Dump Microsoft, Sun Certificate

    Ref: http://www.examcollection.com/

     

    Have you ever prepared for a certification exam using PDFs or braindumps? If yes, then I think you will agree with me that using practice test software is more comfortable and efficient way to prepare.

    The purpose of this site is to help you use TestKing, ExamSheet, ActualTest, Braindumps and other PDFs as practice exams, not the multipage text documents as most of us have used it.

    Here you can download free practice tests for such certifications as MCSE, MCDBA, MCSD, A+, Network+, Security+, CCNA, CCNP, and so on. All tests on this site have been created with Visual CertExam Suite. Visual CertExam Suite is an exam simulator developed for certification exam preparation. You can also use it as a Trandumper replacement. Files with VCE extension can be opened with this program.

    Visual CertExam Manager Visual CertExam Manager

    Will it help me? Just look at our I'm Certified forum.

    Top 30 Practice Exams
    Exam

    Microsoft TestKing 70-290 v48.0 by lehnon.vce
    70-290

    Microsoft TestKing 70-270 v34 by sHaDYvB 210q.vce
    70-270

    Microsoft ActualTests 70-290 by Beebe717 436q.vce
    70-290

    Microsoft ActualTests 70-291 v01.01.06 by Manfish.vce
    70-291

    Microsoft ActualTests 70-270 by Beebe717 204q.vce
    70-270

    Microsoft TestKing 70-291 v52 390q.vce
    70-291

    Microsoft ActualTests 70-270 v 09 11 06 by elegipcio 210q.vce
    70-270

    Microsoft TestKing 70-293 v33.0 By Bohack 251q.vce
    70-293

    Microsoft TestKing 70-294 v32 by Adil q254.vce
    70-294

    Microsoft Actualtest 70-431 v03-05-07 by Jim316.vce
    70-431

    Microsoft TestKing 70-431 by Wedge 80q.vce
    70-431

    Microsoft TestKing 70-270 v34 By Darkons 218q.vce
    70-270

    Microsoft TestKing 70-284 v33.0 by Pedro 151q.vce
    70-284

    Microsoft TestKing 70-299 v14.0 by Goswami 124q.vce
    70-299

    Microsoft Pass4sure 70-291 v2.4 by EvilRen 132q.vce
    70-291

    Microsoft TestInside 70-290 v9.5 by Dundar corrected.vce
    70-290

    Cisco TestKing 640-802 v13 182q.vce
    640-802

    Cisco Testking 640-802 v9 by Ajay Vernekar 676q.vce
    640-802

    Microsoft TestKing 70-290 v59 2008-04-14 by Scorplion 839q.vce
    70-290

    Microsoft Pass4Sure 70-647 144q.vce
    70-647

    Microsoft ExactPapers 70-290 by robwm 210q.vce
    70-290

    Microsoft Pass4Sure 70-646 132q.vce
    70-646

    Microsoft Pass4sure 70-649 v2 83 by BerTy 98q.vce
    70-649

    Microsoft Pass4Sure 70-620 v2 73 corrected by mcse cop 112q.vce
    70-620

    Latest VCE Uploads
    Exam
    Date

    EMC ExamWorx E20-340 v2 73 by Alle Fragen 180q.vce
    E20-340
    10-Nov-2008

    Sun TestKing 310-083 v2008-11-07 by Web Component 100q.vce
    310-083
    10-Nov-2008

    Oracle ActualTests 1Z0-042 v2008-04-04 by rrcastro 286q.vce
    1Z0-042
    10-Nov-2008

    Citrix TestKing 1Y0-614 v2.1 by okidoki 61q.vce
    1Y0-614
    10-Nov-2008

    Cisco TestKing 642-901 v11.0 by Osama 647q.vce
    642-901
    10-Nov-2008

    Microsoft TestKing 70-551 v2007-10-25 by FuzzyBeeR 541q.vce
    70-551
    10-Nov-2008

    Microsoft Braindump 70-562 v2008-11-10.vce
    70-562
    10-Nov-2008

    Microsoft CertGuaranteed 70-640 v2008-10-06 by jteylingen 110q.vce
    70-640
    10-Nov-2008

    Microsoft TestInside 70-351 v3 86 2008-11-04 by Remy 87q.vce
    70-351
    10-Nov-2008

    ITIL ExamWorx EX0-101 v2 73 by Ricky64 120q.vce
    EX0-101
    02-Nov-2008

    CheckPoint Braindumps 156-706 v1.0 by EK 90q.vce
    156-706
    02-Nov-2008

    CompTIA ActualTests SY0-101 v2008-10-13 by plan2000 749q.vce
    SY0-101
    02-Nov-2008

    HP ActualTests HP0-207 v2008-07-24 by KiniX 191q.vce
    HP0-207
    02-Nov-2008

    HP CertifyDump HP0-J21 v2008-10-31 by David 73q.vce
    HP0-J21
    02-Nov-2008

    Microsoft ActualCert 70-285 v2008-10-29 by NovaYear 80q.vce
    70-285
    02-Nov-2008

    ITIL TestInside EX0-101 v2008-08-29 by Ricky64 72q.vce
    EX0-101
    27-Oct-2008

    Microsoft CertKiller 70-649 v2008-10-23 370q.vce
    70-649
    23-Oct-2008

    VMware ActualTests VCP-310 v2008-08-22 by PANIC 295q.vce
    VCP-310
    22-Oct-2008

    VMware Actualtests VCP-310 v2008-10-14 by massmagic 295q.vce
    VCP-310
    22-Oct-2008

    Microsoft ActualTests 70-447 v8.1 by DEPOLO 120q.vce
    70-447
    22-Oct-2008

    Latest PDF Store Uploads
    Date

    Citrix TestInside 1Y0-456 v1 72 38q.pdf
    10-Nov-2008

    Microsoft RealExams 70-633 v2 73 165q.pdf
    10-Nov-2008

    Microsoft RealExams 70-634 v2 73 94q.pdf
    10-Nov-2008

    Microsoft RealExams 72-632 v2 73 165.pdf
    10-Nov-2008

    Oracle Braindump 1Z0-046 v2008-10-24 119q.pdf
    10-Nov-2008

    Cisco TestKing 642-901.pdf
    10-Nov-2008

    Cisco TestKing 642-812 v11.0 200q.pdf
    10-Nov-2008

    Sun ActualTests 310-875 v2008-10-27 70q.pdf
    02-Nov-2008

    Sun ActualTests 310-876 v2008-10-27 140q.pdf
    02-Nov-2008

    LPI TestKing 117-102 v18 450q.pdf
    02-Nov-2008

    NetApp Killtest NS0-101 v2008-05 85q.pdf
    02-Nov-2008

    NetApp Killtest NS0-102 v2008-09 176q.pdf
    02-Nov-2008

    Sun ActualTests 310-100 v2008-10-28 138q.pdf
    02-Nov-2008

    HP ActualTests HP0-084 v2008-07-23 80q.pdf
    02-Nov-2008

    HP ActualTests HP0-145 v2008-06-02 95q.pdf
    02-Nov-2008

    Microsoft ActualTests 70-290 v2008-09-18 919q.pdf
    27-Oct-2008

    Microsoft TestKing 70-294 v2008-08-19 411q.pdf
    22-Oct-2008

    VMware Actualtests VCP-310 v2008-10-14-08 295q.pdf
    22-Oct-2008

    VMware TestKing VCP-310 v28.pdf
    20-Oct-2008

    Citrix TestInisde 1Y0-731 v2 21.pdf
    14-Oct-2008

    Phân biệt iPhone 3G bản quốc tế và bản AT&T(lock)

     

    Kể từ khi Apple ra mắt iPhone 3G thì trên thị trường song hành 2 phiên bản iPhone 3G là: iPhone 3G phiên bản quốc tế và phiên bản bị khóa mạng được phân phối qua các Hãng Dịch vụ viễn thông như AT&T, Optus, SingTel, Vodafon...(ở VN chủ yếu là của AT&T - Mỹ). Điểm khác biệt của 2 phiên bản này ngoài giá thành (phiên bản QT 16Gb giá hơn 1100$, phiên bản AT&T + X-sim giá khoảng 900$) còn ở tính ổn định của sản phẩm. iPhone 3G - bản quốc tế không bị khóa mạng nên có thể dùng bất cứ SIM nào có nghe/gọi được ngay, ngoài ra khi update phần mềm, cài ứng dụng vv người dùng hoàn toàn yên tâm.
    Với phiên bản bị locked At&T muốn dùng phải ghép với một thiết bị gọi là X-Sim(hay còn gọi là Fake-Sim) hoặc giải mã phần cứng(mở máy) cho nên về thời lượng Pin cũng như tính ổn định trong vận hành cũng không bằng. Gần đây có thông tin là một số người bán hàng iPhone3G dùng x-Sim(ghép trong máy) nhưng lại nói với khách hàng là bản Quốc tế gây thiệt hại cho người tiêu dùng. Để cung cấp thông tin khách quan giúp khách hàng tránh nhầm lẫn chúng tôi đưa ra một vài điểm để phân biệt giữa 2 phiên bản này:
    1. Phân biệt iphone 3G AT&T (Lock) và iphone 3G phiên bản Quốc Tế thông qua vỏ hộp:
    Ngay từ vỏ hộp của 2 phiên bản cũng có thể phân biệt rất dễ dàng, phiên bản quốc tế(global) không bị khóa máy nên không cần giải mã (legally unlocked). Phiên bản đặc biệt này chỉ bán tại Italia và HongKong, Úc kích thước là Hộp cao hơn phiên bản 2G 1 cm và cao hơn phiên bản 3G AT&T 2,5 cm. Chiều cao của hộp là 7,9 cm và không có Logo AT&T.
    Hình ảnh
    Hình ảnh
    Phụ kiện theo máy : Tai nghe, cáp ( AT&T và Quốc Tế giống nhau) . Nhưng Adaptor Sạc của phiên bản Quốc Tế to như sạc iphone 2G và có thêm 1 đầu nối 3 chấu
    Hình ảnh
    Hình ảnh
    2. Kiểm tra máy:
    - Phiên bản quốc tế thì bạn có thể cho bất kỳ Sim GSM nào là dùng được ngay. Bản locked dùng x-sim khi bật máy thường hiện "no service" một lúc mới có sóng Vinaphone, mobiFone...
    - Cũng có thể xem model máy: Setting> General> Model nếu là:
    Hai ký tự cuối là LL : xxxxxLL thì thường là bản AT&T locked
    Hai ký tự cuối là ZP: xxxxxZP thường là bản quốc tế, xuất sứ HKBa ký tự cuối là 96X: xxx96X thường là bản quốc tế, xuất sứ Úc
    * chúng tôi sẽ tiếp tục cập nhật các đặc điểm , cách phân biệt
    Thảo luận về cách phân biệt iphone 3G quốc tế và iPhone Locked+ x-Sim trên diễn đàn tinh tế: http://tinhte.com/forum/showthread.php?t=96335

     

    Cac Web site ve iPhone

    http://iphoneviet.com/

    http://tinhte.com/forum/showthread.php?t=96335

    November 01

    Service-Oriented Architecture (SOA) and Web Services: The Road to Enterprise Application Integration (EAI)

    Service-Oriented Architecture (SOA) and Web Services: The Road to Enterprise Application Integration (EAI)








     
    By Qusay H. Mahmoud, April 2005  

    Most enterprises have made extensive investments in system resources over the course of many years. Such enterprises have an enormous amount of data stored in legacy enterprise information systems (EIS), so it's not practical to discard existing systems. It's more cost-effective to evolve and enhance EIS. But how can this be done? Service Oriented Architecture (SOA) provides a cost-effective solution.

    SOA is not a new concept. Sun defined SOA in the late 1990's to describe Jini, which is an environment for dynamic discovery and use of services over a network. Web services have taken the concept of services introduced by Jini technology and implemented it as services delivered over the web using technologies such as XML, Web Services Description Language (WSDL), Simple Object Access Protocol (SOAP), and Universal Description, Discovery, and Integration(UDDI). SOA is emerging as the premier integration and architecture framework in today's complex and heterogeneous computing environment. Previous attempts didn't enable open interoperable solutions, but relied on proprietary APIs and required a high degree of coordination between groups. SOA can help organizations streamline processes so that they can do business more efficiently, and adapt to changing needs and competition, enabling the software as a service concept. eBay for example, is opening up its web services API for its online auction. The goal is to drive developers to make money around the eBay platform. Through the new APIs, developers can build custom applications that link to the online auction site and allow applications to submit items for sale. Such applications are typically aimed at sellers, since buyers must still head to ebay.com to bid on items. This type of strategy, however, will increase the customer base for eBay.

    SOA and web services are two different things, but web services are the preferred standards-based way to realize SOA. This article provides an overview of SOA and the role of web services in realizing it. The article provides:

    • An overview of software as a service
    • A tutorial on SOA
    • An overview of Sun's platforms for building web services
    • Guidelines for designing interoperable web services
    • Challenges in moving to SOA
    • An overview of Java Business Integration (JSR 208)
    • A discussion of web services for enterprise application integration
    Service-Oriented Architecture

    SOA is an architectural style for building software applications that use services available in a network such as the web. It promotes loose coupling between software components so that they can be reused. Applications in SOA are built based on services. A service is an implementation of a well-defined business functionality, and such services can then be consumed by clients in different applications or business processes.

    SOA allows for the reuse of existing assets where new services can be created from an existing IT infrastructure of systems. In other words, it enables businesses to leverage existing investments by allowing them to reuse existing applications, and promises interoperability between heterogeneous applications and technologies. SOA provides a level of flexibility that wasn't possible before in the sense that:

    • Services are software components with well-defined interfaces that are implementation-independent. An important aspect of SOA is the separation of the service interface (the what) from its implementation (the how). Such services are consumed by clients that are not concerned with how these services will execute their requests.
    • Services are self-contained (perform predetermined tasks) and loosely coupled (for independence)
    • Services can be dynamically discovered
    • Composite services can be built from aggregates of other services

    SOA uses the find-bind-execute paradigm as shown in Figure 1. In this paradigm, service providers register their service in a public registry. This registry is used by consumers to find services that match certain criteria. If the registry has such a service, it provides the consumer with a contract and an endpoint address for that service.

    Figure 1: SOA's Find-Bind-Execute Paradigm
    Figure 1: SOA's Find-Bind-Execute Paradigm

    SOA-based applications are distributed multi-tier applications that have presentation, business logic, and persistence layers. Services are the building blocks of SOA applications. While any functionality can be made into a service, the challenge is to define a service interface that is at the right level of abstraction. Services should provide coarse-grained functionality.

    Realizing SOA with Web Services

    Web services are software systems designed to support interoperable machine-to-machine interaction over a network. This interoperability is gained through a set of XML-based open standards, such as WSDL, SOAP, and UDDI. These standards provide a common approach for defining, publishing, and using web services.

    Sun's Java Web Services Developer Pack 1.5 (Java WSDP 1.5) and Java 2 Platform, Enterprise Edition (J2EE) 1.4 can be used to develop state-of-the-art web services to implement SOA. The J2EE 1.4 platform enables you to build and deploy web services in your IT infrastructure on the application server platform. It provides the tools you need to quickly build, test, and deploy web services and clients that interoperate with other web services and clients running on Java-based or non-Java-based platforms. In addition, it enables businesses to expose their existing J2EE applications as web services. Servlets and Enterprise JavaBeans components (EJBs) can be exposed as web services that can be accessed by Java-based or non-Java-based web service clients. J2EE applications can act as web service clients themselves, and they can communicate with other web services, regardless of how they are implemented.

    Web Service APIs

    The Java WSDP 1.5 and J2EE 1.4 platforms provide the Java APIs for XML (JAX) that are shown in Table 1.

    Table 1: Java APIs for XML (JAX) provided by J2EE 1.4
    API
    Description
    This API lets you process XML documents by invoking a SAX or DOM parser in your application. JAXP 1.2 supports W3C XML Schema.
    This is an API for building and deploying SOAP+WSDL web services clients and endpoints.
    This is a Java API for accessing different kinds of XML registries. It provides you with a single set of APIs to access a variety of XML registries, including UDDI and the ebXML Registry. You don't need to worry about the nitty-gritty details of each registry's information model.
    This API lets you produce and consume messages conforming to the SOAP 1.1 specification and SOAP with Attachments note.
    JSR 109 defines deployment requirements for web services clients and endpoints by leveraging the JAX-RPC programming model. In addition, it defines standard deployment descriptors using the XML Schema, thereby providing a uniform method of deploying web services onto application servers through a wide range of tools.
     

    Note: JAX-RPC 1.1 and SAAJ 1.2 include support for the Web Services Interoperability (WS-I) and the Web Services Interoperability Basic Profile (WSI-BP), currently being developed by http://www.ws-i.org, which provides a set of guidelines on how to develop interoperable web services.

    With the APIs described in Table 1, you can focus on high-level programming tasks, rather than low-level issues of XML and web services. In other words, you can start developing and using Java WSDP 1.5 and J2EE 1.4 web services without knowing much about XML and web services standards. You only need to deal with Java semantics, such as method invocation and data types. The dirty work is done behind the scenes, as discussed further in the next section.

    Figure 2 illustrates how the JAXR and JAX-RPC APIs play a role in publishing, discovering, and using web services and thus realizing SOA.

    Figure 2: Web services Publish-Discover-Invoke model
    Figure 2: Web services Publish-Discover-Invoke model
    Web Services Endpoints in J2EE 1.4

    The J2EE 1.4 platform provides a standardized mechanism to expose servlets and EJBs as web services. Such services are considered web service endpoints (or web service ports), and can be described using WSDL and published in a UDDI registry so that they can be discovered and used by web service clients.

    Once a web service is discovered, the client makes a request to a web service. The web service processes the request and sends the response back to the client. To get a feeling for what happens behind the scenes, consider Figure 2, which shows how a Java client communicates with a Java web service in the J2EE 1.4 platform. Note that J2EE applications can use web services published by other providers, regardless of how they are implemented. In the case of non-Java-based clients and services, the figure would change slightly, however. As mentioned earlier, all the details between the request and the response happen behind the scenes. You only deal with typical Java programming language semantics, such as Java method calls, Java data types, and so forth. You needn't worry about mapping Java to XML and vice-versa, or constructing SOAP messages. All this low-level work is done behind the scenes, allowing you to focus on the high-level issues.

    Figure 3: A Java Client Calling a J2EE Web Service
    Figure 3: A Java Client Calling a J2EE Web Service (click image for full size)

    Note: J2EE 1.4 and Java WSDP 1.5 support both RPC-based and document-oriented web services. In other words, once a service is discovered, the client can invoke remote procedure calls on the methods offered by the service, or send an XML document to the web service to be processed

    Interoperability

    Interoperability is the most important principle of SOA. This can be realized through the use of web services, as one of the key benefits of web services is interoperability, which allows different distributed web services to run on a variety of software platforms and hardware architectures. The Java programming language is already a champion when it comes to platform independence, and consequently the J2EE 1.4 and Java WSDP 1.5 platforms represent the ideal platforms for developing portable and interoperable web services.

    Interoperability and portability start with the standard specifications themselves. The J2EE 1.4 and Java WSDP 1.5 platforms include the technologies that support SOAP, WSDL, UDDI, and ebXML. This core set of specifications -- which are used to describe, publish, enable discovery, and invoke web services -- are based on XML and XML Schema. If you have been keeping up with these core specifications, you know it's difficult to determine which products support which levels (or versions) of the specifications. This task becomes harder when you want to ensure that your web services are interoperable.

    The Web Services Interoperability Organization (WS-I) is an open, industry organization committed to promoting interoperability among web services based on common, industry-accepted definitions and related XML standards support. WS-I creates guidelines and tools to help developers build interoperable web services.

    WS-I addresses the interoperability need through profiles. The first profile, WS-I Basic Profile 1.0 (which includes XML Schema 1.0, SOAP 1.1, WSDL 1.1, and UDDI 2.0), attempts to improve interoperability within its scope, which is bounded by the specification referenced by it.

    Since the J2EE 1.4 and Java WSDP 1.5 platforms adhere to the WS-I Basic Profile 1.0, they ensure not only that applications are portable across J2EE implementations, but also that web services are interoperable with any web service implemented on any other platform that conforms to WS-I standards such as .Net.

    Challenges in Moving to SOA

    SOA is usually realized through web services. Web services specifications may add to the confusion of how to best utilize SOA to solve business problems. In order for a smooth transition to SOA, managers and developers in organizations should known that:

    • SOA is an architectural style that has been around for years. Web services are the preferred way to realize SOA.
    • SOA is more than just deploying software. Organizations need to analyze their design techniques and development methodology and partner/customer/supplier relationship.
    • Moving to SOA should be done incrementally and this requires a shift in how we compose service-based applications while maximizing existing IT investments.

    Sun has recognized the challenges customers face in moving to SOA and has developed an SOA Opportunity Assessment service offering that leverages years of experience in delivering enabling technology solutions that met the unique needs of each customer. Sun's SOA Opportunity Assessment provides customers with an analysis of their organization's readiness to move to SOA, and a set of best practices developed to complement this service offering, and helps them identify business-relevant opportunities for building their service-oriented applications using architectural best practices and reusable design patterns. For more information on this as well as additional Sun SOA services offerings, see Assessing your SOA Readiness (pdf).

    In addition, Sun's Java BluePrints provide developers with guidelines, patterns, and sample applications. Java BluePrints has a book on Designing Web Services with J2EE 1.4, which is the authoritative guide to the best practices for designing and integrating enterprise-level web services using J2EE 1.4. It provides the guidelines, patterns, and real-world examples architects and developers need in order to shorten the learning curve and start building robust, scalable, and portable solutions.

    It is also worth noting that the Java BluePrints Solutions Catalog has a section on SOA with web services.

    Java Business Integration

    Enterprises have invested heavily in large-scale packaged application software such as enterprise resource planning (ERP), supply chain management (SCM), customer relationship management (CRM), and other systems to run their businesses. IT managers are being asked to deliver the next generation of software applications that will provide new functionality, while leveraging existing IT investments. The solution to this is integration technology; the available integration technology solutions, however, are proprietary and do not interoperate with each other. The advent of web services and SOA offers potential for lower integration costs and greater flexibility.

    JSR 208 Java Business Integration (JBI), is a specification for a standard that describes plug-in technology for system software that enables a service-oriented architecture for building integration server software. JBI adopts SOA to maximize the decoupling between components, and create well-defined interoperation semantics founded on standards-based messaging. JSR 208 describes the service provider interfaces (SPIs) that service engines and bindings plug into, as well as the normalized message service that they use to communicate with each other. It is important to note that JSR 208 doesn't define the engines or tools themselves. JSR 208 has the following business advantages:

    • It is itself a service-oriented architecture that will be highly flexible, extensible, and scalable.
    • Service engines could be implemented in any language as long as they support the SPI definition implemented by JSR 208 compliant systems.
    • New engines can be added to the container by plugging them into the standard SPI and defining the messages they will use to interact with the rest of the system.
    • ISVs that specialize in one of these components could be able to plug special-purpose engines into industry-standard integration solutions.
    • Open interfaces will enable free and open competition around the implementation of these engines. This means that customers will be free to choose the best solution available, and their integration code can be migrated between implementations.

    A JSR 208 example architecture is shown in Figure 4.

    Figure 4: An Example Architecture Based on JSR 208
    Figure 4: An Example Architecture Based on JSR 208 (click image for full size)

    As you can see, JBI provides an environment in which plug-in components reside. Interaction between the plug-in components is by means of message-based service invocation. Services produced and consumed by plug-in components are modeled using WSDL (version 2.0). A normalized message consists of two parts: the abstract XML message, and message metadata (or message context data), which allows for association of extra information with a particular message as it is processed by plug-in and system components.

    Project Shasta

    Sun's Project Shasta, which is based on the JSR 208 architecture, aims to build a next-generation integration solution. This project will be implemented on Sun's J2EE application server and leverage J2EE services such as Java Message Service (JMS), J2EE Connector Architecture (JCA), failover, and high availability. It will feature many of the emerging standards in the web services (such as web service notification, coordination, and transaction management) and integration space. The project will be focused on web services and using them to enable the creation of service-oriented architectures. Figure 5 depicts what a fully implemented product could look like.

    Figure 5: An Example Architecture Based on JSR 208
    Figure 5: An Example Architecture Based on JSR 208 (click image for full size)
    Web Services and J2EE 1.4 for Enterprise Application Integration

    Web services, which build on knowledge gained from other mature distributed environments (such as CORBA and RMI), offer a standardized approach to application-to-application communication and interoperability. They provide a way for applications to expose their functionality over the web, regardless of the application's programming language or platform. In other words, they allow application developers to master and manage the heterogeneity of EIS.

    Web services let developers reuse existing information assets by providing developers with standard ways to access middle-tier and back-end services and integrate them with other applications.

    Since web services represent gateways to existing back-end servers, strong support for back-end integration is required. This is where the J2EE platform comes into play. The J2EE platform provides industry-standard APIs (such as the J2EE Connector Architecture, the JDBC API, Java Message Service (JMS), among others) for accessing legacy information systems. J2EE 1.4 (which supports web services) provides an excellent mechanism to integrate legacy EIS and expose their functionality as interoperable web services, thereby making legacy data available on heterogeneous platform environments.

    Conclusion

    The advent of web services and SOA offers potential for lower integration costs and greater flexibility. An important aspect of SOA is the separation of the service interface (the what) from its implementation (the how). Such services are consumed by clients that are not concerned with how these services will execute their requests. Web services are the next step in the Web's evolution, since they promise the infrastructure and tools for automation of business-to-business relationships over the Internet.

    JSR 208 (Java Business Integration) has the potential to revolutionize the industry as it provides a way for platform vendors, system integrators, and enterprise software developers to collaborate on integration solutions that have the flexibility to move with a changing market.

    For More Information
    Acknowledgments

    Understanding Service Oriented Architecture

    Understanding Service Oriented Architecture

    by David Walend
    04/04/2006

    Service Oriented Architecture (SOA) promises to provide us with the ability to assemble complex, distributed systems by selecting and creating compatible parts called services. So far, SOA has delivered a lot of hyperbole to the Web. Gartner recognized it as one of the five hottest IT trends in 2005, claiming that "By 2008, SOA will provide the basis for 80 percent of development projects." At JavaOne 2005, 82 of the 168 technical session PDFs contained "SOA." In July of 2005, there were 1.4 million Google hits for "service oriented architecture." By February, 2006, there were 72 million. SOA is riding a rising tide as the next big thing for enterprise developers.

    Unfortunately, most developers find it hard to cut through this tide of hype to learn just what service oriented architecture is about. Forests of three-letter acronym (TLA) standards sprout, bloom, and are overgrown before any of us can learn enough about them to decide if they are appropriate for our own projects. The standards compete for our attention and allegiance. Further, most articles and presentations focus on a specific TLA, and how to make some legacy system fit within someone else's favorite web service plumbing. "Legacy" seems to mean "the software that has to keep working to keep the system alive and useful to the business."

    I started working with distributed messaging systems in 1995 and can understand most of the articles, but I find the volume of hype daunting and largely irrelevant. This article focuses on what you can get out of SOA to make developing and maintaining software easy, and help your businesses run better. Here's what you can get out of service oriented architecture:

    • Better understanding of the system being developed.
    • Better-organized, better-focused incremental development.
    • Easier integration with each others' systems.
    • Well-defined boundaries for tests.
    • More big-block reuse of code by reusing services.
    • Scaling up by creating systems of systems.
    • More reliability via restartable services.
    • Development focused on executable business plans.

    That list is a huge promise. No wonder there's so much hype. Unfortunately, the list doesn't hold anything we can code. Aside from being able to restart a service, it's not specific at all. Service oriented architectures bring together specific good ideas from the 1980s and 1990s to create a complex system from simple parts. Service oriented architectures have these characteristics:

    • Services have strong software contracts.
    • Services are encapsulated.
    • Messages are documents.
    • Services share a message bus.
    • Services are loosely coupled.
    • Services have a life cycle.
    • Systems of services are assembled at runtime.
    • Services can be discovered.
    • Systems of services can grow into systems of systems.

    Services Have Strong Software Contracts

    A strong software contract defines the role that the service plays. Services are a realization of software design-by-contract. A service's contract describes what messages a service will receive, what messages a service will send, and what error signals a service will send when things go wrong. In service oriented architecture contracts, hidden state invariants tend to be less important. High-level descriptions of any side effects-- especially changes in exposed internal state--take center stage. The software contract serves as a design guide, test plan, and programmer's interface. Share the service's software contract with people when they ask you what the service does. Use the software contract to help your managers decide which services to build first, to address some immediate needs of your business.

    Java's JavaDoc provides a nice start for software contracts. By using JavaDoc, especially package.html files, you can guide other developers to the important parts of your code and share the important details. Most Java developers have learned to read the JavaDoc if they read anything at all, so it is your best bet for describing your contract to them. WSDL files include a very precise description of a service's programming interface in a computer-readable format. However, WSDL files are separate from code (so they won't be found) and hard on the eyes (so important details will be missed). I like to create Java interfaces to hold specific details of services in my system. JDK 5 annotations can help, too, especially those from JSR-181, which will be standard in JDK 6. Annotations are computer-readable, available in JavaDoc, and are embedded in code. I think they are the best choice for the structural part of a software contract, but are no substitute for a solid written description.

    Services Are Encapsulated

    Services are encapsulated. A service only exposes the behaviors in its contract. Nothing outside the service can observe internal state and state transitions. How a service fulfills the contract remains hidden. No interesting service can achieve ideal encapsulation; even a service on dedicated hardware will still share limited bandwidth on a network. The best way to handle these details is to add them to the contract; if something that matters to the rest of the system is not in the contract, then the service's contract is incomplete. Fixing bugs in your contract is much easier than fixing encapsulation. Observing and enforcing encapsulation helps prevent creeping complexity growth, a maintenance nightmare.

    The goals of encapsulation line up well with the original promise of object oriented programming: keep responsibility localized and defined. I'm not sure there can be a positive standard for encapsulation, a feature defined by an absence. I have used some existing language features to set boundaries. Java's access keywords (public, protected, default, and private) and JavaDoc provide a nice start. By controlling accessibility, you can keep some parts of the programmer's interface hidden. Language designers at Sun have muttered about some kind of friends keyword in JDK 7, but I haven't seen anything concrete yet.

    Message Contents Are Atomic Documents

    Part of service oriented architecture is document oriented architecture. The contents of the messages that flow in the system are well-defined data structures--like documents. Sending a message effectively makes a copy of a data structure. Once sent, the message can not generally be pulled back and changed. Message data structures need to be complete and compact, and have consistent rules for how to maintain referential integrity. You can easily and directly reference one part of this document data structure from another, but referencing something outside of the structure means extra work with foreign keys. The Java Data Object specification section 6.3 describes this dichotomy well. Good JDO first-class objects are like documents, constructed of subordinate second-class objects. XML uses a slightly more implicit approach. XML files are documents that useIDs and IDREFs or XPath expressions for internal references. Most systems of services have a small local service responsible for finding the right document using foreign keys.

    Obviously, one service needs to be able to understand messages received by another. Agreeing on syntax is the easy part; try Java's serialization if you've got Java on both ends, XML otherwise. If you pick XML, decide how your system will handle referential integrity inside the document. XStream provides a very simple solution that plays havoc with XMLSchema. JAXB 2.0 does a very good job. If you are trying to get services produced by separate groups to communicate for the first time, expect to spend an extraordinary amount of time getting the services to understand each other. Sorting out semantic meaning and corner cases is far more difficult than deciding on syntax.

    Services Share a Message Bus

    Services communicate with each other by sending messages over a shared message bus. SOA proscribes messages to avoid the coupling that comes from services sharing a call stack; if the called service fails silently, the calling service has to wait for it to return. Services use messages in three main styles: request/reply, commands, and events. In request/reply, one service sends a request to another, and dedicates resources, usually a thread, to waiting for the reply. This style leads to coupling almost as tight as when sharing a call stack. One service can send another service a command: a fire-and-forget instruction to do something. The command style leads to modest coupling; the commanding service expects some other service to fulfill the command eventually, but does not dedicate any resources to make sure. A service can simply publish events--notifications that something of interest has happened--without depending on any service to receive the message. Event-based systems of services are very loosely coupled, and can scale up to the limit of the message bus. Monitoring the message bus provides great insight into how well the system works, and creates a reassuring picture for your manager.

    My favorite API for messaging is the Java Messaging Service standard. There are many implementations, most of which focus on reliability in enterprise-scale environments, and some of which include APIs for non-Java systems. Some JMS implementations use peer-to-peer technologies to survive transitory internet and wireless networks. I created SomnifugiJMS for messaging between threads in a single Java process for small-scale systems. If you need to scale to something even smaller, try using BlockingQueues from java.util.concurrent. For large-scale systems on unreliable networks, try using JXTA to construct a reliable network.

    Services Are Loosely Coupled

    Ideally, services only interact by fulfilling their contracts over the message bus. The closer you can come to that ideal, the better. Try to discover and record hidden dependencies like shared call stacks, static tunnels in singletons, and shared processors, memory, disks, databases, and networks. Any dependency can lurk in the background, waiting to break your system. Be aware of coupling between services on the message bus. A service that issues commands and requests is assuming that some other service will fulfill these commands and requests. Even services that expect only events assume that some other service will publish the event. Try to catalog potential problems, but focus your energy on decoupling specific trouble spots before they matter. Loose coupling between services makes replacing one service with another possible. When your manager asks what will be involved in integrating a replacement service, you will have a sound answer.

    A service's reaction to a message should be an atomic action, so services work best as optimistic transaction engines that record and attempt to fix problems. Two-phase-commit transactions across services tightly couple those services. Luckily, most systems larger than a database rarely need to roll back the transaction. Instead, a troubleshooting service in the system needs to be alerted to the problems so that the problems can be sorted out. The troubleshooting service fits surprisingly well into most business workflows because the business wants to reroute the problem transaction instead of wiping it out of existence.

    Services Have Independent Life Cycles

    Each service has its own life and life cycle independent of other services. Individual services may be stopped, restarted, and replaced without stopping the whole system. Batching services like end-of-day processes can start, process all pending messages, and stop. A service can join a wireless network briefly, when a connection is available, and then disconnect later without causing harm. You can even replace an obsolete service with a new version without downtime. I haven't found a good standard for turning services on and off, but it isn't that hard to build. Simple volatile flags in a Runnable's main loop have worked fine so far. W3C has a description of possible states and transitions, but it seems like overkill to me. If you start building your own elaborate system, steer towards that W3C standard. The feature you want is the ability to stop one service and start another to replace it, without stopping the whole system.

    Orchestrators Assemble Services into Systems at Runtime

    Orchestrators are special services that gather and assemble services into larger systems at runtime. Some orchestrators match contracts to orchestration instructions to registered services. Orchestrators often start the services they need. Assembling a service this way is a lot like using Simulink blocks; you choose the parts, connect them to a message bus, and sometimes stimulate the system with an initial message. BPEL and workflow engines like Dalma hold a lot of promise for orchestrating large systems, but I haven't used either for more than simple experiments. The java.net website uses Dalma to coordinate registering new projects. For the systems I have actually built, I used simpler, more general-purpose tools like Jython and Beanshell scripts, and simple Java code to orchestrate the services. I haven't found a language I like that lets me specify a workflow yet, although I am hopeful.

    Orchestrators Can Discover other Services Dynamically

    Services generally register themselves with a service locator. An orchestrator can then use the service locator to find the services it needs dynamically, at runtime. The idea is similar to using the Java Naming and Directory Interface (JNDI) to find the right database connection. I have found service locators much more useful within a single process than on a large scale. I think that's because small systems tend to have a lot of diverse parts, and the larger scale systems I design use events, meaning there's less for them to look up. Systems where distributed services appear and vanish, like the battlefield, the internet, and wireless networks, need reliable large-scale service locators. JNDI works quite well as a service locator on a small scale. Jini works great on a larger scale. Jini can find services that implement a specific Java interface, which is very close to finding services by contract. Others report success with Universal Description, Discovery, and Integration (UDDI) when some services are not in Java.

    Systems of Services Grow into Systems of Systems

    A system composed of services can be a service in its own right. The more that messages are treated like events (instead of requests), the better your system can scale up. Scaling up this way can be the technology jewel in a business plan, and is the most interesting feature for academics and hobbyists. We software engineers need to avoid being too charmed by it. We have to stay focused on the problems at hand. However, compatibility and stability on a large scale will make our next project more gentle.

    To make sure that your system of services can be a service in its own right, make sure the larger system has all of the features that a service should have. The larger system should have a strong service contract, be encapsulated, use atomic messages to communicate, be decoupled from other services, have an independent life cycle, and be discoverable. If all of that is true, a larger-scale orchestrator can use your system as service to assemble something bigger.

    Life in the Standards Zoo

    A large zoo of standards already exists for Java coders. If you can use some of these standards, you will save yourself some effort now. With a little luck, your choice will help you be compatible with some undiscovered service later. WSDL and Java interfaces help define software contracts and encapsulation. Shared messaging busses can come from an ESB, JMS, or java.concurrent.BlockingQueues. Messages as documents can come from XML or serializable objects. Assembly at runtime can come from business languages or scripting, plus a service locator like JNDI, Jini, or UDDI. New standards roll out every week. I use JavaOne Online as a starting point, since these days, Google turns up too many pages trying to sell you something.

    Practice some suspicion when you shop for standards. New standards generally haven't been tried in the field. They may solve problems you don't have, and may not solve the problems you care about. Learning how to get the most out of a standard requires some investment of your time; you won't have time to learn many of the standards before the next batch comes out. Welding your project to some new standard involves risk. If you pick the wrong one, you may wind up maintaining a useless, complex layer for a long time. Enterprise computing pundits battle for control of the standards bodies; they want your attention, your participation, and ultimately, want your money.

    Getting encapsulated, well-designed services to fit behind some new standard is relatively easy. The standard tools get better in leaps and bounds. My own career shows the evolution. From 1998 to 2000 my team created an SOA framework ourselves. Needing three days to explain what we were selling contributed to the company's demise. In 2001, I was part of a contracting team that built a system of services using JMS, Perl and databases. In 2003 at a new job, we wrote our own WSDL to use with WSIF, JMS, and Jython, and put together a demonstration system of services in about a month. Converting an existing system has taken about a year. We ultimately dropped the WSDL in favor of Java interfaces, and stopped using WSIF. Restructuring the code was wonderfully straightforward, and will get easier over time. In June 2005 (post-JSR-181), creating a Java web service involved adding Sun's reference implementation JARs and adding @webmethod annotations to existing code. When JDK 6 provides JSR-181, we get the supporting parts just by adding the annotations.

    Wrapping Up

    Service oriented architecture is a collection of ideas and patterns from the 1980s that survived the 1990s. The concepts behind SOA are sound, solid, tested, and proven. SOA ideas directly address details in business plans about how you will deploy, grow, and evolve your system. Creating encapsulated, loosely coupled software that obeys a clear contract requires discipline, but shows immediate benefits. Getting loosely coupled, encapsulated software behind some new web services standard will be easy.

    David Walend started learning Java with the alpha 3 release in 1994 after a kind computer science professor at Tufts University overheard his tantrum on distributed simulations, memory management, multithreaded code and meteorologists of questionable parentage.

    SOA Reusability: Shrinking the Lag between Business and IT

       
     E-mail     Print     Discuss     Blog

    SOA Reusability: Shrinking the Lag between Business and IT SOA Reusability: Shrinking the Lag between Business and IT

    by Mehul Shah
    07/24/2007

    Today there is no shortage of articles, case studies, and analyst research concerning service oriented architecture (SOA), discussing the benefits of exposing existing IT capabilities as services and reusing these services to create composite applications. However, in their articulation, they are missing how these benefits will be useful to the ultimate end user, i.e. business analysts. Since SOA projects are all about business and IT alignments, support from these business end users is a key to successful SOA adoption efforts in any enterprise. Many SOA projects fail when IT doesn't look at the business side of an SOA solution and business doesn't see SOA as important.

    This article articulates the vision of reusability with a different spin around the business users, the ultimate end users of SOA. The objective of this article is to help the SOA architectural team in two ways: understanding the significance of creating generic and configurable services, and explaining reusability benefit of SOA to business users. This article delivers the message that an ultimate goal of SOA should be a near-zero dependency of business users on IT teams to implement new plans, products, or services based on information-based systems.

    The Evolution of Reusability

    Reusability has been a goal of application development for the last three decades. This evolution of reusability, as shown in Figure 1, started with mnemonics used to represent opcodes, machine instructions executed by the processor. Then came the subroutines, where a repeatedly used set sequence of steps in a larger program are put into independent and reusable modules, and then logically related subroutines are grouped into subroutine libraries. This was followed by object oriented programming and software components with stronger emphasis on modularity and offering more advanced form of reusability. The latest design architecture in this evolution of reusability is service oriented architecture (SOA).

    Figure 1. Evolution of reusability
    Figure 1. Evolution of reusability

    The major difference between service oriented architecture and previous design approaches is that the implementation of design architecture as compared to SOA was tightly tied to the specific execution environments, and reusability was mostly limited within the boundary of the IT department. However, with SOA, for the first time in history, this goal of reusability has spanned over the heterogeneous execution environments, crossed the traditional boundaries of the IT department, and reached the business analysts, the ultimate end users.

    The Lag Between Business and IT

    There has always been a lag between today's business needs and its IT deliverables tomorrow, as shown in Figure 2. Let's take a closer look at the current status of business systems to understand this lag.

    Figure 2. IT lags behind business
    Figure 2. IT lags behind business

    Traditionally, each business unit in an enterprise initiated and worked with IT to develop solutions to perform a specific business activity with a specific implementation. Due to a lack of centralized control within the organization, these solutions were reinvented over and over across business units, with the end result that none of them are really reusable. Mergers and acquisitions further fragmented this isolated monolithic architecture.

    As a result, the enterprise ended up with multiple stovepipes having duplicate functionalities. This traditional application landscape of multiple stovepipes was extremely complex and expensive to maintain or extend. So when the business needed a change in systems, IT seemed slow to deliver it.

    Since the applications could not collaborate with each other to exchange data in a business process, both business and IT needed to perform resource-intensive manual processes for tasks like loading data from different data sources, transforming data into the right common format, and checking the accuracy of these data.

    The time lag between business and IT was further fueled by long planning and design cycles due to siloed business owners, and the availability of subject matter experts.

    Thus the maintenance of multiple rigid stovepipes, resource intensive manual processes, and long planning and design cycles caused the lag between today's business needs and tomorrow's IT deliverables.

    Business Processes Before SOA

    In traditional IT organizations, business processes were hard-coded and hard-wired to integrate monolithic applications. Integration of these monolithic applications to enable collaboration and to exchange data was done using middleware, as shown in Figure 3, which shows the integration of a bank's loan approval application with its customer account management system.

    Figure 3. Application integration using middleware
    Figure 3. Application integration using middleware

    Imagine a typical business scenario in the banking industry: an automated loan approval process. In order to frame the business process for the sample scenario, individual applications such as the credit history system, credit score computing application, loan approval application, customer account management system, etc., are integrated to collaborate using middleware, as shown in Figure 4.

    Figure 4. Loan approval business process before SOA
    Figure 4. Loan approval business process before SOA

    Since these business processes were aligned to software functionality, more customization was done to fulfill specific business needs. Hence, business analysts required help from IT to define, change, or optimize business processes. However, changing these rigid business processes required substantial IT effort.

    Thus, changing the business process was a tough business in itself.

    Why SOA?

    SOA is aimed to shrink this lag between today's business needs and when IT can produce deliverables. SOA enables many of these time-sensitive deliveries by eliminating many of the traditional IT hurdles to change, such as rigid business processes, inflexible IT architectures, and incompatible data representations with commitments to continue supporting existing IT operations.

    As the name suggests, SOA is a solution architecture revolving around services, where a service is a standard-based interface encapsulating either a logical unit of functionality or data to facilitate need-based access to computational resources and promote their reuse. These standards-based service interfaces are often described using Web Service Description Language (WSDL), which provides a homogeneous layer of abstraction, hiding implementation specifics of business logic and data for seamless collaboration across the enterprise. The goal is to be more agile by enabling a mix and match of services and connecting them with contextual information to create new discrete business services.

    Service Reuse

    Software reuse is not new inasmuch as the core idea is to get more value from what has originally been built. For the optimal reuse of services, the first step is to find services that will be of value to business. This involves finding where a duplication of effort exists at the enterprise level, and where services should be introduced. The next step is to ensure service flexibility. SOA-based services may be require to expose inflexible business logic or data that were originally developed to solve a specific business issue. In this case, it will take some work to turn these pre-existing business assets into flexible services.

    Now comes the million-dollar question: since there are limited possibilities one can preview or imagine of various contexts in which a service can be used, how do you ensure flexibility? The flexibility of a service is ensured primarily by its three characteristics: genericity, configurability, and extensibility. The generic characteristic promotes service reuse in different business contexts. Being configurable makes a service adaptable to each specific business context. And extensible services help an organization to add to existing services. Services can also be aggregated by other services collaborating together, making it possible to assemble higher-level composite services or business processes.

    The next step is to promote service reuse. Prior to SOA, a lack of centralized control and communication between business units within organizations caused same solutions to be reinvented over and over again. To ensure that duplicate services are not created across the business units in an organization, SOA stakeholders such as business analysts and architects should be able to find existing business services and evaluate their usefulness for reuse in a well-known and systematic way.

    Hence, a centralized registry of services is required for easy discovery and promoting service reuse at the enterprise level. An entry in such a registry provides functional information such as the name of a service, service operations, and service location for its invocation.

    Since services in SOA encapsulate IT assets and represent its business view, the description of a service should include functional information (such as operations, location of WSDL document, etc.) useful to IT, and non-functional information (such as QoS, SLA, and security) understandable to business analysts, without crawling through the WSDL document. Hence, elements of the service are as shown in Figure 5.

    Figure 5. Service Elements
    Figure 5. Service elements

    Since the functional information available in the registry and the metadata in the WSDL document are not sufficient for promoting service reuse to business analysts, an enterprise needs a service repository that provides information about the non-functional offerings (such as QoS, SLA, etc.) of services. The service registry and service repository are integrated together to provide one logical location for the enterprise to categorize and organize services, to browse and search for existing services, and to publish new services.

    The Ultimate Goal of SOA

    The reuse of services and integration of heterogeneous systems are really interim goals of SOA. The ultimate goal of SOA should be that a business user doesn't have to always come to IT to launch new plans, products, or services, or even generate reports based on IT systems.

    Imagine how business would be without IT integration obstacles and with significantly reduced lag between the business needs and IT deliverables. The ultimate goal of SOA should be that an end user needs near-zero help from IT to define, configure, change, or optimize business processes. This lag between business and IT objectives should let the business user actually help design and modify composite applications or business process, in some instances, using graphical tools. Since many business solutions are composed of multiple services that could work well together, let's now think about SOA in the context of defining and changing business processes.

    The Business Process After SOA

    Using a graphical business-process-management modeling tool connected to the service registry and service repository as shown in Figure 6, a business analyst can either go through categories or define the search criteria on various parameters such as keywords or SLAs to locate the available services that can fulfill the needs of the business process. Then he or she can use these available services as building blocks. An easy-to-use, drag-and-drop graphical user interface of this modeling tool enables business analysts to build composite applications or business processes by graphically wiring services together and can orchestrate them as per business needs.

    Figure 6. Business process modeling tool connected to service registry and repository
    Figure 6. Business process modeling tool connected to service registry and repository

    We will now explore the binding pieces in SOA architecture with examples. Let's take the same business scenario we discussed in the Business Processes Before SOA section above, of an automated loan approval process in the banking industry. In order to frame the SOA solution architecture for the sample scenario, we will first list the individual services required, such as the services "get credit history," "calculate credit score," "loan approval," "customer account management," and so on.

    Once these services are identified and placed in the correct sequence, using a modeling tool, the business analyst connects them together and orchestrates the movement of information and the flow of control between services, in a non-programmatic manner, to attain larger business objectives. Since every transaction of fetching a credit history from a credit bureau costs the bank, the business analyst orchestrates business activities in such a sequence where first the SSN and then the address provided by the loan requester is validated before going to the next activity of getting credit history, as shown in Figure 7.

    Figure 7. Loan approval business process after SOA
    Figure 7. Loan approval business process after SOA

    Since SOA abstracts the complexities of the technical integration using open standards providing homogeneous service interfaces, now the business analyst orchestrates the business process without knowing or worrying about technical feasibility, underlying IT infrastructure, or how two applications will exchange information.

    Now let's say that after several months, business analysts discover that the address provided in loan requests are more often invalid as compared to the SSN. So, to optimize the business process, using the graphical tool, the analysts swap the "Verify SSN" and "Verify Address" services. Now the address is validated before SSN. Due to the standardized and loosely coupled integration between services for these two activities, the business analysts can now optimize business processes without any help from the IT staff. The optimized loan approval business process is shown in Figure 8.

    Figure 8. Optimized loan approval business process
    Figure 8. Optimized loan approval business process

    A business analyst may also be able to respond to shifting compliance regulations or business strategy by making minor adjustments to predetermined services parameters rather than moving to new, and expensive, solutions.

    Picture the impact of being able to respond to changes in hours or days rather than weeks or months. Business users will become champions of SOA, because they will finally have the ability to mix and match services to suit their business processes. Freeing business users from the IT department to quickly react to business changes is what makes SOA effective. Don't forget that a governance model is the key to making this happen.

    Summary

    Buy-in from business owners and management is critical to successful adoption of SOA. The more business relies on IT to get a competitive edge, the more valuable SOA becomes in an organization. Monolithic applications, manual processes, and rigid business processes hindered the productivity of IT in delivering business changes and caused the lag between business and IT.

    We saw that SOA is an architectural solution with key characteristics that distinguish it from previous architectural designs. We also saw that the key principle of SOA is providing business agility by making IT flexible to adapt to changes. Flexible services in SOA, along with the service registry and service repository, provide uniform means to offer, locate, and interact. This promotes and maximizes reuse of services at the enterprise level.

    Thus, the combination of business-process modeling tools and SOA enables business analysts to define, configure, change, and optimize the business process with near-zero involvement of the IT staff. This helps organization to respond and adapt quickly to ever-changing business requirements by shrinking the lag between business and IT.

    Resources

    Mehul Shah is a writer, researcher, and software engineer working at the forefront of the IT and business worlds.


    October 21

    Core banking Concept

    Core banking is a general term used to describe the services provided by a group of networked bank branches. Bank customers may access their funds and other simple transactions from any of the member branch offices.

    ==Core Banking== Core Banking is normally defined as the business conducted by a banking institution with its retail and small business customers. Many banks treat the retail customers as their core banking customers, and have a separate line of business to manage small businesses. Larger businesses are managed via the Corporate Banking division of the institution.Core banking basically is depositing and lending of money.

    Normal core banking functions will include deposit accounts, loans, mortgages and payments. Banks make these services available across multiple channels like ATMs, Internet banking, and branches.

    == Core Banking Solutions ==

    Core Banking Solutions is new jargon frequently used in banking circles. The advancement in technology especially internet and information technology has led to new way of doing business in banking. The technologies have cut down time, working simultaneously on different issues and increased efficiency. The platform where communication technology and information technology are merged to suit core needs of banking is known as Core Banking Solutions. Here computer software is developed to perform core operations of banking like recording of transactions, passbook maintenance, interest calculations on loans and deposits, customer records, balance of payments and withdrawal are done. This software is installed at different branches of bank and then interconnected by means of communication lines like telephones, satellite, internet etc. It allows the user (customers) to operate accounts from any branch if it has installed core banking solutions. This new platform has changed the way banks are working. Now many advanced features like regulatory requirements and other specialised services like share (stock) trading are being provided. Core banking solutions are very helpful to SME industries.

    [edit] Around the world

    In countries such as India and Hong Kong that were a part of the British empire, it is only recently that core banking has caught on. This is mainly due to the restrictions by the UK government on free movement of money throughout the region. Also, the IT infrastructure necessary for such services did not exist in these countries until recently. After Britain chose to give these countries their freedom, the economies of these countries went through a drastic change - thus the demand for such services increased and the need to meet such demand were met with today's technologies. Most of the nationalized banks in India for example: State Bank of India, Punjab National Bank, Allahabad Bank, HDFC and ICICI Bank today supports core banking. As of 2007, many Cooperative banks in India such as REPCO Bank where the CBS has been implemented and rollout successfully by Theme Technologies Pvt Ltd, Jain Urban Cooperative Bank, Kangra Central Cooperative Bank, Udaipur Urban Cooperative Bank, Kollam District Cooperative Bank, Kerala State Cooperative Bank and Panchsheel Mercantile Cooperative Bank have started to use and offer centralized Core Banking too. The Four standard software tools used are Intellect Suite from POLARIS, Flexcube from iFlex Solutions, Finacle from Infosys and B@ncs from TATA Consultancy Services.

    In countries such as Japan, core banking is still in its early stages. Although having autonomous reign over their currency for over half a century, the consumers themselves do not see much use for such services - low demand, thus less services. It is only within the last decade that banks started placing ATMs outside the bank premises. Many of the bank services must be done in person at the account holder's registered branch. Japanese banks rely heavily on paperwork and physical evidence, such as the personal chop or Inkan - thus rendering core banking impractical.