Friday, June 15, 2012

Building an iOS App in Corona Labs SDK

Corona SDK - now Corona Labs SDK - is a great tool for building games for iOS and Android. What about building more traditional and standard looking apps? Well, Corona provides a number of widgets which look and behave just like regular iOS controls. Putting these together shows that a few items are missing, but can be built. Corona SDK's Sample Code directory contains a WidgetDemo, to show off the functions provided by the API's Widgets. Here's my list of posts for improving those features:



Tuesday, May 29, 2012

Friday, May 04, 2012

Polygon Triangulation

Massive thanks to the super hero Nicholas Wellcome for this awesome piece of javascript. It allows you to draw a polygon in a clockwise order and then it breaks it into separate polygons - effectively allowing concave to multiple convex polygon conversion. And the best bit? He's provided his nicely commented source code!

Monday, April 23, 2012

Monday, March 26, 2012

Tuesday, February 21, 2012

Wednesday, February 01, 2012

Tuesday, January 31, 2012

Angry Birds in 30 Mins or Less

As posted here on Ansca Mobile's blog:


Here is how to code an Angry Birds style game basis in less than 30 minutes using the awesome Corona SDK...

Friday, January 06, 2012

Thursday, January 05, 2012

Interesting And Social API In Corona SDK

Here is a list of blog posts documenting how to use the most interesting and useful parts of the Corona SDK API by Ansca Mobile...

Many of these can be found on this root page: http://blog.anscamobile.com/category/tutorials/

Firstly, the social API's:
And second, the deeper API's:

Wednesday, January 04, 2012

Tuesday, January 03, 2012

Tuesday, December 13, 2011

Tuesday, December 06, 2011

Calculating Trajectories

