Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Application Development

357 Articles
article-image-data-validation-silverlight-4
Packt
23 Apr 2010
7 min read
Save for later

Data Validation in Silverlight 4

Packt
23 Apr 2010
7 min read
With Silverlight, data validation has been fully implemented, allowing controls to be bound to data objects and those data objects to handle the validation of data and provide feedback to the controls via the Visual State Machine. The Visual State Machine is a feature of Silverlight used to render to views of a control based on its state. For instance, the mouse over state of a button can actually change the color of the button, show or hide parts of the control, and so on. Controls that participate in data validation contain a ValidationStates group that includes a Valid, InvalidUnfocused, and InvalidFocused states. We can implement custom styles for these states to provide visual feedback to the user. Data object In order to take advantage of the data validation in Silverlight, we need to create a data object or client side business object that can handle the validation of data. Time for action – creating a data object We are going to create a data object that we will bind to our input form to provide validation. Silverlight can bind to any properties of an object, but for validation we need to do two way binding, for which we need both a get and a set accessor for each of our properties. In order to use two way binding, we will need to implement the INotifyPropertyChanged interface that defines a PropertyChanged event that Silverlight will use to update the binding when a property changes. Firstly, we will need to switch over to Visual Studio and add a new class named CustomerInfo to the Silverlight project: Replace the body of the CustomerInfo.cs file with the following code: using System;using System.ComponentModel;namespace CakeORamaData{ public class CustomerInfo : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged =delegate { }; private string _cutomerName = null; public string CustomerName { get { return _cutomerName; } set { if (value == _cutomerName) return; _cutomerName = value; OnPropertyChanged("CustomerName"); } } private string _phoneNumber = null; public string PhoneNumber { get { return _phoneNumber; } set { if (value == _phoneNumber) return; _phoneNumber = value; OnPropertyChanged("PhoneNumber"); } } private string _email = null; public string Email { get { return _email; } set { if (value == _email) return; _email = value; OnPropertyChanged("Email"); } } private DateTime _eventDate = DateTime.Now.AddDays(7); public DateTime EventDate { get { return _eventDate; } set { if (value == _eventDate) return; _eventDate = value; OnPropertyChanged("EventDate"); } } private void OnPropertyChanged(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs (propertyName)); } }} Code Snippets Code snippets are a convenient way to stub out repetitive code and increase productivity, by removing the need to type a bunch of the same syntax over and over. The following is a code snippet used to create properties that execute the OnPropertyChanged method and can be very useful when implementing properties on a class that implements the INotifyPropertyChanged interface. To use the snippet, save the file as propnotify.snippet to your hard drive. In Visual Studio go to Tools | Code Snippets Manager (Ctrl + K, Ctrl + B) and click the Import button. Find the propnotify.snippet file and click Open, this will add the snippet. To use the snippet in code, simply type propnotify and hit the Tab key; a property will be stubbed out allowing you to change the name and type of the property. <?xml version="1.0" encoding="utf-8" ?><CodeSnippets > <CodeSnippet Format="1.0.0"> <Header> <Title>propnotify</Title> <Shortcut>propnotify</Shortcut> <Description>Code snippet for a property that raises the PropertyChanged event in a class.</Description> <Author>Cameron Albert</Author> <SnippetTypes> <SnippetType>Expansion</SnippetType> </SnippetTypes> </Header> <Snippet> <Declarations> <Literal> <ID>type</ID> <ToolTip>Property type</ToolTip> <Default>int</Default> </Literal> <Literal> <ID>property</ID> <ToolTip>Property name</ToolTip> <Default>MyProperty</Default> </Literal> <Literal> <ID>field</ID> <ToolTip>Private field</ToolTip> <Default>_myProperty</Default> </Literal> <Literal> <ID>defaultValue</ID> <ToolTip>Default Value</ToolTip> <Default>null</Default> </Literal> </Declarations> <Code Language="csharp"> <![CDATA[private $type$ $field$ = $defaultValue$; public $type$ $property$ { get { return $field$; } set { if (value == $field$) return; $field$ = value; OnPropertyChanged("$property$"); } } $end$]]> </Code> </Snippet> </CodeSnippet></CodeSnippets> What just happened? We created a data object or client-side business object that we can use to bind to our input controls. We implemented the INotifyPropertyChanged interface, so that our data object can raise the PropertyChanged event whenever the value of one of its properties is changed. We also defined a default delegate value for the PropertyChanged event to prevent us from having to do a null check when raising the event. Not to mention we have a nice snippet for stubbing out properties that raise the PropertyChanged event. Now we will be able to bind this object to Silverlight input controls and the controls can cause the object values to be updated so that we can provide data validation from within our data object, rather than having to include validation logic in our user interface code. Data binding We are going to bind our CustomerInfo object to our data entry form, using Blend. Be sure to build the solution before switching back over to Blend. With MainPage.xaml open in Blend, select the LayoutRoot control. In the Properties panel enter DataContext in the search field and click the New button: In the dialog that opens, select the CustomerInfo class and click OK: Blend will set the DataContext of the LayoutRoot to an instance of a CustomerInfo class: Blend inserts a namespace to our class; set the Grid.DataContext in the XAML of MainPage.xaml: <Grid.DataContext> <local:CustomerInfo/></Grid.DataContext> Now we will bind the value of CustomerName to our customerName textbox. Select the customerName textbox and then on the Properties panel enter Text in the search field. Click on the Advanced property options icon, which will open a context menu for choosing an option: Click on the Data Binding option to open the Create Data Binding dialog: In the Create Data Binding dialog (on the Explicit Data Context tab), click the arrow next to the CustomerInfo entry in the Fields list and select CustomerName: At the bottom of the Create Data Binding dialog, click on the Show advanced properties arrow to expand the dialog and display additional binding options: Ensure that TwoWay is selected in the Binding direction option and that Update source when is set to Explicit. This creates a two-way binding, meaning that when the value of the Text property of the textbox changes the underlying property, bound to Text will also be updated. In our case the customerName property of the CustomerInfo class: Click OK to close the dialog; we can now see that Blend indicates that this property is bound by the yellow border around the property input field: Repeat this process for both the phoneNumber and emailAddress textbox controls, to bind the Text property to the PhoneNumber and Email properties of the CustomerInfo class. You will see that Blend has modified our XAML using the Binding Expression: <TextBox x_Name="customerName" Margin="94,8,8,0" Text="{BindingCustomerName, Mode=TwoWay, UpdateSourceTrigger=Explicit}"TextWrapping="Wrap" VerticalAlignment="Top" Grid.Column="1" Grid.Row="1" MaxLength="40"/> In the Binding Expression code the Binding is using the CustomerName property as the binding Path. The Path (Path=CustomerName) attribute can be omitted since the Binding class constructor accepts the path as an argument. The UpdateSourceTrigger is set to Explicit, which causes any changes in the underlying data object to force a re-bind of the control. For the eventDate control, enter SelectedDate into the Properties panel search field and following the same process of data binding, select the EventDate property of the CustomerInfo class. Remember to ensure that TwoWay/Explict binding is selected in the advanced options:
Read more
  • 0
  • 0
  • 1337

article-image-animation-silverlight-4
Packt
20 Apr 2010
8 min read
Save for later

Animation in Silverlight 4

Packt
20 Apr 2010
8 min read
Silverlight sports a rich animation system that is surprisingly easy to use. The animation model in Silverlight is time based, meaning that movements occur based on a set timeline. At the heart of every animation is a StoryBoard, which contains all the animation data and independent timeline. Silverlight controls can contain any number of Storyboards. StoryBoards contain one or more Key frame elements, which are responsible for making objects on screen change position, color, or any number of properties. There are four general types of Key frames in Silverlight 4: Linear, Discrete, Spline, and Easing. The table below illustrates what each one does: Very different than Flash The animation model in Silverlight is markedly different than the one found in Adobe Flash. Animations in Flash are frame-based, whereas in Silverlight they are time-based. The term StoryBoard comes from the motion picture industry, where scenes are drawn out before they are filmed. Time for action – animation time The client would like to transform their text-only logo into something a little more elaborate. The designers have once again given us a XAML snippet of code exported from their graphic design tool. We will need to do the following: Open up the CakeORama logo project in Blend. Blend should have automatically loaded the MainControl.xaml file and your screen should look like this: In the Objects and Timeline tab, you'll see a list of objects that make up this vector drawing. There is Path object for every character. Let's add an animation. On the Object and Timeline tab, click the plus sign (+) to create a new StoryBoard. In the Create Storyboard Resource dialog, type introAnimationStoryboard into the text box and click OK. You'll notice a couple of changes to your screen. For one, the art board is surrounded by a red border and a notification that: intoAnimationStoryboard timeline recording is on just like in this screenshot: If you take a look at the Objects and Timeline tab, you'll see the timeline for our newly created introAnimationStoryboard: Let's add a key frame at the very beginning. The vertical yellow line is the play head, which marks where you currently are in the timeline. Select the canvas1 object. You can switch to the Animation Workspace in Blend by pressing F6. Click on the square icon with a green plus sign to create a new Key frame here at position 0. A white oval appears representing the Key frame that you just created. It should look similar to the following screenshot: Move the play head to 0.7 seconds, by clicking on the tick mark to the immediate left of the number 1. Click the same button you did in step 9 to create a new key frame here so that your timeline looks like this: Move the play head back to zero. Make sure the canvas1 object is still selected, click and drag the logo graphic up, so that all of it is in the grey area. This moves the logo "off stage". Hit the play button highlighted in the below screenshot, to preview the animation and enjoy the show! Now all we need to do is tell Silverlight to run the animation when our control loads, but first we need to get out of recording mode. To do this, click the x button on the Objects and Timeline tab. Click on [UserControl] in the Objects and Timeline tab. On the Properties tab, you'll see an icon with a lightning bolt on it. Click on it to see the events associated with a UserControl object: To wire up an event handler for the Loaded event, type UserControl_Loaded in the text box next to Loaded, as shown in the next screenshot: Once you hit Enter, the code behind will immediately pop up with your cursor inside the event handler method. Add this line of code to the method: introAnimationStoryboard.Begin(); Run the solution via the menu bar or by pressing F5. You should see the logo graphic smoothly and evenly animate into view. If for some reason the animation doesn't get displayed, refresh the page in your browser. You should see it now. What just happened? You just created your first animation in Silverlight. First you created a Storyboard and then added a couple of Key frames. You changed the properties of the canvas on one key frame and Silverlight automatically interpolated them in between points to create a nice smooth animation. If your animation didn't show up on the initial page load but did when you reloaded the page, then you've just experienced how seriously the Silverlight animation engine respects time. Since our animation length is relatively short (0.7 seconds) it's possible that more than that amount of time elapsed from the call of the Begin method, to the amount of time it took for your computer to render it. Silverlight noticed that and "jumped" ahead to that part of the timeline to keep everything on schedule. Just like we did before, let's take a look at the XAML to get a better feel of what's really going on. You'll find the Storyboard XAML in the UserControl.Resources section towards the top of the document. Don't worry if the values are slightly different in your project: <Storyboard x_Name="introAnimationStoryboard"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="canvas1" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"><EasingDoubleKeyFrame KeyTime="00:00:00" Value="-229"/><EasingDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0"/> </DoubleAnimationUsingKeyFrames><DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="canvas1" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"><EasingDoubleKeyFrame KeyTime="00:00:00" Value="1"/><EasingDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0"/> </DoubleAnimationUsingKeyFrames></Storyboard> There are a couple of things going on here, so let's dissect the animation XAML starting with the Storyboard declaration which creates a Storyboard and assigns the name we gave it in the dialog box: <Storyboard x_Name="introAnimationStoryboard"> That's easy enough, but what about the next node? This line tells the Storyboard that we will be modifying a Double value starting at 0 seconds. It also further specifies a target for our animation: canvas1 and a property on our target: <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="canvas1" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"> Clear enough, but what does the TargetProperty value mean? Here is that value highlight below. (UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y) We know that the net effect of the animation is that the logo moves from above the visible area back to its original position. If we're familiar with X, Y coordinates, where X represents a horizontal coordinate and Y a vertical coordinate, then the TranslateTransform.Y part makes sense. We are changing or, in Silverlight terms, transforming the Y property of the canvas. But what's all this TransformGroup about? Take a look at our canvas1 node further down in the XAML. You should see the following lines of XAML that weren't there earlier: <Canvas.RenderTransform> <TransformGroup> <ScaleTransform /> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup></Canvas.RenderTransform> Blend automatically inserted them into the Canvas when we created the animation. They have no properties. Think of them as stubbed declarations of these objects. If you remove them, Silverlight will throw an exception at runtime like the one below complaining about not being able to resolve TargetProperty: Clearly this code is important, but what's really going on here? The TranslateTransform object is a type of Transform object which determines how an object can change in Silverlight. They are packaged in a TransformGroup, which can be set in the RenderTransform property on any object descending from UIElement, which is the base class for any kind of visual element. With that bit of knowledge, we now see that (TransformGroup.Children)[3] refers to the fourth element in a zero-based collection. Not so coincidentally, the TranslateTransform node is the fourth item inside the TransformGroup in our XAML. Changing the order of the transforms in the XAML will also cause an exception at runtime. That line of XAML just tells the Silverlight runtime that we're going to animation, now we tell it how and when with our two EasingDoubleKeyFrame nodes: <EasingDoubleKeyFrame KeyTime="00:00:00" Value="-229"/><EasingDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0"/> The first EasingDoubleKeyFrame node tells Silverlight that, at zero seconds, we want the value to be -229. This corresponds to when the logo was above the visible area. The second EasingDoubleKeyFrame node tells Silverlight that at 0.7 seconds, we want the value of the property to be 0. This corresponds to the initial state of the logo, where it was before any transformations were applied. Silverlight handles all changes to the value in between the start and the end point. Silverlight's default frame rate is 60 frames per second, but Silverlight will adjust its frame rate based on the hardware that it is running on. Silverlight can adjust the amount by which it changes the values to keep the animation on schedule. If you had to reload the web page to see the animation run, then you've already experienced this. Once again, notice how few lines (technically only one line) of procedural code you had to write.
Read more
  • 0
  • 0
  • 1467

