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-installing-and-configuring-drupal
Packt
11 Jul 2012
7 min read
Save for later

Installing and Configuring Drupal

Packt
11 Jul 2012
7 min read
(For more resources on Drupal 7, see here.) Installing Drupal There are a number of different ways to install Drupal on a web server, but in this recipe we will focus on the standard, most common installation, which is to say, Drupal running on an Apache server, which runs PHP with a MySQL database. In order to do this we will download the latest Drupal release, and walk you through all of the steps required to get it up and running. Getting ready Before beginning, you need to ensure that you meet the following minimal requirements: Web hosting with FTP access (or file access through a control panel). A server running PHP 5.2.5+ (5.3+ recommended). A blank MySQL database and the login credentials to access it. Ensure that register globals is set to off in the PHP.ini file. You may need to contact your hosting provider to do this. How to do it... The first step is to download the latest Drupal 7 release from the Drupal download page, which is located at http://drupal.org/project/drupal : This page displays the most recent and recommended releases for both Drupal 6 and 7. It also displays the most recent development versions, but be sure to download the recommended release (development versions are for developers who want to stay on the cutting edge). When the file is downloaded, extract it and upload the files to your chosen web server document root directory on the server. This may take some time. Configure your web server document root and server name (usually through a vhost directive). When the upload is complete, open your browser and in the address bar, type in the server name configured in the previous step to begin the installation wizard. Select Standard option and then select Save and continue: The next screen that you will see is the language selection screen; there should only be one language available at this point. Ensure that English is selected before proceeding: Following a requirements check, you will arrive at the database settings page. Enter your database name, username, and password in the required fields. Unless your database details have been supplied with a specific host name and port, you should leave the advanced options as they are and continue. You will now see the Site configuration page. Under Site information enter the name you would like to appear as the site's name. For Site e-mail address enter an e-mail address. Under the SITE MAINTENANCE ACCOUNT box, enter a username for the admin user (also known as user 1), followed by an e-mail address and password: (Move the mouse over the image to enlarge.) In the Server settings box, select your country from the drop-down, followed by your local time zone. Finally, in the Update notification box, ensure that both options are selected. Click on Save and continue to complete the installation. You will be presented with the congratulations page with a link to your new site. How it works... On the server requirements page, Drupal will carry out a number of tests. It is a requirement that PHP "register globals" is set to off or disabled. Register globals is a feature of PHP which allows global variables to be set from the contents of the Environment, GET, POST, Cookie, and Server variables. It can be a major security risk, as it enables potential hackers to overwrite important variables and gain unauthorized access. The Configure site page is where you specify the site name and e-mail addresses for the site and the admin user. The admin e-mail address will be used to contact the administrator with notifications from the site, and the site e-mail address is used as the originating e-mail address when the site sends e-mails to users. You can change these settings later on in the Site information page in the Configuration section. It's important to select the options to receive the site notifications so that you are aware when software updates are available for your site core and contrib modules; important security updates are available from time to time. There's more... In this recipe we have seen a regular Drupal installation procedure. There are various different ways to install and configure Drupal. We will explore some of these alternatives in the following sections. We will also cover some of the potential pitfalls you may come across with the requirements page. Uploading through a control panel If your web-hosting provider provides web access to your files through a control panel such as CPanel, you can save time by uploading the compressed Drupal installation package and running the unzip function on the file, if that functionality is provided. This will dramatically reduce the amount of time taken to perform the installation. Auto-installers There are other ways in which Drupal can be installed. Your hosting may come with an auto- installer such as Fantastico De Luxe or Softaculous. Both of these services provide a simple way to achieve the same results without the need to use FTP or to configure a database. Database table prefixes At the database setup screen there is an option to use a table prefix. Any prefix entered into the field would be added to the start of all table names in the database. This means that you could run multiple installations of Drupal, or possibly other CMSs from the same database by setting a different prefix. This method, however, will have implications for performance and maintenance. Installing on a Windows environment This recipe deals with installing Drupal on a Linux server. However, Drupal runs perfectly well on an IIS (Windows) server. Using Microsoft's WebMatrix software, it's easy to set up a Drupal site: http://www.microsoft.com/web/drupal Alternative languages Drupal supports many different languages. You can view and download the language packs at http://localize.drupal.org/download. You then need to upload the file to Drupal root/profiles/standard/translations. You will then see the option for that new language in the language selection page of the installation. Verifying the requirements page If all goes to plan, and the server is already configured correctly, then step 3, the server requirements page, will be skipped. However, you may come across problems in a few areas: Register Globals: This should be set to off in the php.ini file. This is very important in securing your site. If you find that register globals is turned on, then you will need to consult your hosting provider's documentation on this feature in order to switch it off. Drupal will attempt to create the following folder: Drupal root/sites/default/ files. If it fails, you may have to manually create this file on the server and give it the permission 755. Drupal will attempt to create a settings.php file by copying the default.settings.php file. If Drupal has trouble doing this, copy the default.settings.php file in the following directory: Drupal root/sites/default/default.settings.php and rename the copied file as settings.php. Give settings.php full write access CHMODD 777. After Drupal finishes the installation process, it will try to set the permission of this file to 444; you must check that this has been done, and manually set the file to 444, if it has not. See also See Installing Drupal distributions for more installation options using a preconfigured Drupal distribution. For more information about installing Drupal, see the installation guide at Drupal.org: http://drupal.org/documentation/install
Read more
  • 0
  • 0
  • 3583

article-image-microsoft-xna-40-game-development-receiving-player-input
Packt
02 Jul 2012
11 min read
Save for later

Microsoft XNA 4.0 Game Development: Receiving Player Input

Packt
02 Jul 2012
11 min read
(For more resources on Microsoft XNA 4.0, see here.) Adding text fields I'm generally a big fan of having as few text fields in an application as possible, and this holds doubly true for a game but there are some occasions when receiving some sort of textual information from the player is required so in these regrettable occasions, a textbox or field may be an appropriate choice. Unfortunately, a premade textbox isn't always available to us on any given gaming project, so sometimes we must create our own. Getting ready This recipe only relies upon the presence of a single SpriteFont file referring to any font at any desired size. How to do it... To start adding textboxes to your own games: Add a SpriteFont to the solution named Text: <?xml version="1.0" encoding="utf-8"?><XnaContent >    <FontName>Segoe UI Mono</FontName>    <Size>28</Size>    <Spacing>0</Spacing>    <UseKerning>true</UseKerning>    <Style>Regular</Style>    <CharacterRegions>      <CharacterRegion>        <Start>&#32;</Start>        <End>&#126;</End>      </CharacterRegion>    </CharacterRegions>  </Asset></XnaContent> Begin a new class to contain the text field logic, and embed a static mapping of the keyboard keys to their respective text characters: class Textbox{           private static Dictionary<Keys, char> characterByKey; Create a static constructor to load the mapping of keys to characters: static Textbox(){    characterByKey = new Dictionary<Keys, char>()    {        {Keys.A, 'a'},        {Keys.B, 'b'},        {Keys.C, 'c'},        {Keys.D, 'd'},     {Keys.E, 'e'},        {Keys.F, 'f'},        {Keys.G, 'g'},        {Keys.H, 'h'},        {Keys.I, 'i'},        {Keys.J, 'j'},        {Keys.K, 'k'},        {Keys.L, 'l'},        {Keys.M, 'm'},        {Keys.N, 'n'},        {Keys.O, 'o'},        {Keys.P, 'p'},        {Keys.Q, 'q'},        {Keys.R, 'r'},        {Keys.S, 's'},        {Keys.T, 't'},        {Keys.U, 'u'},        {Keys.V, 'v'},        {Keys.W, 'w'},        {Keys.X, 'x'},        {Keys.Y, 'y'},        {Keys.Z, 'z'},        {Keys.D0, '0'},        {Keys.D1, '1'},        {Keys.D2, '2'},        {Keys.D3, '3'},        {Keys.D4, '4'},        {Keys.D5, '5'},        {Keys.D6, '6'},        {Keys.D7, '7'},        {Keys.D8, '8'},        {Keys.D9, '9'},        {Keys.NumPad0, '0'},        {Keys.NumPad1, '1'},        {Keys.NumPad2, '2'},        {Keys.NumPad3, '3'},        {Keys.NumPad4, '4'},        {Keys.NumPad5, '5'},        {Keys.NumPad6, '6'},        {Keys.NumPad7, '7'},        {Keys.NumPad8, '8'},        {Keys.NumPad9, '9'},        {Keys.OemPeriod, '.'},        {Keys.OemMinus, '-'},    {Keys.Space, ' '}    };} Add the public instance fields that will determine the look and content of the display: public StringBuilder Text;public Vector2 Position;public Color ForegroundColor;public Color BackgroundColor;public bool HasFocus; Include instance-level references to the objects used in the rendering: GraphicsDevice graphicsDevice;SpriteFont font;SpriteBatch spriteBatch;        RenderTarget2D renderTarget;KeyboardState lastKeyboard;bool renderIsDirty = true; Begin the instance constructor by measuring the overall height of some key characters to determine the required height of the display, and create a render target to match: public Textbox(GraphicsDevice graphicsDevice, int width, SpriteFont font){    this.font = font;    var fontMeasurements = font.MeasureString("dfgjlJL");    var height = (int)fontMeasurements.Y;    var pp = graphicsDevice.PresentationParameters;    renderTarget = new RenderTarget2D(graphicsDevice,        width,        height,        false, pp.BackBufferFormat, pp.DepthStencilFormat); Complete the constructor by instantiating the text container and SpriteBatch:     Text = new StringBuilder();    this.graphicsDevice = graphicsDevice;    spriteBatch = new SpriteBatch(graphicsDevice);} Begin the Update() method by determining if we need to take any notice of the keyboard: public void Update(GameTime gameTime){    if (!HasFocus)    {        return;    } Retrieve all of the keys that are currently being depressed by the player and iterate through them, ignoring any that have been held down since the last update: var keyboard = Keyboard.GetState();foreach (var key in keyboard.GetPressedKeys()){    if (!lastKeyboard.IsKeyUp(key))    {        continue;    } Add the logic to remove a character from the end of the text, if either the Backspace or Delete key has been pressed: if (key == Keys.Delete ||    key == Keys.Back){    if (Text.Length == 0)    {        continue;    }    Text.Length--;    renderIsDirty = true;    continue;} Complete the loop and the method by adding the corresponding character for any keys we recognize, taking note of the case as we do so: char character;        if (!characterByKey.TryGetValue(key, out character))        {            continue;        }        if (keyboard.IsKeyDown(Keys.LeftShift) ||        keyboard.IsKeyDown(Keys.RightShift))        {            character = Char.ToUpper(character);        }        Text.Append(character);        renderIsDirty = true;    }                lastKeyboard = keyboard;} Add a new method to render the contents of the text field to RenderTarget if it has changed: public void PreDraw(){    if (!renderIsDirty)    {        return;    }    renderIsDirty = false;    var existingRenderTargets = graphicsDevice.GetRenderTargets();    graphicsDevice.SetRenderTarget(renderTarget);    spriteBatch.Begin();    graphicsDevice.Clear(BackgroundColor);    spriteBatch.DrawString(        font, Text,         Vector2.Zero, ForegroundColor);    spriteBatch.End();    graphicsDevice.SetRenderTargets(existingRenderTargets);} Complete the class by adding a method to render the image of RenderTarget to the screen: public void Draw(){    spriteBatch.Begin();    spriteBatch.Draw(renderTarget, Position, Color.White);    spriteBatch.End();} In your game's LoadContent() method, create a new instance of the text field: Textbox textbox;protected override void LoadContent(){    textbox = new Textbox(        GraphicsDevice,         400,         Content.Load<SpriteFont>("Text"))    {        ForegroundColor = Color.YellowGreen,        BackgroundColor = Color.DarkGreen,        Position = new Vector2(100,100),        HasFocus = true    };} Ensure that the text field is updated regularly via your game's Update() method: protected override void Update(GameTime gameTime){    textbox.Update(gameTime);    base.Update(gameTime);} In your game's Draw() method, let the text field perform its RenderTarget updates prior to rendering the scene including the text fi eld: protected override void Draw(GameTime gameTime){    textbox.PreDraw();    GraphicsDevice.Clear(Color.Black);    textbox.Draw();    base.Draw(gameTime);} Running the code should deliver a brand new textbox just waiting for some interesting text like the following: How it works... In the Update() method, we retrieve a list of all of the keys that are being depressed by the player at that particular moment in time. Comparing this list to the list we captured in the previous update cycle allows us to determine which keys have only just been depressed. Next, via a dictionary, we translate the newly depressed keys into characters and append them onto a StringBuilder instance. We could have just as easily used a regular string, but due to the nature of string handling in .NET, the StringBuilder class is a lot more efficient in terms of memory use and garbage creation. We could have also rendered our text directly to the screen, but it turns out that drawing text is a mildly expensive process, with each letter being placed on the screen as an individual image. So in order to minimize the cost and give the rest of our game as much processing power as possible, we render the text to RenderTarget only when the text changes, and just keep on displaying RenderTarget on screen during all those cycles when no changes occur. There's more... If you're constructing a screen that has more than one text field on it, you'll find the HasFocus state of the text field implementation to be a handy addition. This will allow you to restrict the keyboard input only to one text field at a time. In the case of multiple text fields, I'd recommend taking a leaf from the operating system UI handbooks and adding some highlighting around the edges of a text field to clearly indicate which text field has focus. Also, the addition of a visible text cursor at the end of any text within a text field with focus may help draw the player's eyes to the correct spot. On the phone If you do have access to a built-in text field control such as the one provided in the "Windows Phone XNA and Silverlight" project type, but still wish to render the control yourself, I recommend experimenting with enabling the prebuilt control, making it invisible, and feeding the text from it into your own text field display.
Read more
  • 0
  • 0
  • 4001

article-image-setting-basics-drupal-multilingual-site-languages-and-ui-translation
Packt
25 Jun 2012
10 min read
Save for later

Setting up the Basics for a Drupal Multilingual site: Languages and UI Translation