When plotting the course of a (lets say) ball thrown in a simulated physics environment it is advantageous to be able to draw the course the ball will follow. Doing some "internet research" brought up this little gem of a site:
From which I was able (yes, it's cheating, but hey) to refactor the javascript and produce the code for a Corona implementation here:
The root of the above site is quite amazing and hopefully can teach everyone (certainly me) about all manner of interesting physics concepts and maths:

Friday, December 02, 2011

Tuesday, November 29, 2011

Wednesday, November 23, 2011

Tuesday, November 22, 2011

Thursday, November 10, 2011

iOS 5 Accessibility Features For Everyone

Playing around under the Settings->General->Accessibility section and found some absolute gems - nice and useful for everyone...

  • General
    • Accessibility
      • Vision
        • Zoom
          Allows 3-finger zoom and pan of any screen, including the lock screen. Controls work as expected.
          Good for when photo zoom doesn't quite do it for you or you need to check pixel-specific placement on a web page.
        • Speak Selection
          Separate from VoiceOver, this allows any selectable text - web pages and such - to be spoken. The usual popup menu gains a "Speak/Pause" item. Speech speed can also be adjusted.
          Good for when you just can't be bothered to read the page.
      • Hearing
        • Custom Vibrations
          When editing a contact this adds a 'Vibration' option immediately beneath the 'Ringtone' option. Vibrations come with 5 pre-set patterns and custom patterns can be very easily recorded, named and re-used.
          Good for when you need to know who is calling you without taking the phone out your pocket.
        • LED Flash for Alerts
          Simply flashes the camera flash LED when an alert, like an incoming call, occurs.
          Good for truly silent but noticeable alerts.
      • Physical & Motor
        • Triple-click Home
          Set this to 'Ask' and it will pop up a menu whenever the Home button is triple-pressed - even when locked.
          Good for easy access to some of the above options.
          From there you've got options to turn On/Off the:
          • VoiceOver
            Not the same as 'Speak Select' - reads anything tapped with a single tap.
          • Zoom
            See above.
          • White on Black
            Inverts the whole screen colour.

Friday, November 04, 2011

Tuesday, November 01, 2011

Doing iOS in CSS3 and HTML5 - iPad Popover Menu

This is really great... Peter Viszt has created an iPad popover menu in CSS, using the design by Morgan Knutson as a basis. It looks really good and he links to a customisability tool:

Wednesday, October 19, 2011

Corona Roadmap Poll

  • In-App Purchase support for Android
  • Improvements to Physics API (friendlier collisions, etc.)
  • Improved transitions: pause/resume methods
  • Improvements to Sprite API
  • MapView support (Android)
  • Improved WebPopup behavior
  • OAuth support
  • Exposed table of active timers
  • Integrated advertising
  • System capabilities API
  • Payment integration Android (Paypal,etc)
  • Analytics
  • Split Features. Don't wait to have feature parity on both Android/iOS. We can live with wichever is
  • Add "2.5d" image transforms
  • Improvements to image saving API
  • Physics: simplified collision detection for "non-physical" cases
  • Improvements to Corona debugger
  • Support for compressed textures
  • Improved line drawing API
  • Support for Android softkeys
  • OpenGL shader support
  • iTunes library support
  • On-device debugging
  • Misc. improvements to core API usability
  • Page Flip
  • Improved Text Fields
  • New Corona UI Features
  • Curve Fitting
  • Object Fill
  • Bezier Manupulation
  • Procedural Graphics
  • Fluid Dynamics
  • Reconstruction of Arbitrary Topology using NURBS
  • LOD Rendering for terrains
  • Bon Jour
  • Device IP
  • BT Stack
  • Timer pause/resume
  • Apple Push Notification
  • Local Notification
  • OpenFeint for Android
  • Tinting
  • Access to bitmap data
  • Contact List (Address book)
  • Email attachments
  • Better XML parser
  • Give Carlos a raise
  • Live Wallpaper for Android
  • Camera objects overlay (video, camera)
  • Better Text Metrics
Created on Oct 19, 2011

Thursday, October 13, 2011

T-SQL Tree Into XML

My previous post contained a link to a Microsoft article detailing how to get well structured XML directly from T-SQL. This post is about getting a tree of data from T-SQL into XML. FOR XML EXPLICIT cannot be used (without major headaches) but a simple recursive function and a SELECT can be used. Here's where I poached my solution from:

  • http://stackoverflow.com/questions/2409228/generate-structured-xml-document-from-hierarchical-table-data-t-sql/2425180#2425180
In short, my code is something like this (generic code for a wider audience):
CREATE function [dbo].[SelectCategoryChild](@categoryid as int)
returns xml
begin
    return (
        select
            categoryid as "@id",
            parentcategoryid as "@parentcategoryid",
            title as "@title",
            dbo.SelectCategoryChild(categoryid)
        from category
        where parentcategoryid = @categoryid
        for xml path('category'), type
    )
end
GO
SELECT
    categoryid AS "@categoryid",
    '' AS "@parentcategoryid",
    title as "@title",
    dbo.SelectCategoryChild(categoryid)
FROM category
WHERE parentcategoryid is null and siteid = 1
FOR XML PATH ('category'), root('categories')
The code above works for a single table created from the statement (references and indices omitted for clarity):
CREATE TABLE [dbo].[Category](
[CategoryID] [int] IDENTITY(1,1) NOT NULL,
[ParentCategoryID] [int] NULL,
[Title] [varchar](150)
)
CategoryID is the primary key,
ParentCategoryID references the CategoryID and provides theone-to-many tree structure, a NULL value indicates the node is a root node (top-level) in the tree,
Title is simply some data (in this case the name) of the node.

T-SQL FOR XML EXPLICIT

An excellent example of producing well formatted and structured XML direct from SQL where a non-tree structure is in use. I have used this to get a complex series of document information out in a specific format.

More Often Than You Think


Monday, September 05, 2011

Thursday, August 11, 2011

Tuesday, July 12, 2011

Monday, July 04, 2011

My HST Programme

Actually, this was donated by a colleague who has used it previously.

2 sets, 8 reps of each
  • Wks 1 - 4
Chest Dumbell press - Flat
Back Lat pulldown
Shoulders Upright Row
Triceps Kick back
Biceps Dumbell curl
Legs Squat
Abs Your choice
  • Wks 5-8
Chest Dumbell press - Incline
Back Reverse fly
Shoulders Dumbell military press
Triceps EZ Bar (supine)
Biceps Hammer curl
Legs Lunge
Abs Your choice
  • Wks 9-12
Chest Dumbell press - Decline
Back Seated Row
Shoulders Single arm side lift
Triceps Close press up
Biceps Reverse curl
Legs Dead lift
Abs Your choice

Thursday, June 30, 2011

Pumping Iron Links

Fat loss:
Food:
Articles:
Training Patterns:
Hypertrophic Training (HST):
Biochemical:
Sites:

Monday, May 16, 2011

Thursday, April 14, 2011

Monday, March 28, 2011

Tiltopolis

So the latest Corona-built iPhone/iPad game is here: Tiltopolis.

It's a twist on the old classic, Blocks. The twist is that the falling blocks land on a balance bar, seesaw, tilting beam - whatever you call it, it's a challenge as you've not just gotta stop the blocks from reaching the top, but reaching the bottom!

The game features Physics Mode (the seesaw reacts to being hit by the blocks) and Arcade Mode (the angle of the seesaw reflects number of blocks on either side) as well as 4 awesome tracks by new Brit band Run Toto Run!

Check it out:







Find Tiltopolis on AppStoreHQ.
Apps at AppStoreHQ

Friday, March 25, 2011

Friday, March 04, 2011

Worth Jailbreaking?

A recent post on El Reg (www.theregister.co.uk) points out that due to the hoops regular (ie: non-techy or can't-be-bothered-techy) mobile users (read: mobile phone and tablet users) have to jump through to get free apps or banned apps (those denied from stores like Apple's iOS App Store) most users are content with paying the low fee of US$0.99 or GB99p for an app on their phone or tablet.

Their article focuses on Open Source software, that of the wind of "Free". However, as a mobile developer myself, spending months working on an app and giving it away for free (especially the prospect that it would be installed via jailbreaking without charge) is rather underwelming.

Quote from El Reg:

"if an app is close enough to free and immediately available, with the added benefit of potentially being higher quality than open-source alternatives (because of the paid investment in developing and polishing the app), will there be any reason to bother downloading an open-source app?
Freedom matters a great deal to some, but arguably not to the consumers flocking to Apple's devices. And perhaps not even to the bulk of developers writing for those consumers."

Thursday, February 24, 2011

Interesting View

[Via: Engadget]

Watch out for the end of 2009 and 2010; The rest is fairly quiet.


Monday, February 21, 2011

Tuesday, February 15, 2011

Friday, January 28, 2011

Corona SDK Goes Windows

Corona SDK, the multi-platform development kit for iOS and Android had a major update this week. There is now a Windows SDK allowing the same lua language apps which can be compiled into iOS and Android Java apps on the Mac to be developed for Android on Windows.

To accompany this Ansca have included a slew of new features, all announced on their blog:
This is a really big step and one I believe will lead to some very interesting developments. Personally, I'm hoping for a lot of developer interest, to help bolster the Corona community and Ansca Mobile themselves, as well as WP7 builds.

I Hate Windows Server 2008

I really do.

But besides that, here's an article written to do justice (if not, comedy) to the annoying 'features' of the server OS. His other articles are about the useful, productive and more positive aspects, so please feel free to find out lots about the system.

Consider this article, however, the warning/watch out/snafu guide:

Slightly More Invasive

Tuesday, January 11, 2011

Wednesday, January 05, 2011

Corona Collision Filters

Ansca Mobile (www.anscamobile.com) have created a truly brilliant multi-mobile-platform SDK (iOS, Android) called Corona, which includes a Box2D (www.box2d.org) physics engine. There are many implementations in many languages for Box2D and one of the things which Ansca have got right is collision filters, one of the trickier things to implement in an physics API.

Brent Sorrentino of IgnisDesign has produced and posted a helper chart for working out which collision filters various objects should be assigned when building physics-based games using Corona:

Friday, November 19, 2010

Finally Developing For iOS

Here's a little post I made a while ago (which languished in draft for some time):
And here's some links I've found recently, now that I've chosen a development platform for iOS - having decided that, essentially, re-learning ANSI C++ with a new IDE (that I can't find any straightforward videos for [the latest version of XCode works slightly - but importantly - differently to that demonstrated in all the online tutorials]) is not my cup of tea...
I've found that for ease of learning the new language and a solid output, Ansca Mobile's Corona platform is performing well, has plenty of good tutorials and material and after the Apple iPhone Developer 1 year license ($99 in the USA, £59 in the UK), the Corona or Corona game license isn't too pricey. Though that might change soon...

