Learn to write software – Lesson 2 – HTML layout

Recap

In Lesson 1 we looked at how to write well-formed markup by following the rules of ensuring that our open tag <car> always ends with a closing tag </car> and any attribute values are enclosed in double quotes <car make=”Porche”></car>. The one thing we failed to talk about in our last lesson is using a special format to emit the closing tag. Instead of using <car></car> we can also use <car/>, this becomes useful where you don’t have any child-tags and maybe only have attributes, <car make=”Porche”/>.

What is HTML?

HTML stands for Hyper Text Markup Language and is the language the Web is built on. Every single website use some HTML. The exciting thing is HTML in the past few years started becoming a language of choice not only for building web pages but also applications on your PC, Mac and Smartphone. Many apps found on iPhone, Android, Windows Phone etc. are written with HTML.

HTML Versions

Before we start looking at how to write HTML we need to quickly talk about HTML through the ages. There is a body called W3C that looks after standards for all things Web, companies like Microsoft, Google, Apple, IBM etc. have an interest in this body and work together to form and adhere to standards for the web.

In the early 90s, html was written without much regard for standards and browsers accepted html in many forms. In 1999 W3C first released the HTML 4 standard and in 2000 the XHTML standard which is the XML format of HTML 4. These standards obviously described much more than just being well-formed.

Since 2000 we did not see much change in how HTML was formed but in 2012 a new standard was formed called HTML 5. This is a significant change in the HTML world and was only finalised as a complete standard in the third quarter of 2014.

We will focus on HTML 5 but in the real world it will probably take more than a decade before HTML 4 is not used anymore and in many cases you will find HTML 5 mixed with HTML 4 standards. Most browsers understand and interpret HTML 5 properly, so it make sense to set our focus on the future and try to learn HTML 5.

HTML 5 Tag and Attribute Syntax

I would have loved if HTML remained well-formed and remained readable by XML parsers , but the people that undoubtedly know more than me decided otherwise. I do still think wherever you are able, try and stick to tags and attributes being well formed.

You will find that some tags especially in the headers omit the closing tag and then the following attribute syntaxes are allowed:

Empty: <input type=”text” value=”John Doe” disabled>

Unquoted: <input type=”text” value=John Doe>

Double-quoted: <input type=”text” value=”John Doe”>

Single-quoted: <input type=”text” value=’John Doe’>

Hands on: Hello World

Let’s go ahead and write the simplest piece of HTML we can and see what it looks like in our browser.

Open Notepad and type the following:

<html>
<body>
    <p>Hello World!</p>
</body>
</html>

Save in Notepad with an extension .html, and double click on the file. The file will open in your browser with Hello World!

All HTML pages will have a open <html> and closing </html> and inside the html tags you will always have a <body></body> tag.

We made use of our first UI tag or element <p> which stands for paragraph. And the web page displayed our text inside the <p> tag.

Tags or Elements will give instruction to the browser rendering the web page how to construct your UI.

HTML Layout

Most HTML pages will have the following layout and special tags:

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8" />
    <meta name="description" content="Learn to write software"/>
    <meta name="keywords" content="HTML,Learn"/>
    <meta name="author" content="Anton"/>
    <meta name="viewport" content="initial-scale=1.0, width=device-width" />
    <title>Learn to write software – Lesson 2</title>
</head>
<body>
    <p>I want to learn</p>
    <p>to write software</p>
    <p>and publish my first HTML app</p>
</body>
</html>

 

<!DOCTYPE html> This tells any browser to interpret the HTML as HTML 5
<html> As you know by now, all html pages start this way
<head> This section is dedicated for special tags like meta tags that crawlers and robots use to index your page.
<meta> Meta is a description of data, and read by engines like Google search to index your page appropriately.
<meta name="description" This is the little blurp you will see when you search in Google and your page is indexed by Google. Best to keep this fairly short.
<meta name="keywords" This tell search engine, crawlers, robots what keywords to index for your page. When someone search for your page this will be taken in consideration, although there are many other rules that apply for optimal search engine rankings.
<meta name="author" For copyright reasons.
<meta name="viewport" This tells other devices like Smartphones to display your content for that device width.
<title> This is the title that will display when your page load in the browser.
<body> As you know by now, all html tags will have a body tag and in the body tag is the content of your web page.

Next Lesson

That concludes this lesson, in the next lesson we will start looking at HTML 5 specific layout and what actually makes HTML be version 5. Try and practice what you already know.

Categories: Learn Tags: ,

Learn to write software – Lesson 1 – Markup Language

January 21, 2015 1 comment

Introduction

In this series I am going to attempt to teach the art of programming to anyone that are able to read. My disclaimer is that my first language is not English and I am bound to make mistakes and sadly I am unable to “compile” English to make sure it works (okay, no more lame jokes).

Objective

In this lesson we are going to explore Markup Language, what is that you may ask. Markup Language is a standard text based format used to ensure that the target system or program will be able to read and interpret the text.

XML

XML is a standard markup format that forms the base of many other markup languages to some extend. XML stands for Extensible Markup Language and in this lesson we are going to learn how to write proper XML. You may ask why start here, well XML forms the base of HTML and XAML, two popular User Interface markup languages. You will learn quite a bit more about HTML in the lessons to follow, by the way HTML stands for Hyper Text Markup Language.

