Windows Phone - Close application like Windows 8

This is just a little experiment in Windows Phone where I can drag the application from top to bottom to close.. Just like Windows 8 App.

Cool right?

I just took my WPF code and implemented it in Windows Phone to see what it looks like but I think it's cool to see something like that. 

Here's a video preview of the app

You can download the code and play with it. You can also use this in your WPF applications since the code is written in MVVM pattern. Just make sure to add WPF in your Conditional Compilation Symbols.

So how to use?

Let's check out the XAML first

<Grid x:Name="LayoutRoot" Background="Transparent">
	<!-- we need canvas so we can use the Top and Left property instead of dealing with Margins -->
	<Canvas>
		<Grid x:Name="MainContent" Canvas.Top="0" Canvas.Left="0" Width="480" Height="760" Background="#FF137900">
			<Grid.RowDefinitions>
				<RowDefinition Height="Auto"/>
				<RowDefinition Height="*"/>
			</Grid.RowDefinitions>
	
			<!--TitlePanel contains the name of the application and page title-->
			<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
				<TextBlock x:Name="ApplicationTitle" Text="Start dragging here from top to bottom" Style="{StaticResource PhoneTextNormalStyle}"/>
				<TextBlock x:Name="PageTitle" Text="ala Windows 8" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
			</StackPanel>

			<!--ContentPanel - place additional content here-->
			<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
		</Grid>

		<!-- our drag bar which is just sitting on top -->
		<Grid x:Name="DragBar" Height="45" Canvas.Top="0" Canvas.Left="0" Background="Transparent" Cursor="Hand" />
	</Canvas>
</Grid>

If you notice, I used Canvas element, because using it is much easier for dealing with child element locations just by using Top and Left properties. It's important that the DragBar grid has to be the last child so it will always stay at the top of other child elements in the Canvas.

Since the code is fairly written in MVVM, you can just it by implementing the iDragComponents interface and instantiating ViewModel_DragComponents class

public partial class MainPage : PhoneApplicationPage, iDragComponents
{
	ViewModel_DragComponents dragcomp;

	// Constructor
	public MainPage()
	{
		InitializeComponent();
		InitializeObjects();
	}

	void InitializeObjects()
	{
		this.dragcomp = new ViewModel_DragComponents(this);
		this.dragcomp.HasToClose += new HasToCloseHandler(dragcomp_HasToClose);
		this.dragcomp.Distance = 200;
	}
	
	// has reached the distance
	void dragcomp_HasToClose(object o, EventArgs e)
	{
		NavigationService.GoBack();
	}

	#region iDragComponents implementation
	public Grid ContentGrid
	{
		get { return this.MainContent; }
		set { this.MainContent = value; }
	}
	public Grid DragBarGrid
	{
		get { return this.DragBar; }
		set { this.DragBar = value; }
	}
	#endregion
}

and so just simple as that.

You can download the code in my Box 

 http://liit.co.nr/?0l6n8

Click here to expand the blog post

Windows Phone Homebrew Application called "Start"

Well I just hope this is not just another Start menu replacement that you already have installed in your Windows Phone. Well it be great if you have another alternative that you can play with.. 

Here's "Start", yes, that's how simple the application name was.

So what's in this application?

  1. It's a Start menu replacement
  2. You can add your quick lunch application
  3. Intuitive search function
  4. Able to run application
  5. And it's fast

It's a Start menu replacement because I got bored with the native one, scrolling down on the list, or even having a jump function still makes me feel bored.. So I made my own. Don't you like having a 4 column, big icons as a start menu? Well I do 

So here's a short video demo of the application

Tap the text on the top-right "JWMD Apps" to see more information

TAKE NOTE

THIS MAY NOT WORK ON OTHER ROMS. Am sorry but I couldn't do anything about that. One reason I can think of why will not work is because Application folder, or the Install folder is hidden. Kind of stupid reason but I have already flashed 2 different ROMs in my Mozart and 1 reason the application fail is because those folder I mentioned were hidden. so .. sorry.

 

Download file is hosted in XDA-Dev here

http://forum.xda-developers.com/showthread.php?t=1931907

Click here to expand the blog post

Windows Phone - Strobe Light Art

Strobe Light Art is an application for Windows Phone that you can use along with your DSLR or any camera that is capable of setting the Exposure Time. The term Light Art is a form of visual art where main media of expression is light (wiki). We have seen LED used to make an artistic way of displaying light art, and sometimes used with those motorized spin board that displays some analog clock or messages. Along with those cool electronics stuff, I present to you an application that can do the same. 

Strobe Light Art

In Strobe Light Art, you can

  1. Create your custom message on the fly.
  2. Have your own LED effects.
  3. Create your own pattern (future)
  4. Save and Restore your patterns (future)

Here are the sample images I taked but using only my Sony Cybershot DSC-W220

You can download the XAP file here in XDA-Developers too

http://forum.xda-developers.com/showthread.php?t=1931935

Click here to expand the blog post

Windows Phone - ApplicationBar Controller

While doing some awesome side project in Windows Phone, I needed a way to have a better control on the Application Bar. I want the ApplicationBar Icon Buttons and Menu Items to be dynamically added, removed, hide/show, or enable/disable, as well as hooking an event for the specific Icon Button or Menu Items. 

But first, what is an ApplicationBar in Windows Phone and how to use it?

In Windows Desktop development, we have a control called Toolbar where you can add a Button, Drop Down Menu, Label, Textbox, or Progressbar and also you can add an Icon to your Buttons or Labels as well. You can have a button as many as you want, position the control around the Form, and you can also have a toolbar on all sides of your Form.

In Windows Phone, there is also a sort of Toolbar, but in this platform, we call it "Application Bar".