Friday, October 22, 2010

Javascript Everyone Should Know - Iterating URL Args

Here's some javascript I'm often looking for, because I can't remember it off the cuff after 3 months of LINQ coding and I've started writing something where JQuery isn't available...

It iterates through all the parameters and their arguments passed in the URL...

var url = window.location.toString();
var query_string = url.split('?')[1];
var params = query_string.split("&");
for (var i = 0; i < params.length; i++)
{
var name = params[i].split("=")[0];
var arg = params[i].split("=")[1];
alert(i+': '+name+' = '+unescape(arg));
}

Thursday, October 21, 2010

Simple Category Tree Walking In T-SQL

I needed, as many have done before me, to create a snippet of SQL which was short and fast and returned a flattened table of tree nodes. In short, if you have a tree of nodes, get all the nodes below a specified node. The result is surprisingly simple and straightforward. Here it is, both as a snippet and a stored procedure. Assume the tree is stored in a table called Category, with CategoryID being the primary key and ParentCategoryID being the foreign key, to the same table, but nullable...

--------------------
declare @collect table ( catid int, tlevel int )
insert into @collect values (3,1)

declare @count int
set @count = 2

declare @maxlevel int
set @maxlevel = 2

while ((select count(1) from @collect where tlevel = @count-1) > 0 and @count <= @maxlevel)
begin

