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
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7018 Articles
article-image-animating-built-button
Packt
19 Mar 2013
8 min read
Save for later

Animating a built-in button

Packt
19 Mar 2013
8 min read
(For more resources related to this topic, see here.) Note that there might be more states to a fully functioning button, for example, there is also a Disabled state, but whether a button is disabled or not usually does not depend on mouse movements or positions, it does not have to be animated, and we do not describe it here. Our purpose in this section is not to create a fully functioning button, but rather to demonstrate some generic concepts for re-styling a control and providing custom animations for it. Let's create a Silverlight project containing a single page with the button in its center. The following is the resulting XAML code of the main page: <UserControl x_Class="AnimatingButtonStates.MainPage" > <Grid x_Name="LayoutRoot" Background="White"> <Button Width="100" Height="25" Background="LightGray" Content="Press Me" /> </Grid> </UserControl> We want to re-style this button completely, modifying it shape, border, colors, and creating custom animations for the transition between states. Now, we'll create a very simple custom template for the button by changing the button code to the following code: <!-- Here we provide custom button template --> <Button> <Button.Template> <ControlTemplate TargetType="Button"> <Grid x_Name="TopLevelButtonGrid"> <!--Button Border--> <Border x_Name="ButtonBorder" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CornerRadius="5" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> </Border> <!-- button content is placed here--> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </ControlTemplate> </Button.Template> <Button> If we run the code, as it is, we shall be able to see the button and its Press Me content, but the button will not react visually to mouse over or press events. That is because once we replace the button's template we will have to provide our own solution to the visual changes for different button states. Now, let's discuss how we want the button to look in the different states and how we want it to handle the transitions between states. When the mouse is over the button, we want a blue border to appear. The animation to achieve this can be fast or even instantaneous. When the button is pressed, we want it to scale down significantly and we want the button to scale up and down several times, each time with lower amplitude before achieving a steady pressed state. Note that the control template developers and designers usually try to avoid changing colors within animations (they are considered to be more complex and less intuitive); instead, they try to achieve color-changing effects by changing opacities of several template parts. So to change the border to blue on mouse over, let's create another border element MouseOverBorder with blue BorderBrush, and non-zero BorderThickness within the control template. At normal state, its opacity property will be 0, and it will be completely transparent. When the state of the button changes to MouseOver, the opacity of this border will change to 1. After we add the MouseOverBorder element together with the visual state manager functionality, the resulting template code will look as follows: <Button> <Button.Template> <ControlTemplate TargetType="Button"> <Grid x_Name="TopLevelButtonGrid"> <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualStateGroup.Transitions> <!-- duration for the MouseOver animation is set here to 0.2 seconds --> <VisualTransition To="MouseOver" GeneratedDuration="0:0:0.2" /> </VisualStateGroup.Transitions> <VisualState x_Name="Normal" /> <VisualState x_Name="MouseOver"> <VisualState.Storyboard> <Storyboard> <!--animation performed when the button gets into "MouseOver" State--> <DoubleAnimation Storyboard. TargetName="MouseOverBorder" Storyboard.TargetProperty="Opacity" To="1" /> </Storyboard> </VisualState.Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <!--Button Border--> <Border x_Name="ButtonBorder" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CornerRadius="5" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> </Border> <!--MouseOverBorder has opacity 0 normally. Only when the mouse moves over the button, the opacity is changed to 1--> <Border x_Name="MouseOverBorder" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CornerRadius="5" BorderBrush="Blue" BorderThickness="2" Opacity="0"> </Border> <!-- button content is placed here--> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </ControlTemplate> </Button.Template> </Button> Now, if we start the application, we'll see that the border of the button becomes blue, if the mouse pointer is placed over it, and returns to its usual color when the mouse pointer is moved away from the button, as shown in the following screenshot: The next step is to animate the pressed state. To achieve this, we add a ScaleTransform object to the top-level grid of the button's template: <ControlTemplate TargetType="Button"> <Grid x_Name="TopLevelButtonGrid" RenderTransformOrigin="0.5,0.5"> <Grid.RenderTransform> <!-- scale transform is used to shrink the button when it is pressed --> <ScaleTransform x_Name="OnPressedScaleTransform" ScaleX="1" ScaleY="1" /> </Grid.RenderTransform> ... The purpose of the ScaleTransform object is to shrink the button once it is pressed. Originally, its ScaleX and ScaleY parameters are set to 1, while the animation that starts when the button is pressed changes them to 0.5. This animation is defined within VisualState defined as Pressed: <VisualStateGroup> ... <VisualState x_Name="Pressed"> <VisualState.Storyboard> <Storyboard> <!-- animation performed when the button gets into "Pressed" State will scale down the button by a factor of 0.5 in both dimensions --> <DoubleAnimation Storyboard.TargetProperty="ScaleX" Storyboard.TargetName="TheScaleTransform" To="0.5" /> <DoubleAnimation Storyboard.TargetProperty="ScaleY" Storyboard.TargetName="TheScaleTransform" To="0.5" /> </Storyboard> </VisualState.Storyboard> </VisualState> ... </VisualStateGroup> VisualState defines the animation storyboard to be triggered once the button switches to the Pressed state. We can also add VisualStateTransition to the VisualStateGroup element's Transition property: <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualStateGroup.Transitions> ... <VisualTransition To="Pressed" GeneratedDuration="0:0:0.5"> <VisualTransition.GeneratedEasingFunction> <!-- elastic ease will provide a few attenuating bounces before the pressed button reaches a steady state --> <ElasticEase /> </VisualTransition.GeneratedEasingFunction> </VisualTransition> </VisualStateGroup.Transitions> ... </VisuateStateGroup> </VisualStateManager.VisualStateGroups> VisualTransition elements allow us to modify the animation behavior depending on what the original and final states of the transition are. It has properties such as From and To for the purpose of specifying the original and final states. In our case, we set only its To property to Pressed, which means that it applies to transit from any state to the Pressed state. VisualTransition sets the duration of the animation to 0.5 second and adds the ElasticEase easing function to it, which results in the button size bouncing effect. Once we started talking about easing functions, we can explain in detail how they work, and give examples of other easing functions. Easing functions provide a way to modify Silverlight (and WPF) animations. A good article describing easing functions can be found at http://tinyurl.com/arbitrarypathanimations. The easing formula presented in this article is: v = (V2 – V1)/T * f(t/T) + V1 Here v is the resulting animation value, t is the time parameter, T is the time period in question (either time between two frames in an animation with frames or time between the To and From values in the case of a simple animation), V2 and V1 are the animation values at the end and beginning of the animation correspondingly at the absence of easing, and f is the easing function. In the previous formula, we assumed a linear animation (not a spline one). There are a bunch of built-in easing functions that come together with the Silverlight framework, for example, BackEase, BounceEase, CircleEase, and so on. For a comprehensive list of built-in easing functions, please check the following website: http://tinyurl.com/silverlighteasing.. Most easing functions have parameters described on this website. As an exercise you can change the easing function in the previous VisualTransition XAML code, modify its parameters, and observe the changes in button animation. Summary Here we have just learned how to animate a built-in button using Silverlight. Resources for Article : Further resources on this subject: Customized Effects with jQuery 1.4 [Article] Python Multimedia: Fun with Animations using Pyglet [Article] Animating Properties and Tweening Pages in Android 3-0 [Article]
Read more
  • 0
  • 0
  • 2528

article-image-getting-started-citrix-access-gateway-product-family
Packt
15 Mar 2013
16 min read
Save for later

Getting Started with the Citrix Access Gateway Product Family