The Application Bar can have a set of circled white icons that stays at the bottom of the screen if it's in Portrait mode, or at the Right, if you turned your phone in Landscape. The Application Bar can only have two controls and that is, the Icon Button and a Menu Item. Just like what you see below (courtesy from Microsoft)

source: Microsoft

Unfortunately, Icon Buttons are limited, and you're pretty much stuck of having a maximum of 4 Icon Buttons. On the other hand, we have Menu Items, and you can add as pretty much as you can. But our main concern is the usability of the Icon Buttons because if you think of a big project, you pretty much has to have different ways of letting your end-users easily navigate around your application and one of them is using ApplicationBar, and having a maximum of 4 Icon Buttons, is not enough. 

So how do we solve the problem? 2 ways, either create a multiple Application Bars or have your Icon Buttons dynamically changing at Run Time. Which one do you choose?

Let's take a moment of showing an example of creating a multiple Application Bars. In Windows Phone DevCenter, they wrote a way to do this

How to: Create an Application Bar in Code for Windows Phone

http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394036(v=vs.92).aspx

As you can see from their example, they have two Application Bars defined in XAML.

Now the problem is, it may soon get very long and unmanageable by means of having a duplicate Menu Items (like what you see there), and what if I have 4 different Application Bars and I need a specific Icon Button to always appear on those Application Bars, so I have to Copy & Paste the XAML definition of that Icon Button to each Application Bar, and possibly, in overtime, I have to change the icon and text, so I have to go over to each Application Bars and change it again. Manipulating the Icon Buttons on those Application Bars in Run time will again introduce another headache.

So what if we could create an easy way of controlling our Icon Buttons in just one single Application Bar? 

So I wrote a class called ApplicationBarController to address the problem where we can have a much smoother control over to our Icon Buttons and Menu Items in one Applicaion Bar. What we can do in this class is we can easily Show the Icon Buttons or Menu Items we need for a specific task, as well as Hide them if not needed anymore like. In the animated image above, I demoed how this class works.

And so, here's the ApplicationBarController class for you.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Phone.Shell;

namespace CAPPLOUD.WP.Controllers
{
    public class ApplicationBarController
    {
        IApplicationBar _appbar;

        public ApplicationBarController(IApplicationBar appbar)
        {
            this._appbar = appbar;
        }

        Dictionary<string, IApplicationBarIconButton> Buttons { get; set; }
        Dictionary<string, IApplicationBarMenuItem> MenuItems { get; set; }

        /// <summary>
        /// Add new Menu Item to the collection.
        /// Must call ShowMenuItems or ShowMenuItem to show the menu
        /// </summary>
        /// <param name="Text">Name of the menu item</param>
        /// <param name="isEnabled"></param>
        /// <param name="e">Delegated event</param>
        public void AddNewMenuItem(string Text, bool isEnabled, EventHandler e)
        {
            if (MenuItems == null)
            {
                MenuItems = new Dictionary<string, IApplicationBarMenuItem>();
            }

            if (MenuItems.ContainsKey(Text)) { return; }

            ApplicationBarMenuItem menuitem = new ApplicationBarMenuItem()
            {
                Text = Text,
                IsEnabled = isEnabled
            };
            menuitem.Click += e;

            MenuItems.Add(Text, menuitem);
        }
        /// <summary>
        /// Add new Icon Button to the collection.
        /// Must call ShowButtons or Showbutton to show the icon button
        /// </summary>
        /// <param name="Text">Text of the icon button</param>
        /// <param name="IconUri">Relative image url</param>
        /// <param name="isEnabled"></param>
        /// <param name="e">Delegated event</param>
        public void AddNewButton(string Text, string IconUri, bool isEnabled, EventHandler e)
        {
            if (Buttons == null)
            {
                Buttons = new Dictionary<string, IApplicationBarIconButton>();
            }

            if (Buttons.ContainsKey(Text)) { return; }

            ApplicationBarIconButton btn = new ApplicationBarIconButton()
            {
                Text = Text,
                IconUri = new Uri(IconUri, UriKind.Relative),
                IsEnabled = isEnabled
            };
            btn.Click += e;
            
            Buttons.Add(Text, btn);
        }

        /// <summary>
        /// Replace and show selected buttons in the application bar
        /// </summary>
        /// <param name="ButtonText">Icon Button texts to show</param>
        public void ShowButtons(params string[] ButtonText)
        {
            this._appbar.Buttons.Clear();

            foreach (string text in ButtonText)
            {
                if (!_appbar.Buttons.Contains(Buttons[text]))
                {
                    _appbar.Buttons.Add(Buttons[text]);
                }
            }
        }
        /// <summary>
        /// Append the icon button in the application bar
        /// </summary>
        /// <param name="ButtonText">Icon Button texts to show</param>
        public void ShowButton(params string[] ButtonText)
        {
            foreach (string text in ButtonText)
            {
                if (!_appbar.Buttons.Contains(Buttons[text]))
                {
                    _appbar.Buttons.Add(Buttons[text]);
                }
            }
        }
        /// <summary>
        /// Remove selected buttonsin the application bar
        /// </summary>
        /// <param name="ButtonText">Icon Button texts to show</param>
        public void RemoveButtons(params string[] ButtonText)
        {
            foreach (string text in ButtonText)
            {
                if (_appbar.Buttons.Contains(Buttons[text]))
                {
                    _appbar.Buttons.Remove(Buttons[text]);
                }
            }
        }
        /// <summary>
        /// Clear all Icon Buttons in the application bar
        /// </summary>
        public void RemoveButtons()
        {
            this._appbar.Buttons.Clear();
        }
        /// <summary>
        /// Enable or Disable selected buttons
        /// </summary>
        /// <param name="Enabled"></param>
        /// <param name="ButtonText">Icon Button texts to Enable or Disable</param>
        public void EnableButtons(bool Enabled, params string[] ButtonText)
        {
            foreach (string text in ButtonText)
            {
                Buttons[text].IsEnabled = Enabled;
            }
        }