Tag or Element

The first thing we are going to learn is what is referred to as a XML/HTML Tag or Element. For the sake of sanity I will call this a tag going forward. A tag basically starts with a “<” sign followed by a specific word like cars and then followed again with a “>” sign.

Something like this: <cars>

A tag formed like this will always be referred to as an open tag which leads you to think, okay there must be a closing tag, and you will be correct an open tag ALWAYS must have a closing tag. Now there is special ways to a shortcut but I will explain that a bit later.

But there is a catch, you cant just use the same format for the closing tag like this <cars><cars> as that will not be well-formed markup. You need to add a “/” after the closing tag starting “<” bracket.

This is well formed <cars></cars>

Child-Tags or Child-Elements

The idea of having an opening <cars> and closing </cars> tag is so that you can add child tags and that the system that need to interpret your markup knows where your parent tag starts and ends. Usually if a tag does not contain child-tags it will contain text between the open and close tag as data.

As an example let’s add a few child tags to our cars parent tag and add the make of the car between the child open and close tag:

<cars>
  <car>Porche</car>
  <car>Ferrari</car>
  <car>Lamborghini</car>
</cars>

As you may have guessed this format is perfect to add multiple levels of child tags to describe your data. Let’s add a few more tags to show how we can expand the depth of our XML tree.

<cars>
  <car>
    <make>Porche</make>
    <models>
      <model>911 Carrera S</model>
      <model>Cayman S</model>
      <model>Boxter S</model>
    </models>
  </car>
  <car>
    <make>Ferrari</make>
    <models>
      <model>Testarossa</model>
      <model>Enzo</model>
      <model>California</model>
    </models>
  </car>
  <car>
    <make>Jeep</make>
    <models>
      <model>Cherokee</model>
      <model>Wrangler</model>
      <model>Patriot</model>
    </models>
  </car>
</cars>

Tag Attributes

Apart from using child-tags to give more information to a parent tag, we can also make use of attributes. Attributes are added after the start bracket “<” and name of the tag and will always have its own name followed by an “=” sign and then VERY important the value of the attribute is then enclosed in double quotes to start and end the value.

Here is an example: <car make=”Porche></car>

It is very important to remember that the value of your attribute must always be enclosed in double quotations to be well-formed markup.

Let’s add the make of our above expanded XML as an attribute instead of a child-tag and also the add the country of origin as another attribute:

<cars>
  <car make="Porche" country="Germany">
    <models>
      <model>911 Carrera S</model>
      <model>Cayman S</model>
      <model>Boxter S</model>
    </models>
  </car>
  <car make="Ferrari" country="Italy">
    <models>
      <model>Testarossa</model>
      <model>Enzo</model>
      <model>California</model>
    </models>
  </car>
  <car make="Jeep" country="America">
    <models>
      <model>Cherokee</model>
      <model>Wrangler</model>
      <model>Patriot</model>
    </models>
  </car>
</cars>

Hands-on

Now it is time for you to write your first XML file and to make sure it is well-formed:

  1. Open Notepad (or any other text editor)
  2. Create a collection of animals and add an attribute to each child tag for the animal’s legs and another for it’s food.
  3. For extra points make a collection of food for each animal and list the different food items.
  4. Save your text file with the extension .xml
  5. Open your .xml file in Internet Explorer to make sure it is well-formed. If you see the layout of your XML then it is correct otherwise you will just see a white page.
Categories: Learn Tags: ,

Cocos2d-x baby steps

I blog for my own reference, if it helps you it is a bonus, so here is my journey as I try and understand the world of game writing in C++

Watch these Videos

Thanks to Sanjeev Dwivedi, Dale Stammen and Eric Mittelette a great starter course is available here http://www.microsoftvirtualacademy.com/training-courses/build-a-game-with-cocos2d-x-for-windows-devices

Download the Tools

You are going to need to following tools:

Download the Universal App Template

One of creators of Cocos2d (Dale Stammen) works closely with the Microsoft Open Technologies team that created a template for cocos2d that includes a Universal App that can run on both Windows Phone and Windows 8.x

The following is an extract from the video above that you will require to get going:

  1. Once you have all the Tools installed listed above
  2. Create a directory somewhere to store your code like C:\GameDev
  3. Right click in the directory and select Git Bash. This option should be available after you installed Git and probably rebooted your PC.
  4. Run the following command in the Git Bash window
  5. $ git clone https://github.com/MSOpenTech/cocos2d-x.git
  6. This will take a little while to download > 300mb

Install the Cocos2d Dependencies

Once the Template is downloaded you need to run the python file located in the root of your source. This will download the dependencies required.

  1. In File Explorer double click on the Python file download-deps.py  located in the cocos2d-x directory.

Create a project from the Template

You will now use the python template to create a project that you can open in Visual Studio.

  1. In your command prompt
  2. Go to the directory where you downloaded the Cocos2d-x source
  3. Go to the sub-directory \tools\project-creator
  4. Run the following Python command. create_project
  5. You will see the help with the parameters that are required
  6. You can choose your own names but it needs to be something like this create_project -project MyGame -package com.MyCompany.game -language cpp
  7. Browse to your source to see the newly created Projects folder with your game source, something like this C:\GameDev\cocos2d-x\projects\MyGame

Open the Universal App

