Selecting rows from the database using ADOdb

In the following example, I am going to query a MySQL table, loop through the results, and print them out to the screen, using PHP and ADOdb.

For the example, I have a table called “tablea”, which has two columns, “id” and “description”.

Also, $db is the database connection, for the avoidance of any doubt.

$result = $db->Execute("select id, description from tablea");
 if ($result === false) die("failed");
 while (!$result->EOF) {
	
     echo " <p>.$result->fields['id']." - ".$result->fields['description']." </p>";   
     
	$result->MoveNext();
	
 }

If you want to use ADOdb’s result caching system, the following change to line one will cache the results for 300 seconds.

$result = $db->CacheExecute(300,"select id, description from tablea");

Windows 10 stopping WampServer from using port 80

Recently I was puzzled as to why WampServer was not working as it should when I was attempting to run a PHP example locally. The telltale sign that all was not well was the status light was orange in the Windows notification area. The issue was that another program was using port 80. To confirm this, I went to wamp icon -> apache -> service -> test port 80

In my case, it was IIS that was using the port.

Your port 80 is actually used by:

Server: Microsoft-IIS/10.0

To stop IIS, run

iisreset / stop

This has to be done via a command line that was opened as an administrator.

It might be a coincidence, but this was the first time I had tried to use WampServer since I upgraded from Windows 7 to Windows 10.

How to access an ASP.Net TreeView node databound to a SiteMap – and remove it

You may have a situation where you are populating an ASP.Net TreeView control from a SiteMap xml file but don’t want certain nodes to be shown on the page.

The following C# code shows how to access the node/s in code behind when they are databound and remove specific nodes based on their Sitemap node title.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 protected void myTreeView_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
 {
     System.Web.UI.WebControls.TreeView tv = (System.Web.UI.WebControls.TreeView)sender;
     SiteMapNode mn = (SiteMapNode)e.Node.DataItem;
 
     System.Web.UI.WebControls.TreeNode nodeToRemove = tv.FindNode(mn.Title);
 
     if (mn.Title == "My Sitemap Node Title")
     {
         System.Web.UI.WebControls.TreeNode parent = e.Node.Parent;
         if (parent != null)
         {
              parent.ChildNodes.Remove(e.Node);
         }
      }
 }

The above code will search for all nodes with the title “My Sitemap Node Title” and remove them from the TreeView, meaning they will not be rendered to the page.

The same can be done with most item collections in the .Net Framework. Here’s another example, this time removing items from an ASP.Net Menu control:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
protected void myMenu_MenuItemDataBound(object sender, MenuEventArgs e)
 {
     System.Web.UI.WebControls.Menu menu = (System.Web.UI.WebControls.Menu)sender;
     SiteMapNode mapNode = (SiteMapNode)e.Item.DataItem;
 
     System.Web.UI.WebControls.MenuItem itemToRemove = menu.FindItem(mapNode.Title);
 
     if (mapNode.Title == "My Sitemap Node Title")
     {
          System.Web.UI.WebControls.MenuItem parent = e.Item.Parent;
          if (parent != null)
          {
                parent.ChildItems.Remove(e.Item);
          }
      }
 }

Assigning a Google Maps container element using a Jquery selector

Selecting an HTML container element to assign a Google map to using the default Jquery selector will not work. This is because the Google map initialisation is expecting a DOM elememt and the default Jquery selector syntax returns a JQuery object instead.

This, for example, will not work:

1
2
 
map = new google.maps.Map($('#map-container'), mapOptions);

All we need to do is add “[0]” to the selector and it will return the DOM element instead – like so:

1
2
 
map = new google.maps.Map($('#map-container')[0], mapOptions);

Strip duplicate values from a comma separated string using Javascript

This function will remove duplicate values from a comma separated string, returning only unique values in the original order.

I encountered a problem when developing a map application using the Google Maps API. When carrying out a reverse geocode call passing a lat/long string to retrieve a physical address, the API function would return the address but sometimes it would also contain duplicate values in the address if Google couldn’t get a specific house number or street name. For example: “Boston, Boston, MA, United States”.

To solve this problem the following Javascript function was created which accepts a string value, does some splitting and trimming of the string and returns only the unique values, with the commas still in place.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function stripDuplicateValues(inValue) 
        {
            var items = inValue.split(",");
            var arrlen = items.length -1;
            var i = 0;
            var outValue = "";
            var prevItem;
                while (i <= arrlen) 
                {
                    if (outValue.length > 0) 
                    {
                        if (prevItem != items[i].trim())
                        {
                            var str = items[i].trim();
                            outValue = outValue.replace(prevItem + ",", "");
                            outValue += ", " + str;
                        }
                    }
                    else 
                    {
                        outValue = items[i].trim();
                    }
                    prevItem = items[i].trim();
                    i++;
                }
            return outValue;
        }