Packt
25 Jun 2012
10 min read
(For more resources on Drupal, see here.) Getting up and running Before we get started, we obviously need a Drupal 7 website to work on. This section gives you two options, namely, roll your own or install the demo. Using your own site You can use your own Drupal 7 site. It can be an existing site or one you create from scratch. If you are creating a brand new site and weren't planning on using a particular installation profile, you can get a head start by using the Localized Drupal Distribution install profile at drupal.org/project/l10n_install. It is probably obvious, but it's best to run the site on a development machine and not in a production environment. Once all the basic Drupal core modules are configured, you will also want to set up the following additional modules to get the most out of the exercises: Panels: A tool for creating pages with custom layouts Path auto: Settings for creating path aliases automatically Views: A tool for creating custom pages and blocks Using the demo site If you'd prefer a jump-start, a full demo website can be created using a special install profile. Instructions for downloading and installing the demo website are included on the Drupal project page available at drupal.org/project/multilingual_book_demo. The demo site contains additional modules including the modules listed previously as well as the following: Administration Menu: Toolbar for quick access to the site configuration Views Bulk Operations: Extra functionality for Views forms Views Slideshow: Slideshows of content coming from Views These modules provide us with a starting point. As more modules are needed for particular exercises, they will be listed so you can add them. Roles, users, and permissions Although you might already have multiple users on your test site, for simplicity it will be assumed that you are logged in as the super admin (user ID 1). Working with languages If we want a multilingual site, the logical first step is to add more languages! In this section, we will add languages to our site, configure how our languages are detected, and set up ways to go between these languages. Adding languages with the Locale module Drupal has language support built into the core, but it's not fully turned on by default. If you go to your site right now and navigate to Configuration | Regional and language, you will see the Regional settings and Date and time comfit page s for configuring default country, time zone, and date/time formats: To get our languages hooked in, let's enable the core module, Locale. Now go back to Configuration | Regional and language to see more options: Click on Languages and you'll see we only have English in our list so far: Now let's add a language by clicking on the Add language link. You can add a predefined language such as German or you can create a custom language. For our purposes, we will work with predefined languages. So choose a language and click on the Add language button. Drupal will then redirect you to the main language admin page and your new language will be added to the list. Now you can simply repeat the process for each language. In my case, I've added three new languages, namely, Arabic, German, and Polish: The overview table shows the language's name (English and native), its code, and its directionality. The language's direction can be Left to right (LTR) or Right to left (RTL), with most languages using the former. 'Right to left' just means that you start at the right side of the page and move towards the left side when you are writing. RTL languages include Arabic, Hebrew, and Syriac, which are written in their own alphabets. You can choose which languages to enable, order them, and set the site default. Links are provided to edit and delete each language. English only has an edit link since it is the system language and cannot be deleted, but English can be disabled if you use a non-English default. If we edit a language, we can modify all the information from the overview table except for the language's code since we need that as a consistent reference string. Do not change the default language once you have started translating or translations might break. Install String Translation from the Internationalization package (drupal.org/project/i18n), go to Configuration | Regional and language | Multilingual settings | Strings, select the Source language, and click on Save configuration. Do not change this setting once it's configured. Detecting languages We have our languages, so now what? If you click around your site, nothing looks different. That's because we are looking at the English version of the site and we haven't told Drupal how we want to deal with the other languages. We'll do that now. Navigate to Configuration | Regional and language | Languages | Detection and selection and you'll see we have a number of choices available to us: The Default detection method is enabled for us, but we can also enable the URL, Session, User, and Browser options. If you want a cookie-based option, check out the Language Cookie and Locale Cookie modules. Let's go over the core options in more detail. URL If you enable this method, users can navigate to URLs such as example.com/de/ news or example.com/deutsch/news (when using the path prefix option) and example.de/news, deutschexample.com/news, or deutsch.example.com/news (when using the domain option). Configuring domains requires web server changes, but using path prefixes does not. This is a common configuration for multilingual sites, and one we'll use shortly. The language's path prefix can be changed when editing the language. If you want to use path-prefixed URLs, then you should decide on your path prefixes before translating content as changing path prefixes might break links (unless you set up proper redirects). If desired, you can choose one language that does not have any path prefix. This is common for the site's default language. For example, if German is the default language and no path prefix is used, the news page would be accessed as example.com/news whereas other languages would be accessed using a path prefix (for example, example.com/en/news). Session The Session option is available if you want to store a user's language preference inside their user session. It was actually proposed by some Drupal community members that this method be removed from the set of choices as it caused a number of issues in other code. One reason you may not want to use this option is due to the possible inconsistency between the content and the URL language. For example, you could enable both URL and Session methods and order them so that the Session method is first. If a user is at example.com/de and if the session is set to French, then the user will see French content even though the URL corresponds with German. My advice is to just skip this one, or, if you need it, at least make sure that it's ordered below the URL option. User Once the Locale module is enabled, users can specify their preferred language when they edit their account profile. If you enable the User method in the detection settings, the user's profile language will be checked when deciding what language to display. Note that the user profile language defaults to the site's default language. Browser Users can configure their browsers to specify which languages they prefer. If the Browser method is enabled, Drupal will check the browser's request to find out the language setting and use it for the language choice. This option may or may not be useful depending on your site audience. Default The default site language is configured on the Configuration | Regional and language | Languages settings page, and is used for the Default detection method. Although you can't disable this method, you can reorder it if you choose. But, it makes the most sense to keep it at the bottom of the list to use it as the fallback language. Detection method order It is important to note that the detection method order is critical to how detection works. If you were to drag the Default method to the top of the list, then none of the other methods would be used and the site would only use the default language. Similarly, if you allow a user profile language and drag User to top of the list, then the URL method would not matter even if it's enabled. Also, if URL detection is ordered below Session, User, and Browser options, the user might see a UI language that does not match up with the URL language, which could be confusing. Make sure to think carefully about the order of these settings. If you use the URL method, it's likely you will want it first. The Default method should be last. The other detection method positions depend on your preference. When using path-prefixed URLs, if one language does not have a prefix, then detection for that language will work differently. For example, if the URL method is first, then no other detection methods will trigger for any URLs with no path prefix such as example.com/news or example.com/about-us. Our choice For our purposes, let's stick with URL detection and use the path-prefix option as this is the easiest to configure (it doesn't require extra domains). This choice will keep our URLs in sync with our interface language, which is also user and SEO-friendly. Check Enabled for the URL method and press the Save settings button. Now click on Configure for that method and you'll see options for Path prefix and Domain. We'll use the default option, that is Path prefix (for example, example.com/de). Don't panic on the next step. You won't see anything different in the UI until we finish our interface translation process later in the article. Now change the URL in your browser to include the path prefix for one of your languages. In my case, I'll try German and go to example.com/de. You should be able to use the path prefixes for each of your configured languages. Switching between languages Most likely you don't want your users to have to manually type in a different URL to switch between languages. Drupal core provides a language switcher block that you can put somewhere convenient for your users. To use the block, navigate to Structure | Blocks, find the Language switcher (User interface text) block, position it where you'd like, and save your block settings. The order of the languages in the block is based on the order configured at Configuration | Regional and language | Languages. Once enabled, the language switcher block looks like the following screenshot: You can now easily switch between your site languages, and the language chosen is highlighted. The UI won't look different when switching until we finish the next section. Two alternatives to the core language switcher block are provided by the Language Switcher and Language Switcher Drop-down modules. Also, if you want country flag icons added next to each language, you can install the Language Icons module.
Read more
  • 0
  • 0
  • 11248

article-image-unity-3x-scripting-character-controller-versus-rigidbody
Packt
22 Jun 2012
16 min read
Save for later

Unity 3.x Scripting-Character Controller versus Rigidbody

Packt
22 Jun 2012
16 min read
Creating a controllable character There are two ways to create a controllable character in Unity, by using the Character Controller component or physical Rigidbody. Both of them have their pros and cons, and the choice to use one or the other is usually based on the needs of the project. For instance, if we want to create a basic role playing game, where a character is expected to be able to walk, fight, run, and interact with treasure chests, we would recommend using the Character Controller component. The character is not going to be affected by physical forces, and the Character Controller component gives us the ability to go up slopes and stairs without the need to add extra code. Sounds amazing, doesn't it? There is one caveat. The Character Controller component becomes useless if we decide to make our character non-humanoid. If our character is a dragon, spaceship, ball, or a piece of gum, the Character Controller component won't know what to do with it. It's not programmed for those entities and their behavior. So, if we want our character to swing across the pit with his whip and dodge traps by rolling over his shoulder, the Character Controller component will cause us many problems. In this article, we will look into the creation of a character that is greatly affected by physical forces, therefore, we will look into the creation of a custom Character Controller with Rigidbody, as shown in the preceding screenshot. Custom Character Controller In this section, we will write a script that will take control of basic character manipulations. It will register a player's input and translate it into movement. We will talk about vectors and vector arithmetic, try out raycasting, make a character obey our controls and see different ways to register input, describe the purpose of the FixedUpdate function, and learn to control Rigidbody. We shall start with teaching our character to walk in all directions, but before we start coding, there is a bit of theory that we need to know behind character movement. Most game engines, if not all, use vectors to control the movement of objects. Vectors simply represent direction and magnitude, and they are usually used to define an object's position (specifically its pivot point) in a 3D space. Vector is a structure that consists of three variables—X, Y, and Z. In Unity, this structure is called Vector3: To make the object move, knowing its vector is not enough. Length of vectors is known as magnitude. In physics, speed is a pure scalar, or something with a magnitude but no direction. To give an object a direction, we use vectors. Greater magnitude means greater speed. By controlling vectors and magnitude, we can easily change our direction or increase speed at any time we want. Vectors are very important to understand if we want to create any movement in a game. Through the examples in this article, we will explain some basic vector manipulations and describe their influence on the character. It is recommended that you learn extra material about vectors to be able to perfect a Character Controller based on game needs. Setting up the project To start this section, we need an example scene. Perform the following steps: Select Chapter 2 folder from book assets, and click on on the Unity_chapter2 scene inside the custom_scene folder. In the Custom scripts folder, create a new JavaScript file. Call it CH_Controller (we will reference this script in the future, so try to remember its name, if you choose a different one): In a Hierarchy view, click on the object called robot. Translate the mouse to a Scene view and press F; the camera will focus on a funny looking character that we will teach to walk, run, jump, and behave as a character from a video game. Creating movement The following is the theory of what needs to be done to make a character move: Register a player's input. Store information into a vector variable. Use it to move a character. Sounds like a simple task, doesn't it? However, when it comes to moving a player-controlled character, there are a lot of things that we need to keep in mind, such as vector manipulation, registering input from the user, raycasting, Character Controller component manipulation, and so on. All these things are simple on their own, but when it comes to putting them all together, they might bring a few problems. To make sure that none of these problems will catch us by surprise, we will go through each of them step by step. Manipulating character vector By receiving input from the player, we will be able to manipulate character movement. The following is the list of actions that we need to perform in Unity: Open the CH_Character script. Declare public variables Speed and MoveDirection of types float and Vector3 respectively. Speed is self-explanatory, it will determine at which speed our character will be moving. MoveDirection is a vector that will contain information about the direction in which our character will be moving. Declare a new function called Movement. It will be checking horizontal and vertical inputs from the player. Finally, we will use this information and apply movement to the character. An example of the code is as follows: public var Speed : float = 5.0; public var MoveDirection : Vector3 = Vector3.zero; function Movement (){ if (Input.GetAxis("Horizontal") || Input.GetAxis("Vertical")) MoveDirection = Vector3(Input.GetAxisRaw("Horizontal"),MoveDirecti on.y, Input.GetAxisRaw("Vertical")); this.transform.Translate(MoveDirection); } Register input from the user In order to move the character, we need to register an input from the user. To do that, we will use the Input.GetAxis function. It registers input and returns values from -1 to 1 from the keyboard and joystick. Input.GetAxis can only register input that had been defined by passing a string parameter to it. To find out which options are available, we will go to Edit | Projectsettings | Input. In the Inspector view, we will see Input Manager. Click on the Axes drop-down menu and you will be able to see all available input information that can be passed to the Input.GetAxis function. Alternatively, we can use Input.GetAxisRaw. The only difference is that we aren't using Unity's built-in smoothing and processing data as it is, which allows us to have greater control over character movement. To create your own input axes, simply increase the size of the array by 1 and specify your preferences (later we will look into a better way of doing and registering input for different buttons). this.transform is an access to transformation of this particular object. transform contains all the information about translation, rotation, scale, and children of this object. Translate is a function inside Unity that translates GameObject to a specific direction based on a given vector. If we simply leave it as it is, our character will move with the speed of light. That happens because translation is being applied on character every frame. Relying on frame rate when dealing with translation is very risky, and as each computer has different processing power, execution of our function will vary based on performance. To solve this problem, we will tell it to apply movement based on a common factor—time: this.transform.Translate(MoveDirection * Time.deltaTime); This will make our character move one Unity unit every second, which is still a bit too slow. Therefore, we will multiply our movement speed by the Speed variable: this.transform.Translate((MoveDirection * Speed) * Time.deltaTime); Now, when the Movement function is written, we need to call it from Update. A word of warning though—controlling GameObject or Rigidbody from the usual Update function is not recommended since, as mentioned previously, that frame rate is unreliable. Thankfully, there is a FixedUpdate function that will help us by applying movement at every fixed frame. Simply change the Update function to FixedUpdate and call the Movement function from there: function FixedUpdate (){ Movement(); } The Rigidbody component Now, when our character is moving, take a closer look at the Rigidbody component that we have attached to it. Under the Constraints drop-down menu, we will notice that Freeze Rotation for X and Z axes is checked, as shown in the following screenshot: If we uncheck those boxes and try to move our character, we will notice that it starts to fall in the direction of the movement. Why is this happening? Well, remember, we talked about Rigidbody being affected by physics laws in the engine? That applies to friction as well. To avoid force of friction affecting our character, we forced it to avoid rotation along all axes but Y. We will use the Y axis to rotate our character from left to right in the future. Another problem that we will see when moving our character around is a significant increase in speed when walking in a diagonal direction. This is not an unusual bug, but an expected behavior of the MoveDirection vector. That happens because for directional movement we use vertical and horizontal vectors. As a result, we have a vector that inherits magnitude from both, in other words, its magnitude is equal to the sum of vertical and horizontal vectors. To prevent that from happening, we need to set the magnitude of the new vector to 1. This operation is called vector normalization. With normalization and speed multiplier, we can always make sure to control our magnitude: this.transform.Translate((MoveDirection.normalized * Speed) * Time. deltaTime); Jumping Jumping is not as hard as it seems. Thanks to Rigidbody, our character is already affected by gravity, so the only thing we need to do is to send it up in the air. Jump force is different from the speed that we applied to movement. To make a decent jump, we need to set it to 500.0). For this specific example, we don't want our character to be controllable in the air (as in real life, that is physically impossible). Instead, we will make sure that he preserves transition velocity when jumping, to be able to jump in different directions. But, for now, let's limit our movement in air by declaring a separate vector for jumping. User input verification In order to make a jump, we need to be sure that we are on the ground and not floating in the air. To check that, we will declare three variables—IsGrounded, Jumping, and inAir—of a type boolean. IsGrounded will check if we are grounded. Jumping will determine if we pressed the jump button to perform a jump. inAir will help us to deal with a jump if we jumped off the platform without pressing the jump button. In this case, we don't want our character to fly with the same speed as he walks; we need to add an airControl variable that will smooth our fall. Just as we did with movement, we need to register if the player pressed a jump button. To achieve this, we will perform a check right after registering Vertical and Horizontal inputs: public var jumpSpeed : float = 500.0; public var jumpDirection : Vector3 = Vector3.zero; public var IsGrounded : boolean = false; public var Jumping : boolean = false; public var inAir : boolean = false; public var airControl : float = 0.5; function Movement(){ if (Input.GetAxis("Horizontal") || Input.GetAxis("Vertical")) { MoveDirection = Vector3(Input.GetAxisRaw("Horizontal"),MoveDirection.y,Input.GetAxisRaw("Vertical")); } if (Input.GetButtonDown("Jump") && isGrounded) {} } GetButtonDown determines if we pressed a specific button (in this case, Space bar), as specified in Input Manager. We also need to check if our character is grounded to make a jump. We will apply vertical force to a rigidbody by using the AddForce function that takes the vector as a parameter and pushes a rigidbody in the specified direction. We will also toggle Jumping boolean to true, as we pressed the jump button and preserve velocity with JumpDirection: if (Input.GetButtonDown("Jump") &&isGrounded){ Jumping = true; jumpDirection = MoveDirection; rigidbody.AddForce((transform.up) * jumpSpeed); } if (isGrounded) this.transform.Translate((MoveDirection.normalized * Speed) * Time.deltaTime); else if (Jumping || inAir) this.transform.Translate((jumpDirection * Speed * airControl) * Time.deltaTime); To make sure that our character doesn't float in space, we need to restrict its movement and apply translation with MoveDirection only, when our character is on the ground, or else we will use jumpDirection. Raycasting The jumping functionality is almost written; we now need to determine whether our character is grounded. The easiest way to check that is to apply raycasting. Raycasting simply casts a ray in a specified direction and length, and returns if it hits any collider on its way (a collider of the object that the ray had been cast from is ignored): To perform a raycast, we will need to specify a starting position, direction (vector), and length of the ray. In return, we will receive true, if the ray hits something, or false, if it doesn't: function FixedUpdate () { if (Physics.Raycast(transform.position, -transform.up, collider. height/2 + 2)){ isGrounded = true; Jumping = false; inAir = false; } else if (!inAir){ inAir = true; JumpDirection = MoveDirection; } Movement(); } As we have already mentioned, we used transform.position to specify the starting position of the ray as a center of our collider. -transform.up is a vector that is pointing downwards and collider.height is the height of the attached collider. We are using half of the height, as the starting position is located in the middle of the collider and extended ray for two units, to make sure that our ray will hit the ground. The rest of the code is simply toggling state booleans. Improving efficiency in raycasting But what if the ray didn't hit anything? That can happen in two cases—if we walk off the cliff or are performing a jump. In any case, we have to check for it. If the ray didn't hit a collider, then obviously we are in the air and need to specify that. As this is our first check, we need to preserve our current velocity to ensure that our character doesn't drop down instantly. Raycasting is a very handy thing and being used in many games. However, you should not rely on it too often. It is very expensive and can dramatically drop down your frame rate. Right now, we are casting rays every frame, which is extremely inefficient. To improve our performance, we only need to cast rays when performing a jump, but never when grounded. To ensure this, we will put all our raycasting section in FixedUpdate to fire when the character is not grounded. function FixedUpdate (){ if (!isGrounded){ if (Physics.Raycast(transform.position, -transform.up, collider.height/2 + 0.2)){ isGrounded = true; Jumping = false; inAir = false; } else if (!inAir){ inAir = true; jumpDirection = MoveDirection; } } Movement(); } function OnCollisionExit(collisionInfo : Collision){ isGrounded = false; } To determine if our character is not on the ground, we will use a default function— OnCollisionExit(). Unlike OnControllerColliderHit(), which had been used with Character Controller, this function is only for colliders and rigidbodies. So, whenever our character is not touching any collider or rigidbody, we will expect to be in the air, therefore, not grounded. Let's hit Play and see our character jumping on our command. Additional jump functionality Now that we have our character jumping, there are a few issues that should be resolved. First of all, if we decide to jump on the sharp edge of the platform, we will see that our collider penetrates other colliders. Thus, our collider ends up being stuck in the wall without a chance of getting out: A quick patch to this problem will be pushing the character away from the contact point while jumping. We will use the OnCollisionStay() function that's called at every frame when we are colliding with an object. This function receives collision contact information that can help us determine who we are colliding with, its velocity, name, if it has Rigidbody, and so on. In our case we are interested in contact points. Perform the following steps: Declare a new private variable contact of a ContactPoint type that describes the collision point of colliding objects. Declare the OnCollisonStay function. Inside this function, we will take the first point of contact with the collider and assign it to our private variable. Add force to the contact position to reverse the character's velocity, but only if the character is not on the ground. Declare a new variable and call it jumpClimax of boolean type. Contacts is an array of all contact points. Finally, we need to move away from that contact point by reversing our velocity. The AddForceAtPosition function will help us here. It is similar to the one that we used for jumping, however, this one applies force at a specified position (contact point): public var jumpClimax :boolean = false; ... function OnCollisionStay(collisionInfo : Collision){ contact = collisionInfo.contacts[0]; if (inAir || Jumping) rigidbody.AddForceAtPosition(-rigidbody.velocity, contact.point); } The next patch will aid us in the future, when we will be adding animation to our character later in this article. To make sure that our jumping animation runs smoothly, we need to know when our character reaches jumping climax, in other words, when it stops going up and start a falling. In the FixedUpdate function, right after the last else if statement, put the following code snippet: else if (inAir&&rigidbody.velocity.y == 0.0) { jumpClimax = true; } Nothing complex here. In theory, the moment we stop going up is a climax of our jump, that's why we check if we are in the air (obviously we can't reach jump climax when on the ground), and if vertical velocity of rigidbody is 0.0. The last part is to set our jumping climax to false. We'll do that at the moment when we touch the ground: if (Physics.Raycast(transform.position, -transform.up, collider. height/2 + 2)){ isGrounded = true; Jumping = false; inAir = false; jumpClimax = false; } Running We taught our character to walk, jump, and stand aimlessly on the same spot. The next logical step will be to teach him running. From a technical point of view, there is nothing too hard. Running is simply the same thing as walking, but with a greater speed. Perform the following steps: Declare a new variable IsRunning of a type boolean, which will be used to determine whether our character has been told to run or not. Inside the Movement function, at the very top, we will check if the player is pressing left or right, and shift and assign an appropriate value to isRunning: public var isRunning : boolean = false; ... function Movement() { if (Input.GetKey (KeyCode.LeftShift) || Input.GetKey (KeyCode. RightShift)) isRunning = true; else isRunning = false; ... } Another way to get input from the user is to use KeyCode. It is an enumeration for all physical keys on the keyboard. Look at the KeyCode script reference for a complete list of available keys, on the official website: http://unity3d.com/ support/documentation/ScriptReference/KeyCode We will return to running later, in the animation section.
Read more
  • 0
  • 1
  • 49506