Once you completed all the steps above you will have your game source ready to develop for almost any platform. To open the project:

  1. Under your MyGame source you will find a directory \proj.win8.1-universal.
  2. Double click the Solution file
  3. Do a clean solution and a rebuild solution from within Visual Studio and make sure it builds.

Download Rocket man source

You are now ready to download the source for the game as used in the video above. The git source can be found here https://github.com/sanjeevdwivedi/rocket-man-game

  1. Open the command prompt or Git Bash in your game source folder root C:\GameDev
  2. Run the following command: git clone https://github.com/sanjeevdwivedi/rocket-man-game.git

Add Rocket-man to the Universal App

You will need to make a few changes in order to get this working and this was ultimately my goal of this blog as it took me a few hours to figure out all the little gremlins. There are two important directories in the root of your source Classes and Resources

  1. You need to make sure you copy Classes and Resources from the root of rocket-man-game to your new Universal app source MyGame in my case. Overwrite all files when prompted.
  2. Open your Universal App solution, MyGame
  3. Expand the project MyGame.Shared
  4. Expand the Classes folder and select all files and right click and choose Remove
  5. Right click on the Classes folder and choose Add –> Existing, choose all the files in your Classes folder, in my case C:\GameDev\cocos2d-x\projects\MyGame\Classes
  6. You are ready to build your application although you may find some errors that I will explain below

ERROR FIX: error C2661: ‘cocos2d::CCMenuItemLabel::create’ : no overloaded function takes 2 arguments

This is the first error I encountered and I believe it happens due to the compiler directive not accepting a CCObject for Win8, but we are using Win8.1

So in your HighScoresLayer.cpp  make sure your signature looks something like this

void HighScoreLayer::_changePlayerDone(CCObject* pObject)

void HighScoreLayer::_cancelPopupPlayer(CCObject* pObject)

and the HighScoresLayer.h

void _changePlayerDone(CCObject* pObject);

void _cancelPopupPlayer(CCObject* pObject);

 

ERROR FIX: App starts but crash

If you add a breakpoint to the first line of the constructor of the MainLayer you will notice that the application crash trying to load sprites.png. The reason for this is it seems that Windows Phone and Windows require these assets to be added as resources.

  1. Expand the MyGame.WindowsPhone project
  2. Right click on Assets and Add –> Existing
  3. Choose all the files in your \Resources\Images and \Resources\fonts and add them.
  4. Make sure you did copy all the Resources from the Rocket-man source
  5. Right click on the Font files in your Assets directory and choose Properties
  6. Click on the dropdown under Content and select Yes
  7. image

Make the App start in Portrait

Rocket-man or TweeJump was designed to run in Portrait mode, so make sure to change the following:

  1. Expand your WindowsPhone and Windows projects
  2. Open the Package.appxmanifest file
  3. Choose Portrait

image

 

Special Thanks

Just a special thanks to Sanjeev Dwivedi, Dale Stammen and Eric Mittelette for the course material and the example source. Without you guys it would have been a very difficult exercise. I am hoping to see the cocos2d-x 3.3 version material soon, maybe adding some cool 3d images and skeleton animations.

Categories: Cocos2d-x

Create .NET Simple Membership Tables

If you created a new Web API project you might feel slightly lost how to create your tables in a SQL server database instead of the local MDB file. Good news is, it is really easy…

 

Change your Web.config

Two changes are required in the web.config file.

 

1. Change the DefaultConnection connection string. In your web.config change the DefaultConnection to point to your local or remote SQL server installation. Something like this:

<add name=”DefaultConnection” connectionString=”Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True” providerName=”System.Data.SqlClient” />

2. Change the EntityFramework section to not point to a local database

<entityFramework>
<defaultConnectionFactory type=”System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework”>
<parameters>
<parameter value=”v11.0″ />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName=”System.Data.SqlClient” type=”System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer” />
</providers>
</entityFramework>

 

Register a user using the API

If you run your new project and click on HELP or navigate to /help you will see all the APIs for your project. We are going to use the api/Account/Register API to create our tables.

1. Open a Web Debugger like Fiddler to

image

  • Enter the localhost url including your unique port as follows  http://localhost:51505/api/Account/Register
  • Change the type to POST
  • In the header add a new header item content-type: application/json
  • In the body add your JSON class

{
“Email”: anton@wordpress.com,
“Password”: “SomePassword01”,
“ConfirmPassword”: “SomePassword01”
}

  • And Execute the POST call

View your tables

If you open your database in SQL server you will notice that .Net would have created all the necessary tables for you

image

Categories: Web API (MVC 4)

Consuming RESTful Services from a Command Line

Objective

Install HTTPIE to use as follows

$ http -f POST example.org hello=World
$ http DELETE example.org/todos/7

What to Download and Install

Download and Install Python https://www.python.org/download . Add the Installed path C:\PythonX to your Path. Found in Environment Variables. You can run the command Path in your command prompt after changing your Path to apply your changes.

Install PIP

Right click on this link and save file to your PythonX directory.  get-pip.py. You can also get instructions here https://pip.pypa.io/en/latest/installing.html.

Open Powershell in Administrator mode. Go to your PythonX directory and run this command.

python get-pip.py

Install HTTPIE

In Powershell in Administrator mode run the following command:

pip --allow-external install --upgrade httpie

Read More

https://github.com/jakubroztocil/httpie#installation

 