insert into @collect
select c.categoryid, @count
from category c inner join @collect b on c.parentcategoryid = b.catid and b.tlevel = @count-1

set @count = @count + 1

end

select * from @collect order by tlevel
--------------------
--------------------
CREATE PROCEDURE [dbo].[GetCategoryTree]
-- Add the parameters for the stored procedure here
@ParentCategoryID int
AS
BEGIN

-- the category id's to be output
declare @collect table ( catid int, tlevel int )
insert into @collect values (3,1)

-- a loop counter used to limit the depth we go to
declare @count int
set @count = 2

-- the deepest level to go to
declare @maxlevel int
set @maxlevel = 2

-- the loop to collect category id's
while
(
(select count(1) from @collect where tlevel = @count-1) > 0 -- keep going while we have categories
and @count <= @maxlevel -- keep going until the max level depth is reached
)
begin

-- insert the categories where the previous level contains the parent ids of the current level
insert into @collect
select c.categoryid, @count
from category c inner join @collect b on c.parentcategoryid = b.catid and b.tlevel = @count-1

-- increment the level being collected
set @count = @count + 1

end

-- return the found category id's
select * from @collect order by tlevel

END
--------------------

Tuesday, October 12, 2010

Writing Windows Services

Just found a really neat (as in compact) post on writing Windows Services in C#:
And here's some Windows Services resources for doing different things in a service:

Friday, October 01, 2010

Monday, September 27, 2010

Monday, September 20, 2010

Wednesday, September 15, 2010

DateDiff

Recently, I had to work out the number of months between two arbitrary dates. In C# this is a bit of a challenge, simply because DateTime.Subtract(DateTime) returns a TimeSpan, which does not have a Months property.

This is because TimeSpan doesn't know which months it would be referring to. Specifically, to know how many months there are in a date range you need to count each month index from date A to date B. Problem being, if you don't know those arbitrary dates - you only have a count of days - how many months does that range cover?

Example: How many months does 30 days represent? Answer: 1.

Wrong.

Why?... Because if we are talking about February, it's two months. If we're talking about August it's not a whole month.

The solution is to take into account the specific dates being used in the subtraction and count their months, unfortunately. Yeah, I don't want to write that code either.