article-image-webgl-animating-3d-scene
Packt
20 Jun 2012
10 min read
Save for later

WebGL: Animating a 3D scene

Packt
20 Jun 2012
10 min read
We will discuss the following topics: Global versus local transformations Matrix stacks and using them to perform animation Using JavaScript timers to do time-based animation Parametric curves Global transformation allows us to create two different kinds of cameras. Once we have applied the camera transform to all the objects in the scene, each one of them could update its position; representing, for instance, targets that are moving in a first-person shooting game, or the position of other competitors in a car racing game. This can be achieved by modifying the current Model-View transform for each object. However, if we modified the Model-View matrix, how could we make sure that these modifications do not affect other objects? After all, we only have one Model-View matrix, right? The solution to this dilemma is to use matrix stacks. Matrix stacks A matrix stack provides a way to apply local transforms to individual objects in our scene while at the same time we keep the global transform (camera transform) coherent for all of them. Let's see how it works. Each rendering cycle (each call to draw function) requires calculating the scene matrices to react to camera movements. We are going to update the Model-View matrix for each object in our scene before passing the matrices to the shading program (as attributes). We do this in three steps as follows: Once the global Model-View matrix (camera transform) has been calculated, we proceed to save it in a stack. This step will allow us to recover the original matrix once we had applied to any local transforms. Calculate an updated Model-View matrix for each object in the scene. This update consists of multiplying the original Model-View matrix by a matrix that represents the rotation, translation, and/or scaling of each object in the scene. The updated Model-View matrix is passed to the program and the respective object then appears in the location indicated by its local transform. We recover the original matrix from the stack and then we repeat steps 1 to 3 for the next object that needs to be rendered. The following diagram shows this three-step procedure for one object: Animating a 3D scene To animate a scene is nothing else than applying the appropriate local transformations to objects in it. For instance, if we have a cone and a sphere and we want to move them, each one of them will have a corresponding local transformation that will describe its location, orientation, and scale. In the previous section, we saw that matrix stacks allow recovering the original Model-View transform so we can apply the correct local transform for the next object to be rendered. Knowing how to move objects with local transforms and matrix stacks, the question that needs to be addressed is: When? If we calculated the position that we want to give to the cone and the sphere of our example every time we called the draw function, this would imply that the animation rate would be dependent on how fast our rendering cycle goes. A slower rendering cycle would produce choppy animations and a too fast rendering cycle would create the illusion of objects jumping from one side to the other without smooth transitions. Therefore, it is important to make the animation independent from the rendering cycle. There are a couple of JavaScript elements that we can use to achieve this goal: The requestAnimFrame function and JavaScript timers. requestAnimFrame function The window.requestAnimFrame() function is currently being implemented in HTML5-WebGL enabled Internet browsers. This function is designed such that it calls the rendering function (whatever function we indicate) in a safe way only when the browser/tab window is in focus. Otherwise, there is no call. This saves precious CPU, GPU, and memory resources. Using the requestAnimFrame function, we can obtain a rendering cycle that goes as fast as the hardware allows and at the same time, it is automatically suspended whenever the window is out of focus. If we used requestAnimFrame to implement our rendering cycle, we could use then a JavaScript timer that fires up periodically calculating the elapsed time and updating the animation time accordingly. However, the function is a feature that is still in development. To check on the status of the requestAnimFrame function, please refer to the following URL: Mozilla Developer Network JavaScript timers We can use two JavaScript timers to isolate the rendering rate from the animation rate. The rendering rate is controlled by the class WebGLApp. This class invokes the draw function, defined in our page, periodically using a JavaScript timer. Unlike the requestAnimFrame function, JavaScript timers keep running in the background even when the page is not in focus. This is not an optimal performance for your computer given that you are allocating resources to a scene that you are not even looking. To mimic some of the requestAnimFrame intelligent behavior provided for this purpose, we can use the onblur and onfocus events of the JavaScript window object. Let's see what we can do: Action (What) Goal (Why) Method (How) Pause the rendering To stop the rendering until the window is in focus Clear the timer calling clearInterval in the window.onblur function Slow the rendering To reduce resource consumption but make sure that the 3D scene keeps evolving even if we are not looking at it We can clear current timer calling clearInterval in the window.onblur function and create a new timer with a more relaxed interval (higher value) Resume the rendering To activate the 3D scene at full speed when the browser window recovers its focus We start a new timer with the original render rate in the window.onfocus function By reducing the JavaScript timer rate or clearing the timer, we can handle hardware resources more efficiently. In WebGLApp you can see how the onblur and onfocus events have been used to control the rendering timer as described previously. Timing strategies In this section, we will create the second JavaScript timer that will allow controlling the animation. As previously mentioned, a second JavaScript timer will provide independency between how fast your computer can render frames and how fast we want the animation to go. We have called this property the animation rate. However, before moving forward you should know that there is a caveat when working with timers: JavaScript is not a multi-threaded language. This means that if there are several asynchronous events occurring at the same time (blocking events) the browser will queue them for their posterior execution. Each browser has a different mechanism to deal with blocking event queues. There are two blocking event-handling alternatives for the purpose of developing an animation timer. Animation strategy The first alternative is to calculate the elapsed time inside the timer callback. The pseudo-code looks like the following: var initialTime = undefined; var elapsedTime = undefined; var animationRate = 30; //30 ms function animate(deltaT){ //calculate object positions based on deltaT } function onFrame(){ elapsedTime = (new Date).getTime() – initialTime; if (elapsedTime < animationRate) return; //come back later animate(elapsedTime); initialTime = (new Date).getTime(); } function startAnimation(){ setInterval(onFrame,animationRate/1000); } Doing so, we can guarantee that the animation time is independent from how often the timer callback is actually executed. If there are big delays (due to other blocking events) this method can result in dropped frames. This means the object's positions in our scene will be immediately moved to the current position that they should be in according to the elapsed time (between consecutive animation timer callbacks) and then the intermediate positions are to be ignored. The motion on screen may jump but often a dropped animation frame is an acceptable loss in a real-time application, for instance, when we move one object from point A to point B over a given period of time. However, if we were using this strategy when shooting a target in a 3D shooting game, we could quickly run into problems. Imagine that you shoot a target and then there is a delay, next thing you know the target is no longer there! Notice that in this case where we need to calculate a collision, we cannot afford to miss frames, because the collision could occur in any of the frames that we would drop otherwise without analyzing. The following strategy solves that problem. Simulation strategy There are several applications such as the shooting game example where we need all the intermediate frames to assure the integrity of the outcome. For example, when working with collision detection, physics simulations, or artificial intelligence for games. In this case, we need to update the object's positions at a constant rate. We do so by directly calculating the next position for the objects inside the timer callback. var animationRate = 30; //30 ms var deltaPosition = 0.1 function animate(deltaP){ //calculate object positions based on deltaP } function onFrame(){ animate(deltaPosition); } function startAnimation(){ setInterval(onFrame,animationRate/1000); } This may lead to frozen frames when there is a long list of blocking events because the object's positions would not be timely updated. Combined approach: animation and simulation Generally speaking, browsers are really efficient at handling blocking events and in most cases, the performance would be similar regardless of the chosen strategy. Then, deciding to calculate the elapsed time or the next position in timer callbacks will then depend on your particular application. Nonetheless, there are some cases where it is desirable to combine both animation and simulation strategies. We can create a timer callback that calculates the elapsed time and updates the animation as many times as required per frame. The pseudocode looks like the following: var initialTime = undefined; var elapsedTime = undefined; var animationRate = 30; //30 ms var deltaPosition = 0.1; function animate(delta){ //calculate object positions based on delta } function onFrame(){ elapsedTime = (new Date).getTime() - initialTime; if (elapsedTime < animationRate) return; //come back later! var steps = Math.floor(elapsedTime / animationRate); while(steps > 0){ animate(deltaPosition); steps -= 1; } initialTime = (new Date).getTime(); } function startAnimation(){ initialTime = (new Date).getTime(); setInterval(onFrame,animationRate/1000); } You can see from the preceding code snippet that the animation will always update at a fixed rate, no matter how much time elapses between frames. If the app is running at 60 Hz, the animation will update once every other frame, if the app runs at 30 Hz the animation will update once per frame, and if the app runs at 15 Hz the animation will update twice per frame. The key is that by always moving the animation forward a fixed amount it is far more stable and deterministic. The following diagram shows the responsibilities of each function in the call stack for the combined approach: This approach can cause issues if for whatever reason an animation step actually takes longer to compute than the fixed step, but if that is occurring, you really ought to simplify your animation code or put out a recommended minimum system spec for your application. Web Workers: Real multithreading in JavaScript You may want to know that if performance is really critical to you and you need to ensure that a particular update loop always fires at a consistent rate then you could use Web Workers. Web Workers is an API that allows web applications to spawn background processes running scripts in parallel to their main page. This allows for thread-like operation with message-passing as the coordination mechanism. You can find the Web Workers specification at the following URL: W3C Web Workers
Read more
  • 0
  • 0
  • 5448

article-image-wordpress-buddypress-courseware
Packt
19 Jun 2012
10 min read
Save for later

Wordpress: Buddypress Courseware

Packt
19 Jun 2012
10 min read
Installing and configuring BP Courseware As BP Courseware is a plugin that runs atop BuddyPress, we must have already installed, activated, and configured BuddyPress. To install BP Courseware, log in to the WordPress dashboard, hover over Plugins in the left sidebar, and choose Add New. Search for BuddyPress ScholarPress Courseware and install the plugin. BuddyPress Courseware requires the Private Messaging BuddyPress component to be enabled. If you have disabled Private Messaging, you will be prompted to enable it before activating BuddyPress Courseware. To enable Private Messaging, log in to the WordPress dashboard and visit the BuddyPress Components screen. BuddyPress Courseware settings While BuddyPress Courseware will work immediately, there are a number of settings that can be adjusted to ensure that the plugin meets our needs. To access the BuddyPress Courseware settings, log in to the WordPress dashboard, hover over BuddyPress in the left sidebar, and select Courseware. Global settings BP Courseware integrates with BuddyPress groups for course management. By default, we must enable courseware individually for each group. Checking the Enable Courseware globally checkbox will turn courseware on for all new groups. This is useful if groups are used exclusively for course management. If you intend to use BuddyPress groups for other purposes, such as student project collaboration, the Enable Courseware globally option should remain unchecked. In this scenario each group will require enabling courseware manually. To do so, follow the instructions given in the Enabling BP Courseware section later in the article. Collaboration settings Within BP Courseware we are able to define users as either teachers or students. By enabling the Collaboration settings option, any site user with a teacher role has the ability to edit and add courses, assignments, and schedules. Make assignment responses private When students submit an assignment their response is public to all site users. By enabling the Make assignment responses private feature, student responses will be visible only to the teachers and the student who has completed the assignment. Gradebook default grade format The default BuddyPress Courseware Gradebook format is numeric. Within the Gradebook default grade format settings we are able to choose between numeric, letter, or percentage grading for assignments. Webservices API integration BP Courseware has the ability to integrate with WorldCat and ISBNdb web services to aid in locating books and articles. To integrate these services with BuddyPress Courseware, follow the links from the BudddyPress Courseware settings screen to sign up for a free API key. Customization Cascading stylesheets (CSS) are the files that control the look and formatting of a web page. BuddyPress Courseware allows administrators with advanced web skills to create a custom stylesheet for fine grain control over the look of Courseware. Renaming the groups page BP Courseware utilizes the BuddyPress group feature for course content. While the term Groups makes sense in the context of a standard BuddyPress installation, it can be confusing when using BuddyPress Courseware as a learning management system. To prevent this confusion, I find it helpful to rename the Groups page to Courses.   To rename Groups: Log in to the WordPress dashboard. Create a new WordPress page titled Courses by hovering over Pages in the left sidebar, and choosing Add New. Title the page Courses, leaving the page content blank, and click on the blue Publish button Adjust the BuddyPress page settings by hovering over BuddyPress in the left sidebar and selecting the Pages tab. In the menu next to User Groups, select the Courses option and click on the Save button. Delete the Groups page by clicking on Pages in the left sidebar. From the All Pages screen, hover over the Groups page and click on the red Trash link. Setting Courses as the site home page Using the BuddyPress Courseware plugin, we may wish to enable our Courses page as the site's front page. Doing so will allow students to quickly access course information and prevent confusion regarding how to find the courseware dashboard.   To enable the Courses page as our site's home page: Log in to the WordPress dashboard. If you have not already done so, create an empty page titled Blog Hover over Settings in the left sidebar and select the Reading tab. From the Reading Settings screen, select Front page displays | A static page option. Select Courses from the Front page menu choices and Blog as the Posts page Creating a course When setting up a course we must first create a BuddyPress group. To create course or group: From our public facing site, visit the Courses page (or Groups if not renamed). Click on the Create a Group button. From the Details screen, provide a Group Name such as the course name and section number and enter a Group Description such as the course catalog information. On the Privacy Options page, select This is a public group, allowing any site member to join. Complete the installation by optionally adding an avatar image and inviting members. Enabling BP Courseware Once the course group has been created, we may enable BP Courseware. This step may be skipped, if we selected Enable Courseware globally from the BuddyPress Courseware settings screen. To enable BP Courseware: Visit the page of the newly created group. Click on the Admin tab Click on the Courseware link from the row of links below the Admin tab. Below Courseware Status , select Enable to enable BP Courseware for the group. Optionally, if you wish to keep student assignment responses private, select Enable below Private Responses. Click on the Save button. Courseware dashboard Within BP Courseware, the courseware dashboard acts as the course home screen for both instructors and students. From the courseware dashboard, instructors are able to add and manage course content. Students use the dashboard to access course materials and submit assignments. To access the courseware dashboard, visit the Courses page (or Groups if unchanged) and click on the Courseware link located below the course/group description. The teacher dashboard appears as shown in the following screenshot: The student dashboard appears as shown in the following screenshot: Adding course content Adding course content to BP Courseware allows educators to easily organize and share course information with students. The BP Courseware plugin provides a structure for managing course lectures, assignments, quizzes, grades, resources, and schedules. Lectures Adding lecture information allows instructors to share course notes, resources, and slides with students in a structured format. While the term lecture implies the lecture format of university courses, I find it useful to think of lectures in terms of teaching units. The lecture pages can serve as a resource for a chunk of course content. To add a new lecture, click on the Add a new lecture button from the course dashboard. We may then edit the content of the lecture much in the same way as a WordPress post adding text, images, links, and embedded media. Lectures will appear in the Latest Lectures section of course dashboard, with the most recently posted lecture appearing at the top. This allows students to quickly access the most recently posted course lecture. Assignments BP Courseware provides a means for us to post assignments and collect student responses. The assignments can take multiple formats, allowing students to respond to questions, upload a file, or embed media. Posting assignments as a teacher As a teacher, we have the ability to post assignments. To post an assignment, visit the course dashboard and click on the Create an assignment button. This will take us to the New Assignment screen. From the New Assignment screen, we may enter the details of the assignment. From the New Assignment screen, assign a title to the assignment and enter the assignment description and necessary information. This acts much in the same way as WordPress posts, allowing us to enter text, images, media, and links. In the right column, we may choose the corresponding lecture topic and select the assignment due date. Once the assignment information is complete, click on the Publish assignment button to make it visible to students. Submitting assignments as a student Students can access assignments by clicking on the All Assignments button or viewing the Latest Assignments from the course dashboard. By clicking on the Assignment Title, students can see the detailed assignment information written by the instructor. Clicking on the Add a response button, will give the students an opportunity to submit the assignment. For standard assignments, students will be presented with a text input area similar to the WordPress post editor. Within this text area, students may type a written response, add links, embed media, and attach files. Viewing student responses Instructors have access to all student assignment responses, while students are only able to view their own. To view student assignment responses, visit the individual assignment page and click on the Responses button, located in the right sidebar. This will present us with a list of student responses. Clicking on the individual assignment link, will take us to a screen containing the student's assignment response. Gradebook BP Courseware provides us with a Gradebook feature for assessing student assignments. To access the Gradebook, visit an individual assignment page and click on the Gradebook button, located in the right sidebar. This will take us to the Gradebook screen for the assignment. For each student, we are given the option to enter a grade value, a private comment, and a public comment. Once the grades and comments have been entered, we may click on the Save grades button. After an assignment has been graded, students will receive a message containing the grade. Students will be alerted to this message by a notification, but may access their grades directly by visiting the individual assignment page. The grade is posted in the Assignment Meta sidebar of the assignment page. Bibliography The Bibliography is designed so that educators can easily maintain a list of course materials and resources. To add entries to the bibliography, visit the Courseware dashboard and click on the Manage bibliography button. From the Bibliography page we may add entries manually or import them by pasting information from BibTeX. The bibliography is ideal for courses utilizing a wide range of materials. BibTeX is a tool for formatting references. It is typically used in conjunction with the LaTeX typesetting system. More information can be found at http://www.bibtex.org. Schedule and calendar The BuddyPress Schedule page functions as a course calendar, automatically containing assignment due dates as well as manually managed schedule items. To view the course calendar, visit the Courseware Dashboard and click on the Schedules link. To schedule more items, click on the Add a schedule button from the Courseware dashboard. Complete the New Schedule form and click on the Publish Schedule button once it is complete. New schedule items will be added to the calendar as well as featured in a list format on the Schedules page.
Read more
  • 0
  • 0
  • 3491
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-runescape-gold-strategy-guide-avoiding-scams
Packt
19 Jun 2012
8 min read
Save for later