Categories: RESTful

Finding the table name of a specific column name

Introduction

I recently faced the challenge of finding to what table a specific column belongs to. Trying to add some logic to an overly complicated and very old stored procedure with more lines than Shakespeare’s Romeo and Juliet I was faced with the lovely error “Procedure x, Line y Ambiguous column name ‘TypeID’. Below is an easy script to find a specific column.

T-SQL

SELECT S.name as SchemaName,O.name as ObjectName, O.type_desc as ObjectType,C.name
FROM sys.schemas S
INNER JOIN sys.objects O ON S.schema_id=O.schema_id
INNER JOIN sys.columns C ON O.object_id=C.object_id
WHERE O.type in(‘U’,’V’) and C.name = ‘TypeID’
ORDER BY S.name,O.type_desc, O.name,C.Name

Resources

Thanks to SQL Like

Categories: TSQL

Keeping the Session alive when running Silverlight

What is the problem?

It happens every so often that you will experience an error after a while when trying to access your RIA services from your Silverlight application. The error will usually be some sort of “Load Operation failed for query” message.

What is the Solution?

I discovered that this happens when the session on the server expires and keeping it alive stopped this error from happening.

How to do this?

1. Create a Ping.ashx file and add the following code to the code-behind:

public class PingHttpHandler : IHttpHandler, IRequiresSessionState
{

public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = “text/plain”;

ContactDomainService service = new ContactDomainService();
bool heartBeat = service.HeartBeat();

context.Response.Write(heartBeat.ToString());
}

public bool IsReusable
{
get
{
return false;
}
}
}

2. Add Javascript to your Master page or Page hosting the Silverlight plugin

In your Master page or plugin hosted web page add the following script:

<script type=”text/javascript” src=”Scripts/jquery-1.4.4.js”></script>
<script type=”text/javascript”>
function heartbeat() {
$.get(“~/Ping.ashx?what=resuldata”);
}

$(document).ready(function () {
setInterval(heartbeat, 900000); // 15 minutes
});
</script>

Make sure your paths are correct for the files you reference.

Final words

We found this code from some source on the web a long time ago. I am not sure exactly where I did find this, if you recognize it, let me know please.

Categories: RIA Services

Sharing data between Pages in Silverlight using MVVM

Intro

Recently someone asked on the silverlight.net forums how they can change an Image loaded on Page1 and Page2 from the MainPage. Although there might other ways of doing this I would recommend using MVVM for the sake of good coding practices.

MVVM

Just shortly MVVM which stands for Model-View ViewModel is a pattern that address separation of concerns between the View and ViewModel which in short is the UI and it’s code. One of the main reasons for doing this is to enable your code to be tested more easily with Unit Testing since all code in the ViewModel is unaware of a View therefore unaware of things that ties it to a specific View Implementation like button clicks with specific signatures etc. It also just all around creates a cleaner implementation of your code that is easier to maintain and will most probably have a longer life than code that is tightly coupled into the UI. Other patterns that address this issue are MVC and MVP.

Create the Views

So from the Intro we want to create a simple Navigation project in Silverlight using the Navigation template or Business template. We then want to add two pages Page1 and Page2 that we can navigate to, so here some quick steps:

  1. Open Visual Studio 2010
  2. Create a new Project choosing the Navigation template
    • The template will create a MainPage view for you with the menu having pages for home and about already.
  3. Right click on the View folder in your SL application and add a New Page and call it Page1
  4. Repeat Step 3 but add another page called Page2
  5. Add two links to your menu for Page 1 and Page 2 like so:

<Border x:Name="LinksBorder" Style="{StaticResource LinksBorderStyle}">
<StackPanel x:Name="LinksStackPanel" Style="{StaticResource LinksStackPanelStyle}">
<HyperlinkButton x:Name="Link1" Style="{StaticResource LinkStyle}"
NavigateUri="/Home" TargetName="ContentFrame" Content="home"/>

<Rectangle x:Name=”Divider1″ Style=”{StaticResource DividerStyle}”/>
<HyperlinkButton x:Name=”Link2″ Style=”{StaticResource LinkStyle}”
NavigateUri=”/About” TargetName=”ContentFrame” Content=”about”/>
<HyperlinkButton Style=”{StaticResource LinkStyle}”
NavigateUri=”/Page1″ TargetName=”ContentFrame” Content=”page 1″/>
<HyperlinkButton Style=”{StaticResource LinkStyle}”
NavigateUri=”/Page2″ TargetName=”ContentFrame” Content=”page 2″/>
</StackPanel>
</Border>

When you run the application you will notice your menu will have 2 new menu items, make sure you can click on them and that they do take you to your newly created blank pages.

Create the ViewModel

So let’s first define the ViewModel before wiring the View and ViewModel together.

  1. Create a new folder in your SL project, called ViewModel.
  2. Right click on the ViewModel folder and click on Add Class and name the class SomeViewModel.cs
  3. We need to inherit from INotifyPropertyChanged. I would strongly advise your create your own ViewModelBase that inherit and implement this interface or download the MVVM light toolkit and use this. We make use of the MVVM light toolkit as it Command ability is very simple to implement. http://mvvmlight.codeplex.com/
  4. For the sake of completeness we will inherit directly from INotifyPropertyChanged.
  5. Add a Property that will contain your Image as below:

using System.ComponentModel;
using System.Windows.Media.Imaging;

namespace SilverlightApplication2.ViewModel
{
public class MainViewModel: INotifyPropertyChanged
{
#region SomeImage

private BitmapImage _SomeImage = new BitmapImage(new Uri(“http://www.sa-venues.com/gallery/tablemountain-01.jpg”, UriKind.Absolute));
public BitmapImage SomeImage
{
get { return _SomeImage; }
set
{
if (_SomeImage != value)
{
_SomeImage = value;
RaisePropertyChanged(“SomeImage”);
}
}
}

#endregion SomeImage

#region INotifyPropertyChanged Implementation

public event PropertyChangedEventHandler PropertyChanged;

private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

#endregion INotifyPropertyChanged Implementation
}
}

Creating the ViewModelLocator

The ViewModelLocator is a class that can be referenced from the View to discover the ViewModel. The MVVM light toolkit has some easy implementations of this see http://mvvmlight.codeplex.com/documentation for more information.

Again for the sake of completeness we will take slightly different route but I would advise you make use of the MVVM light toolkit for this.

  1. Add the following code to your App.xaml.cs

private static MainViewModel _ViewModel = null;
public static MainViewModel ViewModel
{
get
{
if (_ViewModel == null)
_ViewModel = new MainViewModel();

return _ViewModel;
}
}

  1. Right click on the ViewModel folder and Add a new Class, name the class ViewModelLocator.cs
  2. Add the following code into the ViewModelLocator:

public class ViewModelLocator
{
public MainViewModel MainViewModel
{
get { return App.ViewModel; }
}
}

Again this is a shortcut and not necessarily the best way of implementing a ViewModelLocator.

Wiring up the View to the ViewModel

Add a new namespace to your Page1 and Page2 (Make sure to copy your ViewModel’s namespace exactly as you created it to replace below where we used SilverlightApplication2)

xmlns:vm="clr-namespace:SilverlightApplication2.ViewModel"

Add a Resource to the UserControl as follows:

<UserControl.Resources>
<vm:ViewModelLocator x:Key="ViewModelLocator"/>
</UserControl.Resources>

Add a Image to your Page as follows:

<Image Source="{Binding MainViewModel.SomeImage, Mode=TwoWay, Source={StaticResource ViewModelLocator}}"/>

Do the above for both Page1 and Page2

Adding a button to change the Image

When your navigation framework loads it will load the Home.xaml page as the first page, so we are going to add a simple button on this page to change the picture on Page1 and Page2.

  1. Open View\Home.xaml
  2. Add the following button to the Page

<StackPanel x:Name="ContentStackPanel">
<TextBlock x:Name="HeaderText" Style="{StaticResource HeaderTextStyle}"
Text="Home"/>
<TextBlock x:Name="ContentText" Style="{StaticResource ContentTextStyle}"
Text="Home page content"/>
<Button Content="Change Picture" Click="Button_Click"/>
</StackPanel>

3. In the Codebehind of the Home.xaml page add the following code to change the picture.

private void Button_Click(object sender, RoutedEventArgs e)
{
App.ViewModel.SomeImage = new BitmapImage(new Uri("http://www.sa-venues.com/gallery/tablemountain-02.jpg", UriKind.Absolute));
}

Run the App

When you done with the steps above, run the application and click on Page1 and Page2, you will notice that a Image will be loaded.

Click on home from the menu and click on the Change Picture button, the Image will change to the image specified in your code behind.

Final words

There are great resources on proper implementation of the MVVM pattern, see the MVVM light toolkit and JohnPappa.net for more resources.

Categories: MVVM Pattern

Adding drawings from Expression Design to XAML

Recently I’ve seen a question how to add “clipart” from Blend to your Silverlight application. This is one of the many things that makes XAML just beyond powerful, anything can become any control and re-used where ever you like.

Below I will show some steps how to add a Happy face button and a Sad face button by copying your Expression Design XAML.

HappySadFaces

In Expression Design