Packt
15 Mar 2013
16 min read
(For more resources related to this topic, see here.) Security and Remote Access Solutions addressed by Citrix Access Gateway Firstly, let us address a little of the history of Citrix Systems, the purpose of CAG, and why this is used within corporates, from small companies to large enterprise networks. Citrix has been providing levels of remote access since 1989, first with their Multi-User OS2 terminal server. Following the success of Citrix-Multi-User, they went on to develop for the Microsoft Windows operating systems and the milestones include: 1993 – WinView releases 1995 – WinFrame releases 1998 – MetaFrame releases 2008 – XenApp releases In the early days of WinFrame and MetaFrame terminal servers, you would have to provide some third-party virtual private network (VPN) solution to be able to access these servers from the Internet. In many respects, the weakness of these early solutions is that they do not address secure remote access. To mitigate this issue, Citrix introduced a product into the market, in 2001, called Citrix Secure Gateway (CSG). This is still available today and is bundled with XenApp 6.5. This, much in the same way as CAG, is a remote access solution that can be used to provide remote users on the Internet connectivity to your internal resources, such as your XenApp or XenDesktop servers. Without CAG or CSG, each Citrix XenApp server and/or each XenDesktop virtual machine would require a public IP address to be accessible from the outside world. Of course, this is not practical, especially when we look at XenDesktop; do you have 300 public IP addresses available for your virtual desktops or VDI environment? Both the CSG and CAG can act as an ICA proxy to provide connectivity to your internal Citrix servers. ICA is the Citrix protocol for remote access. This can be listened on TCP port 1494 (for standard ICA connections) or TCP port 2598 (for session reliability). Session reliability tunnels ICA traffic through port 2598 to allow for momentary loss of connectivity, as would be experienced with mobile networks, and to allow seamless reconnection to the session. So, if both devices can provide the ICA proxy functionality, why use CAG? In 2005, Citrix systems acquired NetScaler, Inc. This gave them the NetScaler product range, and ultimately, Access Gateway. Quite simply, CAG is a secured system dedicated to remote access. It is supplied as either a hardware appliance or virtual appliance. By "dedicated", it is meant that CAG has no other function, purpose, or unnecessary services. It is hardened or locked down for security at the time of production. CSG, on the other hand, is a software that installs onto a running operating system. We are, then, reliant on the OS that it is installed upon to be specifically hardened to provide the same level of security that you find out-of-the-box with CAG. In addition to this, CAG can provide standard VPN connectivity into your private networks for remote users, not just connectivity to XenApp or XenDesktop. Choosing the appliance-based CAG includes support for additional applications and protocols. The software-based Secure Gateway is not only less secure but is also limited to supporting traffic directed to computers running XenApp or XenDesktop. Therefore, organizations that use the Secure Gateway might also have to deploy a remote access solution for other types of internal network resources, adding additional expense and management workload for already busy administrators. CAG can handle your organization's remote access needs by securing traffic to applications hosted by Citrix XenApp and desktops hosted by Citrix XenDesktop as well as access to internal resources, such as e-mail, internal Web applications, and network file shares. In short, CAG is a secure remote access solution to provide VPN or ICA proxy access to internal resources to your mobile or remote workforce. The following diagram illustrates that users connecting from the Internet pass through the external corporate firewall to the Access Gateway. From here, the incoming HTTPS is converted to an ICA stream targeting XenApp or XenDesktop servers. Possibly, even native protocols are converted to non-Citrix products when using a full VPN connection. Citrix Access Gateway hardware CAG, as mentioned already, can run as a virtual appliance or on physical hardware. The physical hardware device is a dedicated Citrix NetScaler appliance and comes in various shapes and sizes. The CAG firmware is installed into the NetScaler appliance, which runs an embedded Linux operating system. The same firmware that is used to run CAG on the hardware appliance can be used on the VPX edition, for example, both the VPX appliance and NetScaler 2010 model run Access Gateway 5.x firmware. NetScaler Model 2010 Appliance Model 2010 Appliance represents entry-level dedicated hardware and supports Access Gateway 5.0 and Access Gateway Standard Edition. In this book we will focus on Access Gateway 5.0.4. You can install Model 2010 in the DMZ or the secure network. The preconfigured IP address of the Access Gateway is 10.20.30.40. Citrix will tell you that you are able to change the IP address using a serial cable and a terminal emulation program such as Microsoft Windows Telnet Client, or you can connect Access Gateway using network cables and Access Gateway Management Console in Access Gateway 5. Usually, connecting via the network to change the IP address is the simplest method; just ensure you are plugged into a non-production environment when making the change, and then switch the appliance back into the DMZ. The following is a screenshot of NetScaler MPX 5500 Appliance model: NetScaler Model MPX 5500 Appliance This model boasts multiple processors, and from that, you can gain faster throughput and more concurrent connection support. Citrix provides Access Gateway in multiple forms to suit your organizational needs. This model supports Access Gateway Enterprise Edition. The preconfigured IP address of Access Gateway is 192.168.100.1 with a 16-bit or class B subnet mask. The IP address is changed in the same way as Model 2010. Other hardware appliances are available to support the growing amount of concurrent connections that you may require. You can install the Access Gateway Enterprise Edition appliances in the DMZ or the secure network as with Access Gateway 5. The main difference between the models is their hardware specifications. The higher the specification of the hardware, the more users the appliance will support, and it will be quicker in those tasks. One of the first tasks in the planning of your appliance is to answer the question "how many concurrent connections do we need to support?" or, simply "how many users will be connected to the appliance at the same time?". If you are using VPX, the specifications can be managed by assigning fewer or less resources such a RAM and CPU to the virtual machine. The following table conveniently lists each of the hardware appliances and their main specifications: Appliance Specifications 2010 5500 Processors RAM in GB Power supplies 1 1 1 1 dual core 4 1 Citrix Access Gateway versions The very latest version of Access Gateway, as of June 2012, is Access Gateway 10, which is being introduced as a replacement for Access Gateway 9.3 Enterprise Edition. Both the Access Gateway 9.x and 10.x models require NetScaler 5500 or higher as a hardware platform. The earlier editions of Access Gateway Version 4.x and 5.x can run on NetScaler 2010 or the virtual appliance. Many of the features are the same, but it is the enterprise class high availability of the premium models that sets them apart. Much of this high availability can be mirrored within your virtual host environment if you choose to use the VPX editions. To gain an appreciation of where Citrix began on the Access Gateway product, we introduce to you the major milestones for the product under the ownership of Citrix Systems. Access Gateway Milestones Milestones of Access Gateway include: 2005 – Citrix acquires NetScaler 2005 – Citrix Access Gateway names product of the year by SearchNetworking 2006 – Citrix Access Gateway Enterprise Edition launches 2008 – MPX or multi-processor version of the Access Gateway hardware appliances (NetScaler) launches 2009 – Citrix launches Access Gateway VPX edition, a cost-effective replacement for CSG in 2009 2012 – CAG 10 introduces in 2012 Access Gateway 10 The latest and greatest offering from Citrix, Citrix NetScaler Access Gateway Version 10, offers support for: Clientless access for a receiver on the Web: Connect to your internal resources with a secure VPN connection with just a web browser Multi-stream ICA that allows you to partition multiple ICA streams in the same session: Multi-stream ICA is a quality of service (QoS) enhancement developed in XenDesktop 5.5 and XenApp 6.5. When implemented, Multi-stream ICA uses four separate TCP connections to carry the ICA traffic between the client and the server. Each of these TCP connections will be associated with a different class of service. ICA traffic has always implemented multiple internal channels. These channels represent clipboard mapping, audio, drive mappings, and so on. With Multi-stream ICA, the four TCP connections are assigned a QoS priority, and each ICA stream is defined to work with one of these TCP connections inheriting the QoS. Very high priority (for real-time channels, such as audio) High priority (for interactive channels, such as graphics, keyboard, and mouse) Medium priority (for bulk virtual channels, such as drive mapping, scanners) Low priority (for background virtual channels, such as printing) Web socket protocol support that allows bi-directional communication between user devices and servers over HTTPS. Organizational benefits of Access Gateway 10 include: Secure remote access for the most demanding and complex environments that require increased scalability and performance High availability of guaranteed access to resources and compliance with Service-level agreements (SLAs) Highest level of integration and control of remotely delivered Citrix XenApp applications, data through SmartAccess (endpoint analysis), and published desktops with Citrix XenDesktop Natural progression for existing XenApp customers who have used the Secure Gateway and wish to benefit from the added security and full VPN access Enterprise-class SSL VPN features, including client-side cache cleanup, detailed auditing, and policy-based access control for web and server applications Ability for remote users to work with files on shared network drives, access e-mail and intranet sites, and run applications as if they are working within your organization's firewall Support for the Access Gateway universal license. These licenses enable SmartAccess and can be purchased separately but are also bundled with XenApp Premium Edition Access Gateway 9.3 Enterprise Edition Access Gateway 9.3 Enterprise Edition is very commonly deployed and probably represents many of the enterprise class installations of Access Gateway, more so than version 10 as that is so very new. There were no new features in version 9.3 over those included in the predecessor, Access Gateway 9.2 EE; the enhancements in 9.3 relate more to security. Access Gateway 9.2 Enterprise Edition Access Gateway 9.2 Enterprise Edition offers the following benefits: Secure remote access for the most demanding and complex environments that require increased scalability and performance High availability for guaranteed access to resources and compliance with SLAs Highest level of integration and control of remotely delivered Citrix XenApp applications, data through SmartAccess, (endpoint analysis), and published desktops with Citrix XenDesktop Natural progression for existing XenApp customers who have used the Secure Gateway and wish to benefit from the added security and full VPN access Enterprise-class SSL VPN features, including client-side cache clean-up, detailed auditing, and policy-based access control for web and server applications Ability for remote users to work with files on shared network drives, access e-mail and intranet sites, and run applications as if they are working within your organization's firewall Support for the Access Gateway universal license; these licenses enable SmartAccess and can be purchased separately but are also bundled with XenApp Premium Edition Access Gateway 9.2 and 9.3 do not provide support for ICA Multi-stream. ICA Multi-stream is supported in Access Gateway 10, 5.03, and 5.04. Earlier versions of Access Gateway Enterprise Edition exist, but these versions are enough to cater for what you will encounter in the current market. Access Gateway 5.x The Citrix Access Gateway can be used on NetScaler Model 2010 and the VPX Edition. The Gateway has two modes of operation, Standalone and Controller. Access Controller is an additional piece of software that is installed onto Windows Server 2008 R2 to allow access policies to be defined from within the standard XenApp Group Policies filters. The focus of this book is on Access Gateway in Standalone mode. The key features of Citrix Access Gateway are as follows: Authentication of users against LDAP directories or RADIUS Termination point for encrypted sessions Authorization of users to access resources Secure VPN through traffic relay for authorized users Support for multiple logon points that can allow for basic or SmartAccess endpoint analysis Citrix Access Gateway VPX Edition The purpose of this book is to specifically help you understand and deploy the VPX edition of Access Gateway. As organizations have increased their use of remote access solutions, Citrix has had to cater to that need with a diverse offering of systems. These solutions need to provide the same flexibility as the customer base is diverse. Access Gateway VPX is a virtual appliance delivering the same features and functionality as the Model 2010 physical appliance. Customers will find that Access Gateway VPX is ideal for: Natural progression for existing XenApp customers, who have used the Secure Gateway and wish to benefit from the added security and full VPN access. Access Gateway VPX supports Citrix Receiver and XenDesktop whereas Citrix Secure Gateway does not. Consolidation of physical resources where rack space may be limited. Meeting the needs of green IT by reducing cooling needs and power consumption within the data center. Minimizing downtime by utilizing the HA infrastructure that is already maintained with your virtual machine hosts, maximizing the investment that you have with Citrix XenServer or VMware. Multi-tenant solutions with the availability of multiple logon points. In simple terms, the virtual appliance is an easy choice for organizations that already implement a virtual machine infrastructure. The high availability that is not provided in the VPX is maintained by XenServer or VMware. Performance can be optimized by assigning more RAM or VCPUs (virtual processors) to the Access Gateway virtual machine. Citrix suggests a maximum of 500 concurrent users on each virtual appliance. The Citrix Access Gateway VPX Express is free but is limited to just five concurrent users. The VPX is downloaded from the Citrix website. If you do not already have a MyCitrix login, you will be required to register for an account. Virtual machine resources required by the Access Gateway VPX are as follows: XenServer version VMware version Memory Concurrent users VCPU Virtual NICS Disk space 5.5 or Higher ESX/ESXi 4.0 or higher 1 to 4 GB RAM 500 1 to 4 VCPUs (2 recommended) 1 to 4 NICS 12 GB minimum   The following screenshot shows the console screen from Citrix Access Gateway while running on XenServer: Designing a secure Remote Access solution So, now we understand a little of what the CAG models can provide for us and are clear that we can use hardware or virtual appliances. At this point, we can take the opportunity to review the security solutions provided with CAG and how to design a secure deployment. Availability How many users do you need to support concurrently? Part of a secure solution will be making sure the system maintains its presence. Partly, that involves not overloading the system. CAG maintains all incoming connections and passes all VPN traffic into and out of your LAN. Each Model 2010 appliance and VPX can support 500 users, the MPX can support 5500 users, and a massive can support 5000 users. If you're using the VPX, make sure you have enough appliances deployed and load-balanced. Using ICA Proxy to access XenApp/ XenDesktop When connecting from the Internet, your remote users are going to connect into your server farms and request a published application from XenApp or a virtual desktop from XenDesktop. The corresponding ICA file that is returned to the client will contain the IP address of the server that will accept the connection. This is usually a private IP Address and the client will have no route to the network. If remote users are presented with the internal address of the hosted applications or desktops, they will not be able to connect. Thus the need for ICA proxy. Ensuring there is no path for a single protocol to traverse the DMZ From a security perspective, your network will be more secure if we can ensure that no single protocol can traverse from the external firewall of your DMS into the internal network hosting your private resources. Implementing an ICA proxy on CAG will allow users to connect via HTTPS to the gateway, and the Gateway to forward the connection into the private network using ICA. Without the Access Gateway ICA, traffic is unchallenged in the DMZ. Resolving remote access issues using Citrix Access Gateway In its simplest form, Access Gateway will proxy incoming requests— in this case, for ICA connections to XenApp/XenDesktop. As the client only ever connects to CAG, ICA traffic need not be allowed through the exterior firewall. Additionally, as the client never connects directly to the XenApp servers, they do not need public addresses and need only to be routable to CAG. The following diagram shows that the client connects using HTTPS from their client to CAG within the DMZ and CAG connects using ICA to the internal resources of XenApp/XenDesktop: If you need access to other resources, we have full VPN connections CAG can additionally provide similar VPN access via SSL and to your internal resources using SmartAccess logon points. Multiple logon points can exist on single CAG to provide flexible access. Authentication To allow for secure remote access, authentication of your users should take place within the DMZ. In this way, users are authenticated without the need to connect them to internal resources. CAG addresses these issues by authenticating any user request before they are connected. In addition, your existing directory infrastructure can be used as the authentication source. CAG can connect with Microsoft Active Directory and Novell eDirectory as well as Remote Authentication and Dial-In User Service (RADIUS) and other LDAP providers. PKI Certificates The communication from the client to CAG is secured with SSL. When planning for your CAG deployment, you will need to consider the provision of public-key infrastructure (PKI) certificates for the appliance. The public key from the issuing authority and the server's own key pair must be added to the device. Summary In this article, we have become familiar with the CAG range and considered which model we require and how many appliances we will need to support our projected concurrent user load. We should also now be able to envision how the gateway will provide remote access solutions to both ICA-based resources, such as XenApp and traditional VPN access to file shares, reducing your reliance on multiple remote access products. Resources for Article : Further resources on this subject: Getting Started with XenApp 6 [Article] Designing a XenApp 6 Farm [Article] Managing Citrix Policies [Article]
Read more
  • 0
  • 0
  • 12489

article-image-extending-your-structure-and-search
Packt
15 Mar 2013
6 min read
Save for later

Extending Your Structure and Search

Packt
15 Mar 2013
6 min read
(For more resources related to this topic, see here.) Indexing data that is not flat Not all data is flat. Of course if we are building our system, which ElasticSearch will be a part of, we can create a structure that is convenient for ElasticSearch. However, it doesn't need to be flat, it can be more object-oriented. Let's see how to create mappings that use fully structured JSON objects. Data Let's assume we have the following data (we store it in the file called structured_data.json): { "book" : { "author" : { "name" : { "firstName" : "Fyodor", "lastName" : "Dostoevsky" } }, "isbn" : "123456789", "englishTitle" : "Crime and Punishment", "originalTitle" : "Преступлéние и наказáние", "year" : 1886, "characters" : [ { "name" : "Raskolnikov" }, { "name" : "Sofia" } ], "copies" : 0 } } As you can see, the data is not flat. It contains arrays and nested objects, so we can't use our mappings that we used previously. But we can create mappings that will be able to handle such data. Objects The previous example data shows a structured JSON file. As you can see, the root object in our file is book. The root object is a special one, which allows us to define additional properties. The book root object has some simple properties such as englishTitle, originalTitle, and so on. Those will be indexed as normal fields in the index. In addition to that it has the characters array type, which we will discuss in the next paragraph. For now, let's focus on author. As you can see, author is an object that has another object nested in it, that is, the name object, which has two properties firstName and lastName. Arrays We have already used array type data, but we didn't talk about it. By default all fields in Lucene and thus in ElasticSearch are multivalued, which means that they can store multiple values. In order to send such fields for indexing to ElasticSearch we use the JSON array type, which is nested within the opening and closing square brackets []. As you can see in the previous example, we used the array type for characters property. Mappings So, what can we do to index such data as that shown previously? To index arrays we don't need to do anything, we just specify the properties for such fields inside the array name. So in our case in order to index the characters data present in the data we would need to add such mappings as these: "characters" : { "properties" : { "name" : {"type" : "string", "store" : "yes"} } } Nothing strange, we just nest the properties section inside the array's name (which is characters in our case) and we define fields there. As a result of this mapping, we would get the characters.name multivalued field in the index. We perform similar steps for our author object. We call the section by the same name as is present in the data, but in addition to the properties section we also tell ElasticSearch that it should expect the object type by adding the type property with the value object. We have the author object, but it also has the name object nested in it, so we do the same; we just nest another object inside it. So, our mappings for that would look like the following code: "author" : { "type" : "object", "properties" : { "name" : { "type" : "object", "properties" : { "firstName" : {"type" : "string", "store" : "yes"}, "lastName" : {"type" : "string", "store" : "yes"} } } } } The firstName and lastName fields would appear in the index as author.name.firstName and author.name.lastName. We will check if that is true in just a second. The rest of the fields are simple core types, so I'll skip discussing them. Final mappings So our final mappings file that we've called structured_mapping.json looks like the following: { "book" : { "properties" : { "author" : { "type" : "object", "properties" : { "name" : { "type" : "object", "properties" : { "firstName" : {"type" : "string", "store" : "yes"}, "lastName" : {"type" : "string", "store" : "yes"} } } } }, "isbn" : {"type" : "string", "store" : "yes"}, "englishTitle" : {"type" : "string", "store" : "yes"}, "originalTitle" : {"type" : "string", "store" : "yes"}, "year" : {"type" : "integer", "store" : "yes"}, "characters" : { "properties" : { "name" : {"type" : "string", "store" : "yes"} } }, "copies" : {"type" : "integer", "store" : "yes"} } } } To be or not to be dynamic As we already know, ElasticSearch is schemaless, which means that it can index data without the need of first creating the mappings (although we should do so if we want to control the index structure). The dynamic behavior of ElasticSearch is turned on by default, but there may be situations where you may want to turn it off for some parts of your index. In order to do that, one should add the dynamic property set to false on the same level of nesting as the type property for the object that shouldn't be dynamic. For example, if we would like our author and name objects not to be dynamic, we should modify the relevant parts of the mappings file so that it looks like the following code: "author" : { "type" : "object", "dynamic" : false, "properties" : { "name" : { "type" : "object", "dynamic" : false, "properties" : { "firstName" : {"type" : "string", "store" : "yes"}, "lastName" : {"type" : "string", "store" : "yes"} } } } } However, please remember that in order to add new fields for such objects, we would have to update the mappings. You can also turn off the dynamic mapping functionality by adding the index.mapper.dynamic : false property to your elasticsearch.yml configuration file. Sending the mappings to ElasticSearch The last thing I would like to do is test if all the work we did actually works. This time we will use a slightly different technique of creating an index and adding the mappings. First, let's create the library index with the following command: curl -XPUT 'localhost:9200/library' Now, let's send our mappings for the book type: curl -XPUT 'localhost:9200/library/book/_mapping' -d @structured_mapping.json Now we can index our example data: curl -XPOST 'localhost:9200/library/book/1' -d @structured_data.json If we would like to see how our data was indexed, we can run a query like the following: curl -XGET 'localhost:9200/library/book/_search?q=*:*&fields=*&pretty=true' It will return the following data: { "took" : 1, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 1, "max_score" : 1.0, "hits" : [ { "_index" : "library", "_type" : "book", "_id" : "1", "_score" : 1.0, "fields" : { "copies" : 0, "characters.name" : [ "Raskolnikov", "Sofia" ], "englishTitle" : "Crime and Punishment", "author.name.lastName" : "Dostoevsky", "isbn" : "123456789", "originalTitle" : "Преступлéние и наказáние", "year" : 1886, "author.name.firstName" : "Fyodor" } } ] } } As you can see, all the fields from arrays and object types are indexed properly. Please notice that there is, for example, the author.name.firstName field present, because ElasticSearch did flatten the data.
Read more
  • 0
  • 0
  • 1973