RuneScape Gold Strategy Guide : Avoiding Scams

Packt
19 Jun 2012
8 min read
(For more resources on Runescape, see here.) What do the scammers hope to gain? RuneScape is a popular game, and there's a huge real-world market for RuneScape gold and high level RuneScape characters. A character with a high combat level, some decent non-combat skills, and a lot of quest points and gold can go for more than $300 on the black market. That might not sound like much if you're a RuneScape player that is attached to your character, but if you're a scammer that steals other people's accounts in bulk, and has no regard for the law, that starts to sound like some pretty easy money. RuneScape gold is also sold on the black market, at a price of approximately £0.45 per million gold. Some of this gold is bought from players looking to recoup some of the costs of their account, but it's a safe bet to assume that a lot of the gold comes from stolen accounts being cleaned out, or scammers ripping off players and selling on their ill-gotten gains. Let's not forget the people who scam for less nefarious reasons. Some people just like to feel that they've gotten the better of other people, and will steal from newbies or unsuspecting older players, just because they can. Falling for a scam is frustrating, and can set you back a long way in your goals of earning that coveted party hat, cracker, or set of armor. It's also embarrassing, because in hindsight the scam always seems so obvious. Stay on your guard, and don't put yourself in positions where you are likely to be scammed. Popular scams There are several different types of scam. Some scammers rely on quirks of the RuneScape user interface, others rely on fast talking or social engineering, or on a player who does not quite understand the rules of the game. Trading scams Trading scams are some of the most popular types of scam. Scamming players will open a trade window, then close it, blaming lag. They'll keep putting up a trade then close it again, hoping that you'll agree to trade quickly (to avoid the lag). At some point during this opening and closing of the trade window, they'll alter the trade, hoping you won't notice that you're not getting what you originally agreed to trade for; they've swapped their side of the trade for a worthless item. Rounding out your money Some cunning players will say I'm quitting RuneScape! I'm giving away my money. Show me how much you've got and I'll round your money up to an impressive figure. You open a trade window and show them 700,000 coins. They put 300,000 in their side of the trade window. That looks like one million to you, so you accept, right? Think about it for a second; you're giving them 700,000 gold. They're giving you 300,000 gold. They profit by 400,000 and you end up losing money. A surprising number of people fall for this scam. Double your money You may have encountered this scam in other games. It's certainly a popular one in EVE Online, where it's easy to tip people money without having to actually open a trade window with them. It happens a lot in RuneScape too, though. The scammer offers to double whatever money you send to them. If you send them a small amount, say 10,000 gold, they probably will double it. Sometimes, they'll even double a large quantity of money for one or two people, so that those people will vouch that the scammer is legit. In most cases, though, the scammer will just log in a couple of alternative accounts of their own to shill for them. Once a few people believe that the scammer is legitimate, people will get greedy and trade him large amounts of gold. Of course, he'll log out at this point, and keep all the money. Teleport scams If someone offers you a teleport, look up the location before you accept it. Or even better, just don't accept random teleport offers from people you don't know. It's common for people to offer teleports to safe-sounding locations that are actually in the wilderness. When you accept the teleport, you'll find yourself surrounded by player killers looking to kill you and take whatever you drop. Armor scamming Don't trust people offering to trim your armor. Armour that you obtain untrimmed cannot be trimmed (well, with the exception of Dragon Armour, which you can trim with an ornamental kit). You can buy trimmed armor on the Grand Exchange, or you can earn it by completing the relevant scrolls, but that's the only way you can get trimmed armor. Anyone offering to trim your rune set is just hoping you'll hand it over so that they can run off with it. Duping scams If someone offers to tell you a way to dupe your valuable items, report them. For starters, if they know a way to duplicate items, then they know an exploit. Using exploits is forbidden by Jagex. They should have reported the exploit that they'd found to Jagex, so that it could be fixed. It's more than likely that they don't actually know an exploit, and if you hear them out, they'll tell you to hand over an item, or run an executable file that they'll send to you, or drop an item on the floor and then press a magic key combination (Alt + F4, anyone?). The end result of their secret method will be that you either hand over an item to them, infect your computer with a Trojan, or drop an item on the floor and close your browser. They take either the item, or your account password. You lose a prized possession and end up looking, and feeling, foolish. Don't do it. Fake drop parties Real drop parties> are held in the Party Room in North East Falador. In a real drop party, players will put items into a chest, and the items will be released through balloons, which the players have to race to pop, so that they could pick up the items. Scammers often pretend that they're holding drop parties so that people will give them valuable items, which they have no intention of dropping. If you want to take part in a drop party, use the Falador party room don't hand your items to another player unless you know and trust them. Password scams Password scams come in several shapes and sizes. Sometimes, you'll get a message from someone impersonating a Jagex support worker, or a moderator, who will ask you for your password. Don't ever give your password out. Jagex will never ask you for your password under any circumstances. You should report anyone who asks you for it. Another way that people try to get player's passwords from inside the game is by saying The chat filter hides your password. Look! My password is ********, see? Of course, the player scamming has just manually typed a bunch of * characters. If you try it with your password, it will be visible for the world to see. Some bold scammers try telling people to reset their password to a certain phrase and then log out to get free stuff. The players then look out for people logging out, and try their username and password. Jagex now require newer players to use an e-mail account instead of a username, which protects new players from this sort of scam, but older accounts that use a username are vulnerable to it. Trade scams If you see someone spamming chat with a bulk trade for a popular item, check the Grand Exchange to make sure the price they're offering is legitimate, and then use a calculator to make sure the figures add up. You may find that they've conveniently added a zero to their price (or even just tweaked it by a little bit so they can claim that they've made an honest mistake, which still amounts to a sizeable profit for them). When it comes to buying or selling, it pays to take your time and work everything out twice if you have to. If players get angry, yell at you to hurry up, or just act pushy, don't trade with them. There are plenty of other people who will be happy to let you take your time and have a successful, honest transaction with you. (For more resources on Runescape, see here.) Out-of-game scams In-game scams are easy enough to avoid if you are cautious, and keep in mind the age-old mantra of if it looks too good to be true, it probably is, but Out-of-game scams are another matter. You've probably already heard of phishing, the practice of sending authentic-looking e-mails to try to trick people into clicking a link and giving away your account details. Some phishing e-mails are pretty easy to spot. They contain a lot of spelling mistakes and poor formatting. However, some scammers are getting more creative, and they are taking the time to produce authentic looking emails that will fool most The e-mail looks legitimate, right? It uses official RuneScape images. It mentions Jagex, and the blue underlined link looks like it points to the RuneScape website. http://secure.runescape.com.secure.scammerlogin.fakedomain/ m=weblogin/loginform.html?mod=www&ssl=0&dest.
Read more
  • 0
  • 0
  • 5897

article-image-article-vmware-view-5-desktop-virtualization-vcenter-vdesktop
Packt
15 Jun 2012
8 min read
Save for later

VMware View 5 Desktop Virtualization

Packt
15 Jun 2012
8 min read
Core components of VMware View This book assumes a familiarity with server virtualization, more specifically, VMware vSphere (sometimes referred to as ESX by industry graybeards). Therefore, this article will focus on: The VMware vCenter Server The types of View Connection Server Agent and client software vCenter Server VMware vCenter is a required component of a VMware View solution. This is because the View Connection Server interacts with the underlying Virtual Infrastructure (VI) through vCenter Web Service (typically over port 443). vCenter is also responsible for the complementary components of a VMware View solution provided by the underlying VMware vSphere, including VMotion and DRS (used to balance the virtual desktop load on the physical hosts). When an end customer purchases VMware View bundles, VMware vCenter is automatically included and does not need to be purchased via a separate Stock Keeping Unit (SKU). In the environments leveraging vSphere for server virtualization, vCenter Server is likely to already exist. To ensure a level set on the capabilities that VMware vCenter Server provides, the key terminologies are listed as follows: vMotion: It is the ability to live migrate a running virtual machine from one physical server to another with no downtime. DRS: It is the vCenter Server capability that balances virtual machines across physical servers participating in the same vCenter Server cluster. Cluster: It is a collection of physical servers that have access to the same networks and shared storage. The physical servers participating in a vCenter cluster have their resources (for example, CPU, memory, and so on) logically pooled for virtual machine consumption. HA: It is the vCenter Server capability that protects against the failure of a physical server. HA will power up virtual machines that reside on the failed physical server on available physical servers in the same cluster. Folder: It is a logical grouping of virtual machines, displayed within the vSphere Client. vSphere Client: It is the client-side software used to connect to vCenter Servers (or physical servers running vSphere) for management, monitoring, configuration, and other related tasks. Resource pool: It is a logical pool of resources (for example, CPU, memory, and so on). The virtual machines (or the groups of virtual machines) residing in the same resource pool will share a predetermined amount of resources. Designing a VMware View solution often touches on typical server virtualization design concepts such as the proper cluster design. Owing to this overlap in design concepts between server virtualization and VDI, many server virtualization engineers apply exactly the same principles from one solution to the other. The first misstep that a VDI architect can take is that VDI is not server virtualization and should not be treated as such. Server virtualization is the virtualization of server operating systems. While it is true that VDI does use some server virtualization (for the connection infrastructure, for example), there are many concepts that are new and critical to understand for success. The second misstep a VDI architect can make is in understanding the pure scale of some VDI solutions. For the average server virtualization administrator with no VDI in their environment, he/she may be tasked with managing a dozen physical servers with a few hundred virtual machines. The authors of this book have been involved in VDI solutions involving tens of thousands of vDesktops, well beyond the limits of a traditional VMware vSphere design. VDI is often performed on a different scale. The concepts of architectural scaling are covered later in this book, but many of the scaling concepts revolve around the limits of VMware vCenter Server. It should be noted that VMware vCenter Server was originally designed to be the central management point for the enterprise server virtualization environments. While VMware continues to work on its ability to scale, designing around VMware vCenter server will be important. So why do we need VMware vCenter in the first place, for the VDI architect? VMware vCenter is the gateway for all virtual machine tasks in a VMware View solution. This includes the following tasks: The creation of virtual machine folders to organize vDesktops The creation of resource pools to segregate physical resources for different groups of vDesktops The creation of vDesktops The creation of snapshots VMware vCenter is not used to broker the connection of an end device to a vDesktop. Therefore, an outage of VMware vCenter should not impact inbound connections to already-provisioned vDesktops as it will prevent additional vDesktops from being built, refreshed, or deleted. Because of vCenter Server's importance in a VDI solution, additional steps are often taken to ensure its availability even beyond the considerations made in a typical server virtualization solution. Later in this book, there is a question asking whether an incumbent vCenter Server should be used for an organization's VDI or whether a secondary vCenter Server infrastructure should be built. View Connection Server View Connection Server is the primary component of a VMware View solution; if VMware vCenter Server is the gateway for management communication to the virtual infrastructure and the underlying physical servers, the VMware View Connection Server is the gateway that end users pass through to connect to their vDesktop. In classic VDI terms, it is VMware's broker that connects end users with workspaces (physical or virtual). View Connection Server is the central point of management for the VDI solution and is used to manage almost the entire solution infrastructure. However, there will be times when the architect will need to make considerations to vCenter cluster configurations, as discussed later in this book. In addition, there may be times when the VMware View administrator will need access to the vCenter Server. The types of VMware View Connection Servers There are several options available when installing the VMware View Connection Server. Therefore, it is important to understand the different types of View Connection Servers and the role they play in a given VDI solution. Following are the three configurations in which View Connection Server can be installed: Full: This option installs all the components of View Connection Server, including a fresh Lightweight Directory Access Protocol (LDAP) instance. Security: This option installs only the necessary components for the View Connection portal. View Security Servers do not need to belong to an Active Directory domain (unlike the View Connection Server) as they do not access any authentication components (for example, Active Directory). Replica: This option creates a replica of an existing View Connection Server instance for load balancing or high availability purposes. The authentication/ LDAP configuration is copied from the existing View Connection Server. Our goal is to design the solutions that are highly available for our end customers. Therefore, all the designs will leverage two or more View Connection Servers (for example, one Full and one Replica). The following services are installed during a Full installation of View Connection Server: VMware View Connection Server VMware View Framework Component VMware View Message Bus Component VMware View Script Host VMware View Security Gateway Component VMware View Web Component VMware VDMDS VMware VDMDS provides the LDAP directory services. View Agent View Agent is a component that is installed on the target desktop, whether physical (seldom) or virtual (almost always). View Agent allows the View Connection Server to establish a connection to the desktop. View Agent also provides the following capabilities: USB redirection: It is defined as making a USB device—that is connected locally—appear to be connected to vDesktop Single Sign-On (SSO): It is done by using intelligent credential handling, which requires only one secured and successful authentication login request, as opposed to logging in multiple times (for example, at the connection server, vDesktop, and so on) Virtual printing via ThinPrint technology: It is the ability to streamline printer driver management through the use of ThinPrint (OEM) PCoIP connectivity: It is the purpose-built VDI protocol made by Teradici and used by VMware in their VMware View solution Persona management: It is the ability to manage a user profile across an entire desktop landscape; the technology comes via the recovery time objective (RTO) acquisition by VMware View Composer support: It is the ability to use linked clones and thin provisioning to drastically reduce operational efforts in managing a mid-to-large-scale VMware View environment View Client View Client is a component that is installed on the end device (for example, the user's laptop). View Client allows the device to connect to a View Connection Server, which then directs the device to an available desktop resource. Following are the two types of View Clients: View Client View Client with Local Mode These separate versions have their own unique installation bits (only one may be installed at a time). View Client provides all of the functionality needed for an online and connected worker. If Local Mode will be leveraged in the solution, View Client with Local Mode should be installed. VMware View Local Mode is the ability to securely check out a vDesktop to a local device for use in disconnected scenarios (for example, in the middle of the jungle). There is roughly an 80 MB difference in the installed packages (View Client with Local Mode being larger). For most scenarios, 80 MB of disk space will not make or break the solution as even flash drives are well beyond an 80 MB threshold. In addition to providing the functionality of being able to connect to a desktop, View Client talks to View Agent to perform the following tasks: USB redirection Single Sign-On
Read more
  • 0
  • 0
  • 4174