        /// <summary>
        /// Replace and show selected menu items in the application bar
        /// </summary>
        /// <param name="MenuItemText">menu items texts to show</param>
        public void ShowMenuItems(params string[] MenuItemText)
        {
            this._appbar.MenuItems.Clear();

            foreach (string text in MenuItemText)
            {
                if (!_appbar.MenuItems.Contains(MenuItems[text]))
                {
                    _appbar.MenuItems.Add(MenuItems[text]);
                }
            }
        }
        /// <summary>
        /// Append the menu items in the application bar
        /// </summary>
        /// <param name="MenuItemText">menu items texts to show</param>
        public void ShowMenuItem(params string[] MenuItemText)
        {
            foreach (string text in MenuItemText)
            {
                if (!_appbar.MenuItems.Contains(MenuItems[text]))
                {
                    _appbar.MenuItems.Add(MenuItems[text]);
                }
            }
        }
        /// <summary>
        /// Remove selected menu items in the application bar
        /// </summary>
        /// <param name="MenuItemText">menu items texts to show</param>
        public void RemoveMenuItems(params string[] MenuItemText)
        {
            foreach (string text in MenuItemText)
            {
                if (_appbar.MenuItems.Contains(MenuItems[text]))
                {
                    _appbar.MenuItems.Remove(MenuItems[text]);
                }
            }
        }
        /// <summary>
        /// Clear all menu items in the application bar
        /// </summary>
        public void RemoveMenuItems()
        {
            _appbar.MenuItems.Clear();
        }
        /// <summary>
        /// Enable or Disable selected menu items
        /// </summary>
        /// <param name="Enabled"></param>
        /// <param name="MenuItemText">menu items texts to Enable or Disable</param>
        public void EnableMenuItems(bool Enabled, params string[] MenuItemText)
        {
            foreach (string text in MenuItemText)
            {
                MenuItems[text].IsEnabled = Enabled;
            }
        }

        /// <summary>
        /// Show or Hide application bar
        /// </summary>
        /// <param name="Show"></param>
        public void ShowAppBar(bool Show)
        {
            if (this._appbar.IsVisible != Show)
            {
                this._appbar.IsVisible = Show;
            }
        }
    }
}

This ApplicationBarController class can pretty much do what ever you want. You can:

  • Add or Remove an Icon Button or Menu Items
  • Show or Hide Icon Buttons or Menu Items
  • Enable or Disable an Icon Button or Menu Items.

Here's an easy way you can implement ApplicationBarController class.

First thing you have to do is to hook the ApplicationBar for the current page.

// Hook the ApplicationBar in the current page
ApplicationBarController appbar = new ApplicationBarController(this.ApplicationBar);

Next is to prepare your Icon Buttons and Menu Items that you are going to need in your project.

void InitializeApplicationBar
{
	// prepare all Icon Buttons and Menu Items
	this.appbar.AddNewButton("add", "/icons/appbar.add.rest.png", true, ApplicationBarIconButton_Click);
	this.appbar.AddNewButton("save", "/icons/appbar.save.rest.png", true, ApplicationBarIconButton_Click);
	this.appbar.AddNewButton("cancel", "/icons/appbar.close.rest.png", true, ApplicationBarIconButton_Click);
	this.appbar.AddNewButton("delete", "/icons/appbar.delete.rest.png", true, ApplicationBarIconButton_Click);
	this.appbar.AddNewButton("clear", "/icons/appbar.close.rest.png", true, ApplicationBarIconButton_Click);

	this.appbar.AddNewButton("ff", "/icons/appbar.transport.ff.rest.png", true, ApplicationBarIconButton_Click);
	this.appbar.AddNewButton("play", "/icons/appbar.transport.play.rest.png", true, ApplicationBarIconButton_Click);
	this.appbar.AddNewButton("pause", "/icons/appbar.transport.pause.rest.png", true, ApplicationBarIconButton_Click);
	this.appbar.AddNewButton("rew", "/icons/appbar.transport.rew.rest.png", true, ApplicationBarIconButton_Click);

	this.appbar.AddNewButton("add menu", "/icons/appbar.add.rest.png", true, ApplicationBarIconButton_Click);
	this.appbar.AddNewButton("clear menus", "/icons/appbar.close.rest.png", true, ApplicationBarIconButton_Click);
	this.appbar.AddNewMenuItem("Message", true, ApplicationBarMenuItem_Click);
}

private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
	ApplicationBarIconButton btn = (ApplicationBarIconButton)sender;
	string text = btn.Text.ToLower();
	
	// your conditions here
	if (text == "add")
	{
		MessageBox.Show("Add button was clicked");
	}
	// add more conditions here
}

private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
{
	ApplicationBarMenuItem menu = (ApplicationBarMenuItem)sender;
	string text = menu.Text.ToLower();
	
	// your conditions here
}

Then while at run time, you can simple show the Icon Buttons or Menu Items you need for the current task in your page

this.appbar.ShowButtons(new string[] { "add", "delete", "clear" });
// or the same as
this.appbar.ShowButtons("add", "delete", "clear");
// or
this.appbar.ShowButtons("add", "clear");

and the same way with Menu Items. One important to note is, the Text you give to the Icon Button or Menu Items acts as a Key and it's case sensitive.

Download the code here

http://www.codeproject.com/Articles/470063/Windows-Phone-ApplicationBar-Controller

Click here to expand the blog post

C# Passing Values Between Multiple Projects using Interface