article-image-common-design-patterns-and-how-prototype-them
Packt
15 Mar 2013
7 min read
Save for later

Common design patterns and how to prototype them

Packt
15 Mar 2013
7 min read
(For more resources related to this topic, see here.) When you tackle a design challenge and decide to re-use a solution that was used in the past, you probably have a design pattern. Design patterns are commonly used concepts that plead to be re-used. They save time, they are well recognized by a majority of users, they provide their intended functionality, and they always work (well, assuming you selected the right design pattern and used it in the right place). In this article , we will prototype one of the commonly used design pattern,: Module tabs pattern Once you created a design pattern prototype, you can copy and paste it into an Axure project. A better alternative is to create a custom widgets library and load it into your Axure environment, making it handy for every new prototype you make. Module tabs Module tabs pattern allows the user to browse through a series of tabs without refreshing the page. Why use it? Module tabs design pattern is commonly used in the following situations: When we have a group of closely related content, and we do not want to expose it to the user all at once. (In order to decrease cognitive load, because we have limited space, or maybe in order to avoid a second navigation bar.) When we do not care for (or maybe even prefer) a use case where a visitor interacts only with one pane at a time, thereby limiting his capability to easily compare information or process data simultaneously. Hipmunk.com is using it A module tabs design is used in www.hipmunk.com for a quick toggle between Flights and Hotels. By default, the user is exposed to Hipmunk's prime use case, which is the flight search. Prototyping it This is a classic use of the Axure dynamic panels. We will use a mixture of button-shaped widgets along with a dynamic panel. A module tabs design is comprised of a set of clickable tabs, located horizontally on top of a dynamic content area. Tabs can also be located vertically on the left side of the content area. We will start with creating a content area having three states: Drag a Rectangle-Dropshadow widget from the Better Defaults library into the wireframe and resize it to fit a large enough content area. This will be our background image for all content states. Now drag a Dynamic Panel widget, locate it on top of the rectangle, and resize it to fit the blank area. Label the dynamic panel with a descriptive name (the Label field is in the Widget Properties pane). In this example we will use the label: content-area dPanel. Examine your dynamic panel on the Dynamic Panel Manager pane, and add two more states under it. Since we are in the travel business, you can name them as flight, hotel, and car (these states are going to include each tab's associated content). Put some text in each of the three dynamic panel states to easily designate them upon state change (later on you can replace this text with some real content). In the screenshot that follows, you can see the content-area dPanel with its three states. Next, we will add three tab buttons to control these three states: We are going to experiment a little bit with styles and aesthetics, so let's hide the dynamic panel object from view by clicking on the small, blue box next to its name on the Dynamic Panel Manager pane. Hiding a dynamic panel has no functional implication; it will still be generated in the prototype. Drag one basic Rectangle widget, and place it above our large dropshadow rectangle. Resize the widget so that it will have the right proportions. In the following screenshot, you can see the new rectangle widget location. Also you can see what happens when we hide the dynamic panel from view: When a tab is selected (becomes active), it is important to make it look like it is part of the active area. We can achieve this by giving it the same color of the active state background as well as eliminating any border line separating them. But let's start with reshaping the rectangle widget, making it look like a tab: Right-click on the Rectangle widget and edit its shape (click on Edit button shape and select a shape). Choose the rounded top shape. This shape has no bottom border line and that's why we like it. Notice the small yellow triangle on top of the rounded top. Try to drag it to the left. You will see that we can easily control its rounded corners' angle, making it look much more like a tab button (See the screenshot that follows). Now that we have a nice looking tab button we can move forward. By default, the tab should have a gray color, which designates an unselected state. So, select the widget and click on Fill color button on the Axure toolbar to set its default color to gray. Once the tab is selected, it needs to be painted white, so that it easily blends with the content area background color under it. To do that, right-click on the tab and edit its selected style (Edit button shape Edit selected style|); the fill color should be set to white (select the preview checkbox to verify that). We are almost done. Duplicate the tab and place three identical widgets above the content area. Move them one pixel down so that they overlap and hide the rectangle border line underneath them. In the screenshot that follows, you can see how the three tabs are placed on top of the white rectangle in such a way that they hide the rectangle's border line. Examine the split square in the upper-left corner of each tab widget you created. You can preview the rollover style and selected state style of the widget by hovering over and clicking on it. Try it! The last thing to do is to add interactions. We would like to set a tab to the selected state upon mouse click, and to change the state of content-area dPanel accordingly. Put a name on each tab (Flight, Hotel, and Car), and give each tab a descriptive label. Set the OnClick event for each tab to perform two actions: Set Widget(s) to selected state: Setting the widget after it was clicked to be in a selected style. Set Panel state(s) to state(s): Setting the dynamic panel state to the relevant content (Flight, Hotel, or Car). Since we would like to have only one selected widget at a time, we should put the three of them in a selection group. Do that by selecting all the three widgets, right-clicking, and choosing the menu option Assign Selection Group. Each time this page is loaded, the Flight tab needs to be selected. To do that, we will configure the OnPageLoad event to set the Flight tab to be selected (find it at the pane located under the wireframe). By the way, there is no need to set the dynamic panel state to flight as well since it is already located on top of the three states in the Dynamic Panel Manager pane, making it the default state. In the screenshot that follows, you can see the Page Interactions pane located under the wireframe area. You can also see that the flight state is the one on top of the list, which makes it the dynamic panel's default view. The menu navigation widget cannot be used as an alternative for the tab buttons design explained here. The reason is that the navigation menu does not support the Selection Group option. Summary In this article, we learned about one of the three commonly used UI design patterns, Module Tabs and learned how to prototype them using the key features of Axure. We can now work more efficiently with Axure and will be able to deliver detailed designs much faster. Resources for Article : Further resources on this subject: Using Prototype Property in JavaScript [Article] Creating Your First Module in Drupal 7 Module Development [Article] Axure RP 6 Prototyping Essentials: Advanced Interactions [Article]
Read more
  • 0
  • 0
  • 6393

article-image-titanium-best-practices
Packt
15 Mar 2013
13 min read
Save for later

Titanium Best Practices

Packt
15 Mar 2013
13 min read
(For more resources related to this topic, see here.) CommonJS CommonJS is a set of specifications, and its purpose is to give a common guide to building JavaScript frameworks. It is not a framework in its own right. Appcelerator implementing these standards to their Titanium framework brings it inline with other frameworks such as NodeJS, and enables us as developers to use the same practices in more than one framework. The implications of this cannot be overstated. Developers can now switch between JavaScript frameworks, which have implemented the CommonJS model, without having a massive learning curve on the framework itself. CommonJS works by using an initial bootstrap file, which in Titanium is app.js. You then abstract your code into separate modules that are required into other modules when needed. Within Titanium, you can have native modules that enhance and expand the Titanium framework. These should not be confused with a CommonJS module, which is part of the main application. Code formatting How often have you needed to modify code that was written by other people or has been updated, modified, rewritten, or just generally messed around with? You find different people using different coding styles, braces on different lines, and equals signs at different positions; the list is endless. You then have to work your way through this code, getting more and more annoyed. Titanium Studio has a solution—an automatic code formatter, which you can set up as you require. To get to the configuration settings, go through the main menu to Preferences | Titanium Studio | Formatter, select JavaScript , and click on the edit icon. You will see the Preferences panel and you can configure it as required. If you wish to have these configurations across your development team, then you can export and import them as required. To format a file's code, open the file, go to the main menu, and select Source | Format. Alternatively, if you are on a Mac, the relevant shortcut keys are shift +command +F. If you have selected a section of code then that will be formatted, otherwise the whole file will be formatted. A gotcha with the formatter: If there are too many JavaScript errors it won't format the code. Code validation As developers, we spend our days hunting down spurious code anomalies. It could be a missing comma, semicolon, or that an event listener wasn't added while looping an array of objects. Anything that can make this task easier and show potential issues while we are writing code is a good thing. JSLint is one of those tools that you could use, as it highlights potential issues as you code. It has been described as your worst nightmare but also your best friend. When you first start using it, it may drive you mad with some of the seemingly meaningless warnings, but sort them out and be persistent; it will improve your codebase in the long term. Titanium Studio has JSLint built in but switched off by default. To enable it, go to Preferences | Titanium Studio | Validation, select JavaScript , and switch on JSLint Validator. As you can see, there are other validators on the list, which also help give you a hit list of potential issues. It is worth spending a little time making sure you understand what these are and how they work. Comment meaningfully Adding comments to your code should not be seen as a chore, instead they can be as important as the code itself. A well-commented codebase can and will save hours in the future, as you or a colleague go to update and maintain it. Always put a comment block at the start of source files, explain what the file does, and include a maintenance log, where the date, time, developer's name, and a brief description of the changes can be maintained. If you have a complex function put a comment block before it, explaining what it does. Also place inline comments where needed to explain certain pieces of code. /* * A CommonJS Module. * * This module does something … * * Author : Name * * Date : Today * * Maintenance Log * * Date : Author: * Changes : * */ Do not add comments for the sake of adding them. Make them meaningful, relevant, and useful. Too many comments can confuse the code structure. Do not pollute the global object Within an application you can define various application objects. Declare and use these with caution, as they use up resources and can easily cause clashes with other private and local objects. Application-level variables are not really required and should be avoided. If you require a small piece of data to move around the application, consider using persistent data or passing it to the required modules. Application-level event handlers are required for various tasks including, amongst others, background services and geolocation. If you do use them, always remove them when they are no longer needed. To control the flow of an application, you may need to set up a global listener, but you only need one with a common function to control the flow. In CommonJS there is no global scope; declaring a variable within a module makes it private to that module. Declaring variables in app.js as Ti.App.varName = [], does make them global, but is highly discouraged. JavaScript instance A JavaScript instance is where a session of the interpreter is invoked. In Titanium it is possible to create multiple instances within a single application. This is done by creating a window object with a url property to load the content. Var win = Ti.UI.createwindow({ url: '/app/ui/newWindow.js' }); Don't do this unless you have a very, very specific requirement. To benefit from all the advantages CommonJS provides, always work in a single JavaScript instance. The consequences of multiple instances include no scope across them, additional memory and resource usage, and a high risk of memory leaks. CommonJS modules With the adoption of the CommonJS specification by Appcelerator into the Titanium framework, you should only use the CommonJS modules, which are also referred to as factories. This provides many advantages: separation of code into specific modules, a more structured codebase, separate object scope, code maintainability, and much more. By using this method it becomes very difficult to pollute the global scope, as each module has its own object scope. Understanding this is key to the CommonJS method. Each module or factory contains functions and variables that can be exported; unless they are exported they are private to that module. This enables variable or function names to be the same in different modules without a scoping clash. By exporting only what is required at the end of the module, it enables the module to be self contained. /* A typical module format myModule.js */ var object1 = "1234"; var object2 = "5678"; /* My modules function */ functionmyModule(args){ … do something nice return mainObject; } exports.object1 = object1; exports.myModule = myModule; When a CommonJS module is required by another module it is loaded into memory. If you then require the same module elsewhere, it doesn't reload it into memory; it just makes it available to the new calling module. This means t hat if the first requiring module sets a value in the called module, when the called module is required by another module, the values which have been set are still set. It doesn't load a new instance of the module and reinitialize all the values. A few rules about modules: Only load them when needed Only export what is required by the calling module Use prototype where appropriate Avoid recursive requires Working with CommonJS recursive requires can cause major issues and, basically, you can't do it. A recursive require is where module A requires module B and module B then requires module A. You will quickly notice if you try this that this leads to a loop trying to process the continual call of the requires, and finally dies with a nondescript error message. CommonJS best practices CommonJS is one of the best things to have happened to the Titanium framework. To get the most out of the framework and the enhanced performance, these are a few things that should be considered: Be modular Be private Return an object Protect the global scope Control file loading One of the main advantages of CommonJS is the way it lends itself to creating well-structured, separated code. By being modular you create specific modules for separate sections of the code, i.e. a separate module for each window. This methodology facilitates the creation of common modules enabling a constructive codebase that is easy to understand and maintain. A good example of a common module would be one that contains the geolocation code and is then used across the whole application. Common modules enable the code to be extracted down, but don't go too far. It is tempting to extract code out into its own module when it actually lives in the module it is in. Do not be tempted to take code modularization to the extreme, having a module for each function is not necessary or productive. Remember that modules are loaded into memory once they have been required and they remain there. Making functions and variables private to a module maintains the module's integrity. Do not export all the functions in a module unless they are actually called from the requiring module. Export the required functions and variables at the end of the module, not by default. The following code example shows the two methods for exporting functions: // This exports the function inline exports.outFunc = function () { .. code .. return object; } // This only exports the function when and if required. function outFunc() { .. code .. return object; } exports.outFunc = outFunc; By defining the module functions in the second method, they become local to that module. This means that they can be used directly by any other function within the module. As you separate your code into modules, separate your modules into functions. Having one exported parent function that returns the main object after processing through other functions is a good practice. It is quite easy to declare module variables; you just declare them outside of any function. This gives them a scope that is global to the module. It is a very good way of maintaining a persistent state across the calling modules, but use them sparingly as they use up more resources. JavaScript, by default, returns the last action of a function to the calling function. This may not always be what is required, especially in the CommonJS model. Always return what you require from a function even if that is nothing. // New window function returning the null object. functionnewWin() { // Do something return; } exports.newWin = newWin; For an exported function always return the function's main object. Hence, creating a new window in a function should return that window object as the following code example shows: // New window function returning the parent object. function newWin() { var win = Ti.UI.createWindow({ .. parameters .. }); return win; } exports.newWin = newWin; The global scope should be considered as nonexistent, but you can still add application-level variables. If you have to use these, only declare them in the app.js file; do not declare them in any of the modules. At times you will have to create an application event listener in a module. Only do this when you have to and always, always remove the listener after you have finished with it. The following code example shows an event listener added with an in-built function. This is not good practice, as you cannot remove it later. The only way it will be removed is when the parent object is destroyed, which for application-level listeners is when the application is stopped, not put into background. function adList() { varmainObj = Ti.UI.createImageView(); mainObj.addEventListener('click', function(e) { .. do something here .. }); return mainObj; } Instead of defining listeners with an in-built function, always declare them to a calling function as the following example shows. They can then easily be removed, as you have to declare the called function to be identical in both addEventListener and removeEventListener. varmainObj = null; function eveList(e){ .. do something here … mainObj.removeEventListener('click', eveList); } function adList() { mainObj = Ti.UI.createImageView(); mainObj.addEventListener('click', eveList); return mainObj; } Managing memory We have explored some of the practices that will help in managing the application's memory. These practices range from controlling when the modules file is loaded to not using application-level events or variables. When you open a window, it is added to the window stack, and every time you open that window it is added to the stack. If you have a navigation system that enables you to move through the windows in any order, it is likely that you will end up with a large stack. Close the windows when they are not in use. varwin =i.UI.createWindow(); varwinBut =i.UI.createButton({ title : 'Press' }); function loadWin2() { varwin = Ti.UI.createWindow(); win.close(); win = null; win2.open(); } winBut.addEventListener('click', loadWin2); // opening a window win.add(winBut); win.open(); Some additional memory-intensive APIs in Titanium are web views, large tables, and events. It is not a good idea to have more than one web view instance running in the application at a time. If you do not close the window containing the web view instance and move to another one, at least remove the web view instance from the previous window and reload it when focus is made. The same applies to tables and map views. When you remove an object such as a web view from a window it may not always release the memory—even closing a window does not always release the memory. In all cases, null is your friend. The final code example shows a window with web view, an event listener, and how to clean up when a window is closed: // clean up example module function createWin() { var win = Ti.UI.createWindow(); varwebV = Ti.UI.createWebView(); win.addEventListener('open', openFunc); win.addEventListener('close', function(e) { win.removeEventListener('open'openFunc); win.remove(webV); webV = null; win = null; } win.add(webV); return win; } In this example the close event doesn't call another function. This is acceptable because when we close the window, the close event will fire, which nulls the win object and this removes the object's event listener. It is done this way to prevent having to use module variables to handle the window and web view objects being cleaned up in another function. Summary As you have seen, there are quite a few considerations to take into account when coding with Titanium. Some of these can also be applied to other programming languages. It is completely optional to follow best practices; they are there as a guide, as a place to start, and as a way to manage your code going forward. As a developer you will find your own way to implement the methodology used within the application, you will decide when, where, and what comments to add, which code format to use, and which module to put what code into. But best practices and guidelines are developed for a reason; they keep code consistent within the application, they allow other developers to pick up what is going on quickly, and enable clean and reliable code. Always apply a good coding style to your application. You will thank yourself in the future. Resources for Article : Further resources on this subject: Animating Properties and Tweening Pages in Android 3-0 [Article] Creating, Compiling, and Deploying Native Projects from the Android NDK [Article] Appcelerator Titanium: Creating Animations, Transformations, and Understanding Drag-and-drop [Article]
Read more
  • 0
  • 0
  • 3396