  1. Open Expression Design
  2. Draw a Sad face
  3. Go to Select > All (ctrl + a)
  4. Go to Object > Compound Path > Make (ctrl + 8 )
  5. Go to Edit > Copy XAML

The XAML that would have been copied would look something like this:

<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="Layer_1_4" Width="266.633" Height="266.633" Canvas.Left="0" Canvas.Top="0">
<Path Width="58.6593" Height="61.9922" Canvas.Left="58.6593" Canvas.Top="59.6592" Stretch="Fill" StrokeThickness="1.33317" StrokeLineJoin="Round" Stroke="#FF000000" Fill="#FFFFFFFF" Data="M 73.4908,70.9911C 80.7617,70.9911 86.6558,75.9153 86.6558,81.9897C 86.6558,88.0641 80.7617,92.9884 73.4908,92.9884C 66.22,92.9884 60.3258,88.0641 60.3258,81.9897C 60.3258,75.9153 66.22,70.9911 73.4908,70.9911 Z M 102.487,72.9908C 109.942,72.9908 115.986,77.9151 115.986,83.9895C 115.986,90.0639 109.942,94.9881 102.487,94.9881C 95.0323,94.9881 88.9889,90.0639 88.9889,83.9895C 88.9889,77.9151 95.0323,72.9908 102.487,72.9908 Z M 84.4894,95.6547C 93.7851,95.6547 101.321,98.3407 101.321,101.654C 101.321,104.967 93.7851,107.653 84.4894,107.653C 75.1938,107.653 67.6582,104.967 67.6582,101.654C 67.6582,98.3407 75.1938,95.6547 84.4894,95.6547 Z M 78.6568,81.3232C 77.6166,82.1034 76.7421,83.8263 77.3237,84.9893C 77.6047,85.5515 78.0471,86.1701 78.6568,86.3225C 79.1388,86.443 79.7012,86.0603 79.99,85.6559C 80.9925,84.2525 80.3682,80.8705 78.6568,80.6566C 78.2159,80.6015 77.6379,80.3423 77.3237,80.6566C 76.2211,81.7592 76.8997,83.9595 77.657,85.3227C 77.9716,85.8889 78.009,86.9891 78.6568,86.9891C 80.0084,86.9891 79.2898,82.6183 77.9903,82.9896C 77.3674,83.1676 76.91,84.0133 76.9904,84.6561C 77.0593,85.2073 77.8078,85.8623 78.3236,85.6559C 78.8495,85.4456 78.5943,84.5525 78.6568,83.9895C 78.7059,83.5478 78.6568,83.1007 78.6568,82.6563C 78.6568,82.2119 79.1012,81.3232 78.6568,81.3232C 78.16,81.3232 78.2125,82.2119 77.9903,82.6563M 94.3216,82.323C 94.0994,82.7674 93.7755,83.1742 93.655,83.6562C 93.2423,85.3069 92.9242,88.55 94.6548,84.6561C 94.8409,84.2375 95.4462,83.3229 94.9881,83.3229C 92.2773,83.3229 94.2593,90.6553 95.3214,90.6553C 97.9901,90.6553 98.2207,81.9232 95.6547,82.6563C 95.1206,82.8089 94.9881,83.5451 94.6548,83.9895C 94.3216,84.4339 93.85,84.8025 93.655,85.3227C 93.4989,85.7387 93.655,86.2114 93.655,86.6558C 93.655,87.1002 93.2106,87.989 93.655,87.989C 94.2105,87.989 94.4064,87.1527 94.6548,86.6558C 94.8597,86.2461 94.9313,85.7772 94.9881,85.3227C 95.0433,84.8817 95.4325,83.9895 94.9881,83.9895C 94.4913,83.9895 94.4421,84.8406 94.3216,85.3227C 94.2138,85.7538 94.3216,86.2114 94.3216,86.6558M 88.3223,69.3246C 86.9834,65.9774 84.4861,63.2099 82.3231,60.3258M 95.3214,67.3249C 97.5278,66.2217 99.5764,64.7364 101.321,62.9921M 59.3259,118.985C 61.1582,117.611 62.5141,115.456 64.6586,114.652C 66.323,114.028 68.2137,114.652 69.9913,114.652C 74.7684,114.652 79.5748,115.18 84.3228,114.652C 87.6372,114.284 91.0072,114.687 94.3216,114.319C 98.8541,113.815 103.562,112.546 107.987,113.652C 111.657,114.57 114.382,117.958 116.652,120.985"/>
</Canvas>

Repeat the process but this time make a happy face.

In Expression Blend

Now we will create the Buttons that you can use for your art.