Earlier when I was doing some major update on a project I was working on for a client, I was also thinking how to optimize the code, not just by using MVP pattern and also the way of passing values between projects. Some of my class libraries where using the same type of property and then gets updated in the main form. I noticed though that setting the same value into the multiple objects with one type of property is pretty hard and unmanageable and also producing a lot of lines of codes. So I experimented a little bit and made an proof on concept how to pass values into multiple projects with minimal coding and using Interface

Let's see the sample animation below. What was shown there is we have satellite that moves in the form and there are 3 child forms. Those 3 child forms are the other 3 projects which are PlanetEarth, PlanetMars, and PlanetSaturn project and the big the form is our Main project. You'll notice that the 3 forms are getting updated everytime the satellite make its next move.

What is so interesting in using an Interface is you can share its values to whoever uses it. Like what I did on that simple P.O.S. project. Those 3 forms, PlanetEarth, PlanetMars, and PlanetSaturn is using one interface but they all get the update.

So why Interface instead of making a property for each project?

Because like I said, you can share the values between multiple projects or whoever uses it.

Let's get into the code

In this sample VS solution. We have 5 projects.

GlobalInterface class library project which contains the Interface code which have an NextPosition property signature what we're going to use later on the Main Project

public interface iSatellite
{
	Point NextPosition { get; set; }
}

Then we have 3 projects that has the same code (For demo only) which is using this iSatellite interface. These are the PlanetEarth, PlanetMars, and PlanetSaturn. Let's take PlanetEarth for example

GlobalInterface.iSatellite Satellite;

public Form1()
{
	InitializeComponent();

	timer1.Interval = 100;
	timer1.Tick += new EventHandler(timer1_Tick);
}

void timer1_Tick(object sender, EventArgs e)
{
	// update the location information of the satellite
	label2.Text = string.Format("X: {0}\r\nY:{1}", this.Satellite.NextPosition.X, this.Satellite.NextPosition.Y);
}

public void InitializeSatellite(GlobalInterface.iSatellite satellite)
{
	this.Satellite = satellite;
	this.timer1.Start();
}

As you noticed, we used Timer object to show the next location of the satellite. We could also use Event to shout that the satellite is making a next move.

InitializeSatellite(GlobalInterface.iSatellite satellite) will be called on our Main Project to bind the "this.Satellite" into our Main project.

Next is our Main project that implements iSatellite interface

public partial class MainController : Form, GlobalInterface.iSatellite
{
	TweenLibrary tween;
	Random destXY = new Random(DateTime.Now.Millisecond);
	List<Form> forms;

	public MainController()
	{
		InitializeComponent();
		InitializeControls();
		InitializeControlEvents();
	}

	public void InitializeControls()
	{
		// show our 3 forms
		PlanetEarth.Form1 earth = new PlanetEarth.Form1();
		earth.InitializeSatellite(this);
		earth.Show();

		PlanetMars.Form1 mars = new PlanetMars.Form1();
		mars.InitializeSatellite(this);
		mars.Show();

		PlanetSaturn.Form1 saturn = new PlanetSaturn.Form1();
		saturn.InitializeSatellite(this);
		saturn.Show();

		// then put them on the list to update their location
		forms = new List<Form>()
		{
			earth, mars, saturn
		};

		tween = new TweenLibrary();

		timer1.Interval = Convert.ToInt32(TimeSpan.FromSeconds(3).TotalMilliseconds);
		timer1.Tick += new EventHandler(timer1_Tick);
		timer1.Start();
	}

	public void InitializeControlEvents()
	{
		this.LocationChanged += new EventHandler(Form1_LocationChanged);
	}

	/// <summary>
	/// update child form positions
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	void Form1_LocationChanged(object sender, EventArgs e)
	{
		int last_y = this.Location.Y;

		foreach (Form frm in forms)
		{
			frm.Location = new Point(this.Location.X + this.Size.Width, last_y);
			last_y = frm.Location.Y + frm.Size.Height;
		}
	}

	void timer1_Tick(object sender, EventArgs e)
	{
		this.NextPosition = new Point()
		{
			X = destXY.Next(this.ClientSize.Width),
			Y = destXY.Next(this.ClientSize.Height)
		};

		tween.startTweenEvent(picSatellite, this.NextPosition.X, this.NextPosition.Y, "easeinoutcubic", 100);
	}

	/// <summary>
	/// Implement GlobalInterface.iSatellite property
	/// </summary>
	public Point NextPosition { get; set; }
}

As you can see just below on that code, we implemented iSatellite interface with NextPosition property with a Point type which we're going to use to update the location of the satellite. In the timer1_Tick event, this gets triggered every 3 seconds and you can see, we update the "NextPosition" X and Y values. The 3 projects that is bound in the interface are automatically updated.

So what is the benefit of the Interface in this type of problem about passing values between multiple visual studio projects?

  • Lesser code
  • We do not need to update the values for each project.
  • Easy to manage
  • More structured.

Comparing the usage of Property vs Interface

Let's say each projects PlanetEarth, PlanetMars, and PlanetSaturn are using NextPosition Property

void timer1_Tick(object sender, EventArgs e)
{
	Point newXY = new Point()
	{
		X = destXY.Next(this.ClientSize.Width),
		Y = destXY.Next(this.ClientSize.Height)
	};
	
	this.earth.NextPosition = newXy;
	this.mars.NextPosition = newXy;
	this.saturn.NextPosition = newXy;
}

But when we use Interface

void timer1_Tick(object sender, EventArgs e)
{
	this.NextPosition = new Point()
	{
		X = destXY.Next(this.ClientSize.Width),
		Y = destXY.Next(this.ClientSize.Height)
	};

	tween.startTweenEvent(picSatellite, this.NextPosition.X, this.NextPosition.Y, "easeinoutcubic", 100);
}