Using the original example, the following would be returned: “Boston, MA, United States”.

Retrieve querystring values using Javascript

This small javascript function is a way of grabbing querystring values from a url.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function getQueryStrings() 
{
     var assoc = {};
     var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
     var queryString = location.search.substring(1);
     var keyValues = queryString.split('&');
 
     for (var i in keyValues) 
     {
          var key = keyValues[i].split('=');
 
          if (key.length > 1) 
          {
               assoc[decode(key[0])] = decode(key[1]);
          }
     }
 
     return assoc;
}

You can then assign these values to variables, inside an initialisation function for example, and use them as you see fit, like so:

1
2
3
4
5
6
function init()
{
     var qs = getQueryStrings();
     var name = qs["name"];
     var address = qs["address"];
}

Umbraco – Getting child nodes (.net)

using umbraco.NodeFactory; 
//umbraco.presentation.nodeFactory is now depricated;

protected void Page_Load(object sender, EventArgs e)
    	{
    		//If you just want the children of the current node use the following method
    		var currentNode = Node.GetCurrent();

    		//If you need a specific node based on ID use this method (where 123 = the desired node id)
    		var specificNode = new Node(123);

    		//To get the children as a Nodes collection use this method
    		var childNodes = specificNode.Children;

    		//Iterating over nodes collection example
    		foreach(var node in childNodes)
    		{
    			Response.Write(string.Format("{0}<br />", node.Name));
    		}

    		//To get the nodes as a datatable so you can use it for DataBinding use this method
    		var childNodesAsDataTable = node.ChildrenAsTable();

    	   //Databind example
    	   GridViewOnPage.DataSource = childNodesAsDataTable;
    	   GridViewOnPage.DataBind();
    	}

Hiding the PageSizeComboBox and ChangePageSizeLabel from a Telerik RadGrid

By default, there is no setting to hide the PageSizeComboBox or ChangePageSizeLabel from the pager control in a Telerik RadGrid control.  Instead, we must use the grid’s ItemDataBound event to handle the hiding of these items, like so:

1
2
3
4
5
6
7
8
9
10
11
12
protected void myRadGrid_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridPagerItem)
{
GridPagerItem pager = (GridPagerItem)e.Item;
Label lbl = (Label)pager.FindControl("ChangePageSizeLabel");
lbl.Visible = false;
 
RadComboBox combo = (RadComboBox)pager.FindControl("PageSizeComboBox");
combo.Visible = false;
}
}

The above code checks to see if the item being data bound is of the type “GridPagerItem”. If it is, it then creates a pager item and casts a label from this pager item so that it’s “visible” attribute can be set to “false”, thus hiding it from the grid at run time.

The same is done for the combobox, only this time a RadComboBox is cast from the pager item instead, and then hidden too.

Cache control in PHP

Set a cache control expiry for a PHP page. This will mean a repeat visitor will only request a new copy of the page if their cached version is older than the date/time specified in the Expires setting.

//sets an expiry of plus one hour
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); 
header('Cache-Control: public');
header('Pragma: cache');

Ensure that you do this before sending any content to the browser.

You can use this cache cheatsheet to determine how many seconds you want to enter in the code above.

I would only recommend using cache control for php pages that are either very large, or that require a lot of computing power to generate. Also, only use this if you do not plan on updating the page within the expiry timeframe. There is no easy way for you to force a user to retrieve a fresh copy from your site. You could ask them to refresh their cache by hitting F5, but that’s not ideal.

You could also use your web server (Apache, or nginx) to determine the cache control, but I dont tend to use cache control for php files, and instead use it for static files, like css, javascript or images.

Using cookieless sessionState in ASP.Net

If your ASP.Net application is storing sessionState data and you want to avoid using cookies, this can be achieved by simply setting the sessionState cookieless parameter to “true”. This will create a unique id for the sessionState and ammend any application URLs by adding this id to them.

For example, if the URL of your application homepage normally looks like this

http://localhost/myapplication/default.aspx

Cookieless sessionState would ammend the URL to read:

http://localhost/myapplication/(S(somerandomID))/default.aspx

Setting this up is simple. It is merely a case of changing the cookieless value of the sessionState entry in the Web.config file of your application, like so:

<system.web>
     <sessionState mode="InProc" timeout="60" cookieless="true" />
</system.web>

The example above uses the InProcess sessionState mode (which ASP uses by default for performance), sets a session timeout of 60 minutes and enables cookieless sessionState. The beauty of this built in feature means that ASP.Net handles all sessionState cookieless features for you. All URLs in your application will be ammended with this sessionState ticket and sent with the queryString at every postback to the server – no other coding is required.

Please note that the state will be lost if the user url-rewrites any of the links within your application, but so long as the user keeps to the links within your site then state will be maintained and any data you have stored in the way of session variables, for example, will be available to the application.