However, for the C#'ers among us, there is a solution. VB has a DateDiff class which can do this for you. Just use the Microsoft.VisualBasic namespace and the static DateDiff method, as I found out here:
Here's a post about writing your own:

Friday, September 10, 2010

Wednesday, September 08, 2010

Tuesday, September 07, 2010

The Register: iPad Apps Galore

The Register has pulled together a collection of iPad apps for geeks, techies and web pros...

Monday, September 06, 2010

LINQ2SQL Transaction

A good thread to read on LINQ to SQL transactions, centred on commits and rollbacks:

Wednesday, September 01, 2010

Why Not? "Wave-Enabled" Google Email Server

I was thinking that it's a shame that Google didn’t take the Wave, build it into their email server and have just an option that let you “email in real time”, ie: any email on their system could be seen to be edited in real time (as wave showed) but in the gmail editor.

The major work would be in the server, so that it is still an email system, exchange compatible and all, but also makes this new function available. Hopefully, people would use it more and more as rapid email repliers discover they are responding quickly.

Perhaps Google could then market their own email server as “Wave-enabled, MS Exchange-compatible”.

So simple really – read this:

Tuesday, August 31, 2010

ImageButton Without A SRC Value Causes GET Request!

Situation:

Click submit on a submit button.
Page posts back with IsPostBack == true.
Browser shows page render.

Problem:

Server (in debug mode) shows another request perform, this time a GET, so IsPostBack == false.

Evidence:

An ImageButton was on the page with no SRC attribute at all. This caused the browser (so far happening in (Windows...) Chrome, Firefox and (MAC...) Safari to resolve the URL of the image, for the image button, to be the same as the page the button is sitting on. The request for this then causes a standard GET request to the page and IsPostBack becomes false again.

Solution:

Remove the image button or give it a valid src attribute url.

Result:

Happy developer.

Friday, August 20, 2010

Javascript: Finding All The Properties Of A JScript Object

Just a little function to dump out into an alert all the properties, methods, etc of any javascript object...

function listout(obj) {
var keys;
for (var key in obj) {
keys += key + ' , ';
}
alert(keys);
}

Wednesday, August 18, 2010

Friday, August 13, 2010

LINQ2SQL Exception: The query contains references to items defined on a different data context

When getting the exception
The query contains references to items defined on a different data context.
Check that the context object being used for each 'from' and 'join', etc, within LINQ statements is not a new object but the same one being re-used!

JQuery

A few JQuery links:

Wednesday, August 11, 2010

Reset The Primary Key Of A Table

Lets say you've got 28 rows in your table but because you've been doing a lot of inserts and rollbacks the next key to be inserted is much higher than your highest primary key. This would be a problem if you've done a lot of inserts and have maybe reached the maximum value of the int type being used as the primary key field type.

You would want to reset the index (as all primary keys are special indices) like this:

DBCC CHECKIDENT ({tablename}, reseed, {number})

Don't make my initial mistake and think that the 'reseed' in the middle there is a place holder for a value - it isn't. Just leave it as is; it's a command. The operation is called reseeding, not resetting - but that will be all academic to most of us.

References:

LINQ: NOT IN / NOT EXISTS

So, while trying to get a fairly straight forward (I thought) select ... from ... where ... not in (...) I found that there is not really an equivalent in LINQ, or so I thought...

Read the solution here:
var orphans = (from c in context.Instances
orderby c.Title
where !(from o in context.CategoryInstances
select o.InstanceID)
.Contains(c.InstanceID)
select c).Skip(PageIndex * PageSize).Take(PageSize);

Essentially, the query does the same thing in C# - that is, to get the list of IDs to check within and then check within it for the ID which is hoping to be not found. Because the whole thing is compiled into SQL before before executed, LINQ generates a NOT EXISTS statement in the WHERE clause, rather than the slower NOT IN.

Concept Car Designs

Found this the other day and thought these were all really cool designs, possibly inspired by the forth-coming Tron movie...

Wednesday, July 21, 2010

Elite For The iPhone And iPad

Unfortunately, I cannot post a link to the game here - I do want to bung down as much as I can and hopefully one day link to it...

I would love to see the Archimedes version of Elite - in my opinion the best version, because it had solid 3D graphics and very smooth controls - ported to the iPhone and iPad, possibly with the iPhone being able to act as a remote control for the iPad running the game.

However, first, a link to nostalgia:
The company Frontier, started by David Braben which now continues the Elite legacy:
Ian Bell's Elite FAQ:

Server Error With Virtual Directory

Trying to put a virtual directory under a web site in WinSrv2003, I hit this problem:

Server Error in '/TestSubSite' Application.


Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Could not load file or assembly 'SControls' or one of its dependencies. The system cannot find the file specified. (D:\web\testsite\web.config line 211)

Source Error:

Line 209:     Line 210:     Line 211:       Line 212:     Line 213:  

Source File: D:\web\testsite\web.config Line: 211




Fortunately, the answer is to wrap the system.web element in a location element, with the attributes path="." and inheritInChildApplications="false".

I've documented this fun on stackoverflow.com:

Thursday, July 15, 2010

How To Get DateTime In XSLT

It's actually quite easy, though definately not obvious, to perform a fairly standard =DateTime.Now operation in XSLT, even when using C# (the default Microsoft XSL parser is only on version 1.)

Here's the XSLT:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:my="urn:sample" extension-element-prefixes="msxml">

<msxsl:script language="JScript" implements-prefix="my">
function today()
{
return new Date();
}
</msxsl:script>
<xsl:template match="/">

Today = <xsl:value-of select="my:today()"/>

</xsl:template>
</xsl:stylesheet>

Here's the C#:

/// <summary>
/// Takes a string containing XML to be parsed and a string containing the the XSLT to do the parsing.
/// </summary>
public static string XSLTransformation(string xml, string xsl)
{
// create the readers for the xml and xsl
XmlReader reader = XmlReader.Create(new StringReader(xsl));
XmlReader input = XmlReader.Create(new StringReader(xml));

// create the xsl transformer
XslCompiledTransform t = new XslCompiledTransform(true);
XsltSettings settings = new XsltSettings(false, true);
t.Load(reader, settings, null);

// create the writer which will output the transformed xml
StringBuilder sb = new StringBuilder();
XmlWriterSettings tt = new XmlWriterSettings();
//tt.Encoding = new UTF8Encoding(false);
XmlWriter results = XmlWriter.Create(new StringWriter(sb)); //, tt);

// write the transformed xml out to a stringbuilder
t.Transform(input, null, results);

// return the transformed xml
return sb.ToString();
}

References:

Every Project Fails

Every project fails - you and I both know it - in two places: the Beginning and the End. Both of these, as Douglas Adams put it, are due to sloppy thinking. The first is because the full scope of the thing is not realised. The second is because the full scope of the thing is realised. The are known, in order, as "not writing the spec properly" and "feature creep". Often, the spec is not written properly because it is perceived to have been written properly or that it is someone else's job to write it out more, read: "flesh it out", also read: "passing the buck". Further, the feature creep happens not because due diligence is not done, but because discipline is not employed in keeping the extra features out. Even further, those features only come about because it's easier to think of new things when you've had time to think about the existing things. Give a project 3 months to progress and I guarantee that everyone on that project will have thought about some feature that wasn't in the original (even aged-) concept, simply because they've had more time to think.

What can be done about these? Some would say agile development is one (of many) approach, providing the time to define a concept but with development time allotted for later to deliberately increase the feature set as time, or units of the project, get completed. This is fine, as long as the wider scope of the project is realised at the start.

Wednesday, July 14, 2010

Google

How does Google work?...

Thursday, July 08, 2010

Parsing XML Into T-SQL Tables

Ok, some heavy SQLXML work here...

The aim was to make a query which would take any XML and list, in one table, all the elements, their attributes and their element and attribute values of the immediate child nodes of the root node. On top of that, each immediate child of the root had to be enumerated so it could be referenced properly when being inserted into another table/s.

Example input:

<root>
<date>07/07/10</date>
<start>07/02/10</start>
<m code="AL">
<Time>10:22</Time>
<Ask>1943.25</Ask>
<Open>1940.00</Open>
</m>
<m code="AA">
<Time>14:42</Time>
<Ask>143.05</Ask>
<Open>230.50</Open>
</m>
</root>

Example output:

ElementIndexParentElementFieldNameNodeTypeFieldValue
1mTimeelement10:22
1mAskelement1943.25
1mOpenelement1940.00
1mcodeattributeAL
2mTimeelement14:42
2mAskelement143.05
2mOpenelement230.50
2mcodeattributeAA

And finally, the SQL...

declare @xml XML
set @xml = 'YOUR XML HERE'

create table #t
(
rownum int,
xmlextract xml
)

-- populate the table with the child nodes of the root, if they have their own sub nodes
insert into #t
SELECT
row_number() over(order by getdate()) as 'RowNum',
pref.query('.') as XmlExtract
FROM
@xml.nodes('/*/*') AS extract(pref)
WHERE
pref.value('./*[1]', 'nvarchar(50)') IS NOT NULL

SELECT distinct rownum 'ElementIndex', ParentName 'ParentElement', FieldName, NodeType, FieldValue FROM
(
-- selects the attributes and their values from the xml
SELECT DISTINCT
rownum,
SubEl.SubElem.value('local-name(..)', 'nvarchar(50)') AS ParentName,
SubEl.SubElem.value('local-name(.)', 'nvarchar(50)') AS FieldName,
'attribute' as NodeType,
SubEl.SubElem.value('.', 'nvarchar(150)') AS FieldValue
FROM
#t
CROSS APPLY
xmlextract.nodes('//@*') AS SubEl(SubElem)
UNION
-- selects the inner element and their values from the xml
SELECT
rownum,
SubEl.SubElem.value('local-name(..)', 'nvarchar(50)') AS ParentName,
SubEl.SubElem.value('local-name(.)', 'nvarchar(50)') AS FieldName,
'element' as NodeType,
SubEl.SubElem.value('.', 'nvarchar(150)') AS FieldValue
FROM
#t
CROSS APPLY
xmlextract.nodes('/*/*') AS SubEl(SubElem)
) as tmp
ORDER BY ElementIndex, ParentElement, FieldName

drop table #t

However, for performance and tidy-up reasons, when using this code in a stored procedure, you may want to use a table variable. Here's the modified version:

declare @xml XML
set @xml = 'YOUR XML HERE'

declare @t table
(
rownum int,
xmlextract xml
)

-- populate the table with the child nodes of the root, if they have their own sub nodes
insert into @t
SELECT
row_number() over(order by getdate()) as 'RowNum',
pref.query('.') as XmlExtract
FROM
@xml.nodes('/*/*') AS extract(pref)
WHERE
pref.value('./*[1]', 'nvarchar(50)') IS NOT NULL

SELECT distinct rownum 'ElementIndex', ParentName 'ParentElement', FieldName, NodeType, FieldValue FROM
(
-- selects the attributes and their values from the xml
SELECT DISTINCT
rownum,
SubEl.SubElem.value('local-name(..)', 'nvarchar(50)') AS ParentName,
SubEl.SubElem.value('local-name(.)', 'nvarchar(50)') AS FieldName,
'attribute' as NodeType,
SubEl.SubElem.value('.', 'nvarchar(150)') AS FieldValue
FROM
@t
CROSS APPLY
xmlextract.nodes('//@*') AS SubEl(SubElem)
UNION
-- selects the inner element and their values from the xml
SELECT
rownum,
SubEl.SubElem.value('local-name(..)', 'nvarchar(50)') AS ParentName,
SubEl.SubElem.value('local-name(.)', 'nvarchar(50)') AS FieldName,
'element' as NodeType,
SubEl.SubElem.value('.', 'nvarchar(150)') AS FieldValue
FROM
@t
CROSS APPLY
xmlextract.nodes('/*/*') AS SubEl(SubElem)
) as tmp
ORDER BY ElementIndex, ParentElement, FieldName

References:

Tuesday, July 06, 2010