We only update the property we implemented from iSatellite and all 3 projects are automatically updated as well.

Hope you learned about another special way of implementing Interface in your projects, not only in Windows Forms, but in Windows Phone, Windows 8, Silverlight, and WPF projects as well.

Here's the a sample project that you can play with.

Click here to expand the blog post

Using WCF (Web Service) in Windows Phone, Windows Forms, ASP.NET, Silverlight, Windows 8

In this tutorial, I'm going to show you how to make a simple Windows Communication Foundation (WCF or also called "Web Service", diff) and then use it in Windows Phone, Windows Forms, ASP.NET, Silverlight, or Windows 8.

Shout Out Application

We're going to make a simple Shout Out application and we will be using SQL Server as our backend database, WCF for communicating back and forth into our database and use it in our application.

On the left is the preview of the application that we're going to make.

So what the application does is

  • It can retrieve the latest shouts from the database server
  • It can post your shout
  • Have your own name
What you need
  • An ASP.NET web hosting
  • With SQL SERVER
  • Your favorite SQL Management tools
  • Visual Studio 2010 / Visual Studio 2012

First thing we need to do is to setup our database server

It's important that your database server must be hosted somewhere. Not locally! My database is hosted in GoDadadah.

Let's create a simple table with 4 fields.

  • ID (should be the PK and an Identifier so it automatically increments the ID)
  • Name
  • Shout
  • DatePosted
and name the table as ShoutBox. Then add some records so we can use it later.

Let's now create our Shout Out Service

watch the video

Once you're done with the WCF services. Upload all the files in your ASP.NET web hosting and test it. Here's what it looks like

http://wcf.jaysonragasa.net/ShoutOutService.svc

Here are the classes and interface shown in the video

ShoutOutService

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

using System.Data;
using System.Data.SqlClient;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ShoutOutService" in code, svc and config file together.
public class ShoutOutService : IShoutOutService
{
	// our connection string
    string connstr = ConfigurationManager.AppSettings["constr"].ToString();

    /// <summary>
    /// AddShout - add user's shout
    /// </summary>
    /// <param name="name"></param>
    /// <param name="shout"></param>
    public void AddShout(string name, string shout)
    {
        using (SqlConnection sqlconn = new SqlConnection(this.connstr))
        {
            using (SqlCommand cmd = sqlconn.CreateCommand())
            {
                cmd.CommandText = "insert into shoutbox(name, shout, dateposted) values(@thisname, @thisshout, @thisdateposted)";

                cmd.Parameters.Clear();
                cmd.Parameters.Add(new SqlParameter("@thisname", name));
                cmd.Parameters.Add(new SqlParameter("@thisshout", shout));
                cmd.Parameters.Add(new SqlParameter("@thisdateposted", DateTime.Now.ToString()));

                cmd.CommandType = CommandType.Text;
                sqlconn.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }

    /// <summary>
    /// Get all shouts from the users
    /// </summary>
    /// <returns></returns>
    public List<ShoutModel> GetAllShouts()
    {
        List<ShoutModel> result = new List<ShoutModel>();

        using (SqlConnection sqlconn = new SqlConnection(this.connstr))
        {
            using (SqlCommand cmd = sqlconn.CreateCommand())
            {
                cmd.CommandText = "select top 15 name, shout, DatePosted from ShoutBox order by DatePosted DESC";

                cmd.CommandType = CommandType.Text;
                sqlconn.Open();

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        result.Add(new ShoutModel()
                        {
                            Name = reader.GetString(reader.GetOrdinal("name")),
                            Shout = reader.GetString(reader.GetOrdinal("shout")),
                            DatePosted = reader.GetDateTime(reader.GetOrdinal("DatePosted")).ToString("MM/dd/yy hh:mm"),
                        });
                    }
                }
            }
        }

        return result;
    }
}

IShoutOutService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IShoutOutService" in both code and config file together.
[ServiceContract]
public interface IShoutOutService
{
    [OperationContract]
    void AddShout(string name, string shout);

    [OperationContract]
    List<ShoutModel> GetAllShouts();
}

ShoutModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;

/// <summary>
/// Summary description for ShoutModel
/// </summary>
[DataContract]
public class ShoutModel
{
    [DataMember]
    public string Name
    {
        get;
        set;
    }

    [DataMember]
    public string Shout
    {
        get;
        set;
    }

    [DataMember]
    public string DatePosted
    {
        get;
        set;
    }
}

The next step is how to use the WCF service in Windows Phone

watch the video

Here are the codes that were demoed on the video

MainPage.xaml