article-image-understanding-expression-blend-and-how-use-it-silverlight-4
Packt
16 Apr 2010
5 min read
Save for later

Understanding Expression Blend and How to Use it with Silverlight 4

Packt
16 Apr 2010
5 min read
Creating applications in Expression Blend What we've done so far falls short of some of the things you may have already seen and done in Silverlight. Hand editing XAML, assisted by Intellisense, works just fine to a point, but to create anything complex requires another tool to assist with turning our vision into code. Intellisense is a feature of Visual Studio and Blend that auto-completes text when you start typing a keyword, method, or variable name. Expression Blend may scare off developers at first with its radically different interface, but if you look more closely, you'll see that Blend has a lot in common with Visual Studio. For starters, both tools use the same Solution and Project file format. That means it's 100% compatible and enables tighter integration between developers and designers. You could even have the same project open in both Visual Studio and in Blend at the same time. Just be prepared to see the File Modified dialog box like the one below when switching between the two applications: If you've worked with designers on a project before, they typically mock up an interface in a graphics program and ship it off to the development team. Many times, a simple graphic embellishment can cause us developers to develop heartburn. Anyone who's ever had to implement a rounded corner in HTML knows the special kind of frustration that it brings along. Here's the good news: those days are over with Silverlight. A crash course in Expression Blend In the following screenshot, our CakeNavigationButton project is loaded into Expression Blend. Blend can be a bit daunting at first for developers that are used to Visual Studio as Blend's interface is dense with a lot of subtle cues. Solutions and projects are opened in Blend in the same manner as you would in Visual Studio. Just like in Visual Studio, you can customize Expression Blend's interface to suit your preference. You can move tabs around, dock, and undock them to create a workspace that works best for you as the following screenshot demonstrates: If you look at the CakeNavigationButton project, on the left hand side of the application window, you have the toolbar, which is substantially different from the toolbox in Visual Studio. The toolbar in Blend more closely resembles the toolbar in graphics editing software such as Adobe Photoshop or Adobe Illustrator. If you move the mouse over each button, you will see a tooltip that tells you what that button does, as well as the button's keyboard shortcut. In the upper-left corner, you'll notice a tab labeled Projects. This is functionally equivalent to the Solution Explorer in Visual Studio. The asterisk next to MainPage.XAML indicates that the file has not been saved. Examine the next screenshot to see Blend's equivalent to Visual Studio's Solution Explorer: If we look at the following screenshot, we find the Document tab control and the design surface, which Blend calls the art board. On the upper-right of the art board, there are three small buttons to control the switch between Design view, XAML view, or Split view. On the lower edge of the art board, there are controls to modify the view of the design surface. You can zoom in to take a closer look, turn on snap grid visibility, and turn on or off the snapping to snap lines.   If we then move to the upper-right corner of the next screen, we will see the Properties tab, which is a much more evolved version of the Properties tab in Visual Studio. As you can see in this screenshot, the color picker has a lot more to offer. There's also a search feature that narrows down the items in the tab based on the property name you type in.   At the lower left side of the next screen, there is the Objects and Timeline view, which shows the object hierarchy of the open document. Since we have the MainPage.XAML of our CakeNavigationButtons project, the view has StackPanel with six Buttons all inside a grid named LayoutRoot inside of a UserControl. Clicking on an item in this view selects the item on the art board and vice versa. Expression Blend is an intricate and rich application. Time for action – styles revisited Earlier in this chapter, we created and referenced a style directly in the XAML in Visual Studio. Let's modify the style we made in Blend to see how to do it graphically. To do this, we will need to: Open up the CakeNavigationButtons solution in Expression Blend. In the upper right corner, there are three tabs (Properties, Resources, and Data). On the Resources tab, expand the tree node marked [UserControl] and click on the button highlighted below to edit the [Button default] resource. Your art board should look something like this:
Read more
  • 0
  • 0
  • 1660
Banner background image

article-image-control-templates-visual-state-manager-and-event-handlers-silverlight-4
Packt
16 Apr 2010
7 min read
Save for later

Control templates, Visual State Manager, and Event Handlers in Silverlight 4

Packt
16 Apr 2010
7 min read
Skinning a control So far, you've seen that while styles can change the look of a control, they can only go so far. No matter how many changes we make, the buttons still look like old-fashioned buttons. Surely, there must be a way to customize a control further to match our creative vision. There is a way, its called skinning. Controls in Silverlight are extremely flexible and customizable. This flexibility stems from the fact that controls have both a VisualTree and a LogicalTree. The VisualTree deals with all the visual elements in a control, while the Logical tree deals with all the logical elements. All controls in Silverlight come with a default template, which defines what a control should look like. You can easily override this default template by redefining a control's visual tree with a custom one. Designers can either work directly with XAML in Blend or use a design tool that supports exporting to XAML. Expression Design is one such tool. You can alsoimport artwork from Adobe Illustrator and Adobe Photoshop from within Blend. In our scenario, let us pretend that there is a team of graphic designers. From time to time graphic designers will provide us with visual elements and, if we're lucky, snippets of XAML. In this case, the designers have sent us the XAML for a rectangle and gradient for us to base our control on: <Rectangle Stroke="#7F646464" Height="43" Width="150"StrokeThickness="2" RadiusX="15" RadiusY="15" VerticalAlignment="Top"> <Rectangle.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFEE9D9D" Offset="0.197"/> <GradientStop Color="#FFFF7D7D" Offset="0.847"/> <GradientStop Color="#FFF2DADA" Offset="0.066"/> <GradientStop Color="#FF7E4F4F" Offset="1"/> </LinearGradientBrush> </Rectangle.Fill></Rectangle> After inputting the above XAML, you will be presented with this image: We need to make this rectangle the template for our buttons. Time for action – Skinning a control We're going to take the XAML snippet above and skin our buttons with it. In order to achieve this we will need to do the following: Open up the CakeNavigationButtons project in Blend. In the MainPage.XAML file, switch to XAML View, either by clicking the XAML button on the upper-right corner of the art board or choosing View|Active Document View|XAML from the menu bar. Type in the following XAML after the closing tag for the StackPanel: (</StackPanel>)<Rectangle Stroke="#7F646464" Height="43" Width="150" StrokeThickness="2" RadiusX="15" RadiusY="15" VerticalAlignment="Top" > <Rectangle.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFEE9D9D" Offset="0.197"/> <GradientStop Color="#FFFF7D7D" Offset="0.847"/> <GradientStop Color="#FFF2DADA" Offset="0.066"/> <GradientStop Color="#FF7E4F4F" Offset="1"/> </LinearGradientBrush> </Rectangle.Fill></Rectangle> Switch back to Design View, either by clicking on the appropriate button on the upper right corner of the art board or choosing View|Active Document View|Design View from the menu bar. Right-click on the rectangle and click on Make Into Control. In the dialog box, choose Button, change the Name (Key) field to navButtonStyle and click OK. You are now in template editing mode. There are two on-screen indicators that you are in this mode: one is the Objects and Timeline tab: And one is the MainControl.xaml at the top of the art board: Click on the up button to exit template editing mode. Delete the button that our Rectangle was converted into. Select all the buttons in the StackPanel by clicking on the first one and then Shift+clicking on the last one. With all the buttons selected, go to the Properties tab, type Style into the search box. Using the techniques you've learned in this chapter, change the style to navButtonStyle, so that your screen now looks like this: The result is still not quite what we're looking for, but it's close. We need to increase the font size again; fortunately, we know how easy that is in Blend. Click on one of the buttons and choose Object|Edit Style|Edit Current from the menu bar to get into style editing mode. Make note of all the visual indicators. In the Properties tab, change the FontSize to 18, the Cursor to Hand, the Height to 45, and the Width to 200. You should see the changes immediately. The cursor change will only be noticeable at run time. Exit the template editing mode. There is a slight problem with the last button; the font is a little too large. Click on the button and use the Properties tab to change the FontSize to 12. Run the project and your application will look something like this: Run your mouse over the buttons. The button no longer reacts when you mouse over it, we'll fix that next. What just happened? We just took a plain old button and turned it into something a little more in line with the graphic designers' vision but how did we do it? When in doubt, look at the XAML The nice thing about Silverlight is that you can always take a look at the XAML to get a better understanding of what's going on. There are many places where things can "hide" in a tool like Blend or even Visual Studio. The raw naked XAML, however, bares all. For starters, we took a chunk of XAML and, using Blend, told Silverlight that we wanted to "take control" over how this button looks. This data was encapsulated into a Style and we told all our buttons to use our new style. When the new style was created, we lost some of our formatting data. We then inserted it back in and added a few more properties. If you're really curious to see what's going on, let's take a closer look at the XAML that Blend just generated for us: <Style TargetType="Button"> <Setter Property="FontSize" Value="18.667"/> <Setter Property="Background" Value="Red"/> <Setter Property="FontStyle" Value="Italic"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Margin" Value="5"/></Style><Style x_Key="smallerTextStyle" TargetType="Button"> <Setter Property="FontSize" Value="9"/> </Style><Style x_Key="navButtonStyle" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <Rectangle RadiusY="15" RadiusX="15" Stroke="#7F646464" StrokeThickness="2"> <Rectangle.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFEE9D9D" Offset="0.197"/> <GradientStop Color="#FFFF7D7D" Offset="0.847"/> <GradientStop Color="#FFF2DADA" Offset="0.066"/> <GradientStop Color="#FF7E4F4F" Offset="1"/> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="FontSize" Value="24"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Height" Value="45"/> <Setter Property="Width" Value="200"/></Style> You'll immediately notice how verbose XAML can be. We've not done a great deal of work, yet we've generated a lot of XAML. This is where a tool like Blend really saves us all those keystrokes. The next thing you'll see is that we're actually setting the Template property inside of a Setter node of a Style definition. It's not until toward the end of the Style definition that we see the Rectangle which we started with. There's also a lot of code here devoted to something called the Visual State Manager. Prior to us changing the control's template, you'll remember that when you moved your mouse over any of the buttons, they reacted by changing color. This was nice, subtle feedback for the user. Now that it's gone, we really miss it and so will our users. If you carefully study the XAML, it should come as no surprise to you that the button doesn't do anything other than just sit there: we've not defined anything for any of the states listed here. The nodes are blank. Let's do that now.
Read more
  • 0
  • 0
  • 1607