Packt
11 Jun 2012
17 min read
Save for later

Developing BizTalk Artifacts — Creating Orchestrations

Packt
11 Jun 2012
17 min read
Orchestrations Many integrations are based on pure messaging scenarios, that is, they do not need Orchestrations. They consist of receiving a message through an adapter, applying some form of transformations to the message, routing it to one or more subscribers, and sending them out again, using the same or another adapter. They might also require a response. In cases where that response is synchronous, and the ports are con fi gured with the request-response message exchange pattern, this can be handled without an Orchestration. However, as soon as you have an integration that implies more than one logical step, you use an Orchestration. It is usually stated that Orchestrations exist to coordinate business processes. I would drop the word "business" from that. In a nutshell, the Orchestration engine is the work fl ow engine employed by the BizTalk Server to allow you to handle various processes, whether they have their roots based in business or technology. Orchestrations are based on the C#-like language named XLANG/s. Though you sometimes resort to writing XLANG/s statements directly, you most often work with modeling your process using Orchestration shapes and setting properties. Basic shapes and configuration Orchestrations, and the executable processes they implement, are modeled using a sequence of shapes. Each shape has a distinct meaning and usage. The shapes can be divided into five areas, as follows: Message and Data Handling Containers Flow Control Orchestration Nesting Other The available shapes are the ones you have to work with. Orchestration shape is not an area of extensibility. You do, however, like with the Scripting Functoid for Maps, have a way of writing code or calling external components to perform processing. In Orchestrations, this has the form of the Expression shape. Message and Data Handling Within this category, there are shapes that help to receive, send, construct, transform, or assign message variables as follows: table 1 Some shapes require nesting, such as the Assign and Transform shapes, which always need to be put into a Construct shape, as shown in the following diagram: Containers Containers are shapes that, either visually or technically, group other shapes, as follows: table 2 Flow control Since Orchestrations model processes, and processes are much about the fl ow of messages, there are many shapes used to handle that fl ow, as follows: table 3 Orchestration Nesting Orchestrations can be nested and called from other Orchestrations, similar to methods in .NET. The shapes that control that are as follows: table 4 Other These shapes are dynamic and either allow for advanced message processing, decision making, or actions through calling Business Rules, or allow for making arbitrary XLANG/s statements through calling .NET helper components. The shapes are as follows: table 5 More information about the limitations and structure of the XLANG/s language can be found at http://msdn.microsoft.com/en-us/ library/aa577463(v=BTS.70).aspx. Orchestration activation Orchestrations can be activated in one of two ways: by message publication to the MessageBox, fulfilling the Orchestrations activation subscription, as specified by the activating Receive Port and its binding option, or through their being called from another Orchestration. This activation process is not arbitrary. Instead, you need to determine how an Orchestration should be activated when you design it. Activating Receive An activating Receive shape is used when the Orchestration is fi rst constructed. It is fulfi lled by a message publication matching the activation subscription. This port can be of any binding type. The two main differentiators from any other port in the Orchestration are as follows: The port is triggered by an activation subscription, based on design-time-determined filter criteria . The Receive shape connected to the port is marked with Activate set to True, as shown in the following screenshot: In this case, the Filter criteria for subscription has not been set explicitly. We will examine when it is needed and when it is not, later in this chapter, as we discuss port binding options. Call and Start Call or Start Orchestration is used when an Orchestration is used in the same way as a .NET method, that is, when it is called from another Orchestration directly using design-time coupling. Parameters are used to relay information. Such parameters might be variables, ports, messages, and so on. Call is a direct synchronous instantiation that does not rely on message publication. It waits for the called Orchestration to complete and then returns the control back to the caller. Start is a fire-and-forget style asynchronous instantiation that uses message publication. A called Orchestration can return a response in the form of out or updated reference parameters, while a started Orchestration cannot return a result through parameters to its starter. However, it can use ports to receive a result. Persistence During the execution of an Orchestration, the state of the process is saved, or persisted. This enables the Orchestration to recover from failures and retry or restart from a previous point of execution. Persistence may occur at the following occasions: After the execution of a Send Port After the execution of a Start Orchestration shape After the successful execution (commit) of a transactional scope When the Orchestration instance is suspended When the Orchestration instance is completed When the Orchestration engine shuts down gracefully When a debugging breakpoint is hit When dehydration is determined appropriate by the engine Persistence and serialization of the entire Orchestration, including all messages, variables, and state information, brings with it the requirement that everything used within an Orchestration must be serializable. If a class used within an Orchestration is not serializable, you must use it within a transactional scope marked as atomic. Dehydration and rehydration Persistence also enables dehydration and rehydration , saving on precious processing resources by removing Orchestration from active memory and serializing it to the database awaiting its next step (dehydration), for example, the correlation of a response message. Once that event occurs, usually in the form of a message being published to the MessageBox., the Orchestration is rehydrated and processing is continued. The scenarios in which dehydration is considered by the engine are as follows: When the Orchestration instance is waiting for a response message When the Orchestration is listening for a message using the Listen shape When the Orchestration engine determines that it has reached an idle delay threshold The algorithm that the engine uses to determine dehydrations is based on the last 10 delays at that point in the Orchestration, and compared with a runtime calculated value, that differs depending on available resources and other factors, but is between a configurable minimum and maximum time (that, by default, is 0 and 1800 seconds respectively). Transactions Orchestrations employ the use of transactions to compose operations in units or work, isolated from others, and to recover from failures. Transactions in BizTalk Server can be either Long Running or Atomic. Transaction types Long Running transactions are Long Running units of work for which you want to have the ability to define custom compensating logic and exception handling, or those that need to serve as an umbrella for nested transactions. Long Running transactions persist state, and send operations are committed to the MessageBox and seen by subscribers immediately. Atomic transactions are transactional, and follow the Atomicity, Consistency, Isolation, and Durability (ACID) rules. Either everything within the transaction is correctly committed, or none of it is. The persisted state of the Orchestration is either the state before the transaction began or the state after all operations are committed. The changes performed by any operation during the transaction, such as a message being published to the MessageBox, is not visible to anyone during the transaction, but only after commit. Any changes, once committed, are persisted so that they are available, even if the system fails after the transaction is committed. Read more on the ACID rules of transactions at the following URL: http://en.wikipedia.org/wiki/ACID#Characteristics Scopes Scopes are the way to handle transactions within the Orchestrations. All scopes have the following properties: Synchronized Transaction Type Synchronized scopes ensure that the data being read is not simultaneously written to by other branches in a parallel shape. Scopes are, by default, not synchronized, though Atomic scopes are implicitly synchronized, regardless of the property value. A scope can be marked as transactional by the Transaction Type property being set to either Long Running or Atomic. The third option for the Transaction Type property is None, as shown in the following screenshot: Long Running When configuring the Long Running Transaction Type, the following additional properties (over a non-transactional scope) will become available: Compensation Timeout Transaction Identifier   Compensation Isolation Level Retry Timeout Transaction Identifier   Read Committed: It reads only committed rows and prevents reading changes that are not yet committed by other transactions, but it does not prevent data it has read from being changed by other transactions before it has completed. Repeatable Read: It prevents updates to rows read by this scope until the transaction is completed. Serializable: It prevents data being committed by other transactions in such a way that queries used by this transaction would give a different result than when executed.   Create a .NET assembly. In this sample, we will use a Helper component that uses directory services to fi nd the full name of the sales representative that created a sales order for a car. The ADHelper class is contained in the Chapter04-Example01.ClassLibary project. The code looks as follows: code 1 Create an Orchestration that will call the assembly. The Orchestration SalesOrderProcess is implemented in Chapter04-Example01. Orchestrations in Chapter04-Example01.sln, for this sample, look similar to the following screenshot: The expression in the CreateSOOut Message Assignment shape looks similar to that in the following screenshot: Since the expression is using a static method, no variable of type ADHelper is required, and the method can be called outside an Atomic scope, even if the class is not marked as serializable. Build the solution. GAC the Chapter04-Example01.ClassLibary assembly, so that it can be located and used from the BizTalk Server. Deploy the Orchestration. Create ports. For simplicity, a Binding File is located at C:\BTS2010CertGuide\Chapter04\Example01- Orchestrations\ BTS2010CertGuide-Ch02- Orchestrations.xml. Con fi gure the Orchestration. Start and test the Orchestration. The default Isolation Level is Serializable. Nesting Long Running transactions can contain other transactions, either Long Running or Atomic. Atomic transactions can contain no other transactions. Conceptually, when it comes to transactions and nesting, you can look at the Orchestration level as a scope, that is, the Orchestration can be marked as a transaction in the same way as a scope. If you want to put an Atomic transactional scope directly inside the Orchestration, then the Orchestration needs to be con fi gured as Long Running. Transaction reach Another important concept about transactions in BizTalk Server is their reach. Transactions initiated in Orchestrations end in the MessageBox. This means that marking a scope as Atomically transactional does not allow you to have a transactional conversation with the intended recipient of the message through the MessageBox from within the Orchestration. The reach of a transaction is depicted in the following diagram: As the diagram shows, it is possible to extend the reach of a transaction from an Orchestration to a COM+ (Enterprise Services-managed) component. Storing configuration information Many Orchestrations may rely on con fi guration parameters. There are different ways of supplying configuration to an Orchestration. We will examine some of these and look for the pros and cons. Orchestration variables Orchestration variables are a very static place to have con fi guration values. If variables point to a class, the default constructor of that class can be called automatically to instantiate the variable. If anything other than the default constructor is called, this needs to be done in an Expression shape. Also, when Orchestrations are called or started, the caller can supply the initial values for parameters. However, they have to originate from somewhere. Configuration placed in BTSNTSvc.exe.config The BTSNTSvc.exe file is an executable file used by all BizTalk in-process Host Instances. As a .NET executable, it reads its configuration from the BTSNTSvc. exe.config file at startup. It is possible to place custom configuration into that file. The issue with this approach is that any addition or change to a configuration value requires the Host Instance to be restarted. Since the introduction of 64-bit processes, there is also a BTSNTSvc64.exe file with a corresponding con fi guration fi le. This requires confi guration to be duplicated in two places (and on as many BizTalk Servers as there are in the group). Also, any con fi guration property supplied in this file is not available to the isolated Hosts, though that is not an issue with Orchestrations, since they only run in process. Accessing files under the Program Files folder might also be restricted in some organizations. Configuration placed in web.config for isolated Hosts For Isolated Hosts, it is possible to place configuration in web.config, in the directory of the web service being called. In the end, this is just a bad practice resulting in many configuration duplications and maintenance challenges, not to mention confi guration being overwritten and removed if the service is republished. Configuration placed in machine.config Configuration in machine.config solves the issue of having different places for in-process or isolated Hosts. There is still the issue of whether to choose 32- or 64-bit, which will have their machine confi gs in C:\Windows\Microsoft.NET\ Framework\v4.0.30319\Config\machine.config and C:\Windows\Microsoft. NET\Framework64\v4.0.30319\Config\machine.config, respectively. Also, as with BTSNTSvc.exe.config, if your BizTalk environment consists of more than one server, you will need to apply settings to all machines. machine.config settings are also only read when the process is initiated, so this placement also requires Host restart for updates or new additions. Accessing the machine.config fi le is also often restricted in many organizations. Some configuration can be placed on the Adapter handlers Specifically, WCF extension configuration can be placed in the Send and Receive Handlers for the WCF-Custom adapter. Through the message Configuration values can be sent in as part of the message. It is not uncommon to determine the outcome of a process, based on the content of the message. However, sending in pure configuration values through the message is uncommon. Through the message context Configuration values can be part of the message context. A common place to con fi gure values to be placed in the context is through the use of a custom Pipeline component, whose job is to write (or promote) the appropriate values to the context. Configuration can then be done in the Pipeline on a per-instance runtime con fi guration. The downside of this is that Orchestrations that can get their messages from more than one Receive Location must have those properties con fi gured in all the locations. Also, more than one value (that is, either two Pipeline components or an un-typed one) needs to be put into the context, where it is hard to keep track of the format for inputting con fi guration values. The ESB Toolkit uses a variation of this approach where the "itinerary" is included in the message context. Business Rules For configuration values that change often or for those you would like an out of the box-versioned user interface for, Business Rules are a good choice. They are centrally stored in the database, and as such are available on all machines to all types of Hosts. Business Rules can be, in some cases, a cumbersome addition to the solution just for the sake of configuration properties from some perspectives, but they are de fi nitely a good viable option. There are also Application Programming Interfaces (APIs) available in the form of the Call Rules Orchestration shape that allows you to call Business Rules easily. SSO Single Sign-on (SSO) can be used as a centralized data store for configuration values. Besides storing user account mappings, it also stores custom con fi guration for adapters and can be used for secure storage of custom confi guration for custom logic, as well. Although there are no easy, out of the box options for using SSO this way, there are samples in the documentation and tooling available from the BizTalk Community that makes this relatively easy. Using a .NET helper component If you decide to use a .NET helper component to store and retrieve your con fi guration, then you can get the con fi guration from anywhere, say a fi le or a database. File storage will have its drawbacks, but it is certainly possible. In many cases, using a custom component may seem easy, but you should strive to use built-in functionality and features wherever possible, if you want to minimize maintenance costs. Integrating with .NET assemblies Sometimes there are methods or logic contained within .NET helper components that you would like to use from within an Orchestration. Even though there is no option to call an external assembly, like with the Scripting Functoid, doing so is easy. It requires an assembly reference added to the project, a variable of that type, and an Expression shape. The following are the steps required to call a .NET assembly from an Orchestration: For Atomic transaction, the Timeout value indicates the amount of time that passes before the transaction is marked as failed and is rolled back, but only if it was coordinated in a transaction, together with another resource, by the Distributed Transaction Coordinator (DTC). The Retry value indicates whether PersistenceException (caused by database connectivity issues) and RetryTransactionException (explicitly thrown in the Orchestration) should cause the transaction to be retried. Only these exceptions wil be affected by the Retry flag. All other exceptions will cause the transaction to fail. Isolation levels Isolation levels control the locking levels used in the database by the engine while dealing with reads and writes for the actions performed by shapes in the scope. These transaction levels are available as follows: For Atomic transaction, the Timeout value indicates the amount of time that passes before the transaction is marked as failed and is rolled back, but only if it was coordinated in a transaction, together with another resource, by the Distributed Transaction Coordinator (DTC). The Retry value indicates whether PersistenceException (caused by database connectivity issues) and RetryTransactionException (explicitly thrown in the Orchestration) should cause the transaction to be retried. Only these exceptions wil be affected by the Retry flag. All other exceptions will cause the transaction to fail. Isolation levels Isolation levels control the locking levels used in the database by the engine while dealing with reads and writes for the actions performed by shapes in the scope. These transaction levels are available as follows: Compensation can be Default or Custom. Setting it to Custom has the same effect as selecting to add a new Compensation Block to the scope. The Timeout property specifies the amount of time spent in the scope before TimeoutException is raised. Atomic While configuring the Atomic Transaction Type, the following additional properties (over a non-transactional scope) will become available: Compensation can be Default or Custom. Setting it to Custom has the same effect as selecting to add a new Compensation Block to the scope. The Timeout property specifies the amount of time spent in the scope before TimeoutException is raised. Atomic While configuring the Atomic Transaction Type, the following additional properties (over a non-transactional scope) will become available:
Read more
  • 0
  • 0
  • 3914