<phone:PhoneApplicationPage 
    x:Class="ShoutOut.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait"  Orientation="Portrait"
    shell:SystemTray.IsVisible="False">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <!--Pivot Control-->
        <controls:Pivot Title="CAPPLOUD Labs">
            <!--Pivot item one-->
            <controls:PivotItem Header="Shout outs!">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="523*" />
                        <RowDefinition Height="70" />
                    </Grid.RowDefinitions>
                    <StackPanel Margin="0,0,0,0" VerticalAlignment="Stretch">
                        <ListBox x:Name="lbShouts" ItemTemplate="{StaticResource ShoutTemplate}" HorizontalAlignment="Stretch" />
                    </StackPanel>
                    <StackPanel Grid.Row="1" Background="Transparent">
                        <StackPanel x:Name="panelFields" Orientation="Horizontal" Opacity="1">
                            <TextBox x:Name="txShout" HorizontalAlignment="Stretch" Width="327" />
                            <Button x:Name="btnShout" Content="Shout!" />
                        </StackPanel>
                    </StackPanel>
                </Grid>
            </controls:PivotItem>

            <!--Pivot item two-->
            <controls:PivotItem Header="Setting">
                <Grid>
                    <StackPanel>
                        <TextBlock Text="your name" />
                        <TextBox x:Name="txName" />
                    </StackPanel>
                </Grid>
            </controls:PivotItem>
        </controls:Pivot>
    </Grid>
 
    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace ShoutOut
{
    public partial class MainPage : PhoneApplicationPage
    {
        ConsumeShoutOutService.ShoutOutServiceClient shoutout;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            InitializeControlEvents();
            InitializeControls();
        }

        void InitializeControls()
        {
            this.shoutout = new ConsumeShoutOutService.ShoutOutServiceClient();
            this.shoutout.AddShoutCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(shoutout_AddShoutCompleted);
            this.shoutout.GetAllShoutsCompleted += new EventHandler<ConsumeShoutOutService.GetAllShoutsCompletedEventArgs>(shoutout_GetAllShoutsCompleted);

            txName.Text = "User" + DateTime.Now.ToString("MMddhhmm");
        }

        void InitializeControlEvents()
        {
            btnShout.Tap += new EventHandler<GestureEventArgs>(btnShout_Tap);
        }

        void RefreshShoutOutList()
        {
            this.shoutout.GetAllShoutsAsync();
        }

        void btnShout_Tap(object sender, GestureEventArgs e)
        {
            this.shoutout.AddShoutAsync(txName.Text, txShout.Text);
        }

        void shoutout_GetAllShoutsCompleted(object sender, ConsumeShoutOutService.GetAllShoutsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                lbShouts.ItemsSource = e.Result;
            }
            else
            {
                // something went wrong
                // so do something here too
                System.Diagnostics.Debug.WriteLine(e.Error.Message);
            }
        }

        void shoutout_AddShoutCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                RefreshShoutOutList();
            }
            else
            {
                // something went wrong
                // so do something here too
                System.Diagnostics.Debug.WriteLine(e.Error.Message);
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            RefreshShoutOutList();
        }
    }
}

App.xaml ShoutTemplate for ListBox Item Template

<Application 
    x:Class="ShoutOut.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">

    <!--Application Resources-->
    <Application.Resources>
        <DataTemplate x:Name="ShoutTemplate">
            <StackPanel Margin="0,0,0,20" Background="#8000D3BE">
                <StackPanel Orientation="Horizontal">
                    <TextBlock HorizontalAlignment="Left" Text="{Binding Path=Name}" VerticalAlignment="Stretch" Foreground="#FFFFEE00" FontWeight="Bold" Padding="5" />
                    <TextBlock HorizontalAlignment="Right" Text="{Binding Path=DatePosted}" VerticalAlignment="Stretch" Foreground="#FFD1D1D1" Margin="20,0,0,0" Padding="5" />
                </StackPanel>
                <TextBlock HorizontalAlignment="Stretch" Text="{Binding Path=Shout}" VerticalAlignment="Stretch" TextWrapping="Wrap" Padding="5" />
            </StackPanel>
        </DataTemplate>
    </Application.Resources>

    <Application.ApplicationLifetimeObjects>
        <!--Required object that handles lifetime events for the application-->
        <shell:PhoneApplicationService 
            Launching="Application_Launching" Closing="Application_Closing" 
            Activated="Application_Activated" Deactivated="Application_Deactivated"/>
    </Application.ApplicationLifetimeObjects>

</Application>

I hope you learned something on this WCF and Windows Phone tutorial and here's the complete ShoutOut solution that you can study. Part 2 will be using the same WCF service in other Microsoft platforms.

Click here to expand the blog post

Isolated Storage Browser Control for Windows Phone

Here's a simple and effective Isolated Storage Browser user control I made for Windows Phone. What it does is it gives you a way to browse through your isolated files and folders in your application isolated storage. So why control? I had a problem throwing back the selected file if I made this as a page, so instead, I made a user control and custom event to throw the selected file. 

Download the sample solution here

Click here to expand the blog post

Cordova Igniter for Windows Phone powered by Cordova PhoneGap and jQueryMobile

 

Cordova Igniter is a HTML5 IDE that you can use to build HTML5 applications and it's a great way to build an instant application access native features directly in your Windows Phone!

What you can do?

  • You want your custom media player? Build it directly in Codova Igniter fast and simple.
  • You need a map with GPS navigation? Build it directly in Codova Igniter fast and simple.
  • You need an accelerometer based game?  Build it directly in Codova Igniter fast and simple.
  • You need a twittter app? Build it directly in Codova Igniter fast and simple.
  • You need a facebook app? Build it directly in Codova Igniter fast and simple.
  • You need a RSS app? Build it directly in Codova Igniter fast and simple.
  • and so much more!!

other cool feature is you can download and upload a file so incase you needed an update to your current existing HTML5 application, you can edit it directly in your mobile phone, anytime, anywhere!

Alpha Stage

Cordova Igniter is still in beta stage but I can show you an early preview of this Windows Phone application powered by Cordova/PhoneGAP and jQueryMobile.

Powered by

  

Click here to expand the blog post

Anaglyph Renderer for Windows Phone version 1.1

I made an update from my previous Anaglyph renderer code to support background threading. This is also a reason to get away from having a cross-thread problem with WriteableBitmap and BitmapImage. Am not sure what's going on why in the previous code, it was spitting out a cross-threading problem even if the object was instantiated in the background thread. hmmm... anyway

Here's my version 1.1

/*
 * AnaglyphRenderer version 1.1
 * date: 04 09 2012
 * author: Jayson Ragasa
 * link: wall.jaysonragasa.net
 */
namespace WindowsPhone3D
{
    using System;
    using System.IO;
    using System.Diagnostics;

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

