Josh-CO Dev

Solving the worlds problems one line of code at a time.


1 Comment

Automating a WebInspect Scan using PowerShell and the WebInspect API

I have been struggling with the WebInspect API for quite some time now. It seems that I could always call the get methods just fine, but some of the post methods had some weird syntax that I could never figure out. After a lot of trial and error, I finally figured out how to use PowerShell to start a scan with the WebInspect API. I am posting this here hoping it will help out others. It seems that Google does not turn up anything on the API other than some HP help files which really do not help.

$wiapiScan = "http://vmwebinspect01:8083/webinspect/scanner" #set this to the location of your webinspect API instance

$body = @{
    settingsName="Default"    #the settings name to use for this scan
    
    overrides= 
    @{
        ScanName="Testing"    #The name to give the scan
        StartUrl="http://scrubbed"   #the url to scan
        CrawlAuditMode="CrawlOnly"   #crawl, audit, or both.
        StartOption="Url"    #refer to the API documentation for the other options
    } | convertto-json
} 

$response = Invoke-webrequest -Method Post -Body $body -Uri $wiapiScan #put it all together

Be sure that $wiapiScan is set to point to your WebInspect instance. Remember that the API has to be configured and started wherever you are hosting WebInspect. In my case, I am using a dedicated VM.


Leave a comment

PowerShell – Browser Automation

I have had a need to perform browser automation for some time. Apparently, this can be done pretty easily with PowerShell, providing you have a basic understanding of the DOM and how to manipulate it.

Start by create an Internet Explorer object. I know, I know. Internet Explorer. PowerShell is Microsoft, so just get over it. We all know it sucks.

#create a new browser object to handle all of our navigation
    $Browser = New-Object -com InternetExplorer.Application

If you want to watch the automation, which you do because it’s cool, be sure to set the visible property to true.

#go ahead and show the browser window
    $Browser.visible = $true

To browse to a specific url, just use the navigate method.

#Navigate to the URL Defined above
    $Browser.navigate("www.google.com") 

In some cases, you need to tell the thread to sleep for an arbitrary amount of time. Otherwise the script will just keep running and you won’t accomplish much. I put a statement similar to this after almost every call.

#Sleep the thread while the page is loading
    Start-Sleep -Milliseconds 1000;

To click on an item, you need to know it’s name in the DOM

$Browser.Document.getElementByID("overridelink").Click()

You can set the value of a text-box

$Browser.Document.getElementById("tbName").value = $reportName

Check a box

$Browser.Document.getElementById("CheckBoxList1_1").checked = $true

There’s a lot more that can be done. Play around with the Browser.Document properties a little bit. In the end, it’s a lot easier to use a tool like Auto IT, but it’s cool to script out some automation.


Leave a comment

PowerShell – Delete folders older than a certain timeframe based on a filename

I was recently asked to come up with a script that will go through a directory and delete any folders based on a naming convention. The naming convention was something like 20150730…….The obvious pattern here is YYYYMMDD……. Now that we know this, a loop and some substrings are our friend.

$directory = "directory to purge"

Get-ChildItem $directory | Where-Object {$_.PSIsContainer} | ForEach-Object {
    $DirName = $_.Name

    $DirYear = $_.Name.Substring(0,4)
    $DirMonth = $_.Name.Substring(4,2)
    $stringDate = $DirMonth + "/01/" + $DirYear

    $FolderDTime = [datetime]$stringDate
    
    $Today = get-date

    $timespan = NEW-TIMESPAN –Start $Today –End $FolderDTime

    if ($timespan.Days -lt -365) {
        Remove-Item $_.FullName
        write-output ((get-date).ToShortDateString() + " - " + $DirName + " was deleted") | out-file -append "C:\LogRhythmArchives\Inactive\del_archives_log.txt"
    }

} 

So, let’s break this down.