article-image-android-database-programming-binding-ui
Packt
07 Jun 2012
6 min read
Save for later

Android Database Programming: Binding to the UI

Packt
07 Jun 2012
6 min read
(For more resources on Android, see here.) SimpleCursorAdapters and ListViews There are two major ways of retrieving data on Android, and each has its own class of ListAdapters, which will then know how to handle and bind the passed-in data. The first way of retrieving data is one that we're very familiar with already – through making queries and obtaining Cursor objects. The subclass of ListAdapters that wrap around Cursors is called CursorAdapter, and in the next section we'll focus on the SimpleCursorAdapter, which is the most straightforward instance of CursorAdapter. The Cursor points to a subtable of rows containing the results of our query. By iterating through this cursor, we are able to examine the fields of each row. Now we would like to convert each row of the subtable into a corresponding row in our list. The first step in doing this is to set up a ListActivity (a variant of the more common Activity class). As its name suggests, a ListActivity is simply a subclass of the Activity class which comes with methods that allow you to attach ListAdapters. The ListActivity class also allows you to inflate XML layouts, which contain list tags. In our example, we will use a very bare-bones XML layout (named list.xml) that only contains a ListView tag as follows: <?xml version="1.0" encoding="utf-8"?><LinearLayout android_orientation="vertical" android_layout_width="fill_parent" android_layout_height="wrap_content" > <ListView android_id="@android:id/android:list" android_layout_width="fill_parent" android_layout_height="wrap_content" /></LinearLayout> This is the first step in setting up what's called a ListView in Android. Similar to how defining a TextView allows you to see a block of text in your Activity, defining a ListView will allow you to interact with a scrollable list of row objects in your Activity. Intuitively, the next question in your mind should be: Where do I define how each row actually looks? Not only do you need to define the actual list object somewhere, but each row should have its own layout as well. So, to do this we create a separate list_entry.xml file in our layouts directory. The example I'm about to use is the one that queries the Contacts content provider and returns a list containing each contact's name, phone number, and phone number type. Thus, each row of my list should contain three TextViews, one for each data field. Subsequently, my list_entry.xml file looks like the following: <?xml version="1.0" encoding="utf-8"?><LinearLayout android_orientation="vertical" android_layout_width="fill_parent" android_layout_height="wrap_content" android_padding="10dip" > <TextView android_id="@+id/name_entry" android_layout_width="wrap_content" android_layout_height="wrap_content" android_textSize="28dip" /> <TextView android_id="@+id/number_entry" android_layout_width="wrap_content" android_layout_height="wrap_content" android_textSize="16dip" /> <TextView android_id="@+id/number_type_entry" android_layout_width="wrap_content" android_layout_height="wrap_content" android_textColor="#DDD" android_textSize="14dip" /></LinearLayout> So we have a vertical LinearLayout which contains three TextViews, each with its own properly defined ID as well as its own aesthetic properties (that is, text size and text color). In terms of set up – this is all we need! Now we just need to create the ListActivity itself, inflate the list.xml layout, and specify the adapter. To see how all this is done, let's take a look at the code before breaking it apart piece by piece: public class SimpleContactsActivity extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list); // MAKE QUERY TO CONTACT CONTENTPROVIDER String[] projections = new String[] { Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone.TYPE }; Cursor c = getContentResolver().query(Phone.CONTENT_URI, projections, null, null, null); startManagingCursor(c); // THE DESIRED COLUMNS TO BE BOUND String[] columns = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER, Phone.TYPE }; // THE XML DEFINED VIEWS FOR EACH FIELD TO BE BOUND TO int[] to = new int[] { R.id.name_entry, R.id.number_entry, R.id.number_type_entry }; // CREATE ADAPTER WITH CURSOR POINTING TO DESIRED DATA SimpleCursorAdapter cAdapter = new SimpleCursorAdapter(this, R.layout.list_entry, c, columns, to); // SET THIS ADAPTER AS YOUR LIST ACTIVITY'S ADAPTER this.setListAdapter(cAdapter); }} So what's going on here? Well, the first part of the code you should recognize by now – we're simply making a query over the phone's contact list (specifically over the Contact content provider's Phone table) and asking for the contact's name, number, and number type. Next, the SimpleCursorAdapter takes as two of its parameters, a string array and an integer array which represent a mapping between Cursor columns and XML layout views. In our case, this is as follows: // THE DESIRED COLUMNS TO BE BOUNDString[] columns = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER, Phone.TYPE };// THE XML DEFINED VIEWS FOR EACH FIELD TO BE BOUND TOint[] to = new int[] { R.id.name_entry, R.id.number_entry, R.id.number_type_entry }; This is so that the data in the DISPLAY_NAME column will get bound to the TextView with ID name_entry, and so on. Once we have these mappings defined, the next part is to just instantiate the SimpleCursorAdapter, which can be seen in this line: // CREATE ADAPTER WITH CURSOR POINTING TO DESIRED DATASimpleCursorAdapter cAdapter = new SimpleCursorAdapter(this, R.layout.list_entry, c, columns, to); Now, the SimpleCursorAdapter takes five parameters – the first is the Context, which essentially tells the CursorAdapter which parent Activity it needs to inflate and bind the rows to. The next parameter is the ID of the R layout that you defined earlier, which will tell the CursorAdapter what each row should look like and, furthermore, where it can inflate the corresponding Views. Next, we pass in the Cursor, which tells the adapter what the underlying data actually is, and lastly, we pass in the mappings. Hopefully, the previous code makes sense, and the parameters of SimpleCursorAdapter make sense as well. The result of this previous Activity can be seen in the following screenshot: Everything looks good, except for these random integers floating around under the phone number. Why are there a bunch of 1s, 2s, and 3s at the bottom of each row where the types should be? Well, the phone number types are not returned as Strings but are instead returned as integers. From there through a simple switch statement, we can easily convert these integers into more descriptive Strings. However, you'll quickly see that with our very simple, straightforward use of the built-in SimpleCursorAdapter class, there was nowhere for us to implement any "special" logic that would allow us to convert such returned integers to Strings. This is when overriding the SimpleCursorAdapter class becomes necessary, because only then can we have full control over how the Cursor's data is to be displayed in each row. And so, we move onwards to the next section where we see just that.
Read more
  • 0
  • 0
  • 2505
article-image-construct-game-development-platformer-revisited-2d-shooter
Packt
05 Jun 2012
11 min read
Save for later

Construct Game Development: Platformer Revisited, a 2D Shooter

Packt
05 Jun 2012
11 min read
(For more resources on Game Development, see here.) Before we start As there is a large amount of ground to cover in this chapter, we'll be moving quickly through steps similar to those we've done before. If it's been a while since you've used Construct, then you may find it useful to read through a chapter or two again before continuing, because certain steps assume that you are able to complete acO ons we have performed in the past. Multiplayer: getting your friends involved We're ready to start our next game, a multiplayer side-scrolling shooter, but before we add any shooO ng, we'll need to have the multiplayer side-scroller part finished first. So let's get to it! Time for action – creating the game assets and title screen The first thing we will need to do is to create our game content and create the first layout of the game, the title screen. First, draw up our player graphics and guns. We'll want the torso to be a separate object from the legs for easier animation. Use red dots where the legs will be attached to as markers for image point placement later on. Also include drawings for three weapons: a pistol, an uzi, and a shotgun: Next, we can draw up our enemies for the game. In this case, we'll use an enemy robot with a turret arm that shoots balls of plasma: We'll also need some scenery and ground objects for the levels: Finally, we'll need a graphic to tell the player to go onto the next screen when no enemies are present: Now we can move on to starting our game. Create a new project and set its Name to SideShooter, and enter your Creator name. Then set the window size to 800 by 600. Create the global variables CanGoNext, CurrentScreen, NumPlayers, P1Lives, P2Lives, GameWonLost, and RespawnY with values 0, 0, 1, 3, 3, 0, and 100 respectively. Following that, rename the first layout to Title and its event sheet to Title events . On this layout, create the layers Text, Buttons, and Background in top-to-bottom order. Selecting the Background layer, create a Panel object and name it Background before setting its top corner filters to Green and bottom corner filters to DarkGreen. Stretch this object to cover the whole of the layout and lock the layer. Now, on the Buttons layer, create a sprite and draw a box with the word Play in it. PosiO on this object in the center of the layout. This will be the start button for our game and should have the name btnPlay. Next, add the Mouse & Keyboard and XAudio2 objects into the layout and give them the global property. In order to finish the layout design, create a Text object on the Text layer and set its name to Title and its text to SideShooter, and position it above the btnPlay object: Switch over to the event sheet editor to add in a Start of layout event and use it to play a music file, Title.mp3, and loop it. This can be any title music you'd like, and it will also be played at the game's end screen. Next, create an event for the MouseKeyboard object with the condition Mouse is over object to check if the mouse overlaps btnPlay. Give this event the action Set colour filter for the btnPlay object to set the filter to Grey – 40. Now create an Else event to set the filter color back to White. In order to finish the event sheet, create an event with the condition On object clicked and select the object btnPlay. Add actions to this event to set the value of NumPlayers to 1 and the value of CurrentScreen to 0 before adding the final System action Next Layout: Time for action – designing the level Now that we have our graphics created, we can put them into our second layout and make the first playable level. Now we're ready to create a level layout. Create a layout and name it Level1 and its event sheet Level1 events . Then create our main game event sheet Game. For the layout, set its width to a multiple of the screen width (800), and check the box for Unbounded scrolling. In the event sheet of this layout, include our main event sheet Game. Next, give this layout the layers HUD, Foreground, FrontScenery, Objects, LevelLights, ShadowCasters, BackScenery, and Walls in top-to-bottom order. After that, set the ScrollX and ScrollY rates of the HUD and Walls layers to 0% On the objects layer, create a Tiled Background object named Ground and give it the smaller light gray tile image. Ensure it has the Solid attribute and stretch and place some of them to form a level design. Now create a Sprite object with the light green tile image and name it CrateBox . Give it the Solid attribute as well and place some around the level too. Have its collisions mode set to Bounding box. Next, create a Sprite named ExitLevel and fill it with a solid color. Give it a width of 32 and stretch it so that it's taller than the display height (600). Then finish the object by checking the box for Invisible on start and placing it at the end of the level: With the base layout complete, we can now add in three more invisible objects to handle scrolling. These are going to be Box objects with the names BackStopper, FrontStopper, and GoNextScreen. Have the BackStopper and FrontStopper objects colored red and marked Solid with a width of 120. Set the Hotspot property of the BackStopper object to Bottom-right, and the FrontStopper to Bottom-Left, before positioning them at 0,600 and 800,600 respectively. Next, have the GoNextScreen box colored green and a width of 32 as well as a Hotspot of Bottom-right. Position this object at 800,600: Time for action – creating player characters and conveyor belt objects Now we can create our player character objects and also add moving and staO c conveyor belts into our level. We are now ready to create our player objects. Start by inserting a Sprite and paste the standing image of the player character legs into it. Have an image point named 1 at the red spot that we drew earlier, and then place the hotspot at the bottom-middle point of the image ( num-pad 2) as shown in the following image: Name this sprite P1Legs, and for its Default animation, set the animation Tag to Stopped before checking the Auto Mirror checkbox in the main Appearance settings of the object. Next, give it the platform behavior with the settings shown as follows: Next, scroll down to the Angle properties box and check the Auto mirror checkbox. Now we are ready to add the object to a family. Scroll up to the Groups sub-group Families and click on Add to bring up the Construct: New Family screen. Note that Construct Classic comes with some default families, but will also display any family that have been used previously: Click on Edit Families to bring up the Construct: Families editor screen. On this screen, enter the name Legs and click on the + button: We can now draw the family image using the image editor that appears, shown as follows: After finishing the image, save it by exiting out of the image editor and check that the family is now in the list. Once finished, click on Done to return to the family selection page. Now select the Legs family and click on Ok: Now we can add the animation Walk in for our object. In this animation, set the Tag to Walking, and add the other leg sprites so they match the following image: Now change the settings of the animation to have an Animation speed of 5 and check the Loop checkbox. Next, copy the object and right-click on the layout to use the Paste Clone option, and name this clone as P2Legs. In the Platform behavior for this object, change the Control setting to Player 2 . Now go into the project properties and scroll to the bottom section, Controls. Click on the Add / Edit option for the Manage Controls setting at the bottom to bring up the controls box: Use the red X button to remove all of the controls below Jump. Then click on the Green plus button to add a new control. Select this control and click on the Pencil and paper button to change its name to Move Left. Click on the Key name for this control to bring up a drop-down box and set it to A. Now, in the Player drop-down box, select Player 2 for this control. It should match the following screenshot: Now continue to add controls until it matches the settings in the following screenshot before clicking on Done: Next, we'll create the bodies of our player objects. Create a Sprite called P1Torso and paste the normal body image of our character into it. Then position the Hotspot in the bottom-middle of the body. Give this sprite an image point 1 in the centre of its hand: Rename the Default animation to Normal and set its speed to 0, and check the Auto Mirror checkbox for this object as well. Create two more animations, Up and Down respectively. Set their frames to match the following screenshot: Now give the object a new family and name it Body. Then create Private Variables of names Weapon, Ammo, and GunAngle . Set the starting values to 0, 99, and 0 respectively. Clone this object as well to create P2Torso, and replace the sprites with the second player graphics. Now select P1Legs and scroll down to the Groups | Container properties to click on Add object and select P1Torso. The properties box and sprites should match the following screenshot: Next, put the P2Torso object into the container P2Legs using the same method. Now, on the Walls layer, create a Tiled Background object named FactoryWall and paste the dark wall graphic into it. Then resize it to 800 in Width by 600 in Height and set its position to 0,0 . The layout should look similar to the following screenshot: Switch to the FrontScenery layer and create a Tiled Background object called ConveyorMiddle, and give it the center piece of the conveyor belt images: Give this object the Private Variables of Direction and Speed with starting values of 0. Place these around the map to act as scenery, as well as using them as an object to move players with at certain points. Set the Direction variable to 1 to have the conveyor belt move right, and 2 to move left. Speed is the attribute used to determine how fast a player character is moved by the conveyor belt; a speed of 25 works well in this instance. The following screenshot shows a moving conveyor belt in the layout: On the same layer, create a Sprite with the name ConveyorStart and Collisions set to None. Use the starting conveyor belt image for this object and set the Hotspot to the middle-right (num-pad 6). Give this sprite the Attribute of Destroy on Startup. Create a second Sprite with the same setttigs called ConveyorEnd and a Hotspot in the middle-left (num-pad 4). Both sprites are shown in the following screenshot: Time for action – creating the HUD objects Now, we will move on to creating the Heads Up Display (HUD) objects for our game. We are now ready to create the HUD objects for our game. Switch to the HUD layer and create a Sprite called P1Face, and give it an image of the P1Torso head and set its Collisions mode to Bounding Box: Next, create a Text object called P1Info and set it up to match the following screenshot: Create similar objects replacing P1 with P2 for the second player. In this case, have the objects match the following layout screenshot: Now create a Text object for when the second player is not playing, and call it P2Join. Set its text to Press left control to join and have it matched to the following screenshot: Give it a Sine behavior to make it fade in and out by matching its settings to those in the following screenshot: Now create the final HUD item, a Sprite called NextSign, and place the next arrow image into it. Set the Collisions of this object to None:
Read more
  • 0
  • 0
  • 7433

article-image-basic-skills-traits-and-competencies-manager
Packt
29 May 2012
18 min read
Save for later

Basic Skills, Traits, and Competencies of a Manager