    public class AnaglyphRenderer
    {
        public enum Algorythm
        {
            TrueAnaglyph,
            GrayAnaglyph,
            ColorAnaglyph,
            HalfColorAnaglyph,
            OptimizedAnaglyph
        }

        WriteableBitmap leftWB;
        WriteableBitmap rightWB;

        int[] leftPixels;
        int[] rightPixels;

        public Size PictureSize;

        public void PrepareBitmap(Stream imgLeft, Stream imgRight, Size size)
        {
            leftWB = new WriteableBitmap(Convert.ToInt32(size.Width), Convert.ToInt32(size.Height)); ;
            leftWB.SetSource(imgLeft);
            leftPixels = leftWB.Pixels;

            rightWB = new WriteableBitmap(Convert.ToInt32(size.Width), Convert.ToInt32(size.Height));
            rightWB.SetSource(imgRight);
            rightPixels = rightWB.Pixels;
        }

        public void RenderAnaglyph(Algorythm algo = Algorythm.GrayAnaglyph)
        {
            for (int i = 0; i < leftPixels.Length; i++)
            {
                try
                {
                    double r = 0;
                    double g = 0;
                    double b = 0;

                    int leftColor = leftWB.Pixels[i];
                    int rightColor = rightWB.Pixels[i];

                    byte[] leftColorVals = BitConverter.GetBytes(leftWB.Pixels[i]);
                    byte[] rightColorVals = BitConverter.GetBytes(rightWB.Pixels[i]);

                    ComputeColor(algo, out r, out g, out b, leftColorVals, rightColorVals);

                    Color c = Color.FromArgb((byte)255, Convert.ToByte(r), Convert.ToByte(g), Convert.ToByte(b));

                    // http://smartypantscoding.com/content/get-and-put-pixel-silverlight-3-writeablebitmap
                    leftWB.Pixels[i] = c.A << 24 | c.R << 16 | c.G << 8 | c.B;
                }
                catch
                {
                    // todo
                    break;
                }
            }
        }

        public BitmapImage FinalResult()
        {
            BitmapImage result = null;

            using (MemoryStream ms = new MemoryStream())
            {
                Extensions.SaveJpeg(leftWB, ms, (int)PictureSize.Width, (int)PictureSize.Height, 0, 100);

                result = new BitmapImage();
                result.SetSource(ms);
            }

            return result;
        }

        // ref
        // http://3dtv.at/Knowhow/AnaglyphComparison_en.aspx
        // http://www.aforgenet.com/framework/docs/html/49942a11-2da2-a707-713b-f5cbf19085db.htm
        void ComputeColor(Algorythm algo, out double R, out double G, out double B, byte[] leftColorVals, byte[] rightColorVals)
        {
            R = 0; G = 0; B = 0;

            switch (algo)
            {
                case Algorythm.TrueAnaglyph:
                    R = (0.299 * Convert.ToInt32(leftColorVals[0])) +
                        (0.587 * Convert.ToInt32(leftColorVals[1])) +
                        (0.114 * Convert.ToInt32(leftColorVals[2]));

                    G = 0;

                    B = (0.299 * Convert.ToInt32(rightColorVals[0])) +
                        (0.587 * Convert.ToInt32(rightColorVals[1])) +
                        (0.114 * Convert.ToInt32(rightColorVals[2]));

                    break;

                case Algorythm.GrayAnaglyph:
                    R = (0.299 * Convert.ToInt32(leftColorVals[0])) +
                        (0.587 * Convert.ToInt32(leftColorVals[1])) +
                        (0.114 * Convert.ToInt32(leftColorVals[2]));

                    G = (0.299 * Convert.ToInt32(rightColorVals[0])) +
                        (0.587 * Convert.ToInt32(rightColorVals[1])) +
                        (0.114 * Convert.ToInt32(rightColorVals[2]));

                    B = (0.299 * Convert.ToInt32(rightColorVals[0])) +
                        (0.587 * Convert.ToInt32(rightColorVals[1])) +
                        (0.114 * Convert.ToInt32(rightColorVals[2]));

                    break;

                case Algorythm.ColorAnaglyph:
                    R = leftColorVals[0];

                    G = rightColorVals[1];

                    B = rightColorVals[2];

                    break;

                case Algorythm.HalfColorAnaglyph:
                    R = (0.299 * Convert.ToInt32(leftColorVals[0])) +
                        (0.587 * Convert.ToInt32(leftColorVals[1])) +
                        (0.114 * Convert.ToInt32(leftColorVals[2]));

                    G = rightColorVals[1];

                    B = rightColorVals[2];

                    break;

                case Algorythm.OptimizedAnaglyph:
                    R = (0.7 * leftColorVals[1]) +
                        (0.3 * leftColorVals[2]);

                    G = rightColorVals[1];

                    B = rightColorVals[2];

                    break;
            }
        }
    }
}

How to use:

The previous code was pretty straight forward. Here's an example code of how to use this new class if you're using BackgroundWorker object

AnaglyphRenderer glyph = new AnaglyphRenderer();
AnaglyphRenderer.Algorythm selectedAlgo = new AnaglyphRenderer.Algorythm();

// this goes to whereever you want to initialize your stuff
{
	selectedAlgo = AnaglyphRenderer.Algorythm.GrayAnaglyph;

	// get the actual image size using WriteableBitmap
	glyph.PictureSize = this.picActualSize;
	glyph.PrepareBitmap(this.leftBmpImage,
						this.rightBmpImage,
						this.picActualSize);
}
					
// this goes to DoWork event -------------
{
	glyph.RenderAnaglyph(this.selectedAlgo);
}