article-image-accessing-oracle
Packt
15 Mar 2013
6 min read
Save for later

Accessing Oracle

Packt
15 Mar 2013
6 min read
(For more resources related to this topic, see here.) Getting ready Open a PowerShell session for the appropriate processor architecture, x86 or x64 according to your ODAC installation. See the preceding recipe, Setting up your environment (Simple) for more information. Often it is easiest to start with the PowerShell ISE (Integrated Scripting Environment) for a better editing and debugging experience. How to do it... The Oracle Data Provider for .NET (ODP.NET) is included with ODAC in Oracle. DataAccess.dll and is generally the best choice for accessing Oracle. The first step is loading this library into memory: $odpAssemblyName = "Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342" [System.Reflection.Assembly]::Load($odpAssemblyName) GAC Version Location --- ------- -------- True v2.0.50727 C:WindowsassemblyGAC_32Oracle.DataAccess 2.112.3.0__89b483f429c47342Oracle.DataAccess.dll Once the assembly is loaded you can start creating types. If you are not sure what object types are available, use the following code to enumerate public types in the Oracle.DataAccess assembly. $asm = [appdomain]::currentdomain.getassemblies() | where-object {$_.FullName -eq $odpAssemblyName} $asm.GetTypes() | Where-Object {$_.IsPublic} | Sort-Object {$_. FullName } | ft FullName, BaseType | Out-String With the assembly loaded, and the types to create known, you can now start creating objects. A logical place to start is with a connection object: $conn = New-Object Oracle.DataAccess.Client.OracleConnection How it works... First the .NET Framework's Assembly.Load method is called and a fully qualified assembly name is specified. By default PowerShell 2.0 runs against the .NET Framework 2.0 so the 2.x version of Oracle.DataAccess is specified in $odpAssemblyName. The parts of the assembly name can be found by inspecting %WINDIR%assembly in Windows Explorer. Because the output was not explicitly captured or discarded, details of the loaded assembly are shown. Next, the AppDomain.CurrentDomain.GetAssemblies method is invoked and the list is filtered down to the Oracle.DataAccess assembly. This verifies that the assembly loaded and provides a reference to it. Finally it gets the types in that assembly, narrows them down by public types, sorts the data by full name, and formats the resulting table with the full name and base type properties of each Oracle type that is available. There's more... To discard the output of the assembly load, use either [void] or a pipe to Out-Null. [System.Reflection.Assembly]::Load($odpAssemblyName) | Out-Null [void][System.Reflection.Assembly]::Load($odpAssemblyName) Alternatively, capture the output to a variable and format another way: $odpAsm = [System.Reflection.Assembly]::Load($odpAssemblyName) "Loaded Oracle.DataAccess from {0}" -f $odpAsm.Location Here are three other ways of loading ODP.NET: [Reflection.Assembly]::LoadWithPartialName("Oracle.DataAccess") $filename = "C:Oracleproduct11.2.0client_1odp.netbin2.x Oracle.DataAccess.dll" [void][Reflection.Assembly]::LoadFile($filename) [void][Reflection.Assembly]::LoadFrom($filename) LoadWithPartialName is convenient but blindly loads an unknown version of ODP.NET. Both LoadFile and LoadFrom can also lead to issues. See http://msdn.microsoft.com/en-us/library/dd153782.aspx for assembly loading best practices. Using Load with an explicit, full assembly identity is safest, despite more typing. Now, let's find out how to get help with ODP.NET, and some other ways of accessing Oracle. Getting help with ODP.NET Oracle's ODP documentation can be accessed via the Start Menu, with Windows Explorer under ORACLE_BASEORACLE_HOMEODACDocDocumentationLibrary, or online at http://docs.oracle.com. Also, PowerShell's Get-Member (alias gm) is useful for inspecting available members of objects; for example, use $conn | gm to list all the properties and methods available on the OracleConnection that was created. Loading ODP.NET 4.0 The ODAC installation installs two versions of Oracle.DataAccess, one for .NET Framework 2 and another for PowerShell 2.0, which was built before .NET Framework 4.0. As such, you cannot directly load Version 4.0 assemblies by default. Generally the Version 2.0 will suffice. If there are specific 4.0 features you want, you have a few options: Change a global registry setting that forces all .NET 2.0 assemblies to run under .NET 4 (from PowerShell or otherwise); this has a number of serious consequences and should almost always be avoided. Create or update powershell.exe.config and powershell_ise.config in $pshome (that is %WINDIR%SysWOW64WindowsPowerShellv1.0) for x86 and/or x64 to run PowerShell sessions under .NET 4.0; this is better than the first option, but still applies globally. See http://poshcode.org/2045 for details. Use custom script code to selectively run a given script block or file as a .NET 4.0 child process from within PowerShell's .NET 2.0 context. This has the least potential impact but can make running and debugging more difficult. For example:https://gist.github.com/882528. Use PowerShell 3.0, which uses .NET 4.0 by default. This is the best option. If PowerShell 3.0 is available that is the path of least resistance. Otherwise the PowerShell configuration modifications are most likely the next best route, unless you have various other PowerShell scripts or cmdlets (built-in or custom) that may not execute correctly when run under the .NET Framework 4.0 runtime. Once configured, load the assembly as before but specify the 4.X version number. $odpAssemblyName = "Oracle.DataAccess, Version=4.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342" [System.Reflection.Assembly]::Load($odpAssemblyName) To get the assembly name and other details here, you can open %WINDIR%Microsoft. NETassembly in Windows Explorer, navigate to Oracle.DataAccess.dll, and open the DLL in a dissembler such as dotPeek by JetBrains. Using OLE DB One alternative to ODP.NET is using OLE DB (included with ODAC). In this case the assembly is already loaded; just start creating the types. $conn = New-Object System.Data.OleDb.OleDbConnection The only real advantage of OLE DB is your scripts are more portable in that your data access script logic can be reused for databases other than Oracle. This comes at the cost of slow performance with COM interop, the loss of some Oracle optimizations, and less functionality than ODP.NET. Using Microsoft's Data Provider for Oracle Microsoft's .NET Framework Data Provider for Oracle (System.Data.OracleClient) is deprecated and generally should not be used. It does provide a more lightweight footprint than a full ODAC install but has a number of performance and functionality limitations and is not being maintained. [System.Reflection.Assembly]::Load("System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") $conn = New-Object System.Data.OracleClient.OracleConnection Summary: Using an ODBC driver (included with ODAC) is an older technique but could be useful in conjunction with systems that do not support newer drivers. Another option is loading a .NET data access DLL from PowerShell. This could be either a standard .NET class library or one that references System.Management.Automation.dll and exposes cmdlets for friendly PowerShell usage. You can also use Oracle's SQL*Plus client from PowerShell to send commands and receive outputs via pipes. This book will focus primarily on using ODP.NET directly from PowerShell. Despite some heft, ODP.NET provides the best performance and functionality and staying in a PowerShell script context prevents more involved work of developing compiled DLLs. Resources for Article : Further resources on this subject: High Availability: Oracle 11g R1 R2 Real Application Clusters (RAC) [Article] Oracle Tools and Products [Article] Oracle Integration and Consolidation Products [Article]
Read more
  • 0
  • 0
  • 7372
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 €18.99/month. Cancel anytime
article-image-creating-mobile-friendly-themes
Packt
15 Mar 2013
3 min read
Save for later

Creating mobile friendly themes