Packt
29 May 2012
18 min read
In India, being a Manager is highly valued. A majority of people see themselves taking a managerial position some day. However, can anyone become a manager? A really good manager? Are managers born or made? Do all managers, at least all good managers, share something in common? When we look around and see the journeys being taken by different managers, their working styles and behaviors, we can hypothesize that: Managers are born and made. Some folks have a natural flair to be a manager and some acquire essential skills to be a manager in a given situation. Not everyone may enjoy being a manager. While you may be 'promoted' to become a manager, you may find that you don't really enjoy the time spent talking to people, driving them to results, and compiling status reports for your management. It appears that good managers do have many things in common, even though they may have their own style of execution. In this article by Rahul Goyal author of Management in India: Grow from an Accidental to a Successful Manager in the IT & Knowledge Industry , we will explore the skills, traits, talents, and competencies that are usually required and expected for playing a manager role, and also burst some myths surrounding managers. (For more resources on management, see here.) Skills, traits, talents, and competencies We all have heard these terms. Let's try to understand what they mean and how they are different or similar to each other. Skills Skill is defined as the ability or capacity to do something, acquired through specific training. Skills are learned abilities. Technically, anybody can take a course in a specific subject and acquire that skill. Of course, the person should have the aptitude to learn those skills. Developing skills does not need to be in a formally-structured or schooled way. Babies develop motor skills as a natural process of learning. People develop communication skills, which are part formal learning and part informal learning. How well somebody can translate that acquired ability, that is, skill, goes beyond the definition of skill. In order to be an engineer, you need to acquire the engineering skills, or in order to become a chef, you need to acquire cooking skills. This alone will not make you a good chef or an engineer. Traits Traits are at the other end of the spectrum. Traits are personal. Traits are often linked to a person's character. Being shy is a trait. Some people are introverts and others are extroverts. Traits determine your response or behavior in a wide variety of situations. Some people are fearless by nature and others are cautious. Traits are often described in pairs of opposing behaviors; for example, extrovert-introvert and honest-dishonest. Many people consider traits to be innate, and that can definitely be true. However, it is not always true. There are traits that people develop by their upbringing and the environment they live in. As people progress through life they acquire new traits or modify ones they already have; these are called learned traits. Also, people display contradictory traits, so an honest person can become dishonest and vice versa. Talents Talent is an oft-used word in business today. A pure definition of talent from Webster's Dictionary (1913) is as follows: Intellectual ability, natural or acquired; mental endowment or capacity; skill in accomplishing; a special gift, particularly in business, art, or the like; faculty. It sounds like a lot of things, but the key phrases are intellectual, natural, and skill in accomplishing. Talents are supposed to be God's gift to you being applied to a specific craft or job. Specific application is the key phrase here.   It is very possible that Yuvraj Singh could have become a successful soccer player had he chosen to pursue that. Anyway, we are all glad that he chose cricket. Michael Jordan, the basketball legend, is an excellent golfer now and he tried his hand at professional baseball as well. Both Yuvraj and Jordan have most certainly a combination of different talents, such as physical stamina, focus, and discipline, which when applied to a particular sport created a great performance. Competencies Competencies are behaviors an employee displays in order to translate the knowledge and skills and leverage the traits to deliver a performance on the job. Competencies are related to a given job function. Hence different jobs will require different competencies. An offshore software engineer needs to have the necessary technical skills to write the code and written and verbal communication skills to effectively communicate across the world, among others. In this case, the communication competency is highly valuable, given the offshore nature of the work. If the job description changes to that of a software engineer working as a database administrator, a slightly different set of competencies apply. While related technical skills are very important, in this case, expertise will be desired given the fact that databases are critical to the business and scope for errors is less. Communication competencies are always required but basic communication may be enough for this function. However, a meticulous attitude and handling high levels of stress will be important, given the requirement criticality of the infrastructure. Competencies are the application of all that we know and can do. Almost all employers describe a job function in terms of competencies and results required. Also, almost all employee appraisal forms will attempt to grade people in terms of competencies on some scale. For example, a competency of 'Result Orientation' may be measured on a scale of 1 through 5, and an appraiser may be advised to comment on the reasons behind the rating. Top skills, traits, and competencies expected of a manager Let's look at some key skills, traits, and competencies that are expected of a good manager. Love of working with people Most managers will spend a majority of their time managing people, and everything that is connected with people, even more so in the knowledge industry. Do you find yourself talking to people all the time? Do people tend to bring their problems to you? And when they do so, do you see it as adding value to finding a solution, or do you see that as a headache which you shouldn't have to deal with? If you find satisfaction in just being with people and helping them achieve their results, you have a primary quality to be a manager. Going to parties and having a good time with people also displays that you love being around people and surely shows your love for food or drink, but not the essential part of helping people achieve their goals. Although all interactions count, including phone conversations, e-mail, or Instant Messenger, it's the face time that has the most impact. If you'd rather spend your time in your own office by yourself, perhaps a manager role isn't for you. You can, of course, force yourself to spend time with people as part of the job requirement, but unless you really enjoy that time, it will be hard to sustain and excel as a manager. You may end up limiting your interactions to a select few, where comfort levels are high, at the risk of alienating others. Global managers today get less and less face time with some of their team members, sometimes as little as 12 hours in the entire working year. Without the love of working with people, the interaction with remote workers can really become difficult, as it'll take an extra effort to be connected at a deeper level than just work. If you like to work with people, you are likely to be high on empathy. When people approach you with a problem, you may feel the problem to be your own. Even before the person tells you there's a problem, you already know there is a problem by the look on his/her face, the voice, and the body language. Your body language will be inviting and welcoming. While the person describes their problem to you, you listen intently and non-judgmentally, even supporting them so that he/she is encouraged to open up. If you are high on empathy, you may also have a feel of what kind of suggestion will work with this person and how it should be put across. You follow up and when you see the person getting over the problem you feel a sense of satisfaction. Empathy also helps in understanding and working in a diverse environment, for example, working with people who grew up culturally different from you. Especially in India, there is a high degree of diversity with people from different backgrounds, and also while the working population is highly skewed towards men, women have a growing presence, especially in the knowledge industry. Please note that a manager doesn't have to be an extrovert to love working with people. Extroversion is often equated with being outgoing, and that isn't the same as having a love of working with people. Myth: nice manager Sometimes managers wish to be seen as popular, someone who everyone wants to work for. A nice manager, who listens to his people and rarely says no to anything, be it taking vacations or a promotion. Being a people person doesn't mean being nice all the time. While being a people person is a great thing, usual business rules still apply. A good manager balances the priorities of the people and business and can be nice and tough at the same time. Easy to approach While you may love to work with people, the people around you should also love to work with you, and a measure of that is the number of people who feel comfortable coming up and talking to you. A non-threatening, if not friendly, demeanor would certainly help. But even more important is the rest of the interaction that will follow. Do people come to you for problem solving and leave with more problems to solve? Do they come to you to share the overload of work and leave with more work to do? Is there a fair give and take in your interactions with people? Myth: I'm easy to approach, I have an open door policy Approachability is not to be confused with accessibility. Accessibility is a measure of the number of channels and the time you are accessible to others. Today, channels of accessibility are hardly an issue, given the multiple modes of contact, including Instant Messengers. Time availability will always remain an issue and you'll have to consciously make time for people. Approachability isn't the same as availability or an open door policy. Your approachability is defined by the way you respond to people's attempts to get in touch with you. Do you respond quickly and positively, or do you buzz them off for a few days? Do you have a friendly disposition towards people? Do you let people speak? Do you listen to what they have to say before responding? All of these define the degree of approachability you exhibit. Farmer mentality: sow, nurture, grow, reap There are thousands of types of jobs, but none of them is as involved, as complete, and perhaps as spiritual as farming. It requires hard work, investment, belief, knowledge, teamwork, patience, faith, ownership, and a sense of creativity. And of course, the elements of risk, especially in India where farmers still depend on the monsoon. Farmers go through a cycle of preparation, investment, nurturing, protection, seeing it grow, and then enjoying the benefits of all the effort. They go through this year after year and while they make it better every cycle, they take the losses when decisions go bad. Nevertheless, the basic approach remains the same. Managers need to develop the traits of a farmer. You need to have a sense of preparation and investment, since it's the most basic, key part of the process and then wait while nurturing and supporting for the benefits to roll in. This needs to be done with every person, process, and project. Myth: fast moving managers—in a tearing hurry Some people believe that a hotshot manager is always juggling many tasks and pushes everyone to move faster, but that simply isn't true. Most exceptional managers have a farmer mentality. Farmers are always required to be patient. You can't push certain processes to be faster than the natural cycle. You can help and catalyze, but improvements are usually marginal and need to be evaluated for the long term. Too much of anything, even the catalyst, can yield bad results. Managers also need to be patient and respect the personal growth cycle for each individual and for different processes. Managers can help catalyze the process but need to allow the cycle to take it's own course. Once a growth or improvement cycle is over, the next growth cycle can start. Core values: honesty, integrity, truthfulness, trustworthiness, consideration for others, and more There is no substitute for core values like honesty, integrity, and trustworthiness. These are very important for any employee in general, and are even more important for managers, as managers have a high impact on people and processes. There will be many challenges that will come a manager's way and many decisions that managers need to make. Core values will be a guide in all of these. Many questions cannot be answered by looking at the rulebook, but very easily answered by using the value system yardstick. There will be lots of opportunities for a manager to make quick gains, by using a shortcut and possibly lowering the value standard. This would usually be impossible to sustain, and will come back to haunt you in the longer term. Consider this: Vijay comes to his manager's office and expresses the monetary problems he is facing. He is a good contributor and quite important to the current project. Vijay mentions that he has an offer for about 30 percent more than what he makes right now and although he likes the company, he'd like to resign. The manager's options are to relieve him in a month's time or promise him more than 30 percent in a few months' time when the annual salary revision is due. The manager knows that it may not really be possible to give Vijay 30 percent because the expected budget may not allow that; however, Vijay may stay until then and the project will be past the critical stage. At the same time, the manager is not breaking any rules, as he is fine with giving Vijay a 30 percent raise if the budget is available, plus the manager can always say that upper management rejected the change. Even simpler situations such as taking a day off for being sick while you are really not or using the official network and resources to watch adult material or taking office stationary home are all situations which call for basic values to be applied. Values are the foundation of good behavior and nothing less is expected from a leader. Not a myth: corporate greed The recent financial crisis the world underwent is a grim reminder of corporate greed, which of course is a result of a few individuals propagating a culture of greed through the system. Poor governance and integrity standards have led to many a scandal with dire consequences. Satyam in India or Worldcom in the US have cost thousands of jobs and the loss of credibility for the entire industry. Tolerance for ambiguity and patience We all know: the better the map, the easier it is to follow, but unfortunately the working map in an organization is not always clear. Sometimes the destination is not clear and there are multiple ways to get there and also, there are too many detours. You'd be lucky if the map does not change half way through. It would be great if the directions to follow were clear, but who is supposed to make it clear and easy to follow? A manager needs to deal with this ambiguity—find the best way given all the other factors. Ambiguity is the order of today's knowledge industry. A lot of things are fuzzy and need definition. It takes time to remove some of the fuzziness, and a manager needs to deal with it. It will require tolerance for fuzziness and patience to figure it out. Some people are pre-disposed to display patience, and others can learn to be patient. Patience defines the quality of your daily interactions, your responses, and some people believe, your respect towards others' opinions. Simple day-to-day necessity, like good communication, requires you to be patient. Patient people wait for others to complete their thoughts so they can take the time to respond well and with complete information. Good communication skills—especially listening Communication is the bread and butter for a manager. There is a lot of information which needs to be processed and communicated by a manager in all directions, to his directs and beyond, to his management chain, and also to many other parallel groups. Communication is NOT smooth talking. Many people confuse good communication with fast talking or smooth talking, where one person dominates a discussion and the other party. Good communication is not a love of talking. A rather quiet person, who can listen to others and respond with clarity, is a much more powerful communicator than somebody who simply loves to talk. Communication includes all forms of communication, the usual written communication such as e-mail and formal memos, letters, and so on. New age communication such as SMS, Instant messaging, and so on, and verbal communication, via phone or video conference and with the person face-to-face. Body language is also part of communication, although it's becoming less of a factor given that a majority of communication is not face-to-face anymore. Even people who sit half a floor away communicate via e-mail or IM. The tone of your voice over phone or tone of your instant message plays an important part in perception of the message. Good communication skills also include understanding your audience and communication in such a way that the audience can understand and communicate back to you. As such, your communication style will change a little based on the audience it's intended for. Finally, the single biggest factor in good communication is listening. Unfortunately, the importance of listening gets lost very often and a large population of people suffer from a lack of listening. Especially in India, people tend to cut into a discussion or start talking before the other person has finished, and perhaps get impatient to answer with the assumption that they know what the other person is talking about. Indian managers do need to work twice as hard to develop good listening skills. Myth: quiet people can't be managers Many people believe that managers are people who stand up and speak at every opportunity. It's not uncommon to see meetings where the manager takes all the talking time with very little being said by anyone else. Remember the term talkative. The term instantaneously takes us back to middle school, when kids who would talk too much in the class were called talkative. It's often believed that managers need to be talkative. At every opportunity they get, they talk. It is indeed true that a large number of managers tend to talk too much, and unfortunately the problem grows over the years. Over time, people tend to avoid managers who ramble. You can be a quiet person as such, and as long as you don't shy away from speaking when it is required, quietness will be a strength. I have been fortunate to meet a lot of highly successful managers, who are quiet by usual standards but have an impeccable record of delivery and team management. Team building—hiring, retaining, developing good people, and nurturing team spirit Another key competency for a manager is to be able to build teams. Although, at a literal level, a team is made up of a set of people, in reality a team isn't really a team without the binding glue called team spirit. A manager is as good as the team he/ she builds. A manager's capacity and ability to deliver is equal to the capacity and ability of the team. To start with, building teams requires good hiring skills. It requires: Position identification. Defining skill requirements for the position. Defining the process for identification and skills testing. Most organizations will have a pre-defined process and supporting team to do this. Look for fitment. Deciding appropriate compensation. Following required organizational process for completing the hiring process. Besides having a team, it is important to configure a team. For example, a team of 10 people may need to be balanced in terms of experience, youth and freshness, and a variety of technical skills. A team needs to have defined positions and each team member should know what role and position he/she is supposed to play. Finally, a manager needs to create an environment to foster team spirit and bonding, so that a set of people works as a team and not as multiple individuals. Once a team is in place, a manager needs to constantly nurture the team and also the individuals. Most people love to work in a team, but they are individuals too and have unique needs and aspirations. This will lead to better retention, which is a definite success criterion for a manager in today's knowledge industry.
Read more
  • 0
  • 0
  • 13811

article-image-1z0-451-oracle-soa-foundation-practitioner-exam-reference
Packt
28 May 2012
9 min read
Save for later

1Z0-451: Oracle SOA Foundation Practitioner Exam Reference