article-image-navigation-widgets-and-styles-microsoft-silverlight-4
Packt
09 Apr 2010
5 min read
Save for later

Navigation Widgets and Styles in Microsoft Silverlight 4

Packt
09 Apr 2010
5 min read
Retrofitting a website The first thing the client would like to do to their website is spice it up with a new navigation control and a playful, interactive logo for the top of the page. First, we'll work on a navigation control to replace the text links on the left hand side of the page of the current website. As you will notice in the following image, the current website navigation mechanism isn't fancy, but it's simple. However, the client would like the website to be more modern, while preserving ease of use. Adding pizzazz with Silverlight Cake-O-Rama would like to add a fancy navigation widget to their site. They've commissioned a graphic artist to create the following look for the widget.   A few words on search engine optimization We could easily create a Silverlight application that would encompass all the content and functionality of a whole website. However, doing so would severely limit the website's visibility to search engines. Search engines have programs called spiders, or robots, that 'crawl' the internet scanning for content. Generally, these programs can only see text exposed in the HTML. Search results are ranked based on this text-only content. Placing all our content inside a rich internet application platform like Silverlight would effectively hide all of our content. The net result would be reduced visibility on search engines. All Rich Internet Application (RIA) platforms have this issue with search engine visibility. Until this problem is resolved, the best approach is to augment the page's HTML content on sites that you want to be found more easily by search engines. Building a navigation control from the ground up Silverlight 4 has the Grid, Canvas, StackPanel, Border, WrapPanel, ViewBox, and ScrollViewer layout panels. Why are there so many? Well, each one serves a unique purpose. Picking the right kind of container You wouldn't fill a cardboard box with water or drink milk out of a gasoline can, would you? The same could be said of the various layout containers in Silverlight, each one serves a unique purpose and some are better at certain tasks than others. For instance, when you want to create a toolbar, you would probably use a StackPanel or WrapPanel , and not a Canvas. Why? While you could manually code the layout logic to place all the child controls, there's no good reason to. After all, there are already controls to do the heavy lifting for you. Below are the most common layout containers in Silverlight 4: Container Layout Behavior Canvas Manual positioning of items using X and Y coordinates Grid Lays out items using a defined grid of rows and columns InkPresenter Canvas that can handle digital ink StackPanel Stacks items on top of or next to one another WrapPanel Lines up items and wraps them around Border Draws a border around an item Viewbox Scales an item up to take up all the available space ScrollViewer Places a scroll bar around the control Silverlight also provides the means to write your own layout code. While there may be situations where this is warranted, first think about how you can achieve the desired result with a combination of the existing containers. Stack it up: Using the StackPanel Based on the website's current navigation links, StackPanel seems like the best choice. As the name implies, it lays out child controls in a stack, which seems like a good fit for our list of links. Time for action – building navigation buttons in Silverlight Now, let's make a StackPanel of button controls to navigate around the site. In order to do this, we will need to do the following: Launch Visual Studio 2010 and click on File|New Project. Choose to create a new Silverlight Application as shown in the next screen: Name the project CakeNavigationButtons and click OK to accept the default settings. In the MainPage.xaml file, write the following lines of XAML inside the Grid tag: <StackPanel> <Button Content="Home" /> <Button Content="Gallery"/> <Button Content="Order"/> <Button Content="Locations"/> <Button Content="Contact Us"/> <Button Content="Franchise Opportunities"/></StackPanel> Return to Visual Studio 2010 and click on Debug|Start Debugging or press F5 to launch the application. On the following screen, click OK to enable debugging. Your application should look something like this: We have now created a StackPanel of button controls to navigate around the website using Silverlight, but the application is not exactly visually appealing, not to mention, the buttons don't do anything. What we need them to do is reflect the design we've been provided with and navigate to a given page when the user clicks on them. What just happened? What we created here is the foundation for what will eventually become a dynamic navigation control. You have created a new Silverlight application, added a StackPanel, and then added button controls to it. Now, let's move on to make this little navigation bar sparkle. Adding a little style with Styles Many people refer to Silverlight controls as being "lookless", which may sound strange at first as they clearly have a "look." The term refers to the fact that the logic in a control defines its behavior rather than its appearance. That means that all the controls you've seen in Silverlight so far have no presentation logic in them. Their look comes from a default resource file. The good news is that we can create our own resources to customize the look of any control. You can re-style a control in Silverlight in much the same way as you can in Cascading Style Sheets (CSS).
Read more
  • 0
  • 0
  • 1042

article-image-core-principles-service-oriented-architecture-biztalk-server-2009
Packt
06 Apr 2010
11 min read
Save for later

The core principles of a service-oriented architecture with BizTalk Server 2009

Packt
06 Apr 2010
11 min read
So what exactly is a service? A service is essentially a well-defined interface to an autonomous chunk of functionality, which usually corresponds to a specific business process. That might sound a lot like a regular old object-oriented component to you. While both services and components have commonality in that they expose discrete interfaces of functionality, a service is more focused on the capabilities offered than the packaging. Services are meant to be higher-level, business-oriented offerings that provide technology abstraction and interoperability within a multipurpose "services" tier of your architecture. What makes up a service? Typically you'll find: Contract: Explains what operations the service exposes, types of messages, and exchange patterns supported by this service, and any policies that explain how this service is used. Messages: The data payload exchanged between the service consumer and provider. Implementation: The portion of the service which actually processes the requests, executes the expected business functionality, and optionally returns a response. Service provider: The host of the service which publishes the interface and manages the lifetime of the service. Service consumer: Ideally, a service has someone using it. The service consumer is aware of the available service operations and knows how to discover the provider and determine what type of messages to transmit. Facade: Optionally, a targeted facade may be offered to particularly service consumers. This sort of interface may offer a more simplified perspective on the service, or provide a coarse-grained avenue for service invocation. What is the point of building a service? I'd say it's to construct an asset capable of being reused which means that it's a discrete, discoverable, self-describing entity that can be accessed regardless of platform or technology. Service-oriented architecture is defined as an architectural discipline based on loosely-coupled, autonomous chunks of business functionality which can be used to construct composite applications. Through the rest of this article we get a chance to flesh out many of the concepts that underlie that statement. Let's go ahead and take a look at a few of the principles and characteristics that I consider most important to a successful service-oriented BizTalk solution. As part of each one, I'll explain the thinking behind the principle and then call out how it can be applied to BizTalk Server solutions. Loosely coupled Many of the fundamental SOA principles actually stem from this particular one. In virtually all cases, some form of coupling between components is inevitable. The only way we can effectively build software is to have interrelations between the various components that make up the delivered product. However, when architecting solutions, we have distinct design decisions to make regarding the extent to which application components are coupled. Loose coupling is all about establishing relationships with minimal dependencies. What would a tightly-coupled application look like? In such an application, we'd find components that maintained intimate knowledge of each others' working parts and engaged in frequent, chatty synchronous calls amongst themselves. Many components in the application would retain state and allow consumers to manipulate that state data. Transactions that take place in a tightly coupled application probably adhere to a two-phase commit strategy where all components must succeed together in order for each data interaction to be finalized. The complete solution has its ensemble of components compiled together and singularly deployed to one technology platform. In order to run properly, these tightly-coupled components rely on the full availability of each component to fulfill the requests made of them. On the other hand, a loosely-coupled application employs a wildly different set of characteristics. Components in this sort of application share only a contract and keep their implementation details hidden. Rarely preserving state data, these components rely on less frequent communication where chunky input containing all the data the component needs to satisfy its requestors is shared. Any transactions in these types of applications often follow a compensation strategy where we don't assume that all components can or will commit their changes at the same time. This class of solution can be incrementally deployed to a mix of host technologies. Asynchronous communication between components, often through a broker, enables a less stringent operational dependency between the components that comprise the solution. What makes a solution loosely coupled then? Notably, the primary information shared by a component is its interface. The consuming component possesses no knowledge of the internal implementation details. The contract relationship suffices as a means of explaining how the target component is used. Another trait of loosely coupled solutions is coarse-grained interfaces that encourage the transmission of full data entities as opposed to fine-grained interfaces, which accept small subsets of data. Because loosely-coupled components do not share state information, a thicker input message containing a complete impression of the entity is best. Loosely-coupled applications also welcome the addition of a broker which proxies the (often asynchronous) communication between components. This mediator permits a rich decoupling where runtime binding between components can be dynamic and components can forgo an operational dependency on each other. Let's take a look at an example of loose coupling that sits utterly outside the realm of technology. Completely non-technical loose coupling exampleWhen I go to a restaurant and place an order with my waiter, he captures the request on his pad and sends that request to the kitchen. The order pad (the contract) contains all the data needed by the kitchen chef to create my meal. The restaurant owner can bring in a new waiter or rotate his chefs and the restaurant shouldn't skip a beat as both roles (services) serve distinct functions where the written order is the intersection point and highlight of their relationship. Why does loose coupling matter? By designing a loosely-coupled solution, you provide a level of protection against the changes that the application will inevitably require over its life span. We have to reduce the impact of such changes while making it possible to deploy necessary updates in an efficient manner. How does this apply to BizTalk Server solutions? A good portion of the BizTalk Server architecture was built with loose coupling in mind. Think about the BizTalk MessageBox which acts as a broker facilitating communication between ports and orchestrations while limiting any tight coupling. Receive ports and send ports are very loosely coupled and in many cases, have absolutely no awareness of each other. The publish-and-subscribe bus thrives on the asynchronous transfer of self-describing messages between stateless endpoints. Let's look at a few recommendations of how to build loosely-coupled BizTalk applications. Orchestrations are a prime place where you can either go with a tightly-coupled or loosely-coupled design route. For instance, when sketching out your orchestration process, it's sure tempting to use that Transform shape to convert from one message type to another. However, a version change to that map will require a modification of the calling orchestration. When mapping to or from data structures associated with external systems, it's wiser to push those maps to the edges (receive/send ports) and not embed a direct link to the map within the orchestration. BizTalk easily generates schemas for line-of-business (LOB) systems and consumed services. To interact with these schemas in a very loosely coupled fashion, consider defining stable entity schemas (i.e. "canonical schemas") that are used within an orchestration, and only map to the format of the LOB system in the send port. For example, if you need to send a piece of data into an Oracle database table, you can certainly include a map within an orchestration which instantiates the Oracle message. However, this will create a tight coupling between the orchestration and the database structure. To better insulate against future changes to the database schema, consider using a generic intermediate data format in the orchestration and only transforming to the Oracle-specific format in the send port. How about those logical ports that we add to orchestrations to facilitate the transfer of messages in and out of the workflow process? When configuring those ports, the Port Configuration Wizard asks you if you want to associate the port to a physical endpoint via the Specify Now option. Once again, pretty tempting. If you know that the message will arrive at an orchestration via a FILE adapter, why not just go ahead and configure that now and let Visual Studio.NET create the corresponding physical ports during deployment? While you can independently control the auto-generated physical ports later on, it's a bad idea to embed transport details inside the orchestration file. On each subsequent deployment from Visual Studio.NET, the generated receive port will have any out-of-band changes overwritten by the deployment action. Chaining orchestration together is a tricky endeavor and one that can leave you in a messy state if you are too quick with a design decision. By "chaining orchestrations", I mean exploiting multiple orchestrations to implement a business process. There are a few options at your disposal listed here and ordered from most coupled to least coupled. Call Orchestration or Start Orchestration shape: An orchestration uses these shapes in order to kick off an additional workflow process. The Call Orchestration is used for synchronous connection with the new orchestration while the Start Orchestration is a fire-and-forget action. This is a useful tactic for sharing state data (for example variables, messages, ports) from the source orchestration to the target. However, both options require a tight coupling of the source orchestration to the target. Version changes to the target orchestration would likely require a redeployment of the source orchestration. Partner direct bound ports: These provide you the capability to communicate between orchestrations using ports. In the forward partner direct binding scenario, the sender has a strong coupling to the receiver, while the receiver knows nothing about the sender. This works well in situations where there are numerous senders and only one receiver. Inverse partner direct binding means that there is a tight coupling between the receiver and the sender. The sender doesn't know who will receive the command, so this scenario is intended for cases where there are many receivers for a single sender. In both cases, you have tight coupling on one end, with loose-coupling on the other. MessageBox direct binding: This is the most loosely-coupled way to share data between orchestrations. When you send a message out of an orchestration through a port marked for MessageBox direct binding, you are simply placing a message onto the bus for anyone to consume. The source orchestration has no idea where the data is going, and the recipients have no idea where it's been. MessageBox direct binding provides a very loosely-coupled way to send messages between different orchestrations and endpoints. Critical pointWhile MessageBox direct binding is great, you do lose the ability to send the additional state data that a Call Orchestration shape will provide you. So, as with all architectural decisions, you need to decide if the sacrifice (loose coupling, higher latency) is worth the additional capabilities. Decisions can be made during BizTalk messaging configuration that promote a loosely-coupled BizTalk landscape. For example, both receive ports and send ports allow for the application of maps to messages flying past. In each case, multiple maps can be added. This does NOT mean that all the maps will be applied to the message, but rather, it allows for sending multiple different message types in, and emitting a single type (or even multiple types) out the other side. By applying transformation at the earliest and latest moments of bus processing, you loosely couple external formats and systems from internal canonical formats. We should simply assume that all upstream and downstream systems will change over time, and configure our application accordingly. Another means for loosely coupling BizTalk solutions involves the exploitation of the publish-subscribe architecture that makes up the BizTalk message bus. Instead of building solely point-to-point solutions and figuring that a SOAP interface makes you service oriented, you should also consider loosely coupling the relationship between the service input and where the data actually ends up. We can craft a series of routing decision that take into account message content or context and direct the message to one or more relevant processes/endpoints. While point-to-point solutions may be appropriate for many cases, don't neglect a more distributed pattern where the data publisher does not need to explicitly know exactly how their data will be processed and routed by the message bus. When identifying subscriptions for our send ports, we should avoid tight coupling to metadata attributes that might limit the reuse of the port. For instance, you should try to create subscriptions on either the message type or message content instead of context attributes such as the inbound receive port name. Ports should be tightly coupled to the MessageBox and messages it stores, not to attributes of its publisher. That said, there are clearly cases where a subscriber is specifically looking for data that corresponds to a targeted piece of metadata such as the subject line of the email received by BizTalk. As always, design your solution in a way that solves your business problem in an efficient manner.
Read more
  • 0
  • 0
  • 1886
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €14.99/month. Cancel anytime
article-image-biztalk-server-standard-message-exchange-patterns-and-types-service
Packt
06 Apr 2010
4 min read
Save for later