Packt
15 Mar 2013
3 min read
(For more resources related to this topic, see here.) Getting ready Before we start working on the code, we'll need to copy the basic gallery example code from the previous example and rename the folder and files to be pre fixed with mobile. After this is done, our folder and file structure should look like the following screenshot: How to do it... We'll start off with our galleria.mobile.js theme JavaScript file: (function($) { Galleria.addTheme({ name: 'mobile', author: 'Galleria How-to', css: 'galleria.mobile.css', defaults: { transition: 'fade', swipe: true, responsive: true }, init: function(options) { } }); }(jQuery)); The only difference here from our basic theme example is that we've enabled the swipe parameter for navigating images and the responsive parameter so we can use different styles for different device sizes. Then, we'll provide the additional CSS file using media queries to match only smartphones. Add the following rules in the already present code in the galleria. mobile.css file: /* for smartphones */ @media only screen and (max-width : 480px){ .galleria-stage, .galleria-thumbnails-container, .galleria-thumbnails-container, .galleria-image-nav, .galleria-info { width: 320px; } #galleria{ height: 300px; } .galleria-stage { max-height: 410px; } } Here, we're targeting any device size with a width less than 480 pixels. This should match smartphones in landscape and portrait mode. These styles will override the default styles when the width of the browser is less than 480 pixels. Then, we wire it up just like the previous theme example. Modify the galleria. mobile-example.html file to include the following code snippet for bootstrapping the gallery: <script> $(document).ready(function(){ Galleria.loadTheme('galleria.mobile.js'); Galleria.run('#galleria'); }); </script> We should now have a gallery that scales well for smaller device sizes, as shown in the following screenshot: How to do it... The responsive option tells Galleria to actively detect screen size changes and to redraw the gallery when they are detected. Then, our responsive CSS rules style the gallery differently for different device sizes. You can also provide additional rules so the gallery is styled differently when in portrait versus landscape mode. Galleria will detect when the device screen orientation has changed and apply the new styles accordingly. Media queries A very good list of media queries that can be used to target different devices for responsive web design is available at http://css-tricks.com/snippets/css/media-queriesfor-standard-devices/. Testing for mobile The easiest way to test the mobile theme is to simply resize the browser window to the size of the mobile device. This simulates the mobile device screen size and allows the use of standard web development tools that modern browsers provide. Integrating with existing sites In order for this to work effectively with existing websites, the existing styles will also have to play nicely with mobile devices. This means that an existing site, if trying to integrate a mobile gallery, will also need to have its own styles scale correctly to mobile devices. If this is not the case and the mobile devices switch to zoom-like navigation mode for the site, the mobile gallery styles won't ever kick in. Summary In this article we have seen how to create mobile friendly themes using responsive web design. Resources for Article : Further resources on this subject: jQuery Mobile: Organizing Information with List Views [Article] An Introduction to Rhomobile [Article] Creating and configuring a basic mobile application [Article]
Read more
  • 0
  • 0
  • 6933

article-image-getting-started-using-chef
Packt
14 Mar 2013
6 min read
Save for later

Getting started with using Chef

Packt
14 Mar 2013
6 min read
(For more resources related to this topic, see here.) In order to provide the instructions for this article to work without modification, you will need administrative access to a system running Ubuntu 12.04 LTS with SSH service running and accessible via a network. Additionally, the system will need to be able to access the Chef Server and the public Internet for package updates and gem installation. Bootstrapping servers Bootstrapping is the process of setting up something without external intervention. Chef uses bootstrap scripts that are executed (over SSH) on a remote server to perform any initial configuration that you desire. These scripts are written using ERB (a Ruby template language) and serve as a launching pad to setting up a new server. Typically these scripts would be run on a brand new server, but can be applied to any server that you can SSH into. Additionally, bootstrap files are Linux-distribution and Ruby-distribution dependent because they have commands that are specific to particular distributions. For example, an Ubuntu Linux server with Ruby 1.9 installed from source, or a RedHat Enterprise Linux server with Ruby 1.8.7 installed from EPEL. In addition to any initial configuration, bootstrapping registers the node with the Chef Server so that it becomes a member of the infrastructure and can have configurations and roles applied to it. How the process works The bootstrapping begins with developing a bootstrap script that targets the distribution and version of that distribution that is running on the server you are looking to provision. Once the script is written, the knife tool is used to remotely log into the new system and run the script to perform the initial configuration. Knife does some interpolation locally of the bootstrap script before it is run on the server. This means that you can leverage Chef's data and configuration during the bootstrap process. Common uses here would include setting up initial firewall rules, routes, users, or other mandatory initial provisioning. Chef provides some pre-written bootstrap scripts for the following platforms, making it easy to get started: centos5-gems fedora13-gems ubuntu10.04-gems ubuntu10.04-apt ubuntu12.04-gems Examining the bootstrap script If you are looking for an example of what a bootstrap file contains, you can find the ones provided with chef in lib/chef/knife/bootstrap inside the directory containing your Chef gem (which, if you used the Opscode packages on a Debian system, would reside in /usr/lib/ruby/vendor_ruby/chef). I strongly suggest reading over the bootstrap script you will be using so that you have a good idea of what you're running on your system as root before doing so. Performing the bootstrap Bootstrapping a server is quite simple and involves a single invocation of knife (once your bootstrap script is complete). Knife looks for bootstrap files in a directory called bootstrap in your local Chef directory. Good names for bootstrap files would include the distribution name as well as the version and type of Ruby installation you are performing (that is, centos5-ruby19, ubuntu11.10-rvm-ruby19, and so on). In our case, we will be using the pre-supplied bootstrap script that configures Ubuntu 12.04 with gems to bootstrap our new system. For example: export SERVER_IP="11.22.33.44" export USER="ubuntu_user" knife bootstrap -x $USER --sudo $SERVER_IP -d ubuntu12.04-gems This is where the environment variable, $SERVER_IP, is set to the IP address of your newly setup server and $USER is set to the user you created on your Ubuntu server that can execute sudo. When executed, this command tells knife to execute the bootstrap command, which is responsible for loading the bootstrap script specified by the -d flag (-d is for distribution) over SSH logging into the remote server specified by the environment variable, $SERVER_IP using the remote user specified by the -x flag. In this case, it would run the following steps: SSH as ubuntu_user to 11.22.33.44 Execute the contents of ubuntu12.04-gems.erb on the remote server using sudo Once that is complete, the server will be bootstrapped according to the steps in the bootstrap file, which, if you were to look at the provided bootstrap script, you would see the following: Update the APT repository Install Ruby 1.8 and some development dependencies from APT Install the latest version of RubyGems Update the local Ruby gems Use gem to install ohai, the system-reporting agent Use gem to install Chef Copy the validation certificate file to the server Copy the encrypted data bag secret (if applicable) Generate any ohai hints needed Copy the Chef Client configuration to the server Copy the first-run JSON data to the server Execute the Chef Client in order to: Register the node Run any initially configured run list data Verifying the registration Once this has been completed, we can verify that the node has been registered with the Chef Server in either of two ways: using knife, or using the web console. Using knife To verify the node was registered with the Chef Server, we will be using the client command provided by knife. This can be accomplished with the list subtask like this: user@server:$> knife client list host1 host2 new-host-name Where new-host-name would be the hostname of the node you just bootstrapped (Chef Client will automatically determine the hostname when it registers itself using the bootstrapped machine's FQDN as you set it up). Via the web console To verify that the node was registered using the web console, we must first log into our Chef Server using the administrative credentials that were configured during setup. Once logged in, there will be a set of tabs along the top where you can switch between the different data collections you can manage. The URL of the web console will vary between installations, but if you followed the instructions earlier, it would be accessible at http://chefserver.yourdomain.com:4040. As you can see, there are tabs for managing environments, roles, nodes, cookbooks, data bags, clients, and users. Additionally, there is a tab for performing searches, which is useful for validating search queries to be used in recipes. Once you are on the Nodes tab, you will see a list of nodes that Chef knows about, which will look like the following screenshot: In our case, chef-server is the Chef Server itself that we registered during the installation phase, and monitoring-production is the hostname of the newly registered server. Summary In this Article, we have discussed the process of getting started with Chef. Resources for Article : Further resources on this subject: OpenAM: Backup, Recovery, and Logging [Article] Starting Up Tomcat 6: Part 1 [Article] SQL Server 2008 R2: Multiserver Management Using Utility Explorer [Article]
Read more
  • 0
  • 0
  • 2912

article-image-getting-started-spring-security
Packt
14 Mar 2013
14 min read
Save for later

Getting Started with Spring Security

Packt
14 Mar 2013
14 min read
(For more resources related to this topic, see here.) Hello Spring Security Although Spring Security can be extremely difficult to configure, the creators of the product have been thoughtful and have provided us with a very simple mechanism to enable much of the software's functionality with a strong baseline. From this baseline, additional configuration will allow a fine level of detailed control over the security behavior of our application. We'll start with an unsecured calendar application, and turn it into a site that's secured with rudimentary username and password authentication. This authentication serves merely to illustrate the steps involved in enabling Spring Security for our web application; you'll see that there are some obvious flaws in this approach that will lead us to make further configuration refinements. Updating your dependencies The first step is to update the project's dependencies to include the necessary Spring Security .jar files. Update the Maven pom.xml file from the sample application you imported previously, to include the Spring Security .jar files that we will use in the following few sections. Remember that Maven will download the transitive dependencies for each listed dependency. So, if you are using another mechanism to manage dependencies, ensure that you also include the transitive dependencies. When managing the dependencies manually, it is useful to know that the Spring Security reference includes a list of its transitive dependencies. pom.xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>3.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>3.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>3.1.0.RELEASE</version> </dependency> Downloading the example code You can download the example code files for all Packt books you have purchased from your account at https://www.packtpub.com. If you purchased this book elsewhere, you can visit https://www.packtpub.com/books/content/support and register to have the files e-mailed directly to you. Using Spring 3.1 and Spring Security 3.1 It is important to ensure that all of the Spring dependency versions match and all the Spring Security versions match; this includes transitive versions. Since Spring Security 3.1 builds with Spring 3.0, Maven will attempt to bring in Spring 3.0 dependencies. This means, in order to use Spring 3.1, you must ensure to explicitly list the Spring 3.1 dependencies or use Maven's dependency management features, to ensure that Spring 3.1 is used consistently. Our sample applications provide an example of the former option, which means that no additional work is required by you. In the following code, we present an example fragment of what is added to the Maven pom.xml file to utilize Maven's dependency management feature, to ensure that Spring 3.1 is used throughout the entire application: <project ...> ... <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.1.0.RELEASE</version> </dependency> … list all Spring dependencies (a list can be found in our sample application's pom.xml ... <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.1.0.RELEASE</version> </dependency> </dependencies> </dependencyManagement> </project> If you are using Spring Tool Suite, any time you update the pom.xml file, ensure you right-click on the project and navigate to Maven | Update Project…, and select OK, to update all the dependencies. Implementing a Spring Security XML configuration file The next step in the configuration process is to create an XML configuration file, representing all Spring Security components required to cover standard web requests.Create a new XML file in the src/main/webapp/WEB-INF/spring/ directory with the name security.xml and the following contents. Among other things, the following file demonstrates how to require a user to log in for every page in our application, provide a login page, authenticate the user, and require the logged-in user to be associated to ROLE_USER for every URL:URL element: src/main/webapp/WEB-INF/spring/security.xml <?xml version="1.0" encoding="UTF-8"?> <bean:beans xsi_schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security- 3.1.xsd"> <http auto-config="true"> <intercept-url pattern="/**" access="ROLE_USER"/> </http> <authentication-manager> <authentication-provider> <user-service> <user name="user1@example.com" password="user1" authorities="ROLE_USER"/> </user-service> </authentication-provider> </authentication-manager> </bean:beans> If you are using Spring Tool Suite, you can easily create Spring configuration files by using File | New Spring Bean Configuration File. This wizard allows you to select the XML namespaces you wish to use, making configuration easier by not requiring the developer to remember the namespace locations and helping prevent typographical errors. You will need to manually change the schema definitions as illustrated in the preceding code. This is the only Spring Security configuration required to get our web application secured with a minimal standard configuration. This style of configuration, using a Spring Security-specific XML dialect, is known as the security namespace style, named after the XML namespace (http://www.springframework.org/schema/security) associated with the XML configuration elements. Let's take a minute to break this configuration apart, so we can get a high-level idea of what is happening. The <http> element creates a servlet filter, which ensures that the currently logged-in user is associated to the appropriate role. In this instance, the filter will ensure that the user is associated with ROLE_USER. It is important to understand that the name of the role is arbitrary. Later, we will create a user with ROLE_ADMIN and will allow this user to have access to additional URLs that our current user does not have access to. The <authentication-manager> element is how Spring Security authenticates the user. In this instance, we utilize an in-memory data store to compare a username and password. Our example and explanation of what is happening are a bit contrived. An inmemory authentication store would not work for a production environment. However, it allows us to get up and running quickly. We will incrementally improve our understanding of Spring Security as we update our application to use production quality security . Users who dislike Spring's XML configuration will be disappointed to learn that there isn't an alternative annotation-based or Java-based configuration mechanism for Spring Security, as there is with Spring Framework. There is an experimental approach that uses Scala to configure Spring Security, but at the time of this writing, there are no known plans to release it. If you like, you can learn more about it at https://github.com/tekul/scalasec/. Still, perhaps in the future, we'll see the ability to easily configure Spring Security in other ways. Although annotations are not prevalent in Spring Security, certain aspects of Spring Security that apply security elements to classes or methods are, as you'd expect, available via annotations. Updating your web.xml file The next steps involve a series of updates to the web.xml file. Some of the steps have already been performed because the application was already using Spring MVC. However, we will go over these requirements to ensure that these more fundamental Spring requirements are understood, in the event that you are using Spring Security in an application that is not Spring-enabled. ContextLoaderListener The first step of updating the web.xml file is to ensure that it contains the o.s.w.context.ContextLoaderListener listener, which is in charge of starting and stopping the Spring root ApplicationContext interface. ContextLoaderListener determines which configurations are to be used, by looking at the <context-param> tag for contextConfigLocation. It is also important to specify where to read the Spring configurations from. Our application already has ContextLoaderListener added, so we only need to add the newly created security.xml configuration file, as shown in the following code snippet: src/main/webapp/WEB-INF/web.xml <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/services.xml /WEB-INF/spring/i18n.xml /WEB-INF/spring/security.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> The updated configuration will now load the security.xml file from the /WEB-INF/spring/ directory of the WAR. As an alternative, we could have used /WEB-INF/spring/*.xml to load all the XML files found in /WEB-INF/spring/. We choose not to use the *.xml notation to have more control over which files are loaded. ContextLoaderListener versus DispatcherServlet You may have noticed that o.s.web.servlet.DispatcherServlet specifies a contextConfigLocation component of its own. src/main/webapp/WEB-INF/web.xml <servlet> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/mvc-config.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> DispatcherServlet creates o.s.context.ApplicationContext, which is a child of the root ApplicationContext interface. Typically, Spring MVC-specific components are initialized in the ApplicationContext interface of DispatcherServlet, while the rest are loaded by ContextLoaderListener. It is important to know that beans in a child ApplicationContext (such as those created by DispatcherServlet) can reference beans of its parent ApplicationContext (such as those created by ContextLoaderListener). However, the parent ApplicationContext cannot refer to beans of the child ApplicationContext. This is illustrated in the following diagram where childBean can refer to rootBean, but rootBean cannot refer to childBean. As with most usage of Spring Security, we do not need Spring Security to refer to any of the MVC-declared beans. Therefore, we have decided to have ContextLoaderListener initialize all of Spring Security's configuration. springSecurityFilterChain The next step is to configure springSecurityFilterChain to intercept all requests by updating web.xml. Servlet <filter-mapping> elements are considered in the order that they are declared. Therefore, it is critical for springSecurityFilterChain to be declared first, to ensure the request is secured prior to any other logic being invoked. Update your web.xml file with the following configuration: src/main/webapp/WEB-INF/web.xml </listener> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> Not only is it important for Spring Security to be declared as the first <filter-mapping> element, but we should also be aware that, with the example configuration, Spring Security will not intercept forwards, includes, or errors. Often, it is not necessary to intercept other types of requests, but if you need to do this, the dispatcher element for each type of request should be included in <filter-mapping>. We will not perform these steps for our application, but you can see an example, as shown in the following code snippet: src/main/webapp/WEB-INF/web.xml <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>ERROR</dispatcher> ... </filter-mapping> DelegatingFilterProxy The o.s.web.filter.DelegatingFilterProxy class is a servlet filter provided by Spring Web that will delegate all work to a Spring bean from the root ApplicationContext that must implement javax.servlet.Filter. Since, by default, the bean is looked up by name, using the value of <filter-name>, we must ensure we use springSecurityFilterChain as the value of <filter-name>. Pseudo-code for how o.s.web.filter.DelegatingFilterProxy works for our web.xml file can be found in the following code snippet: public class DelegatingFilterProxy implements Filter { void doFilter(request, response, filterChain) { Filter delegate = applicationContet.getBean("springSecurityFilterChain") delegate.doFilter(request,response,filterChain); } } FilterChainProxy When working in conjunction with Spring Security, o.s.web.filter. DelegatingFilterProxy will delegate to Spring Security's o.s.s.web. FilterChainProxy, which was created in our minimal security.xml file. FilterChainProxy allows Spring Security to conditionally apply any number of servlet filters to the servlet request. We will learn more about each of the Spring Security filters and their role in ensuring that our application is properly secured, throughout the rest of the book. The pseudo-code for how FilterChainProxy works is as follows: public class FilterChainProxy implements Filter { void doFilter(request, response, filterChain) { // lookup all the Filters for this request List<Filter> delegates = lookupDelegates(request,response) // invoke each filter unless the delegate decided to stop for delegate in delegates { if continue processing delegate.doFilter(request,response,filterChain) } // if all the filters decide it is ok allow the // rest of the application to run if continue processing filterChain.doFilter(request,response) } } Due to the fact that both DelegatingFilterProxy and FilterChainProxy are the front door to Spring Security, when used in a web application, it is here that you would add a debug point when trying to figure out what is happening. Running a secured application If you have not already done so, restart the application and visit http://localhost:8080/calendar/, and you will be presented with the following screen: Great job! We've implemented a basic layer of security in our application, using Spring Security. At this point, you should be able to log in using user1@example.com as the User and user1 as the Password (user1@example.com/user1). You'll see the calendar welcome page, which describes at a high level what to expect from the application in terms of security. Common problems Many users have trouble with the initial implementation of Spring Security in their application. A few common issues and suggestions are listed next. We want to ensure that you can run the example application and follow along! Make sure you can build and deploy the application before putting Spring Security in place. Review some introductory samples and documentation on your servlet container if needed. It's usually easiest to use an IDE, such as Eclipse, to run your servlet container. Not only is deployment typically seamless, but the console log is also readily available to review for errors. You can also set breakpoints at strategic locations, to be triggered on exceptions to better diagnose errors. If your XML configuration file is incorrect, you will get this (or something similar to this): org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'. It's quite common for users to get confused with the various XML namespace references required to properly configure Spring Security. Review the samples again, paying attention to avoid line wrapping in the schema declarations, and use an XML validator to verify that you don't have any malformed XML. If you get an error stating "BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/ schema/security] ...", ensure that the spring-security-config- 3.1.0.RELEASE.jar file is on your classpath. Also ensure the version matches the other Spring Security JARs and the XML declaration in your Spring configuration file. Make sure the versions of Spring and Spring Security that you're using match and that there aren't any unexpected Spring JARs remaining as part of your application. As previously mentioned, when using Maven, it can be a good idea to declare the Spring dependencies in the dependency management section.
Read more
  • 0
  • 0
  • 29606

article-image-life-cycle-management
Packt
13 Mar 2013
16 min read
Save for later

Life Cycle Management

Packt
13 Mar 2013
16 min read
(For more resources related to this topic, see here.) Service stages A service goes through several stages; it has a life cycle. The following figure shows the various stages of this life cycle: Apart from identifying, designing, and implementing a service, you also need to take into account the possibility of cleaning up services. Services can become obsolete, because they don't conform to the requirements anymore, because there are better alternatives or because nobody is using them anymore. The stages deprecated and retired are used for this. The following table explains the different life cycle stages of a service and who is involved in reaching that stage. Stage Description Role Identified The service is identified; the organization is aware that it is needed. The approach to identification can be either top-down, bottom-up, or meet in the middle. Architect: Top-down (and meeting the middle) identification of service is based on the process or user interface requirements. Developer: Bottom-up identification is based on the existing capabilities. Designed The service interface (operations) and contract are known and documented. A developer can create a mockup of the service based on the design by tooling, and clients can be built based on the design. Architect: Top-down design of services based on the process or user interface requirements. Developer: Bottom-up (and meet in the middle) design based on existing capabilities. Implemented The service is available for consumers to use in production systems. Project, or the service is bought from a supplier. Administrator: Deploy the service and makes it available. Deprecated The service is a candidate for replacement or is obsolete. Current consumers can keep using the service for now; new consumers should use a replacement or find other alternatives. Service provider: Decides to move to this state. Retired The service is no longer available for consumers. Service provider decides and the administrator undeploys the service. There are no approval states in this life cycle. Within your organization you need to decide who is responsible for what type of actions and who needs to approve those. For example, you could decide that since you have already created a business case for the realization of the SOA, you don't need to approve identified services explicitly. If something is identified and later you decide you don't need it after all, you can either delete it, or retire it straight away. Another approach is to approve the services in the step define the solution in detail, as part of the approval of the project architecture. Keep details out of the life cycle Beware of adding too many details of the software development and release management in the life cycle of the services. It becomes tedious and outdated very quickly. The only message it needs to convey to the service consumers is, can these services still be used? Versioning of services During the life cycle of a service, the service changes because consumers have change requests, laws and regulations change, and errors need to be fixed. First, you learn about versioning of services, and then the relationship with the different stages of a service is investigated. A common way of keeping track of these changes is using version control. Version control is the management of changes to documents, software, and artifacts. Changes are identified by a number or letter code; a version or revision number. Now when do you give your document, data model, or service a new version number? And what type of versioning scheme are you going to apply? Usually, you make a distinction between minor and major versions of a change. A service consists of an interface, a contract, and an implementation. All these aspects of a service can change. Let's look into the different types of change and how this affects the version of your services. Type of change – contract, interface, and implementation Let's take the example of a diner that offers breakfast. The menu lists all their services. The contract of the service states the quality, price, availability, order time, and so on. The interface is the way we interact with a service. When ordering breakfast we interact with Jane, our waitress, and the menu that is in English and Spanish. The implementation of the service is the cooking of the service, and the serving and eating of it. Changing the contract The contract of the service states: Ingredients are all local and natural Breakfast might contain gluten Breakfast can be ordered from 7 a.m. to 1 p.m. Breakfast costs $9.95 Payment by credit card or cash is accepted Currency that is accepted is in dollars Time between ordering breakfast and the delivery time to the table is 5 minutes to 10 minutes Complaints should be delivered to the manager by telephone Prices of the ingredients increase every year, so after the first year the breakfast place is in business, the cost of the breakfast is increased. This is a major change in the contract, so the owner creates a new menu with the new prices, effectively creating a new version of the service. The waitress informs the regulars (customers that visit the diner every week) about the increase in advance. Other customers find out when they visit the breakfast place. After having been in business for a couple of years, the owner of the breakfast place notices that a lot of tourists from Europe and Asia visit his breakfast place. They are suffering from jet lag and have different breakfast requirements. They would rather have something light and pay less for the breakfast. The manager decides to change something in the contract: not all breakfasts cost the same anymore; it depends on what you order. Now this is good news for customers who want to eat less: they don't have to pay for something they did not order. However, existing customers who were used to the "all inclusive" breakfast concept and eat more won't appreciate the change. Obviously, the owner also has other options, not just changing the service for everyone at once: Change the contract for everyone, everybody pays a la carte Add the "light" breakfast option to the menu as an additional menu for a fixed lower price of $4.95 Offer an a la carte option next to the all-inclusive breakfast After some research, he decides to use the last option, in effect leaving the old contract intact by adding an a la carte option to it. Note that in both examples nothing has changed about the interface, you still order what you want to eat for breakfast, and the implementation has not changed either. The same cook is preparing the breakfast, the same ingredients and kitchen utensils are used, the same cooking method is applied, and so on. The change was in the contract of the service. The first change (increase in price) affected all the customers in the same way. The second change was more complicated, it was an improvement for some customers but the owner did not want to scare away the other group. Obviously, the owner does not use version numbers in his menu, but he did create a new version of the menu. The way this was communicated was not with a version number but with an effective date and an announcement to the customers. Changing the interface Apart from the contract, the interface can also change. As you have read before, a lot of customers are from Europe and Asia. For these people, it is sometimes hard to speak English. So the owner of the diner decides to print the menu in multiple languages: Spanish, French, Japanese, and Chinese. He also hires some waitresses and waiters that speak multiple languages. This change has no impact on the current customers; English is still supported as a language to order the breakfast in. After a while, the waitress who speaks French quits her job and the owner decides not to replace her, because only a small number of customers speak French. This change has an impact on the current customers who speak French; they will have to switch to another language that still is supported. Changing the implementation After a couple of years, the owner of the diner decides to hire some new kitchen staff and replace some of the kitchen tools. The new people improve some of the processes in the kitchen, thus creating a more efficient operation. The customers notice that a dish is served a little faster than in the past and that fewer meals arrive cold or over-cooked as a result of the improved operation. Versioning schemes You want to keep track of changes to a service, using version control. You don't want service consumers to accidently use the wrong version. This can cost money or cause errors to occur. In the case of an IT service, you don't want to break the code of the service consumers. The types of change that can occur in the BreakfastService also apply to IT services; you can change the interface, the implementation, or the contract. The service as a whole is the unit of interest for the service consumer; therefore you need to version the service as a whole. This means that you change the version of the service if any of the parts of a service change, whether this is the implementation, the interface, and/or the contract. As a consequence, there is no need to version the contract, interface or implementation separately. Version the service as a whole Version the service as a whole and you need to version the underlying files. There is no need to version the contract, interface and implementation separately. The following diagram illustrates this for OrderService. Every time a change is made to a file, this is recorded in the version control system. This has no impact on the version of the service. Once you decide to release the change into production, you determine the new version of the service as a whole. The diagram shows OrderService with a version 1.0.1. It consists of an implementation, contract, and an interface. These are not versioned separately, because this is of no interest to the consumer. Three Java files make up the implementation. These are versioned in the version control system, because the service provider needs to keep track of the changes they make. The contract consists of two policy files: a security policy and an availability policy. These are versioned in the version control system as well. The interface consists of an XSD and a WSDL. These are versioned in the version control system. Versioning and life cycle stages There are several things you can do when the version of a service changes, as you learned with the change of contract of BreakfastService: You can replace the current version with the new version Let the new and current (or old) version co-exist (for a limited time period) Apart from deciding what to do with the old version, you also have to decide what to do with the version number. This depends on the impact of the change; to determine whether a change is minor or major, you have to look at the impact the change has on its current consumers. For example, adding an operation or a field has little impact on current consumers. If you want to make a major change, it is good practice to create a new major version of the service, and to support consumers who want to keep using the previous (deprecated) service for a certain time period. The following table shows a common versioning scheme that works well for both consumers and providers: Change type Minor version Major version Previous version Major change To 0 Increase by 1 Keep it (stage is deprecated) Minor change Increase by 1 Stays the same Replace it (stage stays implemented) Let's look at an example; suppose your organization offers OrderService and uses the convention [major version].[major version].[minor version]. The current version is 1.0.0. This means the major version is 1.0 and the minor version is .0. Now if you make a major change, you increase the major version and keep the previous version available to consumers for a little while. This results in two services: OrderService 1.0.0 (stage deprecated with a planned end date) OrderService 1.1.0 (stage implemented) If the change is minor, you increase the minor version and discard the previous version. This results in one service: OrderService 1.0.1 (stage implemented) Supporting two versions has advantages for both the consumers and for the providers. Consumers can plan the migration to the new version, and planning the upgrade for the provider is also a little easier because not everybody needs to test the new service at the same time. Note that you will keep track of all the files that you use during development in your version control system. The version number that is of interest here is the version number that you communicate as a whole to the service consumers when the (new version of the) service is released. Making the version explicit for service consumers When you are using a WSDL to describe your interface to your consumers, you can make the version of the service explicit by putting the (major) version number in the namespace and in its endpoint. A namespace in a WSDL or XSD is used to differentiate between elements, and it enables the document to reference multiple external specifications, including the WSDL specification, the SOAP specification, and the XML Schema specification. By using the version in the endpoint, it is also easier to support two versions of the same service on your server. Let's see how this works with a WSDL for OrderService: <wsdl:definitions name="OrderService-1.0" targetNamespace="http://vennster.nl/CRM/OrderService-1.0" <wsdl:documentation> The Order will create an order for multiple orders Version history V1.0.0 Initial service description </wsdl:documentation> <wsdl:types> </wsdl:types> <wsdl:message> … </wsdl:message> <wsdl:portType> .. </wsdl:portType> <wsdl:binding> … </wsdl:binding> <wsld:service name=OrderService-1.0 <wsdl:port name="OrderServicePort" binding="tns:OrderServiceSoapHttpBinding"> <soap:address location="http://vennster.nl/CRM/OrderService-1.0"/> </wsdl:port> </wsdl:service> </wsdl:definitions> The highlighted parts show the version in the namespace and in the endpoint (soap:address). In this case, the major version is in the namespace (1.0 and the endpoint); the minor version is in the documentation (1.0.0). With REST services you can make a distinction between versions in a similar way. Basically you have two options: Put the version in the URI of the service, for example http://vennster.nl/crm/api/v1/orderscrm/api/v1/orders Put the version in the vendor MIME media type, for example application/ vnd.vennster.crm.orders-v1+xml Multipurpose Internet Mail Extensions (MIME) are used to identify the type of representation that is in the body of an HTTP request or HTTP response. MIME types are sometimes referred to as CONTENT-TYPES. The MIME type has a major type and a subtype, separated by a slash. The major MIME types are text, video, image, audio, and application. Application can refer to a number of formats: application/xml, application/pdf, application/octet-stream, and so on. For vendor specific commercial use, vnd is used as a prefix, followed by the name of the company and the domain for example, application/vnd.vennster.crm. For personal non-commercial use, prs is often used. For experimental or non-standard types you can use x. Putting the version in the vendor MIME media type, has the disadvantage that user agents such as browsers, wget, and so on don't understand the MIME type. So you might not be able to display the resource correctly. The advantage of putting the version in the MIME type is that it has less impact on the client code. To make the version explicit in a service, you can implement an operation getVersion that returns the version of the service (both the major and the minor version). This operation can also be used as a heartbeat operation by monitoring tools. Versioning tips Support the current version and the previous version in case of a major change. Use major and minor versions. Minor versions can be put in the documentation. Major versions can be expressed in the namespace and endpoint in case of WSDL or in URI, or MIME type in case of REST. Implement a getVersion method in your service. Communicating change In the previous paragraph, you learned what type of change could occur in a service and what versioning schemes you can apply. These changes have some impact on the customers or service consumers. To make sure that service consumers can adjust to the new version of the service, you have to take the following steps: Determine if the change is major or minor If the change is major: Change the state of the service to deprecated and determine the "end of life" date; Create a new version of the service with the state identified Announce the change to all current clients Design the new version of the service and change the state of the new service to designed Communicate the new design to clients who want to migrate Realize the new version of the service and change the state to implemented When the "end of life" date is reached, remove the old version If the change is minor: Design the new minor version of the service Announce the change to all current clients Realize the new version of the service Communicate the situation to all current clients and prospects that have indicated interest in the service There are different ways of communicating these changes to your clients: you can announce it in a meeting, you can send emails, or you can update a central registry that describes all the available services. Changing the namespace and endpoint of the service is a good way of communicating the change at runtime. The client calls a service using the namespace in its code, as you can see in the Java example given as follows: public class OrderServiceClient{ public static void main(String[] args) throws Exception { URL url = new URL("http://vennster.nl/CRM/OrderService-1.0?wsdl"); QName qname = new QName("http://vennster.nl/CRM/OrderService-1.0/", "OrderService-1.0"); Service service = Service.create(url, qname); OrderService orderService = service.getPort(OrderService.class); System.out.println(orderService.orderProduct("ipod")); } } Now let's look at tooling support for versioning and life cycle management.
Read more
  • 0
  • 0
  • 1392
article-image-magento-payment-and-shipping-method
Packt
13 Mar 2013
4 min read
Save for later

Magento : Payment and shipping method

Packt
13 Mar 2013
4 min read
(For more resources related to this topic, see here.) Payment and shipping method Magento CE comes with several Payment and Shipping methods out of the box. Since total payment is calculated based on the order and shipping cost, it makes sense to first define our shipping method. The available shipping methods can be found in Magento Admin Panel under the Shipping Methods section in System | Configuration | Sales. Flat Rate, Table Rates, and Free Shipping methods fall under the category of static methods while others are dynamic. Dynamic means retrieval of rates from various shipping providers. Static means that shipping rates are based on a predefined set of rules. For the live production store you might be interested in obtaining the merchant account for one of the dynamic methods because they enable potentially more precise shipping cost calculation in regards to product weight. Clean installation of Magento CE comes with the Flat Rate shipping method turned on, so be sure to turn it off in production if not required by setting the Enabled option in System | Configuration | Sales | Shipping Methods | Flat Rate to No. Setting up the dynamic methods is pretty easy; all you need to do is to obtain the access data from the shipping provider such as FedEx then configure that access data under the proper shipping method configuration area, for example, System | Configuration | Sales | Shipping Methods | FedEx. Payment method configuration is available under System | Configuration | Sales | Payment Methods. Similar to shipping methods, these are defined into two main groups, static and dynamic. Dynamic in this case means that an external payment gateway provider such as PayPal will actually charge the customer's credit card upon successful checkout. Static simply means that checkout will be completed but you as a merchant will have to make sure that the customer actually paid the order prior to shipping the products to him. Clean installation of Magento CE comes with Saved CC, Check / Money order, and Zero Subtotal Checkout turned on, so be sure to turn these off in production if they are not required. How to do it... To configure the shipping method: Log in to the Magento Admin Panel and go to System | Configuration | Sales | Shipping Methods. Select an appropriate payment method, configure its options, and click on the Save Config button. To configure payment method: Log in to the Magento Admin Panel and go to System | Configuration | Sales | Payment Methods. Select an appropriate payment method, configure its options, and click on the Save Config button. How it works... Once a certain shipping method is turned on, it will be visible on the frontend to the customer during the checkout's so-called Shipping Method step, as shown in the screenshot that follows. The shipping method's price is based on the customer's shipping address, products in cart, applied promo rules, and possibly other parameters. Numerous other shipping modules are provided at Magento Connect on the site http://www.magentocommerce.com/magento-connect/integrations/shippingfulfillment.html and new ones are uploaded often so this is by no means a final list of shipping methods. Once a certain payment method is turned on, it will be visible on the frontend to the customer during the checkout's so-called Payment Information step, as shown in the following screenshot: Additionally, there are numerous other payment modules provided at Magento Connect on the site at http://www.magentocommerce.com/magento-connect/integrations/payment-gateways.html. Summary In this article, we have explained the payment and shipping method you may require when you build your own shop using Magneto. Resources for Article : Further resources on this subject: Creating and configuring a basic mobile application [Article] Installing WordPress e-Commerce Plugin and Activating Third-party Themes [Article] Magento: Exploring Themes [Article]
Read more
  • 0
  • 0
  • 2407

article-image-planning-successful-integration
Packt
12 Mar 2013
6 min read
Save for later

Planning for a successful integration

Packt
12 Mar 2013
6 min read
(For more resources related to this topic, see here.) Getting ready Using Team Foundation Server Extensions for the Project Server, project managers can make the Project Server access real-time project status and resource availability of teams who work in Team Foundation Server. Following the successful configuration of the two server products, the synchronization engine maintains the scheduling of data and resource usage in the mapped Project Server enterprise project plan and Team Foundation Server team project. How to do it... There are a few pieces of information we need to collect and a few configuration tasks that we need to make sure have been completed properly. Here is an installation and configuration requirement checklist to make sure that we are ready to begin: Installation and configuration requirement checklist     Sever names for each server involved: Project Server 2010 and Team Foundation Server 2012.   Service account names and login information: You'll want this information to be handy throughout the tasks in this book. See the Active Directory - Highly recommended for production installations section at the end of this article.   Visual Studio 2012 must be installed on the same machine that will be used to configure the integration of the two server products, and on any machine you will use to configure the integration. This does not need to be on one of the server machines.   Project Server 2010 must be updated to SP1. This product's installation and initial configuration will need to be verified operationally.   Project Professional 2010, or Project Professional 2007 SP2 with the KB980209 hotfix (http://support.microsoft.com/kb/980209), or Project Professional 2007 with SP3 must be installed on your administration machine.   The SharePoint web application for the instance of Project Web Access or PWA (Project Web App) must be set to Classic Mode Authentication. You will not be able to register it if the authentication is set to Claims Based Authentication.   Visual Studio Team Foundation Server 2012 will need to be installed on each application-tier server that hosts Team Foundation Server and that will participate in synchronizing data with Project Server. This product's installation and initial configuration will need to be verified operationally.   Team Foundation Server Extensions for Project Server will be needed later on during the installation. For now, just locate the Team Foundation Server 2012 DVD.   Now that the common pre-configuration items are out of the way, we can move on with the planning. How it works... At the core of this integration are the work items in Team Foundation Server, which synchronize with the Tasks in Microsoft Project plans in Project Server. Using this integration, project managers and software development teams can use whichever tools work best for them, and share information transparently. The integration and all products involved in it are scalable from installations of a few users to several thousands. You can easily scale this integration out by using multiple Project Web Access servers mapped to a multi-server, that is, TFS deployment. This is a good spot for an overview diagram. There's more... We have a few final points to keep in mind, and some valuable tips to make your installations go smoothly. This will not be a complicated integration if we follow the given advice. A time saver for your test installations We all know it can take a serious amount of time to build your own testing and demonstration virtual machines. This is especially tough when you are just going to use it for a test installation or a pitch to technical management. Although the following VM link provided by Microsoft is one revision older than the one discussed here, it is much quicker to upgrade this one than to do a fresh installation. For more information, see the following page on the Microsoft website: http://go.microsoft.com/fwlink/?LinkID=196413 You weren't planning a test environment? Now would also be a good time to plan a test system in your deployment schedule. It will not only help you to have an environment to test out configuration changes but will also be a good safety measure to ensure all your mapping is correct before you deploy to a production environment. Active Directory — Highly recommended for production installations Active Directory is technically not required; however, it is highly recommended that you deploy Active Directory in your network. It will help with synchronization of the user accounts, groups, and services within Team Foundation Server and Project Server. Otherwise you'll be doing this manually between the two environments. If you haven't deployed Active Directory yet, but are planning to deploy it, now would be a good time to begin that. SharePoint Authentication mode We mentioned this in the previous checklist, but it bears repeating here. The authentication that is assigned to the SharePoint web application for the instance of PWA must be set to Classic Mode Authentication. You will not be able to register the instance of PWA if the authentication is set to Claims Based Authentication. Backup A server-based product cannot be mentioned completely without a discussion of backup. Do not begin any production installation or upgrade of any product mentioned here without involving a prior backup of all systems. Special attention should be paid to the backup of the Team Foundation Server system. If done improperly, the backup will put your TFS installation into an unusable state after a restore operation, and the worst part will be you won't know this until you start using it again. Please review Microsoft's current recommendation about using marked transactions in your backup strategy with the help of the Understanding Backing Up Team Foundation Server document, which is is available at:http://msdn.microsoft.com/en-us/library/ms253151.aspx Summary In this article we started off with the requirements for a successful implementation, a short overview of integration, and some valuable tips to make your installations go smoothly. This is a very systematic and non-complicated planning of integration of Instant Team Foundation Server 2012 and Project Sever 2010. Resources for Article : Further resources on this subject: Getting Started with TeamCity [Article] How to Focus on Business Results [Article] Visual Studio 2010 Test Types [Article]
Read more
  • 0
  • 0
  • 1458

article-image-article-inter-process-communication
Packt
12 Mar 2013
6 min read
Save for later

Inter-process Communication

Packt
12 Mar 2013
6 min read
(For more resources related to this topic, see here.) Inter-process Communication Inter-process communication refers to the ability for instances of processes to communicate—with other instances of the same process, with instances of other processes, and with services. Such communication is usually implemented so that process instances can work collaboratively to achieve a given goal. Common scenarios when this may occur include: When common logic is extracted from a number of processes into a reusable "utility" process When the occurrence of an event in one process means that another, perhaps separate, process needs to be started—this is often seen where the second process is an audit or investigation process Where a process has a set of data, needs to run a common set of logic over each item in that data set, and then consolidate the results Through normal decomposition of a business process into various levels of granularity, resulting in the need for the process to invoke one or more sub-processes to accomplish its work There are different mechanisms available for processes to communicate with each other. In this chapter, we will explore the options and when we should employ each. Conversations A conversation is a set of message exchanges. The message exchanges can be synchronous or asynchronous, but they should all be about the same subject matter, for example, a particular order, customer, case, and so on. The set of messages that forms the conversation is typically a request and a response, or a request and several (possible) responses. A single process instance can participate in more than one conversation simultaneously. The collaboration diagram allows you to visualize the process in the context of its conversations. You can access the collaboration diagram using the Collaboration Diagram tab at the bottom of the process editor in JDeveloper. An example of a collaboration diagram is shown in the following diagram: This example includes a number of features that will be discussed in this book. The small, disconnected process that begins with Order Over Limit is an event sub-process. Briefly, they are invoked if a particular event (set of circumstances) occurs at any time during the execution of the process they belong to, the ProcessOrder process in this example. If at any time it is determined that the order is over some predefined limit, then an audit is required. The event sub-process sends a message to start the Audit process using a throw message event. The collaboration diagram allows us to see both of the processes that are involved in this collaboration and shows us visually where the interaction between them occurs (with the dotted arrow from the throw message event to the start of the Audit process). Conversations may also be scoped; this means that they may be defined in a smaller scope than the process as a whole. For example, you can define a conversation inside an embedded sub-process. To define a scoped conversation, you must do so in the Structure pane so that the conversation is placed in the correct scope. If you do not define the conversation in the Structure pane, it will inherit the process scope. The following image shows a process with two conversations defined: myconv1 at the process (global) scope, and the scoped conversation scopeConv, which is inside an embedded sub-process: In addition to defining conversations for communication with other processes, each service that you want to interact with will also require a conversation. When implementing your process, you need to create a conversation for each service, choose Service Call as the type, and then select the service you wish to interact with. The default conversation Each process has a default conversation. The default conversation is used to expose services provided by the process, and it therefore controls the interface for invocation of the process. This interface manifests itself as the WSDL port type. The default conversation can be defined "top down" by starting with WSDL (service contract) for the process and creating the conversation from that, or "bottom up" by defining the arguments for the process and having the service interface (WSDL) generated from the process. If we are using the bottom-up approach, the interface is defined by adding arguments to the start node, as shown in the following screenshot. You need to select Define Interface as the message exchange type to use the bottom-up approach. The arguments can have simple types (String, Date, Integer, and so on) or complex types, that is, they can be based on the business object (which in turn can be based on an element or type definition in an XSD). Correlation Correlation is the mechanism that is used to associate a message with the conversation that it belongs to. There are two main classes of correlation: Automatic correlation refers to mechanisms where the correlation is handled automatically. BPM uses mechanisms like WS-Addressing and JMS Message IDs to achieve automatic correlation. Message-based correlation refers to the mechanism the process developer needs to define some keys, which can be extracted from the message in order to determine which conversation a message belongs to. Examples are given in the next section. There are some occasions when message-based correlation is necessary because automatic correlation is not available, for example: When the other participant does not support WS-addressing, or When a participant joins the conversation part way through but has only the data values, but no other information about the conversation If you do not specify any settings for message-based correlation, the runtime engine will attempt to use automatic correlation. If it is not possible to do so, then you will get a correlation fault. The engine checks to see if the called process or service supports WS-addressing, in which case it will insert a WS-addressing header into the call. It will then wait for a matching reply. Similarly, if JMS is being used to transport the message, it will look for a reply message with the JMS correlation ID that matches the JMS message ID of the message it sent. Correlation is especially important inside a loop construct, as there may be multiple threads/receives waiting at once, and the engine needs a way to know which reply belongs with which receive. Summary In this article, we have explored the inter-process communication and the default conversation. This article has introduced us to the theory of how processes can communicate with each other and with other components. A number of topics are covered such as: conversations—what they are, and the default conversation. Resources for Article : Further resources on this subject: Author Podcast - Ronald Rood discusses the birth of Oracle Scheduler [Article] Oracle Integration and Consolidation Products [Article] Author Podcast - Aleksander Seovic Talks About Oracle Coherence 3.5 [Article]
Read more
  • 0
  • 0
  • 1187
Packt
12 Mar 2013
12 min read
Save for later

Parallel Dimensions – Branching with Git

Packt
12 Mar 2013
12 min read
(For more resources related to this topic, see here.) What is branching Branching in Git is a function that is used to launch a separate, similar copy of the present workspace for different usage requirements. In other words branching means diverging from whatever you have been doing to a new lane where you can continue working on something else without disturbing your main line of work. Let's understand it better with the help of the following example Suppose you are maintaining a checklist of some process for a department in your company, and having been impressed with how well it's structured, your superior requests you to share the checklist with another department after making some small changes specific to the department. How will you handle this situation? An obvious way without a version control system is to save another copy of your file and make changes to the new one to fit the other department's needs. With a version control system and your current level of knowledge, perhaps you'd clone the repository and make changes to the cloned one, right? Looking forward, there might be requirements/situations where you want to incorporate the changes that you have made to one of the copies with another one. For example, if you have discovered a typo in one copy, it's likely to be there in the other copy because both share the same source. Another thought – as your department evolves, you might realize that the customized version of the checklist that you created for the other department fits your department better than what you used to have earlier, so you want to integrate all changes made for the other department into your checklist and have a unified one. This is the basic concept of a branch – a line of development which exists independent of another line both sharing a common history/source, which when needed can be integrated. Yes, a branch always begins life as a copy of something and from there begins a life of its own. Almost all VCS have some form of support for such diverged workflows. But it's Git's speed and ease of execution that beats them all. This is the main reason why people refer to branching in Git as its killer feature. Why do you need a branch To understand the why part, let's think about another situation where you are working in a team where different people contribute to different pieces existing in your project. Your entire team recently launched phase one of your project and is working towards phase two. Unfortunately, a bug that was not identified by the quality control department in the earlier phases of testing the product pops up after the release of phase one (yeah, been there, faced that!). All of a sudden your priority shifts to fixing the bug first, thereby dropping whatever you've been doing for phase two and quickly doing a hot fix for the identified bug in phase one. But switching context derails your line of work; a thought like that might prove very costly sometimes. To handle these kind of situations you have the branching concept (refer to the next section for visuals), which allows you to work on multiple things without stepping on each other's toes. There might be multiple branches inside a repository but there's only one active branch, which is also called current branch. By default, since the inception of the repository, the branch named master is the active one and is the only branch unless and until changed explicitly. Naming conventions There are a bunch of naming conventions that Git enforces on its branch names; here's a list of frequently made mistakes: A branch name cannot contain the following: A space or a white space character Special characters such as colon (:), question mark (?), tilde (~), caret (^), asterisk (*), and open bracket ([) Forward slash (/) can be used to denote a hierarchical name, but the branch name cannot end with a slash For example, my/name is allowed but myname/ is not allowed, and myname\ will wait for inputs to be concatenated Strings followed by a forward slash cannot begin with a dot (.) For example, my/.name is not valid Names cannot contain two continuous dots (..) anywhere When do you need a branch With Git, There are no hard and fast rules on when you can/need to create a branch. You can have your own technical, managerial, or even organizational reasons to do so. Following are a few to give you an idea: A branch in development of software applications is often used for self learning/ experimental purposes where the developer needs to try a piece of logic on the code without disturbing the actual released version of the application Situations like having a separate branch of source code for each customer who requires a separate set of improvements to your present package And the classic one – few people in the team might be working on the bug fixes of the released version, whereas the others might be working on the next phase/release For few workflows, you can even have separate branches for people providing their inputs, which are finally integrated to produce a release candidate Following are flow diagrams for few workflows to help us understand the utilization of branching: Branching for a bug fix can have a structure as shown the following diagram:     This explains that when you are working on P2 and find a bug in P1, you need not drop your work, but switch to P1, fix it, and return back to P2. Branching for each promotion is as shown in the following diagram:     This explains how the same set of files can be managed across different phases/ promotions. Here, P1 from development has been sent to the testing team (a branch called testing will be given to the testing team) and the bugs found are reported and fixed in the development branch (v1.1 and v1.2) and merged with the testing branch. This is then branched as production or release, which end users can access. Branching for each component development is as shown in the following diagram:     Here every development task/component build is a new independent branch, which when completed is merged into the main development branch. Practice makes perfect: branching with Git I'm sure you have got a good idea about what, why, and when you can use branches when dealing with a Git repository. Let's fortify the understanding by creating a few use cases. Scenario Suppose you are the training organizer in your organization and are responsible for conducting trainings as and when needed. You are preparing a list of people who you think might need business communication skills training based on their previous records. As a first step, you need to send an e-mail to the nominations and check their availability on the specified date, and then get approval from their respective managers to allot the resource. Having experience in doing this, you are aware that the names picked by you from the records for training can have changes even at the last minute based on situations within the team. So you want to send out the initial list for each team and then proceed with your work while the list gets finalized. Time for action – creating branches in GUI mode Whenever you want to create a new branch using Git Gui, execute the following steps: Open Git Gui for the specified repository. Select the Create option from the Branch menu (or use the shortcut keys Ctrl + N), which will give you a dialog box as follows:     In the Name field, enter a branch name, leave the remaining fields as default for now, and then click on the Create button. What just happened? We have learned to create a branch using Git Gui. Now let's go through the process mentioned for the CLI mode and perform relevant actions in Git Gui. Time for action – creating branches in CLI mode Create a directory called BCT in your desktop. BCT is the acronym for Business Communication Training. Let's create a text file inside the BCT directory and name it participants. Now open the participants.txt file and paste the following lines in it: Finance team Charles Lisa John Stacy Alexander Save and close the file. Initiate it as a Git repository, add all the files, and make a commit as follows: git init git add . git commit –m 'Initial list for finance team' Now, e-mail those people followed by an e-mail to their managers and wait for the finalized list. While they take their time to respond, you should go ahead and work on the next list, say for the marketing department. Create a new branch called marketing using the following syntax: git checkout –b marketing Now open the participants.txt file and start entering the names for the marketing department below the finance team list, as follows: Marketing team Collins Linda Patricia Morgan Before you finish finding the fifth member of the marketing team, you receive a finalized list from the finance department manager stating he can afford only three people for the training as the remaining (Alexander and Stacy) need to take care of other critical tasks. Now you need to alter the finance list and fill in the last member of the marketing department. Before going back to the finance list and altering it, let's add the changes made for the marketing department and commit it. git add . git commit –m 'Unfinished list of marketing team' git checkout master Open the file and delete the names Alexander and Stacy, save, close, add the changes, and commit with the commit message Final list from Finance team. git add . git commit –m "Final list from Finance team" git checkout marketing Open the file and add the fifth name, Amanda, for the marketing team, save, add, and commit. ggit add . git commit –m "Initial list of marketing team" Say the same names entered for marketing have been confirmed; now we need to merge these two lists, which can be done by the following command. git merge master You will get a merge conflict as shown in the following screenshot:     Open the participants.txt ?le and resolve the merge then add the changes, and finally commit them. What just happened? Without any loss of thought or data, we have successfully adopted the changes on the first list, which came in while working on the second list, with the concept of branching – without one interfering with another As discussed, a branch begins its life as a copy of something else and then has a life of its own. Here, by performing git checkout –b branch_name we have created a new branch from the existing position. Technically, the so-called existing position is termed as the position of HEAD and this type of lightweight branches, which we create locally, are called topic branches. Another type of branch would be the remote branch or remote-tracking branch, which tracks somebody else's work from some other repository. We already got exposed to this while learning the concept of cloning. The command git checkout –b branch_name is equivalent to executing the following two commands: git branch branch_name: Creates a new branch of the given name at the given position, but stays in the current branch git checkout branch_name: Switches you to the specified branch from the current/active branch When a branch is created using Git Gui, the checkout process is automatically taken care of, which results in it being in the created branch. The command git merge branch_name merges the current/active branch with the specified branch to incorporate the content. Note that even after the merge the branch will exist until it's deleted with the command git branch –d branch_name. In cases where you have created and played with a branch whose content you don't want to merge with any other branch and want to simply delete the entire branch, use –D instead of –d in the command mentioned earlier. To view a list of branches available in the system, use the command git branch as shown in the following screenshot: As shown in the screenshot, the branches available in our BCT repository right now are marketing and master, with master being the default branch when you create a repository. The branch with a star in front of it is the active branch. To ease the process of identifying the active branch, Git displays the active branch in brackets (branch_name) as indicated with an arrow. By performing this exercise we have learned to create, add content, and merge branches when needed. Now, to visually see how the history has shaped up, open gitk (by typing gitk in the command-line interface or by selecting Visualize All Branch History from the Repository menu of Git Gui) and view the top left corner. It will show a history like in the following screenshot: Homework Try to build a repository alongside the idea explained with the last flow diagram given in the When do you need a branch section. Have one main line branch called development and five component development branches, which should be merged in after the customizations are made to its source.
Read more
  • 0
  • 0
  • 4433

article-image-article-yui-test
Packt
11 Mar 2013
5 min read
Save for later

YUI Test

Packt
11 Mar 2013
5 min read
(For more resources related to this topic, see here.) YUI Test is one of the most popular JavaScript unit testing frameworks. Although YUI Test is part of the Yahoo! User Interface (YUI) JavaScript library (YUI is an open source JavaScript and CSS library that can be used to build Rich Internet Applications), it can be used to test any independent JavaScript code that does not use the YUI library. YUI Test provides a simple syntax for creating JavaScript test cases that can run either from the browser or from the command line; it also provides a clean mechanism for testing asynchronous (Ajax) JavaScript code. If you are familiar with the syntax of xUnit frameworks (such as JUnit), you will find yourself familiar with the YUI Test syntax. In YUI Test, there are different ways to display test results . You can display the test results in the browser console or develop your custom test runner pages to display the test results. It is preferable to develop custom test runner pages in order to display the test results in all the browsers because some browsers do not support the console object. The console object is supported in Firefox with Firebug installed, Safari 3+, Internet Explorer 8+, and Chrome. Before writing your first YUI test, you need to know the structure of a custom YUI test runner page. We will create the test runner page, BasicRunner.html, that will be the basis for all the test runner pages used in this article. In order to build the test runner page, first of all you need to include the YUI JavaScript file yui-min.js—from the Yahoo! Content Delivery Network (CDN)—in the BasicRunner.html file, as follows: code 1 At the time of this writing, the latest version of YUI Test is 3.6.0, which is the one used in this chapter. After including the YUI JavaScript file, we need to create and configure a YUI instance using the YUI().use API, as follows: code 1 The YUI().use API takes the list of YUI modules to be loaded. For the purpose of testing, we need the YUI 'test' and 'console' modules (the 'test' module is responsible for creating the tests, while the 'console' module is responsible for displaying the test results in a nifty console component). Then, the YUI().use API takes the test's callback function that is called asynchronously once the modules are loaded. The Y parameter in the callback function represents the YUI instance. As shown in the following code snippet taken from the BasicRunner.html file, you can write the tests in the provided callback and then create a console component using the Y.Console object: code 1 The console object is rendered as a block element by setting the style attribute to 'block', and the results within the console can be displayed in the sequence of their executions by setting the newestOnTop attribute to false . Finally, the console component is created on the log div element. Now you can run the tests, and they will be displayed automatically by the YUI console component. The following screenshot shows the BasicRunner.html file's console component without any developed tests: Image Writing your first YUI test The YUI test can contain test suites, test cases, and test functions. A YUI test suite is a group of related test cases. Each test case includes one or more test functions for the JavaScript code. Every test function should contain one or more assertion in order to perform the tests and verify the outputs. The YUI Test.Suite object is responsible for creating a YUI test suite, while the YUI Test.Case object creates a YUI test case. The add method of the Test.Suite object is used for attaching the test case object to the test suite. The following code snippet shows an example of a YUI test suite: code 1 As shown in the preceding code snippet, two test cases are created. The first test case is named testcase1; it contains two test functions, testFunction1 and testFunction2. In YUI Test, you can create a test function simply by starting the function name with the word "test". The second test case is named testcase2; and it contains a single test function, testAnotherFunction. A test suite is created with the name Testsuite. Finally, testcase1 and testcase2 are added to the Testsuite test suite. In YUI Test, you have the option of creating a friendly test name for the test function, as follows: code 1 The "some Testcase" test case contains two tests with the names "The test should do X" and "The test should do Y". Summary In this article, we learned about the basics of YUI Test framework which is used for testing JavaScript applications, and also a walkthrough on how to write your YUI test using the Test.Suite object (that is responsible for creating a YUI test suite) and the Test.Case object (for creating a YUI test case). Resources for Article :   Further resources on this subject: Using Javascript Effects to enhance your Joomla! website for Visitors [Article] Exclusive Offer On jQuery Books: Winner Of 2010 Open-Source JavaScript Libraries [Article] Basics of Exception Handling Mechanism in JavaScript Testing [Article]
Read more
  • 0
  • 0
  • 2311
Modal Close icon
Modal Close icon