Using the Clipboard in UWP

How to Copy to Clipboard (Text String)

using Windows.ApplicationModel.DataTransfer;

...

dataPackage = new DataPackage();
dataPackage.RequestedOperation = DataPackageOperation.Copy;
dataPackage.SetText(text);
Clipboard.SetContent(dataPackage);

 

How to Paste from Clipboard (Image/Bitmap Data)

using Windows.Storage.AccessCache;
using Windows.Storage.Streams;

...

DataPackageView dataPackageView = Clipboard.GetContent();

if (dataPackageView.Contains(StandardDataFormats.Bitmap))
{
  IRandomAccessStreamReference imageReceived = null;
  imageReceived = await dataPackageView.GetBitmapAsync();
  if (imageReceived != null)
  {
    using (var imageStream = await imageReceived.OpenReadAsync())
    {
      var bitmapImage = new BitmapImage();
      bitmapImage.SetSource(imageStream);
      imgImage.Source = bitmapImage;

      dec = await BitmapDecoder.CreateAsync(imageStream);

      // https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapdecoder
      // https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapdecoder.getpixeldataasync#Windows_Graphics_Imaging_BitmapDecoder_GetPixelDataAsync
      var data = await dec.GetPixelDataAsync();

      imgBytes = data.DetachPixelData();
      imgWidth = dec.OrientedPixelWidth;
      imgHeight = dec.OrientedPixelHeight;

      // FYI, Overall image L-R, Top-Bottom.
      // Groups in reverse order: BGRA BGRA BGRA

      ByteArrayToPixelMap(imgBytes);
    }
  }
}
Advertisements

Dynamically Populate a UWP Grid using C#

This technique works for columns and rows, you just have to use the correct definition object, ColumnDefinition or RowDefinition.

Note the references to your specific grid instance (e.g. myGrid) and Grid methods (e.g. Grid.SetRow()).

myGrid.Children.Clear();
myGrid.ColumnDefinitions.Clear();

ColumnDefinition colDef;

for(int i = 0; i < myArray.Length; i++)
{
  colDef = new ColumnDefinition();
  myGrid.ColumnDefinitions.Add(colDef);
  colDef.MinWidth = 50;

  // Create a new instance of a TextBlock
  // or any other control; making a factory 
  // method(s) is usually wise.
  TextBlock txt = MyTextBlockFactoryMethod();
  myGrid.Children.Add(txt);
  Grid.SetRow(txt, 0);
  Grid.SetColumn(txt, i);
  txt.Text = myArray[i].ToString();
}

Application Version Info Panel

Here’s how to build a simple panel that shows the user the version info of your UWP application.

First the XAML / UI:

<Border x:Name="pnlInstallLocation" Padding="10" CornerRadius="5" Background="#FFB9D2F6" Margin="0,5,15,0" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
  <RelativePanel>
    <TextBlock x:Name="lbllocation">Install Details</TextBlock>
    <TextBlock x:Name="txtBuildDetails" Text="[build details]" RelativePanel.Below="lbllocation" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" FontSize="12" Padding="2" MinHeight="12" Margin="10,0,0,0" />
    <TextBox x:Name="txtVersion" Text="[version]" RelativePanel.Below="txtBuildDetails" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" FontSize="12" Padding="2" IsReadOnly="True" BorderThickness="0" Background="Transparent" MinHeight="12" Margin="10,0,0,0" />
    <TextBox x:Name="txtLocation_App" Text="[location]" RelativePanel.Below="txtVersion" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" FontSize="12" Padding="2" IsReadOnly="True" BorderThickness="0" Background="Transparent" Height="20" MinHeight="12" Margin="10,0,0,0" />
    <TextBox x:Name="txtLocation_DB" Text="[location]" RelativePanel.Below="txtLocation_App" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" FontSize="12" Padding="2" IsReadOnly="True" BorderThickness="0" Background="Transparent" Height="20" MinHeight="12" Margin="10,0,0,0" />
  </RelativePanel>
</Border>

The code behind:

using Windows.ApplicationModel;