BizTalk Server: Standard Message Exchange Patterns and Types of Service

Packt
06 Apr 2010
4 min read
Identifying Standard Message Exchange Patterns When we talk about Message Exchange Patterns, or MEPs, we're considering the direction and timing of data between the client and service. How do I get into the bus and what are the implications of those choices? Let's discuss the four primary options. Request/Response services This is probably the pattern that's most familiar to you. We're all comfortable making a function call to a component and waiting for a response. When a service uses this pattern, it's frequently performing a remote procedure call where the caller accesses functionality on the distant service and is blocked until either a timeout occurs or until the receiver sends a response that is expected by the caller. As we'll see below, while this pattern may set developers at ease, it may encourage bad behavior. Nevertheless, the cases where request/response services make the most sense are fine-grained functions and mashup services. If you need a list of active contracts that a hospital has with your company, then a request/response operation fits best. The client application should wait until that response is received before moving on to the next portion of the application. Or, let's say my web portal is calling an aggregate service, which takes contact data from five different systems and mashes them up into a single data entity that is then returned to the caller. This data is being requested for immediate presentation to an end user, and thus it's logical to solicit information from a service and wait to draw the screen until the completed result is loaded. BizTalk Server 2009 has full support for both consuming and publishing services adhering to a request/response pattern. When exposing request/response operations through BizTalk orchestrations, the orchestration port's Communication Pattern is set to Request-Response and the Port direction of communication is equal to I'll be receiving a request and sending a response. Once this orchestration port is bound to a physical request/response receive port, BizTalk takes care of correlating the response message with the appropriate thread that made the request. This is significant because by default, BizTalk is a purely asynchronous messaging engine. Even when you configure BizTalk Server to behave in a request/response fashion, it's only putting a facade on the standard underlying plumbing. A synchronous BizTalk service interface actually sits on top of a sophisticated mechanism of correlating MessageBox communication to simulate a request/response pattern. When consuming request/response services from BizTalk from an orchestration, the orchestration port's Communication Pattern is set to Request-Response and the Port direction of communication is equal to I'll be sending a request and receiving a response. The corresponding physical send port uses a solicit-response pattern and allows the user to set up both pipelines and maps for the inbound and outbound messages. One concern with either publishing or consuming request/response services is the issue of blocking and timeouts. From a BizTalk perspective, this means that whenever you publish an orchestration as a request/response service, you should always verify that the logic residing between inbound and outbound transmissions will either complete or fail within a relatively brief amount of time. This dictates wrapping this logic inside an orchestration Scope shape with a preset timeout that is longer than the standard web service timeout interval. For consuming services, a request/response pattern forces the orchestration to block and wait for the response to be returned. If the service response isn't necessary for processing to continue, consider using a Parallel shape that isolates the service interaction pattern on a dedicated branch. This way, the execution of unrelated workflow steps can proceed even though the downstream service is yet to respond.
Read more
  • 0
  • 0
  • 2670

article-image-build-your-own-application-access-twitter-using-java-and-netbeans-part-3
Packt
31 Mar 2010
7 min read
Save for later

Build your own Application to access Twitter using Java and NetBeans: Part 3

Packt
31 Mar 2010
7 min read
This is the third part of the Twitter Java client tutorial article series! In Build your own Application to access Twitter using Java and NetBeans: Part 2 we: Created a twitterLogin dialog to take care of the login process Added functionality to show your 20 most recent tweets right after logging in Added the functionality to update your Twitter status Showing your Twitter friends’ timeline Open your NetBeans IDE along with your SwingAndTweet project, and make sure you’re in the Design View. Select the Tabbed Pane component from the Palette panel and drag it into the SwingAndTweetUI JFrame component: A new JTabbedPane1 container will appear below the JScrollPane1 control in the Inspector panel. Now drag the JScrollPane1 control into the JTabbedPane1 container: The jScrollPane1 control will merge with the jTabbedPane1 and a tab will appear. Double-click on the tab, replace its default name –tab1– with Home, and press Enter: Resize the jTabbedPane1 control so it takes all the available space from the main window: Now drag a Scroll Pane container from the Palette panel and drop it into the white area of the jTabbedPane1 control:   A new tab will appear, containing the new jScrollPane2 object you’ve just dropped in. Now drag a Panel container from the Palette panel and drop it into the white area of the jTabbedPane1 control: A JPanel1 container will appear inside the jScrollPane2 container, as shown in the next screenshot: Change the name of the new tab to Friends and then click on the Source tab to change to the Source view. Once your app code shows up, locate the btnLoginActionPerformed method and type the following code at the end of this method, right below the jTextArea1.updateUI() line: //code for the Friends timeline try { java.util.List<Status> statusList = twitter.getFriendsTimeline(); jPanel1.setLayout(new GridLayout(statusList.size(),1)); for (int i=0; i<statusList.size(); i++) { statusText = new JLabel(String.valueOf(statusList.get(i).getText())); statusUser = new JLabel(statusList.get(i).getUser().getName()); JPanel individualStatus = new JPanel(new GridLayout(2,1)); individualStatus.add(statusUser); individualStatus.add(statusText); jPanel1.add(individualStatus); } } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "A Twitter error ocurred!");} jPanel1.updateUI(); The next screenshot shows how the code in your btnLoginActionPerformed method should look like after adding the code: One important thing you should notice is that there will be 6 error icons due to the fact that we need to declare some variables and write some import statements. Scroll up the code window until you locate the import twitter4j.*; and the import javax.swing.JOptionPane; lines, and add the following lines right after them: import java.awt.GridLayout; import javax.swing.JLabel; import javax.swing.JPanel; Now scroll down the code until you locate the Twitter twitter; line you added in Swinging and Tweeting with Java and NetBeans: Part 2 of this tutorial series and add the following lines: JLabel statusText; JLabel statusUser; If you go back to the buttonUpdateStatusActionPerformed method, you’ll notice the errors have disappeared. Now everything is ready for you to test the new functionality in your Twitter client! Press F6 to run your SwingAndTweet application and log in with your Twitter credentials. The main window will show your last 20 tweets, and if you click on the Friends tab, you will see the last 20 tweets of the people you’re following, along with your own tweets: Close your SwingAndTweet application to return to NetBeans. Let’s examine what we did in the previous exercise. On steps 2-5 you added a JTabbedPane container and created a Home tab where the JScrollPane1 and JTextArea1 controls show your latest tweets, and then on steps 6-8 you added the JPanel1 container inside the JScrollPane2 container. On step 9 you changed the name of the new tab to Friends and then added some code to show your friends’ latest tweets. As in previous exercises, we need to add the code inside a try-catch block because we are going to call the Twitter4J API to get the last 20 tweets on your friends timeline. The first line inside the try block is: java.util.List<Status> statusList = twitter.getFriendsTimeline(); This line gets the 20 most recent tweets from your friends’ timeline, and assigns them to the statusList variable. The next line, jPanel1.setLayout(new GridLayout(statusList.size(),1)); sets your jPanel1 container to use a layout manager called GridLayout, so the components inside jPanel1 can be arranged into rows and columns. The GridLayout constructor requires two parameters; the first one defines the number of rows, so we use the statusList.size() function to retrieve the number of tweets obtained with the getFriendsTimeline() function in the previous line of code. The second parameter defines the number of columns, and in this case we only need 1 column. The next line, for (int i=0; i<statusList.size(); i++) { starts a for loop that iterates through all the tweets obtained from your friends’ timeline. The next 6 lines are executed inside the for loop. The next line in the execution path is statusText = new JLabel(String.valueOf(statusList.get(i).getText())); This line assigns the text of an individual tweet to a JLabel control called statusText. You can omit the String.valueOf function in this line because the getText() already returns a string value –I used it because at first I was having trouble getting NetBeans to compile this line, I still haven’t found out why, but as soon as I have an answer, I’ll let you know. As you can see, the statusText JLabel control was created programmatically; this means we didn’t use the NetBeans GUI interface. The next line, statusUser = new JLabel(statusList.get(i).getUser().getName()); creates a JLabel component called statusUser, gets the name of the user that wrote the tweet through the statusList.get(i).getUser().getName() method and assigns this value to the statusUser component. The next line, JPanel individualStatus = new JPanel(new GridLayout(2,1)); creates a JPanel container named individualStatus to contain the two JLabels we created in the last two lines of code. This panel has a GridLayout with 2 rows and one column. The first row will contain the name of the user that wrote the tweet, and the second row will contain the text of that particular tweet. The next two lines, individualStatus.add(statusUser); individualStatus.add(statusText); add the name of the user (statusUser) and the text of the individual tweet (statusText) to the individualStatus container, and the next line, jPanel1.add(individualStatus); adds the individualStatus JPanel component – which contains the username and text of one individual tweet –to the jPanel1 container. This is the last line of code inside the for loop. The catch block shows an error message in case an error occurs when executing the getFriendsTimeline() function, and the jPanel1.updateUI(); line updates the jPanel1 container so it shows the most recent information added to it. Now you can see your friends’ latest tweets along with your own tweets, but we need to improve the way tweets are displayed, don’t you think so? Improving the way your friends’ tweets are displayed For starters, let’s change some font attributes to show the user name in bold style and the text of the tweet in plain style. Then we’ll add a black border to separate each individual tweet. Add the following line below the other import statements in your code: import java.awt.Font; Scroll down until you locate the btnLoginActionPerformed method and add the following two lines below the statusUser = new JLabel(statusList.get(i).getUser().getName()) line: Font newLabelFont = new Font(statusUser.getFont().getName(),Font.PLAIN,statusUser.getFont().getSize()); statusText.setFont(newLabelFont); The following screenshot shows the btnLoginActionPerformed method after adding those two lines:   Press F6 to run your SwingAndTweet application. Now you will be able to differentiate the user name from the text of your friends’ tweets: And now let’s add a black border to each individual tweet. Scroll up the code until you locate the import declarations and add the following lines below the import statement you added on step 1 of this exercise: import javax.swing.BorderFactory; import java.awt.Color; Scroll down to the btnLoginActionPerformed method and add the following line right after the individualStatus.add(statusText) line: individualStatus.setBorder(BorderFactory.createLineBorder(Color.black)); The next screenshot shows the appearance of your friends’ timeline tab with a black border separating each individual tweet:
Read more
  • 0
  • 0
  • 2225