Get-ChildItem $directory | Where-Object {$_.PSIsContainer} | ForEach-Object {

This is our for loop. This does a Get-ChildItem of $directory. Be sure to set this variable to the folder you want to loop through. The where object is a weird powershell way of saying, exclude files and only give me directories.

    $DirName = $_.Name
    $DirYear = $_.Name.Substring(0,4)
    $DirMonth = $_.Name.Substring(4,2)
    $stringDate = $DirMonth + "/01/" + $DirYear

First, take our goofy name and throw it into a variable. Use a substring to pull the first four characters to make the year, then similarly for the month. Now we use concatenation to build a fake date.

$FolderDTime = [datetime]$stringDate

$Today = get-date

    $timespan = NEW-TIMESPAN –Start $Today –End $FolderDTime

Now, we can take our fake date string and tell powershell to force it into a date time object. Now that we have this, we can create a timespan object to determine the length of time between the file name and today.

    if ($timespan.Days -lt -365) {
        Remove-Item $_.FullName
        write-output ((get-date).ToShortDateString() + " - " + $DirName + " was deleted") | out-file -append "del_archives_log.txt"
    }

Finally, we check to see if the timespan is greater than 365 days. They way I did the timespan creation, we get left with a negative number so we check less than. Now we can call remove-item to permanently delete the file, and write our output to a log.

Please note, remove-item does not send the items to the recycle bin. It is a permanent deletion.


Leave a comment

XNA – Basic Inventory Tutorial, Harvesting

Yet another from the archives. I apologize that I’ve still been unable to get part 2 of the inventory system. It’s kind of needed for this to work, but I’m sure some of you can put something together with it.

To further build on our tutorials for our basic inventory system, let’s add a basic system to harvest our resources. In my code, I have added a new folder named crafting which I intend to use for anything even remotely crafting related. I then created a new class called Harvesting.cs. Here is the code:

using System;
using FarmGame.Inventory;
using FarmGame.TileEngine;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace FarmGame.Crafting
{
    static class Harvesting
    {
        public static void Harvest(GameObject go, ref PlayerInventory CurrentInventory, ref List objects, ContentManager cm)
        {
            if (go.thisType == GameObject.ObjectType.rock)
               HarvestRock(go, ref CurrentInventory, ref objects, cm);
            if (go.thisType == GameObject.ObjectType.bush)
                HarvestBerryBush(go, ref CurrentInventory, ref objects, cm);
            if (go.thisType == GameObject.ObjectType.tree)
                HarvestTree(go, ref CurrentInventory, ref objects, cm);
        }

        private static void HarvestTree(GameObject g, ref PlayerInventory inventory, ref List objects, ContentManager cm)
        {
            objects.Remove(g);

            inventory.AddItemToInventory(new InventoryItem("wood", 5, cm.Load(@"Objects\wood"), InventoryItem.InventoryType.craft));
        }

        private static void HarvestBerryBush(GameObject g, ref PlayerInventory inventory, ref List objects, ContentManager cm)
        {
            objects.Remove(g);

            inventory.AddItemToInventory(new InventoryItem("berry", 5, cm.Load(@"Objects\berries"), InventoryItem.InventoryType.craft));
        }

        private static void HarvestRock(GameObject g, ref PlayerInventory inventory, ref List objects, ContentManager cm)
        {
            objects.Remove(g);

            inventory.AddItemToInventory(new InventoryItem("stone", 2, cm.Load(@"Objects\stones"), InventoryItem.InventoryType.craft));
        }
    }
}

As per usual, the code should be simple and easy to understand. The one difference here compared to most of my other code is that this is a static class. To put it simply, this means that you do not need to declare a new instance of the class before you call a method, it is loaded in memory when the game launches. Simply just call Harvesting.Harvest, pass in the object you are trying to harvest and the player ineventory. I’m also passing in the list of game objects so that we can handle all object manipulation (such as removing the object from the game) directly from this class.

For my implementation, I am checking for a space key press when it is checking all of my game objects. Here is the relevant code:

if (tileRect.Intersects(Player.fowardBox()))
                {
                    bool harvestable;

                    box.Position = new Vector2(tileRect.X + 5, tileRect.Y + 5);

                    //box.textHandler.Output = "Press space to mine this rock.";
                    box.textHandler.Output = GameObjectDialogue.GetOutput(Inventory.EquippedItem, go, out harvestable);
                    dialogBoxNeeded = true;

                    //check for action key
                    if (keyState.IsKeyDown(Keys.Space) && !prevKeyState.IsKeyDown(Keys.Space))
                    {
                        //add additional code here to return items 
                        if (harvestable)
                        {
                            Harvesting.Harvest(go, ref Inventory, ref GameObjects,CM);                    //this.GameObjects.Remove(go);
                            return;
                        }
                    }
                }


Leave a comment

XNA – Object or Character Dialog

Another one from the archives. This one is a goodie! Enjoy!

One thing that was important to me in my latest game was to have actual dialog show on the screen. When the player interacts with objects, I want a box to display on the screen to give them immediate feedback. Granted, my implementation makes some basic assumptions and is quite simple, it is working and scaling quite well for me. Here is a basic implementation:

using System;
using FarmGame.Inventory;
using FarmGame.TileEngine;

namespace FarmGame.Dialogue
{
    static class GameObjectDialogue
    {

        static public string GetOutput(InventoryItem item, GameObject go, out bool harvestable)
        {
            harvestable = false;

            if (go.thisType == GameObject.ObjectType.rock)
                return GetRockOutput(item, out harvestable);
            if (go.thisType == GameObject.ObjectType.bush)
                return GetBushOutput(item, out harvestable);
            if (go.thisType == GameObject.ObjectType.tree)
                return GetTreeOutput(item, out harvestable);
            if (go.thisType == GameObject.ObjectType.house)
                return GetHouseOutput(out harvestable);
            
            return string.Empty;
        }

        private static string GetHouseOutput(out bool harvestable)
        {
            harvestable = false;
            return "This is your house.";    
        }

        private static string GetTreeOutput(InventoryItem ii, out bool harvestable)
        {
            if (ii.ItemName == "axe")
            {
                harvestable = true;
                return "Press space to chop this tree.";
            }
            else
            {
                harvestable = false;
                return "You must have the axe equipped.";
            }
        }

        static public string GetRockOutput(InventoryItem ii, out bool harvestable)
        {
            if (ii.ItemName == "pickaxe")
            {
                harvestable = true;
                return "Press space to mine this rock.";
            }
            else
            {
                harvestable = false;
                return "You must have the pickaxe equipped.";
            }
        }

        static public string GetBushOutput(InventoryItem ii, out bool harvestable)
        {
            if (ii.ItemName == "scythe")
            {
                harvestable = true;
                return "Press space to harvest berries.";
            }
            else
            {
                harvestable = false;
                return "You must have the scythe equipped.";
            }
        }
    }
}

I won’t get too into the details as it should be self explanatory. In this case, you are passing in the equipped item and the object you are interacting with. It will then return if the object is harvestable. In my case, I have rocks, bushes, trees, and a house.

Calling it from your code is equally as simple. I have this in the update method of my level class:

            bool dialogBoxNeeded = false;

if (tileRect.Intersects(Player.fowardBox()))
                {
                    bool harvestable;

                    box.Position = new Vector2(tileRect.X + 5, tileRect.Y + 5);

                    //box.textHandler.Output = "Press space to mine this rock.";
                    box.textHandler.Output = GameObjectDialogue.GetOutput(Inventory.EquippedItem, go, out harvestable);
                    dialogBoxNeeded = true;

                    //check for action key
                    if (keyState.IsKeyDown(Keys.Space) && !prevKeyState.IsKeyDown(Keys.Space))
                    {
                        //add additional code here to return items 
                        if (harvestable)
                        {
                            Harvesting.Harvest(go, ref Inventory, ref GameObjects, CM);
                            //this.GameObjects.Remove(go);
                            return;
                        }
                    }
                }

                box.DrawBox = dialogBoxNeeded;

Basically, the player has a seperate bounding box that projects in front of them. We are checking this bounding box to see if it interacts with a game object. If so, we note the position for our box, determine the text, and flag the code as needing a dialog box.

Now we need to call the draw method:

            if (this.box.DrawBox)
                this.box.Draw(sb);

I’m not going to step through it, but here is the box class:

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Text;
using Microsoft.Xna.Framework.Content;

namespace FarmGame.UI_Elements
{
    class Box
    {
        public Text textHandler { get; set; }
        public Texture2D Texture { get; set; }
        public Vector2 Position { get; set; }
        public bool DrawBox { get; set; }

        //private int TextureWidth { get; set; }
        //private int TextureHeight { get; set; }

        private string Output;
        //StringBuilder sb;

        public Box(ContentManager cm)
        {
            this.Texture = cm.Load(@"UI\popuptext");

            textHandler = new Text(cm, @"Fonts\boxSpriteFont");
            textHandler.TextColor = Color.White;
        }

        public Box(ContentManager cm, string output, Vector2 coords)
        {
            this.Texture = cm.Load(@"UI\popuptext");
            this.Output = output;
            this.Position = coords;

            textHandler = new Text(cm, @"Fonts\boxSpriteFont");
            textHandler.TextColor = Color.White;
        }

        public void Draw(SpriteBatch sb)
        {
            sb.Draw(this.Texture, this.Position, null, Color.White );

            textHandler.FontPos = new Vector2(Position.X + 15, Position.Y + 15);
            textHandler.DrawText(sb);
        }
    }
}


Leave a comment

XNA – Basic Enemy AI

Here’s another from the archives!

One thing I was surprised to find in XNA, was just how simple it really ended up being to add some incredibly basic enemy AI and pathfinding. In my game, the enemies are dumped onto a platform and then are bound by all the same rules of gravity as the player. Initially, they all suffered from Super Mario Bros syndrome where they would just walk off the platform and die. The solution was surprisingly simple: read which way the enemy is facing, project out a separate bounding rectangle, and then go through all of the tiles in our map and see if there is an intersection. If there is not, then the enemy is at the end of the platform and needs to turn around. All of this is called from the update method of our enemy. Here is the relevant code:

public void PathFinding(GameTime gt)
{
int maxX = this.SpriteWidth; // *2;
bool endOfPathFound = true;



Rectangle pathFindingRect = new Rectangle();

if(direction == Direction.Right)
pathFindingRect = new Rectangle(((int)Position.X - this.SpriteWidth/2) + maxX, (int)(Position.Y -this.SpriteHeight) +1,
this.SpriteWidth, this.SpriteHeight);
else if(direction == Direction.Left)
pathFindingRect = new Rectangle(((int)Position.X - this.SpriteWidth / 2) - maxX, (int)(Position.Y - this.SpriteHeight) + 1,
this.SpriteWidth, this.SpriteHeight);

foreach (TileSprite ts in level.Map)
{
if (ts.Landable)
{
if (pathFindingRect.Intersects(ts.BoundingBox))
{
endOfPathFound = false;
}
}
}

if (endOfPathFound)
{
if (direction == Direction.Left)
direction = Direction.Right;
else if (direction == Direction.Right)
direction = Direction.Left;
}
}


Leave a comment

XNA – Sprite Sheet Animation

Dug this article out from the old archives and thought I would post it here. Context might not make sense, but the basic code should work all the same. You can tie this into the tile engine tutorial.

Haven’t had too much time to do any programming this week, but I did just convert my player animation engine to animate a sprite based on a sprite sheet rather than a horizontal imageset. Here is the relevant code.

I realize that this needs to be more object oriented, but I’ll get there.
This is added to the animated sprite class:

public int YFrame
        {
            get { return yFrame; }
            set { yFrame = value; }
        }
        int yFrame = 0;

All the rest of the code is in the player class

private void AnimateLeft(GameTime gt)
        {
            if (currentKBState != previousKBState)
            {
                //CurrentFrame = 5;
                CurrentFrame = 0;
                YFrame = 1;
            }

            Timer += (float)gt.ElapsedGameTime.TotalMilliseconds;

            if (Timer > Interval)
            {
                CurrentFrame++;

                //if (CurrentFrame > 7)
                    //CurrentFrame = 4;
                if (CurrentFrame > 2)
                    CurrentFrame = 0;

                Timer = 0f;
            }
        }

        private void AnimateRight(GameTime gt)
        {
            if (currentKBState != previousKBState)
            {
                //CurrentFrame = 9;
                CurrentFrame = 0;
                YFrame = 2;
            }

            Timer += (float)gt.ElapsedGameTime.TotalMilliseconds;

            if (Timer > Interval)
            {
                CurrentFrame++;

                //if (CurrentFrame > 11)
                   //CurrentFrame = 8;
                if (CurrentFrame > 2)
                    CurrentFrame = 0;

                Timer = 0f;
            }
        }

SourceRect = new Rectangle(CurrentFrame * SpriteWidth, YFrame * SpriteHeight, SpriteWidth, SpriteHeight);

And that’s it. Just use the code that we had from the previous articles, and the animation will now pull from the sprite sheet.