private void Page_Loaded(object sender, RoutedEventArgs e)
{
  Package package = Package.Current;
  PackageId packageId = package.Id;
  PackageVersion version = packageId.Version;

  txtBuildDetails.Text = string.Format("{3} ({4}){0}Package {2}{0}Installed {1}", 
    Environment.NewLine,
    package.InstalledDate, package.Id.Name,
    package.DisplayName, package.Id.Architecture);

  txtVersion.Text = string.Format("Version {0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision);

  txtLocation_App.Text = string.Format("Application folder {0}", package.InstalledLocation.Path);
  txtLocation_DB.Text = string.Format("Database folder {0}", ApplicationData.Current.LocalFolder.Path);


  #if DEBUG
  txtVersion.Foreground = new SolidColorBrush(Windows.UI.Colors.DarkRed);
  #endif
}

 

This code has been lifted from a working app, I haven’t done a detailed checking of the code for this post, but everything needed should be present – uses Windows 10 Anniversary Edition (10.0; Build 14393).

Using Symbols in UWP UI Controls

To use a symbol character from a font like Segoe MDL2 Assets or Segoe UI Symbol as the visible content / text of a UWP control in XAML, use the following schema: &#x1234; where 1234 is the correct symbol code.

E.g.:

<Button x:Name="btnDoSomething" FontFamily="Segoe MDL2 Assets" Content="&#x1234;"></Button>

To set in C# use:

lblMySymbol.Text = "\u1234";

Also see:

  1. https://docs.microsoft.com/en-us/windows/uwp/design/style/segoe-ui-symbol-font
  2. https://www.google.co.nz/search?q=segoe+mdl2+assets+cheatsheet
  3. http://www.kreativekorp.com/charset/font.php?font=Segoe+UI+Symbol

 

About These Code Posts

I no longer code to earn a living, I code for pleasure.  The code snippets posted here are mainly for my own reference – and to benefit anyone who can use them.

Agile – the Rationalism vs Empiricism Epiphany

23-Mar-2018. Just an FYI that I’m currently re-drafting this article with feedback from a couple of colleagues; you can expect some significant changes at some point – all of which should make the article clearer.

I’d like to share with you an epiphany.  I run the risk of it being like a riotously funny party joke, retold later to much less effect: a case of ‘I guess you had to be there’, but that’s seldom stopped me before.

This epiphany is essentially a new way of viewing several things:

  • Waterfall vs agile, and agile vs Agile (big A, little A).
  • Why people often don’t ‘get’ software development; and probably why your developers and project managers have a fractious relationship, especially whenever estimation and deadlines are hot topics.

In short, the epiphany is based in philosophy.  First the recognition that waterfall is inherently rational, whereas agile is inherently empirical.  You then realise that as theories within philosophy they both have roots back in antiquity (Plato and so forth) and have essentially been elaborated and compared for significantly longer than waterfall and agile have been around.  Therefore, we can contemplate agile and waterfall from a purely philosophical viewpoint (without any pretense of ‘brand’ or additional baggage), and we can also draw on significant body of previous philosophical work.

I also suggest to you that there exists a rationalist-empiricist continuum on which each of us are placed – some people are naturally inclined towards one or the other.

Let’s look at this further and see what we can through this lens.

Short Philosophical Primer

Rationalism and Empiricism are both theories within Epistemology – the branch of philosophy concerned with the theory of knowledge:

  • Rationalism is the view that “regards reason as the chief source and test of knowledge”, or in other words, where “the criterion of the truth is not sensory but intellectual and deductive”.
  • Empiricism is a theory that states that knowledge comes only or primarily from sensory experience.

Philosophical literature frequently discusses one in contrast to the other.  One often also sees references to things being ‘a priori’ or ‘a posteriori’.  This isn’t something you need to remember, but it is interesting to note the concept behind these two terms as it’s relevant to our subject and subsequent contemplation:

  • A Priori is “what comes before”, as opposed to
  • a Posteriori which is “what comes after”.

The question (of whether or not something comes before or after) is significant enough that a priori and a posteriori appear in ‘Elements’ – Euclid’s 300 BCE work which served as the model for precise thinking throughout 15th-18th century Europe.

For those of you less well disposed to latin, you might also come across the terms deductive and inductive:

  • A deductive argument is where the conclusion follows from the premise, i.e. via reason.  I think, therefore I am.
  • In contrast, an inductive argument is based on experience/observation; in such cases the argument may be strongly supported by the conclusion but not necessitated by it.

It’s also interesting to note that empiricism is a key part of the scientific method.

So, key takeaway: Rationalism and Empiricism have been around and thought about for ages, and there’s lots we can draw from that.

Is Waterfall Really Rational and Agile Empirical?

If you already ‘get it’, then you can probably skip this section.

Waterfall, as it is practiced in an Information Technology related project delivery context, is a sequential approach.  Typically it consists of phases such as analyse, design, build, test, and so on.  Each phase informs the next: analysis informs us what the problem is, based on this we design a solution, based on this design we implement the solution, and so on.  Only at the end, when the solution is complete, do we see it working and finally see how well it addresses the original problem.

In other words, the basis for the solutions design and implementation is rational thought – what we can deduce.  It’s essentially theoretical.

The planning of waterfall projects is also based on rationalism; at the outset, estimations are made as to how long each phase will take, how much it will cost, who needs to be involved.  All of this happens in advance, and is frequently updated.  Should reality hit the project, the team is forced to ‘re-baseline’ – delivery schedules, resource estimates and costs are all calculated, based mainly on a rational thought process.

Agile, again as practiced in ‘IT’, is based on an empirical approach where work is done and the results evaluated before proceeding.  At the beginning of an agile project effort is spent working out an initial prioritised list of problems to be solved, a small chunk of this is then worked on by the team, the results are evaluated and corrections made – corrections in terms of the base assumptions and the work/output itself.  In this way the project proceeds, repeating a consistent cycle of delivery and inspection.

The planning of agile projects is also based on empiricism; teams typically provide relative estimates based on the size of previous work that they have already done, and in this way the estimates are evidence based.

Agile Explained

As I wrote previously, Marty Cagan has a nice simple way of asking people if they are agile:

  1. How soon can you test?
  2. Does shipping out a release mean you’re finished?

At face-value this appears fairly straight-forward, but I think we can go further:

  • Are you driven by what you have planned or what you can prove through experience?

If you primarily “know” a thing because you have deduced it then you’re not being empirical, and therefore you’re not agile.  It’s that simple.

Agile: A vs a; Big A vs Little A

It’s true that in the context of contemporary software development the concept of Agile (as in the big A, as in the Agile Manifesto) is bundled up with additional ideas: individuals over interactions, collaboration, and so on; and whilst these additions clearly add immense value and have made agile more accessible for many, they don’t alter what’s arguably the single most important foundational idea behind agile – empiricism.

Take the agile manifesto and its guiding principles, for example:

  • Individuals and interactions over processes and tools.
  • Working software over comprehensive documentation.
  • Customer collaboration over contract negotiation.
  • Business people and developers must work
    together daily throughout the project.
  • Build projects around motivated individuals.
    Give them the environment and support they need,
    and trust them to get the job done.

Many of these ideas (such as those listed above) are not mutually exclusive with waterfall; any group of people using waterfall can still choose to collaborate, be motivated and trust each other.  It’s true (in my experience at least) that we don’t often associate the above with waterfall projects – but that’s inductive, just because it’s often the case does not mean it is bound to always be the case.

Sure, waterfall is based on rationalisation, which is often accompanied by process, requiring tools – but I’d argue that often the use of those processes and tools is often driven by other factors: social norms, people hiding behind process, and so on; it is still possible to put ‘individuals and interactions over processes and tools’ and follow a rational process.

There will no doubt be many for whom these additions are in fact indivisible parts of Agile, and I think that view is fine.  My point is that one of the ways to better understand agile/Agile is to mentally remove all of these additions and conceptualise agile/Agile (and waterfall/agile) from a philosophical perspective based on Empiricism and Rationalism.

We can also apply this lens to a more recent phenomenon, the mainstream adoption of Agile as a product to make money off.  Don’t confuse agile (and the key part: learning from experience and evidence) with Agile (i.e. specific recipes, brands and elaborate constructs).

State of Mind

Thinking about social norms and human behavior brings us to my second key point: the existence of a rationalist-empiricist continuum, and the premise that everyone is somewhere on this continuum – usually closer to one end than the other.

In my view, many software developers that I have worked with are empiricists – in that they have a greater affinity to an empirical way of thinking rather than a rational one.  Conversely, many project managers I have worked with are rationalists – they have a greater affinity to an rational way of thinking.

Are these philosophies, these states of mind, mutually exclusive?  I’d say not.  For a start this article is itself based on ideas which have emerged through a combination of both.  Furthermore, I can think of many occasions when I have personally used each.

Both are clearly useful tools, and like all tools they are most useful when the correct tool is matched to the problem being faced (not the other way around).  The problem that rationalists are frequently confronted with in a software project is that the nature of software development is inherently empirical.  Or to be a little more precise, the nature of software development when applied to solving a particular real-world problem, is usually inherently empirical.

I say ‘usually’ because I cannot say for certain that all such problems are categorically empirical.  If we stretch software out to encompass IT, and therefore hardware, rationalism becomes more relevant.

We must acknowledge that for a lot of people, especially the senior executive who’s paying the bill, the basic question of “when will it be ready and how much will it cost” is not unreasonable.  The challenge is how to best answer it – in this regard both Empiricism and Rationalism have their unique challenges.

 

 

Customer Inspired; Technology Enabled – Product Tank Wellington MeetUp with Marty Cagan

The Product Tank Wellington meetup ran a really cool session recently called “Customer Inspired; Technology Enabled” with internationally recognised product guru Marty Cagan.

As you can imagine, someone of Marty’s calibre provides a lot of great wisdom.  Some reinforced or reinvigorated stuff I think I already knew, but much was also new.

Here are my old-school hand-scribbled notes (2 pages) if you’re interested (or neglected to take your own, tsk tsk): Customer Inspired, Technology Enabled with Marty Cagan – 12-Feb-2018 – Adrians notes

Note to anyone doing architecture: broadly speaking, anywhere it says “product” I think we can swap with “solution”.  Which is why I’ve tagged this #ArchitectureInTransformation – architects need to (at least) be mindful of this stuff.

Also, in this context  when we talk about “product” we mean a technical product of some kind (i.e. software/technology related) – not something like floor polish or mint scented vacuum bags.

Key Takeaways and Gems

Asking customers what they want

If you’re looking for where to take your product, the short answer is “don’t”.  Instead, invest your time in asking customers about their problems.

You should not rely on customers to tell you about which direction to take your product, or what new features or capabilities to add, because:

  1. They don’t know what’s possible – they generally aren’t technologists. (The clever technologists should be the people on your team).
  2. Great (new) ideas have to be discovered.  For me personally, Marty was making a strong connection to empiricism – in that you can’t rationalize your way to a “new” idea.

The way to flip the question is to be to ask your customers about things that they do know about: their problem, their constraints.

Another reason why you can’t reliably ask customers what they want is because they themselves don’t actually know what they want until after they’ve seen it.

Engineers

Marty spoke repeatedly and at length about the importance of involving engineers in the product process.  He cited several cases where new successful products had emerged from the techies – essentially from random ideas they had on the fringes of a project, where their inventiveness (based on their deep understanding of the technology) led to something entirely new.

He suggested giving developers time for discovery – something in the ballpark of half an hour a day.

Overall his message was clear:

  1. Work with strong engineers that are passionate about your vision.
  2. Do not shelter them – expose them to the full business context; expose them to customers.
  3. Provide them with constraints, not requirements.

Requirements First?

Speaking of requirements (whilst talking about agile) he neatly flipped the old Analyse > Design > Build model around:

  1. Knowledge of the technology…
  2. > enables design…
  3. > drives desires/needs/requirements

Essentially this comes back to the same point posed by “asking customers what they want” – if customers don’t know what is possible then the requirements will always fail to get the most out of what the technology is capable of.

Are you Agile?  Really.

I had to laugh – Marty’s position on Agile was that it’s a no brainer, like why are people even asking this question.  And it wasn’t just the words that gave me a wry grin, it was also his tone: dry, cuttingly sardonic, with a hint of tactful incredulity and thinly veiled loathing.

Point is, there’s a difference between thinking you’re agile and being agile.  Try these two refreshingly straightforward questions:

  1. How soon can you test?
  2. Does shipping out a release mean you’re finished?

The correct answer to #1 is that if testing is done at the end, it’s too late; if you’re agile you’re testing as early as possible and not just at the end.  If you only test at the end, then that’s where you are putting all the risk.

#2 Is a really key one; it’s about the difference between releasing something and solving a problem.  The common misconception is that when you’ve put out a release, you’re done; but whilst getting stuff delivered is great, you’re only actually “finished” if you’ve solved the problem you set out to solve.  Shipping out a release merely gives you an opportunity to see if you’ve really solved it.

So, if you iterate – great; iterate, test and keep shipping until your target problem is solved.

Roadmaps

Much of Marty’s talk sounded like heresy… in that it would certainly sound blasphemous to many people I can think of.  His discussion on product roadmaps was no exception.

Roadmaps tend to assume that 100% of the ideas on them are good ideas.

The reality is somewhat different.  Marty cited Google: in their experience, for every 10 ideas they have (on a roadmap) only 1 tends to pan out.

Bad use of roadmaps relate back to the second point in “are you agile?” – in that people sometimes confuse delivery with completion.  People walk around with roadmaps and release schedules and focusing on getting stuff delivered.

So if that’s all wrong, what does right look like?

Essentially it comes back to having a strong product vision.

My notes on this part of the talk are scarce – a sign that I was either too deeply engrossed to write, or I agreed with what he said and felt no need to note the obvious.

In either case, the key takeaway for roadmaps takes heavily from the points above: focusing on the product vision – which I think we can safely extrapolate to:

  1. Understanding the customer and their problem.
  2. Giving your teams constraints and time to come-up with the unexpected.
  3. Iterating until solved, not just shipped.

Roadmaps and Agile

From a philosophical perspective, roadmaps are rational – they plan out what is to happen; whereas agile is empirical – it learns from what has happened.

Roadmaps attempt to answer the fundamental questions: how much will it cost, and when will we get it?  And as Marty acknowledges – that’s not an unreasonable thing to want to know.

Agile can answer these questions but only once you’ve done enough work, to provide enough meaningful experience, on which to base a forecast.  Marty elaborated on that theme in terms of a “high-integrity commitment”.  I don’t have any notes on that so allow me to refer you to Marty’s blog:

Teams

  • Measure teams as a whole; not in terms of “functional” teams, but product (solution) teams.  (What does this mean?  Think about the difference between “shipping” and “solving” and you’re pretty much there).
  • Provide teams with a competent and confident product manager.

Product Managers

The final subject I want to cover is around product managers – specifically good ones; it’s important to me because it’s highly relevant to what I see as a architect in solution-architect / domain-architect / enterprise-architect / consultant space.

Marty placed a lot of emphasis on the importance of having a good product manager.  For him the product manager is like the “CEO of the product”, where CEO refers to the calibre of the person in that role, and because good CEO’s know all the elements of their business.

Product managers need to be smart, creative and persistent.

The product manager should must have a deep understanding of:

  1. The customer(s).
  2. Industry trends.
  3. How your business works.

The reason you want a good product manager is because this is type of invaluable knowledge and wisdom they’ll bring to your team, and to your product.

How to Introduce Yourself as an IT Architect

If, like me, you are an “IT” architect, you’ll know that describing what you do to other people is a challenge… even to people who have some idea about information technology.

It’s definitely not like being a fireman.

I think where we go wrong is that we try to explain the totality of what we do, which is too much (too broad, too complex, too nuanced).  Instead, perhaps we should just pick one thing and put it in a context people will understand.

Let’s break it down.  Broadly I think architects do four things:

  1. Create visions
  2. Craft decisions
  3. Technical leadership
  4. Be wise gnomes

Creating visions is all about the ability to paint the metaphorical big picture.  It’s the big picture that helps people understand where we should all be going, and why.  Sometimes the vision is ours – we discover it; other times the vision comes from others – they simply need help crystallizing it and then communicating it.

Crafting decisions is about getting decisions made.  Sometimes it’s about guiding and facilitating people so that they make the necessary decisions, in a logical and sensible way;  other times we need to make and assert decisions – to break an impasse, fill a void, or provide a specific direction.

Technical leadership is about making sure the thing is well made.  It’s dealing with the nuts and bolts, widgets and gizmos.  It’s not just limited to which tools should we use and how should we put the parts together, it also extends into how we should structure our work so that complexity is managed.

Wise gnomes have been there before.  They’ve done that.  They have first-hand knowledge of where the traps are and experience in dealing with them.

Which of these resonates with you the most?  For me, it probably depends on my most recent project, so if someone asks me what I do I’d mentally gravitate to whatever was most front-of-mind.

Explaining it to someone

  1. Pick one thing that you do (i.e. one of the four above if you’re stumped).
  2. Put it into a context the person will relate to.

Putting it into context could mean using the metaphor of someone they know, someone with qualities that have some relevance to what you do:

“Basically I’m like Gandalf, I stop the team getting themselves into trouble, support through mentoring, and take the lead in making hard decisions.”

“I’m like the ‘Spock’ of our team – when something complicated needs to be solved I’m the go-to person for logical advice and to make sure we’re not going to break anything.”

Alternatively the context could be based on something you do:

“I’m like the translator that helps the techies figure out what people want, and I help people understand what the technology can do.  That means I usually get stuck in the middle and have to work out the hard problems.”

“I’m like the navigator of the ship – people have a vague idea of where they want to go but need help deciding exactly where and how to get there.  That’s kinda what I do in terms of choosing which technology we use and how we want to use it.”

“Oh, so you design computers?”
“Sort of, I design systems for [system purpose or name of organisation] and help make the big decisions like which technology we’ll use.”

I’m an IT architect

Do you start with “I’m an IT architect“, or something similar?  Personally I do.  Most people know a little about a regular (i.e. building / civil engineering architect) and that context is useful for helping to explain what is it you do.

Some of my peers think architect is becoming a dirty word in some circles – I hope that’s not really the case.

 

Remember the Audience

Finally, the important foundation underneath all of this, is to tailor your response to the audience – what background information you think they might already have, and how you want to come across.

You’ll notice that in the examples above I’ve largely avoided talking about the specifics of what we do, this is because successfully leveraging those topics requires the audience to already know what you are talking about.

I think the key is to just get the conversation successfully started – stick to small easy concepts, once that’s achieved you can elaborate further or add to it with additional information.