  1. Open Expression Blend
  2. Create a new Silverlight or other XAML based application (WPF, Windows Phone, Windows 8 etc)
  3. Paste the XAML for the Happy and the Sad faces.
  4. You will have 2 Canvas controls in your Object window as shown below:
    •  ExpressionBlend
  5. Right click on each Canvas and select Ungroup so that only your two Path objects are shown.
  6. Right click on each Path and choose Make Into Control.
  7. The default control for the Make Into Control window is a button.
  8. Name the sad face ButtonStyleSad and the happy face ButtonStyleHappy.

The XAML markup

If you look at the markup created for you by Blend you will notice you have two Resources that was added to your control as follows:

<UserControl.Resources>
<Style x:Key="ButtonStyleHappy" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Path Data="M 73.4908,70.9911C 80.7617,70.9911 86.6558,75.9153 86.6558,81.9897C 86.6558,88.0641 80.7617,92.9884 73.4908,92.9884C 66.22,92.9884 60.3258,88.0641 60.3258,81.9897C 60.3258,75.9153 66.22,70.9911 73.4908,70.9911 Z M 102.487,72.9908C 109.942,72.9908 115.986,77.9151 115.986,83.9895C 115.986,90.0639 109.942,94.9881 102.487,94.9881C 95.0323,94.9881 88.9889,90.0639 88.9889,83.9895C 88.9889,77.9151 95.0323,72.9908 102.487,72.9908 Z M 84.4894,95.6547C 93.7851,95.6547 101.321,98.3407 101.321,101.654C 101.321,104.967 93.7851,107.653 84.4894,107.653C 75.1938,107.653 67.6582,104.967 67.6582,101.654C 67.6582,98.3407 75.1938,95.6547 84.4894,95.6547 Z M 58.326,112.653C 60.5442,118.198 65.9825,122.313 71.3244,124.984C 79.7432,129.194 89.6327,131.69 98.9876,130.65C 102.909,130.215 105.906,126.782 108.986,124.318C 113.22,120.931 118.227,117.835 120.652,112.986M 78.6568,81.3232C 77.6166,82.1034 76.7421,83.8263 77.3237,84.9893C 77.6047,85.5515 78.0471,86.1701 78.6568,86.3225C 79.1388,86.443 79.7012,86.0603 79.99,85.6559C 80.9925,84.2525 80.3682,80.8705 78.6568,80.6566C 78.2159,80.6015 77.6379,80.3423 77.3237,80.6566C 76.2211,81.7592 76.8997,83.9595 77.657,85.3227C 77.9716,85.8889 78.009,86.9891 78.6568,86.9891C 80.0084,86.9891 79.2898,82.6183 77.9903,82.9896C 77.3674,83.1676 76.91,84.0133 76.9904,84.6561C 77.0593,85.2073 77.8078,85.8623 78.3236,85.6559C 78.8495,85.4456 78.5943,84.5525 78.6568,83.9895C 78.7059,83.5478 78.6568,83.1007 78.6568,82.6563C 78.6568,82.2119 79.1012,81.3232 78.6568,81.3232C 78.16,81.3232 78.2125,82.2119 77.9903,82.6563M 94.3216,82.323C 94.0994,82.7674 93.7755,83.1742 93.655,83.6562C 93.2423,85.3069 92.9242,88.55 94.6548,84.6561C 94.8409,84.2375 95.4462,83.3229 94.9881,83.3229C 92.2773,83.3229 94.2593,90.6553 95.3214,90.6553C 97.9901,90.6553 98.2207,81.9232 95.6547,82.6563C 95.1206,82.8089 94.9881,83.5451 94.6548,83.9895C 94.3216,84.4339 93.85,84.8025 93.655,85.3227C 93.4989,85.7387 93.655,86.2114 93.655,86.6558C 93.655,87.1002 93.2106,87.989 93.655,87.989C 94.2105,87.989 94.4064,87.1527 94.6548,86.6558C 94.8597,86.2461 94.9313,85.7772 94.9881,85.3227C 95.0433,84.8817 95.4325,83.9895 94.9881,83.9895C 94.4913,83.9895 94.4421,84.8406 94.3216,85.3227C 94.2138,85.7538 94.3216,86.2114 94.3216,86.6558M 88.3223,69.3246C 86.9834,65.9774 84.4861,63.2099 82.3231,60.3258M 95.3214,67.3249C 97.5278,66.2217 99.5764,64.7364 101.321,62.9921M 95.988,84.9893C 95.7658,85.4337 95.8183,86.3225 95.3214,86.3225C 94.8246,86.3225 95.1517,84.9893 94.6548,84.9893C 94.6548,84.9893 95.3214,92.3863 95.3214,85.3227C 95.3214,84.8258 94.8293,86.1906 94.6548,86.6558C 94.494,87.0847 93.9404,87.7349 94.3216,87.989C 94.735,88.2646 95.2413,87.0468 95.6547,87.3224C 96.0359,87.5765 95.7795,88.6556 95.3214,88.6556C 94.8634,88.6556 95.5979,87.7769 95.6547,87.3224C 95.7098,86.8814 96.0991,85.9892 95.6547,85.9892C 95.2103,85.9892 95.6547,87.7668 95.6547,87.3224C 95.6547,86.7669 95.5762,86.2058 95.6547,85.6559C 95.6899,85.41 95.8769,85.2115 95.988,84.9893 Z " Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" StrokeThickness="1.33317" StrokeLineJoin="Round" UseLayoutRounding="False"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ButtonStyleSad" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Path Width="58.6593" Height="61.9922" Canvas.Left="58.6593" Canvas.Top="59.6592" Stretch="Fill" StrokeThickness="1.33317" StrokeLineJoin="Round" Stroke="#FF000000" Fill="#FFFFFFFF" Data="M 73.4908,70.9911C 80.7617,70.9911 86.6558,75.9153 86.6558,81.9897C 86.6558,88.0641 80.7617,92.9884 73.4908,92.9884C 66.22,92.9884 60.3258,88.0641 60.3258,81.9897C 60.3258,75.9153 66.22,70.9911 73.4908,70.9911 Z M 102.487,72.9908C 109.942,72.9908 115.986,77.9151 115.986,83.9895C 115.986,90.0639 109.942,94.9881 102.487,94.9881C 95.0323,94.9881 88.9889,90.0639 88.9889,83.9895C 88.9889,77.9151 95.0323,72.9908 102.487,72.9908 Z M 84.4894,95.6547C 93.7851,95.6547 101.321,98.3407 101.321,101.654C 101.321,104.967 93.7851,107.653 84.4894,107.653C 75.1938,107.653 67.6582,104.967 67.6582,101.654C 67.6582,98.3407 75.1938,95.6547 84.4894,95.6547 Z M 78.6568,81.3232C 77.6166,82.1034 76.7421,83.8263 77.3237,84.9893C 77.6047,85.5515 78.0471,86.1701 78.6568,86.3225C 79.1388,86.443 79.7012,86.0603 79.99,85.6559C 80.9925,84.2525 80.3682,80.8705 78.6568,80.6566C 78.2159,80.6015 77.6379,80.3423 77.3237,80.6566C 76.2211,81.7592 76.8997,83.9595 77.657,85.3227C 77.9716,85.8889 78.009,86.9891 78.6568,86.9891C 80.0084,86.9891 79.2898,82.6183 77.9903,82.9896C 77.3674,83.1676 76.91,84.0133 76.9904,84.6561C 77.0593,85.2073 77.8078,85.8623 78.3236,85.6559C 78.8495,85.4456 78.5943,84.5525 78.6568,83.9895C 78.7059,83.5478 78.6568,83.1007 78.6568,82.6563C 78.6568,82.2119 79.1012,81.3232 78.6568,81.3232C 78.16,81.3232 78.2125,82.2119 77.9903,82.6563M 94.3216,82.323C 94.0994,82.7674 93.7755,83.1742 93.655,83.6562C 93.2423,85.3069 92.9242,88.55 94.6548,84.6561C 94.8409,84.2375 95.4462,83.3229 94.9881,83.3229C 92.2773,83.3229 94.2593,90.6553 95.3214,90.6553C 97.9901,90.6553 98.2207,81.9232 95.6547,82.6563C 95.1206,82.8089 94.9881,83.5451 94.6548,83.9895C 94.3216,84.4339 93.85,84.8025 93.655,85.3227C 93.4989,85.7387 93.655,86.2114 93.655,86.6558C 93.655,87.1002 93.2106,87.989 93.655,87.989C 94.2105,87.989 94.4064,87.1527 94.6548,86.6558C 94.8597,86.2461 94.9313,85.7772 94.9881,85.3227C 95.0433,84.8817 95.4325,83.9895 94.9881,83.9895C 94.4913,83.9895 94.4421,84.8406 94.3216,85.3227C 94.2138,85.7538 94.3216,86.2114 94.3216,86.6558M 88.3223,69.3246C 86.9834,65.9774 84.4861,63.2099 82.3231,60.3258M 95.3214,67.3249C 97.5278,66.2217 99.5764,64.7364 101.321,62.9921M 59.3259,118.985C 61.1582,117.611 62.5141,115.456 64.6586,114.652C 66.323,114.028 68.2137,114.652 69.9913,114.652C 74.7684,114.652 79.5748,115.18 84.3228,114.652C 87.6372,114.284 91.0072,114.687 94.3216,114.319C 98.8541,113.815 103.562,112.546 107.987,113.652C 111.657,114.57 114.382,117.958 116.652,120.985"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>

And two buttons whose Style has been set to that of the respective Resources as follows:

<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Button" Height="71.893" Style="{StaticResource ButtonStyleHappy}" Width="63.659" HorizontalAlignment="Left" Margin="237,99,0,0" VerticalAlignment="Top"/>
<Button Content="Button" Height="71.893" Style="{StaticResource ButtonStyleSad}" Width="63.659" HorizontalAlignment="Left" Margin="140,99,0,0" VerticalAlignment="Top"/>
</Grid>

Final Thoughts

Best practise would be to move your Resources to a separate Style file that is hosted in your application on application level. That way you can re-use it everywhere in your application.

Another nice thing you can do is to create a separate Style file just for your art that you can use between applications by just copying the Style file each time.

Categories: XAML

Writing an Image to SQL CE / Linq to SQL

October 28, 2011 20 comments

Here is a short few steps I used to write an image to a SQL CE database on Windows Phone 7. As you may know Windows Phone 7.5 Mango supports SQL CE which makes it very convenient to store data in a proper relational database on the phone.

Creating the Column

 

There is some excellent help how to create your first SQL CE database which can be found here: http://msdn.microsoft.com/en-us/library/hh286405(v=VS.92).aspx

To create the column add the following code to your [Table] class:

[Column]
        public byte[] ItemImage
        {
            get { return _ItemImage; }
            set
            {
                if (_ItemImage != value)
                {
                    _ItemImage = value;
                    NotifyPropertyChanging(“ItemImage”);
                    NotifyPropertyChanged(“ItemImage”);
                }
            }
        }

Method for Adding the Image to the your Database

 

This method will take the stream you pass from your CameraCaptureTask and convert it to a byte array that can be saved in your database:

private byte[] GetImageBytes(Stream stream)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                WriteableBitmap wb = PictureDecoder.DecodeJpeg(stream, 200, 200);
                wb.SaveJpeg(ms, 200, 200, 0, 30);
                return ms.ToArray();
            }
        }

public void AddNewItem(Stream image, string url)
        {
            //Get Byte array of Image
            byte[] byteArray = GetImageBytes(image);

            //Add Image to Database
            MyDatabaseItem item = new MyDatabaseItem { Count = 1, ItemImageUrl = url, ItemImage = byteArray };
            MyDatabaseItemModel.Add(item);
            MyDatabaseDB.MyDatabaseItems.InsertOnSubmit(item);
            MyDatabaseDB.SubmitChanges();
        }

Showing the Image from your database in XAML

 

You need to make use of a converter that convert the byte array to a BitmapImage, here is the code for the converter you can use:

public class ImageConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is byte[])
            {
                MemoryStream memoryStream = new MemoryStream(value as byte[]);
                WriteableBitmap writeBitmap = PictureDecoder.DecodeJpeg(memoryStream, 200, 200);
                return writeBitmap;
            }
            else
                return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

And then you will need to call the converter in your Image XAML:

<Image Source="{Binding ItemImage, Converter={StaticResource ImageConverter}}" Stretch="UniformToFill"/>

Categories: Windows Phone