article-image-building-flex-type-ahead-text-input
Packt
15 Mar 2010
7 min read
Save for later

Building a Flex Type-Ahead Text Input

Packt
15 Mar 2010
7 min read
Here is an example of how google.com implements the type-ahead list using DHTML: As you can see, once 'type-ahead' is typed into the text field , the user is given a selection of possible search phrases that google is already aware of. My intention with this article is to build a type-ahead list in Flex. To start, lets narrow down the scope of the application and make it easy to expand on. We'll create an application which is used primarily for searching for fruits. Our basic Fruit Finder application will consist of a form with a TextInput field. The TextInput field will allow the user to type in a fruit name and will automatically suggest a fruit if one is partially found in our list of fruits. 1. Building a Basic Form To start, here is what our form looks like: The XML which creates this user interface is quite simple: <?xml version="1.0" encoding="utf-8"?><mx:Application layout="absolute"><mx:Panel title="Fruit Finder"><mx:Form> <mx:FormHeading label="Fruit Finder"/> <mx:FormItem label="Fruit Name"> <mx:TextInput id="fruit"/> </mx:FormItem> <mx:FormItem> <mx:Button label="Search"/> </mx:FormItem> </mx:Form></mx:Panel></mx:Application> You'll notice the normal xml version declaration, the Application tag, a Panel tag and finally the Form tag. Nothing too complicated so far. If you are unfamiliar with the basics of Flex or Forms in Flex, you should take this opportunity to visit Adobe's website to explore them. This XML code gives up 90% of our GUI. In the coming steps will have to define the elements which will make up the fruit list which will appear as a user is typing. Next, we need to define our list of fruits. 2. Adding Data to Our Type Ahead List Now that we have the beginnings of our GUI, lets start building our fruit list. Thinking ahead for a bit, I know that we will have to display a list of fruits to the user. The simplest Flex control to use for this job is the List Control. We will be dynamically adding the List to the application's display list via ActionScript, but for now we just need to define the data which will be displayed in the list. We will start by creating adding a Script tag and adding an ArrayCollection to it. You will have to use the import statement to make the ArrayCollection class available to you. Our ArrayCollection constructor is passed an array of fruit names. Here is what the code looks like: <mx:Script><![CDATA[ import mx.collections.ArrayCollection; public var fruitList:ArrayCollection = new ArrayCollection(['apple', 'orange', 'banana', 'kiwi', 'avocado', 'tomato', 'squash', 'cucumber']);]]></mx:Script> Normally defining the list of items in this way is not commonly performed. For a real world use, getting this list of items through an XML source is more likely (especially in web applications), but this will work for our demonstration. Now that our fruit list is defined, we just need to connect it to a type-ahead list which we will create in the next step. links:http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_4.htmlhttp://livedocs.adobe.com/flex/3/langref/mx/collections/ArrayCollection.html 3. Triggering the Appearance of Our Type Ahead-List It is common in modern web applications that the type ahead list appear automatically upon the user typing. We will add this functionality to our application by using the KeyUp event. Simply put, when the user begins typing into our TextInput field we will do the following: Determine if the type ahead list is already created. For the first key press, there will be no type-ahead list.  In this case we need to create the list, set it's data provider to fruitList (step 2) and add it to the UI. We will also need to position the type ahead list beneath the TextInput field so that the user is properly cued as to what is happening. To start our implementation of Type-Ahead Text Input, we use the KeyUp event. We change our FormItem tag surrounding the TextInput field to look like this: <mx:FormItem label="Fruit Name" keyUp="filterFruits(event)">We then define a filterFruits function like so:public function filterFruits(event:KeyboardEvent):void{ // if the type ahead list is not present, create it if(typeAheadList==null){ // create the list and assign the dataprovider typeAheadList = new List(); typeAheadList.dataProvider = fruitList; // add the list to the screen this.addChild(typeAheadList); }} In the above code we are programmatically creating a List control. Immediately assign the data provider to it. Lastly, we add the child to the application. Our function does everything that we need it to do for a Type-Ahead Text Input with the exception of positioning the type ahead list in the correct place. Here is what our app currently looks like: We are making progress, but without the correct positioning, our type-ahead list creates a bad user experience. To move this list to the correct location we need to use the localtoGlobal method to translate coordinate systems. This requires a short explanation. Flex has multiple coordinate systems on the Flash stage that you can make use of for making your controls and components position properly. The first is call the global corrdinate system. This system starts at the upper left hand corner of the Flash stage and extends down and out. The second is called the local coordinate system which starts at the upper left hand corner of a component. There is also a content coordinate system which encompasses a components content. For our purposes we only need to focus on the local and global systems. link:http://livedocs.adobe.com/flex/3/html/help.html?content=containers_intro_5.html Our goal here is to place our list directly beneath the fruit TextInput field. To accomplish this, we must first grabs the coordinates of the fruit TextInput field. Here is the code for retrieving them: var p1:Point = new Point(fruit.x,fruit.y); We use the Point type which receives the x and y coordinates of the fruit control. p1 now holds the points in the local coordinate system. You may ask, "what is it local to?". In this case it is local to it's parent container which is the FormItem. In order to convert these points to the global system we need to use to the localToGlobal method: var p2:Point = fruit_form_item.localToGlobal(p1); p2 now contains the converted coordinates. Note, we added the id of fruit_form_item to the FormItem Tag which is the parent of our fruit TextInput. From here we can now place the fruit List in the correct place in our application. typeAheadList.x=p2.x;typeAheadList.y=p2.y + fruit.height; // set the widthtypeAheadList.width=fruit.width; Notice above that we added fruit.height to the y value of the typeAheadList. This is necessary to not block the view TextInput field. We are moving it down by n pixels, where n is the height of the TextInput field. We also set the x coordinate of our list so that it is in the correct place. Here is what the final result for this step look like:
Read more
  • 0
  • 0
  • 1996

article-image-flex-multi-list-selector-using-list-control-datagrid-and-accordion
Packt
02 Mar 2010
3 min read
Save for later

Flex Multi-List Selector using List Control, DataGrid, and the Accordion

Packt
02 Mar 2010
3 min read
Instead of files and directories, I'm going to use States, Counties and Cities. Essentially this application will be used to give the user an easy way to select a city. Flex offers many components that can help us build this application. The controls I immediately consider for the job are the List Control, DataGrid, and the Accordion (in combination with the List). The List is the obvious control to start with because it represents the data in the right way - a list of states, counties, and cities. The reason I also considered the DataGrid and the Accordion (with the List) is because the they both have a header. I want an easy way to label the three columns/list 'States','Counties' and 'Cities'. With that said, I selected the Accordion with the List option. Using this option also allows for future expansion of the tool. For instance, one could adapt the tool to add country, then state, county, and city. The Accordion naturally has this grouping capability. With that said, our first code block contains our basic UI. The structure is pretty simple. The layout of the application is vertical. I've added an HBox which contains the main components of the application. The basic structure of each list is a List Control inside a Canvas Container which is inside of an Accordian Control. The Canvas is there because Accordians must have a container as a child and a List is not a part of the container package. We repeat this 3 times, one for each column and give the appropriate name. <?xml version="1.0" encoding="utf-8"?><mx:Application horizontalGap="0" layout="vertical"> <mx:HBox width="100%" height="100%"> <!-- States --> <mx:Accordion id="statesAccoridon" width="100%" height="100%"> <mx:Canvas width="100%" height="100%" label="States"> <mx:List id="statesList" width="100%" height="100%" dataProvider="{locations.state.@name}" click="{selectCounties()}"/> </mx:Canvas> </mx:Accordion> <!-- Counties --> <mx:Accordion id="countiesAccoridon" width="100%" height="100%"> <mx:Canvas width="100%" height="100%" label="Counties"> <mx:List id="countiesList" width="100%" height="100%" click="selectCities()"/> </mx:Canvas> </mx:Accordion> <!-- Cities --> <mx:Accordion id="citiesAccoridon" width="100%" height="100%"> <mx:Canvas width="100%" height="100%" label="Cities"> <mx:List id="citiesList" width="100%" height="100%"/> </mx:Canvas> </mx:Accordion> </mx:HBox> <!-- Selected City --> <mx:Label text="{citiesList.selectedItem}"/> <mx:Script> <![CDATA[ public function selectCounties():void{ countiesList.dataProvider = locations.state.(@name==statesList.selectedItem).counties.county.@name } public function selectCities():void{ citiesList.dataProvider = locations.state.(@name==statesList.selectedItem).counties.county.(@name==countiesList.selectedItem).cities.city.@name; } ]]> </mx:Script> </mx:Application> I've set the width and height to all containers to 100%. This will make it easy to later embed this application into a web page or other Flex application as a module. Also notice how the dataProvider attribute is only set for the statesList. This is because the countiesList and the citiesList are not populated until a state is selected. These dataProviders are set using ActionScript and are triggered by the click event listeners for both objects. Here is what the start of our selector looks like:
Read more
  • 0
  • 0
  • 1469
article-image-jboss-richfaces-33-supplemental-installation
Packt
19 Feb 2010
6 min read
Save for later

JBoss RichFaces 3.3 Supplemental Installation