// this goes to RunWorkerCompleted event -----------
{
	imgGlyph.Source = null; // make sure to reset the source
	imgGlyph.Source = glyph.FinalResult();
}
Click here to expand the blog post

Anaglyph Renderer for Windows Phone

I am working on this Anaglyph application for Windows Phone 7 and I thought I want to share this one too someone could probably make the rendering faster.

Here's the class for rendering Anaglyph. I takes two image stream sources and output size.

/*
 * AnaglyphRenderer version 1.0
 * date: 04 09 2012
 * author: Jayson Ragasa
 * link: wall.jaysonragasa.net
 */
namespace WindowsPhone3D
{
    using System;
    using System.IO;
    using System.Diagnostics;

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

    public class AnaglyphRenderer
    {
        public enum Algorythm
        {
            TrueAnaglyph,
            GrayAnaglyph,
            ColorAnaglyph,
            HalfColorAnaglyph,
            OptimizedAnaglyph
        }

        public BitmapImage RenderAnaglyph(Stream imgLeft, Stream imgRight, Size size, Algorythm algo = Algorythm.GrayAnaglyph)
        {
            BitmapImage result = null;

            Debug.WriteLine("Rendering " + algo.ToString());

            WriteableBitmap leftWB = new WriteableBitmap(Convert.ToInt32(size.Width), Convert.ToInt32(size.Height));
            leftWB.SetSource(imgLeft);
            int[] leftPixels = leftWB.Pixels;

            WriteableBitmap rightWB = new WriteableBitmap(Convert.ToInt32(size.Width), Convert.ToInt32(size.Height));
            rightWB.SetSource(imgRight);
            int[] rightPixels = rightWB.Pixels;

            for (int i = 0; i < leftPixels.Length; i++)
            {
                try
                {
                    double r = 0;
                    double g = 0;
                    double b = 0;

                    int leftColor = leftWB.Pixels[i];
                    int rightColor = rightWB.Pixels[i];

                    byte[] leftColorVals = BitConverter.GetBytes(leftWB.Pixels[i]);
                    byte[] rightColorVals = BitConverter.GetBytes(rightWB.Pixels[i]);

                    ComputeColor(algo, out r, out g, out b, leftColorVals, rightColorVals);

                    Color c = Color.FromArgb((byte)255, Convert.ToByte(r), Convert.ToByte(g), Convert.ToByte(b));

                    // http://smartypantscoding.com/content/get-and-put-pixel-silverlight-3-writeablebitmap
                    leftWB.Pixels[i] = c.A << 24 | c.R << 16 | c.G << 8 | c.B;
                }
                catch
                {
                    // todo
                    break;
                }
            }

            using (MemoryStream ms = new MemoryStream())
            {
                Extensions.SaveJpeg(leftWB, ms, (int)size.Width, (int)size.Height, 0, 100);

                result = new BitmapImage();
                result.SetSource(ms);
            }

            Debug.WriteLine("Rendering " + algo.ToString() + " : Done");

            return result;
        }

        // ref
        // http://3dtv.at/Knowhow/AnaglyphComparison_en.aspx
        // http://www.aforgenet.com/framework/docs/html/49942a11-2da2-a707-713b-f5cbf19085db.htm
        void ComputeColor(Algorythm algo, out double R, out double G, out double B, byte[] leftColorVals, byte[] rightColorVals)
        {
            R = 0; G = 0; B = 0;

            switch (algo)
            {
                case Algorythm.TrueAnaglyph:
                    R = (0.299 * Convert.ToInt32(leftColorVals[0])) +
                        (0.587 * Convert.ToInt32(leftColorVals[1])) +
                        (0.114 * Convert.ToInt32(leftColorVals[2]));

                    G = 0;

                    B = (0.299 * Convert.ToInt32(rightColorVals[0])) +
                        (0.587 * Convert.ToInt32(rightColorVals[1])) +
                        (0.114 * Convert.ToInt32(rightColorVals[2]));

                    break;

                case Algorythm.GrayAnaglyph:
                    R = (0.299 * Convert.ToInt32(leftColorVals[0])) +
                        (0.587 * Convert.ToInt32(leftColorVals[1])) +
                        (0.114 * Convert.ToInt32(leftColorVals[2]));

                    G = (0.299 * Convert.ToInt32(rightColorVals[0])) +
                        (0.587 * Convert.ToInt32(rightColorVals[1])) +
                        (0.114 * Convert.ToInt32(rightColorVals[2]));

                    B = (0.299 * Convert.ToInt32(rightColorVals[0])) +
                        (0.587 * Convert.ToInt32(rightColorVals[1])) +
                        (0.114 * Convert.ToInt32(rightColorVals[2]));

                    break;

                case Algorythm.ColorAnaglyph:
                    R = leftColorVals[0];

                    G = rightColorVals[1];

                    B = rightColorVals[2];

                    break;

                case Algorythm.HalfColorAnaglyph:
                    R = (0.299 * Convert.ToInt32(leftColorVals[0])) +
                        (0.587 * Convert.ToInt32(leftColorVals[1])) +
                        (0.114 * Convert.ToInt32(leftColorVals[2]));

                    G = rightColorVals[1];

                    B = rightColorVals[2];

                    break;

                case Algorythm.OptimizedAnaglyph:
                    R = (0.7 * leftColorVals[1]) +
                        (0.3 * leftColorVals[2]);

                    G = rightColorVals[1];

                    B = rightColorVals[2];

                    break;
            }
        }
    }
}
Click here to expand the blog post

About Jayson Ragasa

Jayson Ragasa is an Applications Developer and founder of CAPPLOUD.

Badges

Free Page Rank Tool

wall.jaysonragasa.net Webutation
Uptime Report for http://wall.jaysonragasa.net/: Last 30 days