Packt
28 May 2012
9 min read
  (For more resources on Oracle SOA, see here.) SOA concepts The service-oriented architecture concepts are as follows: Service Component Architecture (SCA) is the key enabler of the 11g service platform. SDO provides a metadata API, which allows applications, tools, and frameworks to introspect the data model for a data graph. SDO specifications are different from SCA specifications. SCA promotes the use of SDO to represent the business data for assembly and transportation. Business events are not currently part of SCA specifications; they are in the process of getting incorporated into SCA specifications. JCA contributes towards the SOA application standard to establish communication between different applications or enterprise information system such as file, database, queue, topic, and so on. XQuery is an XML traversal path in an XML document to obtain information about a node or a subset of nodes. UDDI is a standard method for publishing and discovering SOA components. WS-Reliable Messaging supports standards to transmit messages with high reliability to enable the QOS. WS-Addressing, WS-I, WS-Security are standards that supplement the WS-RM standards. WS-Coordination supersedes WS-Transaction and WS-AtomicTransaction in defining the context management properties for Web Service transaction management. Oracle has intentionally not implemented nested SCA specifications as the nested composite application implementation leads to circular reference issue. SOA composite applications The key components that build the SOA composite applications are as follows: Oracle BPEL process components used for process/service orchestration. Oracle Business Rule components used for centralized services/ process-related business rule implementation and execution. Various adapter services such as file, JMS, and database adapters. Oracle Mediator components used for filter, data transformation, and routing. Oracle Human Task components used to define the human actions to be executed in the business process flow. EDN that supports an event-driven architecture for event-driven applications. Wires are used to create interaction between service end points, components, and references in SOA composites. A composite is the unit of deployment for SCA. It holds services that can be accessed remotely and it contains one or more components. SCA components are integrated together into one application and communicate with the outside world through binding components such as adapters and Web Services. The ADF BC component can be configured to publish events for the CRUD operations it can perform. SCA provides an assembly model for SOA-style applications. SCA components are basic elements of business functions in an SCA assembly. Components are combined into complete business solutions by SCA composites. Oracle User Messaging Service (UMS) provides a common service responsible for sending out messages from applications to devices. Service interactions within SOA Suite are handled using Oracle Mediator. Service Virtualization cannot be achieved using Mediator. Oracle Service Bus or Enterprise Service Bus is required to carry out Service Virtualization. Only mediation of a service can be achieved using Oracle Mediator. The BPEL/BPM Engine represents the orchestration component of SOA infrastructure. Oracle BPEL Engine supports BPEL 1.1 and 2.0. Incoming and outgoing XML documents for a Partner Link can be validated by setting the validateXML property on a Partner Link to true. Metadata Service (MDS) allows you to share common artifacts such as XML schemas across SOA composites. It supports two types of repositories, namely, file-based repository and database repository. The Service Infrastructure provides the internal message routing infrastructure capabilities for connecting components and enabling data flow. The Service Infrastructure is responsible for the internal routing of messages between service engines and binding components. Weblogic JMS is used as a messaging layer for delivering events through EDN. EDN can also be configured to use EDN-DB. EDN-DB uses an Oracle database as a backend store. Event definitions are stored in the EDL file. Event Delivery Network can work across SOA Suite. Business Activity Monitoring (BAM) is used for visualizing and monitoring business activity. Oracle Service Registry supports UDDI V3 standard. Working with adapters Adapters are used in Oracle SOA Suite 11g to connect to non-service enabled backend systems. File adapter supports four types of operations: read file, write file, synchronous read, and list files. FTP adapter supports four types of operations: get, put, synchronous get file, and list files. Oracle FTP and file adapter do not support XA transaction. XA transaction is supported by all JCA-compliant adapters (for example: DB, JMS, AQ adapter). Inbound adapter-rejected messages are handled through fault policies. The SCA component should participate in the XA transaction and the other adapter should not have the idempotent property enabled. Fault policy doesn't work for both outbound adapters in XA mode and outbound adapters with Mediator in sequential routing. Oracle file adapter provides an option to delete the files after processing. This can be enabled by selecting delete after processing the checkbox in the Adapter Configuration Wizard. Larger payload support is available in Oracle File Adapter. The Oracle adapters support metadata service. The Oracle File Adapter and the FTP adapter provide the features to read the metadata information such as filename, file modified date, and so on. The 'Do not read file content' option in the file adapter helps to achieve this. Adapter Configuration Wizard is the required feature to generate the WSDL for both the request-response and event-notification service. Orchestrating services with BPEL The following image shows the list of BPEL activities: The standard BPEL constructs are given in the following table: S.No Construct Details 1 Invoke Provides the feature to invoke the required Partner Link. 2 Partner Link Partner Link is a Web Service or adapter that is called from the BPEL process. 3 Receive Receive activity can be used to receive the message to the BPEL process. This can be used at the start or in the middle of the BPEL process. 4 Reply Reply activity is used to reply back to the caller of the message. This is used by the BPEL process in synchronous communication. 5 Assign Assigns the variables to values or expressions. 6 Compensate The Compensate activity is a business activity that compensates for the previous executed steps. 7 Empty The Empty activity is used to represent that no action is required on the branch of Flow or While. 8 Terminate The Terminate activity ends the BPEL process execution. 9 Throw Throw activity throws the fault that is captured in the Catch block or the Fault that is constructed in the Catch All block. 10 Wait The Wait activity provides features to pause the BPEL process execution for a specified period of time. 11 Flow The Flow activity  is a unique activity for BPEL. It helps to run tasks in parallel. There are two types of Flow activities. 12 Pick Pick  is also a unique activity for BPEL. This activity is used to receive the message from various different Partner Links. It is used in an asynchronous BPEL process. This can also be used at the start or in the middle of the BPEL process. 13 Scope Scope  is the activity used to group the set of BPEL activities for logically grouping a set of actions to handle faults, define local variables for manipulation, and so on. 14 Sequence Sequence is another grouping construct that is used to sequence the list of BPEL activities. 15 Switch Switch is used in a very similar way to Switch Case constructs in C programming language. 16 While While is a looping construct that is used to execute the list of actions until the condition specified in While constructs return to false. 17 If (BPEL 2.0) Switch is replaced with If in BPEL 2.0. This construct helps us perform the if-else operations. 18 Repeat Until (BPEL 2.0) This is an additional construct introduced in BPEL 2.0 to repeat certain actions until the condition is met. 19 ReThrow (BPEL 2.0) This is an additional construct that allows you to re-throw the fault caught in the Fault Handler block. 20 ForEach (BPEL 2.0) This is an additional construct introduced in BPEL 2.0. This will replace the FlowN construct by allowing parallel execution.   The Oracle extensions to BPEL constructs are given in the following table: S.No Construct Details 1 E-mail Activity to send an e-mail to any target recipient. 2 User Notification Uses the UMS (Unified Messaging Framework) to send SMS, e-mail, IM, and voice messages. 3 Validate Validates a variable data against the schema definition. 4 IM Sends an instance message to the required person. 5 Checkpoint Checkpoint activity helps to dehydrate the BPEL process to the database. 6 Phase This is a special purpose activity which helps to construct an output message based on the business rules defined around the inputs message. This can be used as a replacement for data transformation where multiple condition checks are used. 7 Voice This activity enables the sending of a telephone voice notification. 8 Signal This activity is used in the master process to send a signal to the detailed process. 9 Receive Signal This activity is used in the detail process to receive a signal sent from the master process. 10 Create Entity This activity allows the creation of an entity variable. 11 Bind Entity This activity allows the binding of an entity variable. 12 Transformation This activity allows the calling of an XSLT function from BPEL. BPEL schema validation can be done to validate activity. BPEL exposed as a service can have multiple operations. The process will not be terminated when a fault is thrown from the BPEL process. Pick without Alarm can be the first activity in the BPEL process. Pick cannot be the very first activity in the BPEL process. Events can be generated from BPEL. Fault policies can be used to handle a composite fault as well as a component-level fault. SyncMAxWait is a BPEL container property that controls the synchronous response time of a BPEL. If the BPEL doesn't respond to the caller within this wait time, the BPEL transaction will be timed-out. The doTransformation function takes multiple input parameters for transformation. Wait, Checkpoint, Pick, Mid-process receive activities will dehydrate a BPEL process forcefully.
Read more
  • 0
  • 0
  • 2191
article-image-understanding-true-security-posture-network-environment-being-tested
Packt
28 May 2012
4 min read
Save for later

Understanding the True Security Posture of the Network Environment being Tested

Packt
28 May 2012
4 min read
(For more resources on Open Source, see here.) Getting files to and from victim machines Getting root on a remote machine can be interesting and is definitely a major step in the right direction (and depending on your scope and the purpose of the test, could be the only step necessary). If your task is not complete, then you will need to find methods of transferring data to and from your victim machines. There are several tools that will assist in this task; here are a few that may make your life easier in the long run. Installing and starting a TFTP server on BackTrack 5 TFTP can be very handy at times. Many systems will already have a TFTP client installed and using this protocol is quick and easy. # apt-get install atftpd Be sure that your BackTrack machine is Internet enabled during the installation. To familiarize yourself with the atftpd server type atftpd at the command prompt without any additional input. Starting TFTP as a standalone daemon pointing to /tmp on the standard port and bound to IP address 192.168.75.12 can be accomplished by typing: # atftpd --daemon --port 69 --bind-address 192.168.75.12 /tmp You can check to see if the daemon started correctly by invoking netstat and grepping for 69. # netstat -anu |grep 69 If everything started correctly you should see something similar to: udp        0      0 192.168.75.12:69        0.0.0.0:* Installing and confguring pure-ftpd If your version of Backtrack does not have pure-ftpd installed it may be added by using the apt-get install pure-ftpd command. For full functionality of pure-ftpd you will need to add users and perform other minor confguration changes prior to use. # echo /etc/pure-ftpd/pureftpd.pdb > PureDB Adds /etc/pure-ftpd/pureftpd.pdb to the PureDB confguration fle: # ln -s /etc/pure-ftpd/conf/PureDB /etc/pure-ftpd/auth/50pure Creates a symbolic link to the 50pure fle: # groupadd -g 7777 ftpz Adds a group to the BackTrack guest machine: # useradd -u 7777 -s /bin/false -d /dev/null -c "pureFTP" -g ftpz Testerz Create folders that will be used: # mkdir /var/ftp /var/ftp/public /var/ftp/public/ftplogin Modify the ownership: # chown -R Testerz:ftpz /var/ftp/public/ftplogin Adds the account to the system: # pure-pw useradd ftplogin -u Testerz -d /var/ftp/public/ftplogin Password: password Enter it again: password Sets up a virtual account that can be used with FTP connections: # pure-pw mkdb Reloads the database: # pure-pw show ftplogin Performs a quick lookup in the Pure-FTP database to let us know the user statistics. Login              : ftplogin Password           : $1$/NF5jAg0$I0oRJKViA5NYs455Afelr1 UID                : 7777 (Testerz) GID                : 7777 (ftpz) Directory          : /var/ftp/public/./ Full name          :  Download bandwidth : 0 Kb (unlimited) Upload   bandwidth : 0 Kb (unlimited) Max files          : 0 (unlimited) Max size           : 0 Mb (unlimited) Allowed local  IPs : Denied  local  IPs :  Allowed client IPs :  Denied  client IPs :  Time restrictions  : 0000-0000 (unlimited) Max sim sessions   : 0 (unlimited) Starting pure-ftpd The following command will start pure-ftpd: #/etc/init.d/pure-ftpd start You will be presented with the following output: Starting ftp server: Running: /usr/sbin/pure-ftpd -l pam -8 UTF-8 -E  -u 1000 -O clf:/var/log/pure-ftpd/transfer.log -B This server can be tested by connecting to localhost: # ftp 127.0.0.1 The output should be similar to the following: Connected to 192.168.75.12. 220---------- Welcome to Pure-FTPd [privsep] [TLS] ---------- 220-You are user number 1 of 50 allowed. 220-Local time is now 17:02. Server port: 21. 220-IPv6 connections are also welcome on this server. 220 You will be disconnected after 15 minutes of inactivity. Name (192.168.75.12:root): ftplogin 331 User ftplogin OK. Password required Password: 230-User ftplogin has group access to:  7777       230 OK. Current directory is / Remote system type is UNIX. Using binary mode to transfer fles. ftp> Production versus a controlled test lab environment: Consider setting up a dedicated user account and appropriate security measures on your production BackTrack instance. Make certain to provide FTP accounts with the necessary permissions to write files otherwise; expect to receive errors when making these attempts from victim machines.
Read more
  • 0
  • 0
  • 1875

article-image-supporting-hypervisors-opennebula
Packt
25 May 2012
7 min read
Save for later

Supporting hypervisors by OpenNebula

Packt
25 May 2012
7 min read
(For more resources on Open Source, see here.) A host is a server that has the ability to run virtual machines using a special software component called a hypervisor that is managed by the OpenNebula frontend. All the hosts do not need to have homogeneous configuration, but it is possible to use different hypervisors on different GNU/Linux distributions on a single OpenNebula cluster. Using different hypervisors in your infrastructure is not just a technical exercise but assures you greater flexibility and reliability. A few examples where having multiple hypervisors would prove to be beneficial are as follows: A bug in the current release of A hypervisor does not permit the installation of a virtual machine with a particular legacy OS (let's say, for example,Windows 2000 Service Pack 4), but you can execute it with B hypervisor without any problem. You have a production infrastructure that is running a closed source free-to-use hypervisor, and during the next year the software house developing that hypervisor will request a license payment or declare bankruptcy due to economic crisis. The current version of OpenNebula will give you great flexibility regarding hypervisor usage since it natively supports KVM/Xen (which are open source) and VMware ESXi. In the future it will probably support both VirtualBox (Oracle) and Hyper-V (Microsoft). Configuring hosts The first thing to do before starting with the installation of a particular hypervisor on a host is to perform some general configuration steps. They are as follows: Create a dedicated oneadmin UNIX account (which should have sudo privileges for executing particular tasks, for example, iptables/ebtables,and network hooks that we have configured. The frontend and host's hostname should be resolved by a local DNS or a shared/etc/hosts file. The oneadmin on the frontend should be able to connect remotely through SSH to the oneadmin on the hosts without a password. Configure the shared network bridge that will be used by VM to get the physical network.   The oneadmin account and passwordless login Every host should have a oneadmin UNIX account that will be used by the OpenNebula frontend to connect and execute commands. If during the operating system install you did not create it, create a oneadmin user on the host by using the following command: youruser@host1 $ sudo adduser oneadmin You can configure any password you like (even blank) because we are going to set up a passwordless login from the frontend: oneadmin@front-end $ ssh-copy-id oneadmin@host1 Now if you connect from the oneadmin account on the frontend to the oneadminaccount of the host, you should get the shell prompt without entering any password by using the following command: oneadmin@front-end $ ssh oneadmin@host1 Uniformity of oneadmin UID number Later, we will learn about the possible storage solutions available with OpenNebula. However, keep in mind that if we are going to set up a shared storage, we need to make sure that the UID number of the oneadmin user is homogeneous between the frontend and every other host. In other words, check that with the id command the oneadmin UID is the same both on the frontend and the hosts. Verifying the SSH host fingerprints The first time you connect to a remote SSH server from a particular host, the SSH client will provide you the fingerprintprint of the remote server and ask for your permission to continue with the following message: The authenticity of host host01 (192.168.254.2)can't be established. RSA key fingerprint is 5a:65:0f:6f:21:bb:fd:6a:4a:68:cd: 72:58:5c:fb:9f. Are you sure you want to continue connecting (yes/no)? Knowing the fingerprint of the remote SSH key and saving it to the local SSH client fingerprint cache (saved in ~/.ssh/known_hosts) should be good enough to prevent man-in-the-middle attacks. For this reason, you need to connect from the oneadmin user on the frontend to every host in order to save the fingerprints of the remote hosts in the oneadmin known_hosts for the first time. Not doing this will prevent OpenNebula from connecting to the remote hosts. In large environments, this requirement may be a slow-down when cofiguring new hosts. However, it is possible to bypass this operation by instructing the remote client used by OpenNebula to connect to remote hosts and not check the remote SSH key in ~/.ssh/config. The command prompt will show the following content when the operation is bypassed: Host* StrictHostKeyChecking no. If you do not have a local DNS (or you cannot/do not want to set it up), you can manually manage the /etc/hosts file in every host, using the following IP addresses: 127.0.0.1 localhost 192.168.66.90 on-front 192.168.66.97 kvm01 192.168.66.98 xen01 192.168.66.99 esx01 Now you should be able to remotely connect from a node to another with your hostname using the following command: $ ssh oneadmin@kvm01 Configuring a simple DNS with dnsmasq If you do not have a local DNS and manually managing the plain host's file on every host does not excite you, you can try to install and configure dnsmasq. It is a lightweight, easy-to-configure DNS forwarder (optionally DHCP and TFTP can be provided within it) that services well to a small-scale network. The OpenNebula frontend may be a good place to install it. For an Ubuntu/Debian installation use the following command: $ sudo apt-get install dnsmasq The default configuration should be fine. You just need to make sure that /etc/resolv.conf configuration details look similar to the following: # dnsmasq nameserver 127.0.0.1 # another local DNS nameserver 192.168.0.1 # ISP or public DNS nameserver 208.67.220.220 nameserver 208.67.222.222 The /etc/hosts configuration details will look similar to the following: 127.0.0.1 localhost 192.168.66.90 on-front 192.168.66.97 kvm01 192.168.66.98 xen01 192.168.66.99 esx01 Configure any other hostname here in the hosts file on the frontend by running dnsmasq. Configure /etc/resolv.conf configuration details on the other hosts using the following code: # ip where dnsmasq is installed nameserver 192.168.0.2 Now you should be able to remotely connect from a node to another using your plain hostname using the following command: $ ssh oneadmin@kvm01 When you add new hosts, simply add them at /etc/hosts on the frontend and they will automatically work on every other host, thanks to dnsmasq. Configuring sudo To give administrative privileges to the oneadmin account on the hosts, add it to the sudo or admin group depending on your /etc/sudoers configuration using the following code: # /etc/sudoers Defaults env_reset root ALL=(ALL) ALL %sudo ALL=NOPASSWD: ALL With this simple sudo configuration, every user in the sudo group can execute any command with root privileges, without requiring to enter the user password before each command. Now add the oneadmin user to the sudo group with the following command: $ sudo adduser oneadmin sudo Giving full administrative privileges to the oneadmin account might be considered inappropriate for most security-focused people. However, I can assure you that if you are taking the first step with OpenNebula now, having full administrative privileges could save some headaches. This is a suggested configuration but it is not required to run OpenNebula. Configuring network bridges Every host should have its bridges configured with the same name. Check the following /etc/network/interfaces code as an example: # The loopback network interface auto lo iface lo inet loopback # The primary network interface iface eth0 inet manual auto lan0 iface lan0 inet static bridge_ports eth0 bridge_stp off bridge_fd 0 address 192.168.66.97 netmask 255.255.255.0 gateway 192.168.66.1 dns-nameservers 192.168.66.1 You can have as many bridges as you need, bound or not bound to a physical network. By eliminating the bridge_ports parameter you get a pure virtual network for your VMs but remember that without a physical network different VMs on different hosts cannot communicate with each other.
Read more
  • 0
  • 1
  • 16566
Modal Close icon
Modal Close icon