Packt
19 Feb 2010
6 min read
This installation guide is for the Windows platform. JBoss Server Installation In order to run any web application, an application server is needed. JBoss server is an industry standard and is ideal for running Seam and RichFaces applications.  Downloading the server is a very simple task. First go to the JBoss download page and download the 4.2.2.GA version of the JBoss server. Save it to a directory for downloads such as c:downloads. Unzip the file to the c: directory.  After unzipping, you should have a folder named c: jboss-4.2.2.GA. Test the server installation by going into c:jboss-4.2.2.GAbin and running the file run.bat. A command window should run with server logs. At completion, the logs will indicate that the server has started. Starting JBoss Server Within Eclipse Although you can start JBoss server from the run.bat file, for the purposes of development and learning RichFaces, it is more valuable to start the JBoss server within Eclipse. The Eclipse IDE provides support to run, shutdown and adjust settings for servers. In Eclipse, we will work from the Java Perspective. Change Eclipse to be in the Java Perspective. Go to Window->Open Perspective->Java. We need to have a tab for Server. Go To Window->Show View->Other->Servers->Server. In the Server tab, right click and go to New->Server. Here we are defining a server to launch within Eclipse. Choose JBoss->JBoss v4.2->Next. Choose the JRE, which will typically be the path to where Java is installed. For the Application Server Directory, choose c:jboss-4.2.2.GA then Next. Accept the defaults for Address, Port, JNDI Port and Server Configuration. Click Next->Finish. Next the server settings need to be adjusted. Double click on the JBOSS 4.2 entry in the server tab to bring up the settings menu in eclipse. Click on the edit menu on the right hand side. Figure 1 - JBoss Server settings Uncheck all check boxes and Server Timeout Delay to be Unlimited. The server is ready to run. In the Server tab, right click on the JBOSS 4.2 entry and choose Start. Go to the Console tab and you will see the server logs. At completion, the logs should indicate that the server has started. MySql Installation MySql is the database used to store information in the example applications. Once MySql is installed, the example applications can connect to a persistent store and the developer will be able to see data saved as the application is exercised. Go to the MySql download page and retrieve the installation file. Look for MSI file labeled mysql-essential-5.1.42-winx64.msi (or a similar version). The MSI file is easiest to install as it gives a wizard to guide you through the process. Once the file is saved, double click on it to initiate installation. Choose all the default options. When the id and password is requested, choose root as both the id and password. This is easy to remember for development purposes. Verify installation of MySql by looking for the shortcuts placed Windows Programs Menu. Also verify that MySql has been installed as a Windows service. The easiest way to do this is to go to Start-> Run in Windows and type services.msc. The services dialogue box should have a MySql entry. Make sure the MySql service is started. Run MySql Command Client In order to operate the MySql database, you can use the provided command line client. The client enables the user to look up tables, execute operational commands, and run sql statements.  In the Windows Start menu, go to Start->Programs0->MySql->MySql Server 5.x->MySql Command Line Client. Type in root for the password. A mysql prompt will appear. The command line tool is used for creating the database for the example applications. In order to import a sql script, use the command source <path>. For example: source c:adv_contact_manager_create.sql For a full list of commands for MySql, see the online manual: http://dev.mysql.com/doc/refman/5.1/en/index.html. Download and Install MySql JDBC Connector In order for Java applications to connect to MySql through JDBC, a connector jar is needed. MySql provides connectivity for client applications developed in the Java programming language via a JDBC driver, which is called MySql Connector/J. Go to the connector download page and retrieve the zip file. Unzip the file to a directory. Identify the file mysql-connector-java-5.1.10-bin.jar. Copy this file to the default server lib directory so that it is accessible by all applications: C:jboss-4.2.2.GAserverdefaultlib Build and Deploy Example Applications In order to see the application that is being developed, it is necessary to build and deploy the application onto the server. Applications generated by the seam-gen tool come built with a script armed with many build tasks. Eclipse provides Ant support so we can use it to operate the build file provided within the example application. In Eclipse with the application loaded as a project, open the Ant view. Go to Window-> Show View-> Ant. The Ant view will be displayed. Now load the build.xml in order to operate the Ant targets. Right click in the Ant view and select Add Buildfiles->Choose build.xml for the application. A list of Ant targets will be loaded. In order to execute a task, simply double click on the task. The Console window will display the executed statements. Seam-gen offers several tasks, but a notable few are very useful. deploy – builds and deploys the application to the server undeploy – deletes the application from the server purge – deletes temporary server files associated with the application clean – deletes package application files from the local distribution directory If the deploy task fails, simply go to the JBoss deployment directory and delete the installed application. C:jboss-4.2.2.GAserverdefaultdeploy Applications can also be directly copied into this directory for deployment. Inversely, applications can be directly deleted from this directory for un-deployment. With these basics installations complete, running the example applications should be simple and you will be on your way to mastering RichFaces 3.3. Summary In this article, we discussed the following: JBoss Server Installation Starting JBoss Server within Eclipse MySql Installation Build and Deploy Example applications
Read more
  • 0
  • 0
  • 1486

article-image-build-your-own-application-access-twitter-using-java-and-netbeans-part-2
Packt
19 Feb 2010
17 min read
Save for later

Build your own Application to access Twitter using Java and NetBeans: Part 2

Packt
19 Feb 2010
17 min read
In this tutorial, we’ll develop the simple Java application further to add some more functions. Now that we can connect to our Twitter account via the Twitter4J API, it would be nice to use a login dialog instead of hard-coding our Twitter username and password in the Java application. But before we start to build our enhanced SwingAndTweet application, let me show you how it will look like once we finish all the exercises in this part of the tutorial: And now, let the show begin… Creating a Login dialog for our SwingAndTweet application Open your NetBeans IDE along with your SwingAndTweet project, and make sure you’re in the Design View. Go to the Palette window and locate the Dialog component under the Swing Windows section; then drag and drop it anywhere inside the SwingAndTweetUI JFrame component: A JDialog will be added automatically to your SwingAndTweet application, and it will show up in the Component Inspector tab located at the lower-left part of the screen, under Other Components: Right-click on the jDialog1 component in the Inspector tab and select Change Variable Name… from the pop-up menu. The Rename dialog will show up next. Type twitterLogin in the New Name field and press Enter to change the dialog’s name. Now you can start adding text fields, labels and buttons to your twitterLogin dialog. Double-click on the twitterLogin component under the Inspector tab. The twitterLogin dialog will show up empty in the Design Editor window. Use the Palette window to add two JLabels, one JTextField, one JPasswordField and two JButtons to the twitterLogin dialog. Arrange these controls as shown below: Now let’s change the names of the JTextField control, the JPasswordField control and the two JButton controls, so we can easily identify them within your SwingAndTweet application’s code. Right-click on the first text field (jLabel2), select Change Variable Name… from the pop-up menu and replace the text field’s name with txtUsername. Do the same with the other fields; use txtPassword for the JPasswordField control, btnLogin for the Login button and btnExit for the Exit button. And now the last touch. Right-click anywhere inside the twitterLogin dialog, being careful not to right-click inside any of the controls, and select the Properties option from the pop-up menu. The twitterLogin [JDialog] – Properties dialog will appear next. Locate the title property, double-click on the null value and type Twitter Login to replace it. Next, scroll down the properties list until you find the modal property; click on its checkbox to enable it and then click on Close to save your changes. Basically, in the previous exercise we added all the Swing controls you’re going to need to type your username and password, so you can connect to your Twitter account. The twitterLogin dialog is going to take care of the login process for your SwingAndTweet application. We replaced the default names for the JTextField, the JPasswordField and the two JButton controls because it will be easier to identify them during the coding process of the application. On step 8 we used the Properties window of the twitterLogin dialog to change the title property and give your dialog a decent title. We also enabled the modal property on step 9, so you can’t just close the dialog and jump right to the SwingAndTweetUI main window; you’ll have to enter a valid Twitter username and password combination for that. Invoking the Login dialog Ok, now we have a good-looking dialog called twitterLogin. The next step is to invoke it before our main SwingAndTweet JFrame component shows up, so we need to insert some code inside the SwingAndTweetUI() constructor method. Click on the Source button of the Editor window to change to the Source View: Now locate the SwingAndTweetUI() constructor, and type the following lines right after the initComponents(); line: int loginWidth = twitterLogin.getPreferredSize().width; int loginHeight = twitterLogin.getPreferredSize().height; twitterLogin.setBounds(0,0,loginWidth,loginHeight); twitterLogin.setVisible(true); The code inside the SwingAndTweetUI() constructor method shall now look like this: To see your new twitterLogin dialog in action, press F6 or select Run | Run Project to run your SwingAndTweetUI application. The twitterLogin dialog will pop right up. You’ll be able to type in your username and password, but since we haven’t added any functionality yet, the buttons won’t do anything right now. Click on the Close (X) button to close the dialog window and the SwingAndTweetUI main window will appear next. Click on its Close (X) button to exit your Twitter Java application. Now let’s take a look at the code we added to your twitterLogin dialog. On the first line, int loginWidth = twitterLogin.getPreferredSize().width; we declare an integer variable named loginWidth, and assign to it the preferred width of the twitterLogin dialog. The getPreferredSize method retrieves the value of the preferredSize property from the twitterLogin dialog through the .width field. On the second line, int loginHeight = twitterLogin.getPreferredSize().height; we declare another integer variable named loginHeight, and assign to it the preferred height of the twitterLogin dialog. This time, the getPreferredSize() method retrieves the value of the preferredWidth property from the twitterLogin dialog through the .height field. On the next line, twitterLogin.setBounds(0,0,loginWidth,loginHeight); we use the setBounds method to set the x,y coordinates where the dialog should appear on the screen, along with its corresponding width and height. The first two parameters are for the x,y coordinates; in this case, x=0 and y=0, which means the twitterLogin dialog will show up at the upper-left part of the screen. The last two parameters receive the value of the loginWidth and loginHeight variables to establish the twitterLogin dialog’s width and height, respectively. The last line, twitterLogin.setVisible(true); makes the twitterLogin dialog appear on the screen. And since the modal property of this dialog is enabled, once it shows up on the screen it won’t let you do anything else with your SwingAndTweet1 application until you close it up or enter a valid Twitter username and password, as we’ll see in the next exercise. Adding functionality to the twitterLogin dialog Now your twitterLogin dialog is ready to roll! Basically, it won’t let you go to the SwingAndTweet main window until you’ve entered a valid Twitter username and password. And for doing that, we’re going to use the same login code from Build your own Application to access Twitter using Java and NetBeans: Part 1 of this article series. Go to the end of your SwingAndTweetUI application source code and locate the // Variables declaration – do not modify line. Below this line, you’ll see all the variables used in your application: the btnExit and btnLogin buttons, the text fields from your twitterLogin dialog and your SwingAndTweetUI main window, etc. Add the following line just below the // End of variables declaration line:     Twitter twitter; Now click on the Design button to change to the Design View: You’ll see the twitterLogin dialog again –in case you don’t, double-click on the twitterLogin component under the Inspector tab. Now double-click on the Login button to go back to the Code View. The btnLoginActionPerformed method will show up next. Add the following code inside this method: try { twitter = new Twitter(txtUsername.getText(), String.valueOf(txtPassword.getPassword())); twitter.verifyCredentials(); JOptionPane.showMessageDialog(null, "You're logged in!"); twitterLogin.dispose(); } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "Login failed"); } Make sure you write each line on its own, to avoid errors. The btnLoginActionPerformed method shall look like this: Now you’re ready to test your twitterLogin dialog. Press F6 to run your application. The Twitter Login dialog will show up next. Type your Twitter username and password, and then click on the OK button. If the username and password are correct, the You’re logged in! dialog will show up and you’ll be able to go to the SwingAndTweetUI main window. If they’re not correct, the Login failed dialog will appear instead and, after you click on the OK button, you’ll return to the twitterLogin dialog until you type a correct Twitter username and password combination. To exit your SwingAndTweetUI application, click on the Close(X) button of the twitterLogin dialog and then on the Close(X) button of the SwingAndTweetUI window. You’ll be taken back to the NetBeans IDE. Click on the Design button to go back to the Design View, and double-click on the Exit button to open the btnExitActionPerformed method. Type System.exit(0); inside the btnExitActionPerformed method, as shown below: Now go back to the Design View again, right-click anywhere inside the twitterLogin dialog (just be careful not to right-click over any of the dialog’s controls) and select the Events | Window | windowClosing option from the pop-up menu: NetBeans will change to Code View automatically and you’ll be inside the twitterLoginWindowClosing method. Type System.exit(0); inside this method, as shown below: Now run your application to test the new functionality in your loginTwitter dialog. You’ll be able to exit the SwingAndTweet application when clicking on the Exit or Close(X) buttons, and you’ll be able to go to your application’s main window if you type a correct Twitter username and password combination. You can close your SwingAndTweet application now. And now, let’s examine what we just accomplished. First you added the Twitter twitter; line to your application code. With this line we’re declaring a Twitter object named twitter, and it will be available throughout all the application code. On step 4, you added some lines of code to the btnLoginActionPerformed method; this code will be executed every time you click on the Login button from the twitterLogin dialog. All the code is enclosed in a try block, so that if an error occurs during the login process, a TwitterException will be thrown and the code inside the catch block will execute. The first line inside the try block is twitter = new Twitter(txtUsername.getText(),String.valueOf(txtPassword.getPassword())); This code creates the twitter object that we’re going to use throughout the application. It uses the text value you entered in the txtUsername and txtPassword fields to log into your Twitter account. The next line, twitter.verifyCredentials(); checks to see if the username and password provided to the twitter object are correct; if that’s true, a message dialog box shows up in the screen with the You’re logged in! message and the rest of the code executes once you click on the OK button of this message dialog; otherwise, the code in the catch block executes and a message dialog shows up in the screen with the Login failed message, and the twitterLogin dialog keeps waiting for you to type a correct username and password combination. The next line in the sequence, JOptionPane.showMessageDialog(null, "You're logged in!"); shows the message dialog that we talked about before, and the last line inside the try block, twitterLogin.dispose(); makes the twitterLogin dialog disappear from the screen once you’ve logged into your Twitter account successfully. The only line of code inside the catch block is JOptionPane.showMessageDialog (null, "Login failed"); This line executes when there’s an error in the Twitter login process; it shows the Login failed message in the screen and waits for you to press the OK button. On step 9 we added one line of code to the btnExitActionPerformed method: System.exit(0); This line closes your SwingAndTweet application whenever you click on the Exit button. Finally, on steps 10-12 we added another System.exit(0); line to the twitterLoginWindowClosing method, to close your SwingAndTweet application whenever you click on the Close(X) button of the twitterLogin dialog. Showing your Twitter timeline right after logging in Now let’s see some real Twitter action! The following exercise will show you how to show your most recent tweets inside a text area. Click on the Design button to go to the Design View; then double-click on the [JFrame] component under the Inspector tab to show the SwingAndTweetUI dialog in the Design View window: The SwingAndTweet frame will show the three controls we created during Build your own Application to access Twitter using Java and NetBeans: Part 1. Replace the My Last Tweet text in the JLabel control with the What’s happening text. Then right-click on the JTextField control and select the Change Variable Name… option from the pop-up menu, to change its name from jTextField1 to txtUpdateStatus. Now do the same with the JButton control. Right-click on it and select the Change Variable Name… option from the pop-up menu to change its name from jButton1 to btnUpdateStatus. Right-click on the same button again, but this time select the Edit Text option from the pop-up menu and replace the Login text with Update. Rearrange the three controls as per the following screenshot (you’ll need to make the SwingAndTweet container wider): Now drag a JTextArea control from the Palette window and drop it inside the SwingAndTweetUI container. Resize the text area so it fills up the rest of the container, as shown below: Double-click on the Update button to open the btnUpdateStatusActionPerformed method. The first thing you’ll notice is that it’s not empty; this is because this used to be the old Login button, remember? Now just replace all the code inside this method, as shown below: private void btnUpdateStatusActionPerformed(java.awt.event.ActionEvent evt) { try { if (txtUpdateStatus.getText().isEmpty()) JOptionPane.showMessageDialog (null, "You must write something!"); else { twitter.updateStatus(txtUpdateStatus.getText()); jTextArea1.setText(null); java.util.List<Status> statusList = twitter.getUserTimeline(); for (int i=0; i<statusList.size(); i++) { jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); } } } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "A Twitter Error ocurred!"); } txtUpdateStatus.setText(""); jTextArea1.updateUI(); The next step is to modify your btnLoginActionPerformed method; we need to add several lines of code to show your Twitter timeline. The complete method is shown below (the lines you need to add are shown in bold): private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) { try { twitter = new Twitter(txtUsername.getText(), String.valueOf(txtPassword.getPassword())); twitter.verifyCredentials(); // JOptionPane.showMessageDialog(null, "You're logged in!"); java.util.List<Status> statusList = twitter.getUserTimeline(); for (int i=0; i<statusList.size(); i++) { jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); } twitterLogin.dispose(); } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "Login failed"); } jTextArea1.updateUI(); } Once you have added all the necessary code in each button’s actionPerformed method, press F6 to run the SwingAndTweet application and check if all things work as intended. If you type a message in the txtUpdateStatus text field and then click on the Update button, the timeline information inside the JTextArea1 control will change to reflect your new Twitter status: You can close your SwingAndTweet application now. That was cool, right? Now you have a much better-looking Twitter client! And you can update your status, too! Let’s examine the code we added in this last exercise… private void btnUpdateStatusActionPerformed(java.awt.event.ActionEvent evt) { try { if (txtUpdateStatus.getText().isEmpty()) JOptionPane.showMessageDialog (null, "You must write something!"); else { twitter.updateStatus(txtUpdateStatus.getText()); jTextArea1.setText(null); java.util.List<Status> statusList = twitter.getUserTimeline(); for (int i=0; i<statusList.size(); i++) { jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); } } } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "A Twitter Error ocurred!"); } txtUpdateStatus.setText(""); jTextArea1.updateUI(); On step 7 we added some code to the btnUpdateStatusActionPerformed method. This code will execute whenever you click on the Update button to update your Twitter status. First, let’s look at the code inside the try block. The first two lines, if (txtUpdateStatus.getText().isEmpty()) JOptionPane.showMessageDialog (null, "You must write something!"); are the first part of a simple if-else statement that checks to see if you’ve written something inside the txtUpdateStatus text field; if it’s empty, a message dialog will show the You must write something! message on the screen, and then it will wait for you to click on the OK button. If the txtUpdateStatus text field is not empty, the code inside the else block will execute instead of showing up the message dialog. The next part of the code is the else block. The first line inside this block, twitter.updateStatus(txtUpdateStatus.getText()); updates your twitter status with the text you wrote in the txtUpdateStatus text field; if an error occurs at this point, a TwitterException is thrown and the program execution will jump to the catch block. If your Twitter status was updated correctly, the next line to execute is jTextArea1.setText(null); This line erases all the information inside the jTextArea1 control. And the next line, java.util.List<Status> statusList = twitter.getUserTimeline(); gets the 20 most recent tweets from your timeline and assigns them to the statusList variable. The next line is the beginning of a for statement: for (int i=0; i<statusList.size(); i++) { Basically, what this for block does is iterate through all the 20 most recent tweets in your timeline, one at a time, executing the two statements inside this block on each iteration: jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); Although the getUserTimeline() function retrieves the 20 most recent tweets, we need to use the statusList.size() statement as the loop continuation condition inside the for block to get the real number of tweets obtained, because they can be less than 20, and we can’t iterate through something that maybe doesn’t exist, right? The first line appends the text of each individual tweet to the jTextArea1 control, along with a new-line character ("n") so each tweet is shown in one individual line, and the second line appends the "-----------------------------n" text as a separator between each individual tweet, along with a new-line character. The final result is a list of the 20 most recent tweets inside the jTextArea1 control. The only line of code inside the catch block displays the A Twitter Error occurred! message in case something goes wrong when trying to update your Twitter status. The next line of code right after the catch block is txtUpdateStatus.setText(""); This line just clears the content inside the txtUpdateStatus control, so you don’t accidentally insert the same message two times in a row. And finally, the last line of code in the btnUpdateStatusActionPerformed method is jTextArea1.updateUI(); This line updates the jTextArea1 control, so you can see the list of your 20 most recent tweets after updating your status. private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) { try { twitter = new Twitter(txtUsername.getText(), String.valueOf(txtPassword.getPassword())); twitter.verifyCredentials(); // JOptionPane.showMessageDialog(null, "You're logged in!"); java.util.List<Status> statusList = twitter.getUserTimeline(); for (int i=0; i<statusList.size(); i++) { jTextArea1.append(String.valueOf(statusList.get(i).getText())+"n"); jTextArea1.append("-----------------------------n"); } twitterLogin.dispose(); } catch (TwitterException e) { JOptionPane.showMessageDialog (null, "Login failed"); } jTextArea1.updateUI(); And now let’s have a look at the code we added inside the btnLoginActionPerformed method. The first thing you’ll notice is that we’ve added the '//' characters to the // JOptionPane.showMessageDialog(null, "You're logged in!"); line; this means it’s commented out and it won’t be executed, because it’s safe to go directly to the SwingAndTweet main window right after typing your Twitter username and password. The next lines are identical to the ones inside the btnUpdateStatusActionPerformed method we saw before; the first line retrieves your 20 most recent tweets, and the for block displays the list of tweets inside the jTextArea1 control.  And the last line of code, jTextArea1.updateUI(); updates the jTextArea1 control so you can see the most recent information regarding your latest tweets. Summary Well, now your SwingAndTweet application looks better, don’t you think so? In this article, we enhanced the SwingAndTweet application which we build in the first part of the tutorials series. In short, we: Created a twitterLogin dialog to take care of the login process Added functionality to show your 20 most recent tweets right after logging in Added the functionality to update your Twitter status
Read more
  • 0
  • 0
  • 3378

article-image-normalizing-dimensional-model
Packt
08 Feb 2010
3 min read
Save for later

Normalizing Dimensional Model

Packt
08 Feb 2010
3 min read
First Normal Form Violation in Dimension table Let’s revisit the author problem in the book dimension. The AUTHOR column contains multiple authors, a first-normal-form violation, which prevents us from querying book or sales by author. BOOK dimension table BOOK_SK TITLE AUTHOR PUBLISHER CATEGORY SUB-CATEGORY 1 Programming in Java King, Chan Pac Programming Java 2 Learning Python Simpson Pac Programming Python 3 Introduction to BIRT Chan, Gupta, Simpson (Editor) Apes Reporting BIRT 4 Advanced Java King, Chan Apes Programming Java Normalizing and spinning off the authors into a dimension and adding an artificial BOOK AUTHOR fact solves the problem; it is an artificial fact as it does not contain any real business measure.  Note that the Editor which is an author’s role is also “normalized” into its column in the AUTHOR table (It is related to author, but not actually an author’s name). AUTHOR table AUTHOR_SK AUTHOR_NAME 1 King 2 Chan 3 Simpson 4 Gupta BOOK AUTHOR table BOOK_SK AUTHOR_SK ROLE COUNT 1 1 Co-author 1 1 2 Co-author 1 2 3 Author 1 3 2 Co-author 1 3 3 Editor 1 3 4 Co-author 1 4 1 Co-author 1 4 2 Co-author 1 Note the artificial COUNT measure which facilitates aggregation always has a value of numeric 1. SELECT name, SUM(COUNT) FROM book_author ba, book_dim b, author_dim aWHERE ba.book_sk = b.book_sk AND ba.author_sk = a.author_skGROUP BY name You might need to query sales by author, which you can do so by combining the queries of each of the two stars (the two facts) on their common dimension (BOOK dimension), producing daily book sales by author. SELECT dt, title, name, role, sales_amt FROM (SELECT book_sk, dt, title, sales_amt FROM sales_fact s, date_dim d, book_dim b WHERE s.book_sk = b.book_sk AND s.date_sk = d.date_sk) sales, (SELECT b.book_sk, name, role FROM book_author ba, book_dim b, author_dim a WHERE ba.book_sk = b.book_sk AND ba.author_sk = a.author_sk) authorWHERE sales.book_sk = author.book_sk Single Column with Repeating Value in Dimension table Columns like the PUBLISHER, though not violating any normal form, is also good to get normalized, which we accomplish by adding an artificial fact, PUBLISHED BOOK fact, and its own dimension, PUBLISHER dimension. This normalization is not exactly the same as that in normalizing first-normal-form violation; the PUBLISHER dimension can correctly be linked to the SALES fact, the publisher surrogate key must be added though in the SALES fact. PUBLISHER table   PUBLISHER_SK PUBLISHER 1 Pac 2 Apes BOOK PUBLISHER table BOOK_SK PUBLISHER_SK COUNT 1 1 1 1 2 1 2 3 1 3 2 1 3 3 1 3 4 1 4 1 1 4 2 1 Related Columns with Repeating Value in Dimension table CATEGORY and SUB-CATEGORY columns are related, they form a hierarchy. Each of them can be normalized into its own dimension, but they need to be all linked into one artificial fact. Non-Measure Column in Fact table The ROLE column inside the BOOK AUTHOR fact is not a measure; it violates the dimensional modeling norm; to resolve we just need to spin it off into its own dimension, effectively normalizing the fact table. ROLE dimension table and sample rows   ROLE_SK ROLE 1 Author 2 Co-Author 3 Editor BOOK AUTHOR table with normalized ROLE BOOK_SK AUTHOR_SK ROLE_SK COUNT 1 1 2 1 1 2 2 1 2 3 1 1 3 2 2 1 3 3 3 1 3 4 2 1 4 1 2 1 4 2 2 1   Summary This article shows that both dimensional table and fact table in a dimensional model can be normalized without violating its modeling norm. If you have read this article, you may be interested to view : Solving Many-to-Many Relationship in Dimensional Modeling
Read more
  • 0
  • 0
  • 1786
article-image-build-your-own-application-access-twitter-using-java-and-netbeans-part-1
Packt
05 Feb 2010
6 min read
Save for later

Build your own Application to access Twitter using Java and NetBeans: Part 1

Packt
05 Feb 2010
6 min read
Due to the fact that writing a Java app to control your Twitter account is quite a long process and requires several features, I intend to divide this article in several sections, so you can see in extreme detail all the bells and whistles involved in writing Java applications. Downloading and installing NetBeans for your developing platform To download NetBeans, open a web browser window and go to the NetBeans website. Then click on the Download button and select the All IDE download bundle. After downloading NetBeans, install it with the default options. Creating your SwingAndTweet project Open NetBeans and select File | New Project to open the New Project dialog. Now select Java from the Categories panel and Java Application from the Projects panel. Click on Next to continue. The New Java Application dialog will show up next. Type SwingAndTweet in the Project Name field, mark the Use Dedicated Folder for Storing Libraries option, deselect the Create Main Class box (we’ll deal with that later), make sure the Set as Main Project box is enabled and click on Next to continue: NetBeans will create the SwingAndTweet project and will show it under the Projects tab, in the NetBeans main window. Right click on the project’s name and select JFrame Form... in the pop-up menu: The New JFrame Form window will appear next. Type SwingAndTweetUI in the Class Name field, type swingandtweet in the Package field and click on Finish to continue: NetBeans will open the SwingAndTweetUI frame in the center panel of the main screen. Now you’re ready to assemble your Tweeter Java application! Now let me explain a little bit about what we did in the previous exercise: First, we created a new Java application called SwingAndTweet. Then we created a Swing JFrame component and we named it SwingAndTweetUI, because this is going to act as the foundation, where we’re going to put all the other Swing components required to interact with Twitter. Now I’m going to show you how to download and integrate the Twitter4J API to your SwingAndTweetJava application. Downloading and integrating the Twitter4J API into your NetBeans environment For us to be able to use the powerful classes and methods from the Twitter4J API, we need to tell NetBeans where to find them and integrate them into our Java applications. Open a web browser window, go to http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/ and search for the latest twitter4j.2.X.X.jar file, or download the most recent version at the time of this writing from here:http://repo1.maven.org/maven2/net/homeip/yusuke/twitter4j/2.0.9/twitter4j-2.0.9.jar. Once you download it in your computer, go to NetBeans, right-click on the SwingAndTweet project and select Properties from the context menu. Once at the project properties screen, select the Libraries category under the Categories panel, click on the Add JAR/Folder... button at the middle-right part of the screen to open the Add JAR/Folder dialog, navigate to the directory where you downloaded the twitter4j-2.X.X.jar file and double click on it to add it to your project’s library path: Click on OK to close the Project Properties dialog and return to the NetBeans main screen. Ok, you have integrated the Twitter4J API to your SwingAndTweet application. Now, let’s see how to log into your Twitter account from our Java application... Logging into Twitter from Java and seeing your last Tweet In the following exercise, I’ll show you how easy it is to start communicating with Twitter from a Java application, thanks to the Twitter class from the Twitter4J API. You‘ll also learn how to check your last tweet through your Java application. Let’s see how to log into a Twitter account: Go to the Palette window and locate the JLabel component under the Swing Controls section; then drag and drop it into the TweetAndSwing JFrame component: Now drag a Button and a Text Editor, too. Once you have the three controls inside the SwingAndTweetUI JFrame control, arrange them as shown below: The next step is to change their names and captions, to make our application look more professional. Right click on the JLabel1 control, select Edit from the context menu, type My Last Tweet and hit Enter. Do the same procedure with the other two controls: erase the text in the jTextField1 control and type Login in the jButton1 control. Rearrange the jLabel1 and jTextField1 controls, and drag one of the ends of jTextField1 to increase its length all you can. Once done, your application will look like this: And now, let’s inject some life to our application! Double click on the JButton1 control to open your application’s code window. You’ll be inside a java method called jButton1ActionPerformed. This method will execute every time you click on the Login button, and this is where we’re going to put all the code for logging into your Twitter account. Delete the // TODO add your handling code here: line and type the following code inside the JButton1ActionPerformed method: Remember to replace username and password with your real Twitter username and password. If you look closely at the line numbers, you‘ll notice there are five error icons on lines 82, 84, 85,  88 and 89. That’s because we need to add some import lines at the beginning of your code, to indicate NetBeans where to find the Twitter and JOptionPane classes, and the TwitterException. Scroll up until you locate the package swingandtweet; line; then add the following lines: Now all the errors will disappear from your code. To see your Java application in action, press F6 or select Run  Run | Main Project from the NetBeans main menu. The Run Project window will pop up, asking you to select the main class for your project. The swingandtweet.SwingAndTweetUI class will already be selected, so just click on OK to continue. Your SwingAndTweetUI application window will appear next, showing the three controls you created. Click on the Login button and wait for the SwingAndTweet application to validate your Twitter username and password. If they’re correct, the following dialog will pop up: Click on OK to return to your SwingAndTweet application. Now you will see your last tweet on the textbox control: If you want to be really sure it’s working, go to your Twitter account and update your status through the Web interface; for example, type Testing my Java app. Then return to your SwingAndTweet application and click on the Login button again to see your last tweet. The textbox control will now reflect your latest tweet: As you can see, your SwingAndTweet Java application can now communicate with your Twitter account! Click on the X button to close the window and exit your SwingAndTweet application.
Read more
  • 0
  • 0
  • 4536

article-image-developing-applications-jboss-and-hibernate-part-2
Packt
19 Jan 2010
6 min read
Save for later

Developing Applications with JBoss and Hibernate: Part 2

Packt
19 Jan 2010
6 min read
Adding a web client to your project There are several ways to test our Hibernate application. The simplest of all is adding a web application, which is packaged in an enterprise application along with the Hibernate application. Create a new dynamic web project named HibernateWeb. The first step, before adding servlets and JSPs is linking the HibernateProject libraries to your web application, otherwise, you will not be able to reference the Hibernate POJOs. Right-click on your project and select Properties. Reach the Java Build Path option and select the tab Projects. From there add HibernateProject. Let's move on. This project will contain a main servlet that acts as a controller, and a few JPSs for the client view. We will start by adding com.packtpub.hibernateWeb.HibernateServlet to our project. In the following snippet, you can see the core section of the servlet. Here, we will not detail the Controller logic, which is straightforward if you have some rudiments of the MVC pattern; rather we want to highlight the most interesting part of it, which is how to query and persist Hibernate objects. public class HibernateServlet extends HttpServlet {private SessionFactory getSessionFactory() {return (SessionFactory)getServletContext().getAttribute("sessionFactory");}public void init() { [1]if (getSessionFactory() != null) {return;}InitialContext ctx;try {ctx = new InitialContext();factory = (SessionFactory)ctx.lookup("java:/hibernate/SessionFactory");getServletContext().setAttribute("sessionFactory", factory);}catch (NamingException e) {e.printStackTrace();}}private String saveEmployee(HttpServletRequest request) {Session hsession=null;String name=request.getParameter("name");String salary=request.getParameter("salary");String departmentId=request.getParameter("departmentId");try {hsession = getSessionFactory().openSession();hsession.beginTransaction();Query query = hsession.createQuery("from Department d whered.departmentId = :departmentId"); [2]query.setInteger("departmentId", new Integer(departmentId));Department dep = (Department) query.uniqueResult();Employee emp = new Employee();emp.setDepartment(dep);emp.setEmployeeName(name);emp.setEmployeeSalary(Integer.parseInt(salary));hsession.save(emp); [3]hsession.getTransaction().commit();}catch (Exception e) {// TODO Auto-generated catch block e.printStackTrace();hsession.getTransaction().rollback();}finally {if (hsession.isOpen())hsession.close();}return employeeList(request);}private String employeeList(HttpServletRequest request) {Session hsession=null;Department dep;try {hsession = getSessionFactory().openSession();Query query = hsession.createQuery("select p from Employee pjoin fetch p.department c"); [4]List <Employee>list = query.list();request.setAttribute("employee", list);}catch (Exception e) {e.printStackTrace();}finally {if (hsession.isOpen())hsession.close();}return "/listEmployees.jsp";}private String saveDepartment(HttpServletRequest request) {String depName=request.getParameter("depName");Session hsession=null;Department dep;try {hsession = getSessionFactory().openSession();hsession.beginTransaction();dep = new Department();dep.setDepartmentName(depName);hsession.save(dep); [5]hsession.getTransaction().commit();}catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();hsession.getTransaction().rollback();}finally {if (hsession.isOpen())hsession.close();}return employeeList(request);}} As you can see from the preceding code, we recover the SessionFactory from the JNDI tree in the init() [1] method of the servlet. Instances of SessionFactory are thread-safe and typically shared throughout an application, so we store it in the ServletContext and share it among all servlet instances. The SessionFactory is subsequently used to start a Hibernate session, which is not thread-safe and should only be used for a single transaction or unit of work in an application. In order to store our Employee, in the saveEmployee method, we first retrieve the corresponding Department from our schema [2], and finally the Employee is saved [3] and the transaction is committed. The list of employees is fetched by the employeeList method. Notice we are using a join fetch statement to retrieve all the employees [4], which will be routed to the listEmployees.jsp view. Why? The answer is that with the default fetch mode (Lazy), once the Hibernate session is closed, the client will not be able to navigate through the department field of the Employee. The common solution to this issue is switching to the EAGER fetch mode that reads the related fields (in our case department) in memory, as soon as we query the Employee table. You have more than one option to achieve this. One possible solution, if you don't want to change the default fetch mode for the Employee table, is to build an ad hoc query that forces Hibernate to read also the fields in relation with the Employee table. "select p from Employee p join fetch p.department c" If you prefer to use the XML class files to configure the fetch mode, you can also change the lazy="true" attribute in the employee-department relationship. The last method, saveDepartment [5] takes care to persist a new Department in the corresponding table. We complete our excursus on the web tier with the listEmployees.jsp that is used to display a tabular view of the employees: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html><script language="JavaScript">function doSubmit(url) {document.module.action = url;document.module.submit();}</script><body><table border="1"><tr><th>Name</th><th>Salary</th> <TH>department</th></tr><c:forEach items="${employee}" var="emp"><tr><td> <c:out value="${emp.employeeName}"/> </td><td> <c:out value="${emp.employeeSalary}"/></td><td> <c:out value="${emp.department.departmentName}"/></td></tr></c:forEach></table><form name="module" method="POST"><input type="button" value ="New Employee"onClick="doSubmit('actionServlet?op=newEmployee')"><input type="button" value ="New Department"onClick="doSubmit('actionServlet?op=newDepartment')"></form></body></html> This page uses JSP 2.0 Expression Language (EL) to iterate through the list of employees, as highlighted in the last code snippet. We have also hightlighted the taglib directive, at the beginning of the page. This directive will be used to resolve the JSTL core set of libraries that ships with JBoss AS in the server/xxx/deploy/jbossweb.sar/jstl.jar library. (Eclipse does not contain references to this library when you create a web project; you have to add jstl.jar to your build path, otherwise Eclipse will mark it as an error. However, that's only a visual annoyance because the JBoss Web container has got everything it needs to run JSTL.) The complete web application is available on the Packtpub website (http://www.packtpub.com) and includes two additional JSPs for entering the employee (newEmployee.jsp) and department (newDepartment.jsp) data, plus one placeholder index.jsp that merely forwards to the Hibernate servlet.
Read more
  • 0
  • 0
  • 1112