Scaffold your Windows Phone Application with WpScaffolding

What is WpScaffolding

WpScaffolding is the scaffolding package for Windows Phone. It is analogue of the MvcScaffolding in ASP.NET MVC.  WpScaffolding is using core T4Scaffolding package to execute scaffolders.

WpScaffolding generates full set of MVVM classes of your data model that perform basic CRUD operations. Current version supports in memory database – SqlCE.

The Windows Phone scaffolding package is usefull in the following scenarios:

  • If you are new to Windows Phone programming and you don’t where to start. You can generate your MVVM structured application and investigate the code.
  • If your application requires repeatedly creating similar files and classes, because WpScaffolding is based on T4Scaffolding and you can define your own templates and scaffolders no matter how complex they are.
  • You want to jump start your last mobile application idea

 Installation

Instalation of WpScaffolding package is available through Nuget Package Manager and you can find it at http://nuget.org.:

Install-Package WpScaffolding

First Windows Phone application with WpScaffolding

I will show you how to build a simple Notes application that can Create, Update, List and Show details for notes.

1. Create new Windows Phone Application in Visual Studio

image

2. Open Nuget package manager and install WpScaffolding package

PM> Install-Package WpScaffolding

image

You will see that Helpers and Images folders are added to the project:

image

Helpers folder is using common classes that are used for the implementation of the MVVM pattern:

– RelayCommand and RelayCommand<T> classes that implement ICommand  for using commands in the ViewModel and bind it to the view

– ViewModelBase – that is a base ViewModel class that implement INotifyPropertyChanged. Model classes must implement the INotifyPropertyChanged interface for binding to the View and ViewModelBase is used for base class.

Images folder contains images that will be used in the views application bar

3. Set image files Build Action in the Images folder to Content  so they can be loaded at runtime:

image

4. Add new Models folder to the project

5. Add reference to System.Data.Linq – the assembly for SQLCE

image

image

5. Add new model in the Models folder – a Note class that contains the note fields. As our model is used in the ViewModel we should implement INotifyPropertyChanged or the ViewModelBase class included in WpScaffolding initial package.

 1: using System.Data.Linq.Mapping;

 2: using WpScaffolding.ViewModels;

 3:

 4: namespace NotesApplication.Models

 5: {

 6:     [Table(Name = "Notes")]

 7:     public class Note : ViewModelBase

 8:     {

 9:         private int _noteId;

 10:         [Column(IsPrimaryKey = true, IsDbGenerated = true)]

 11:         public int NoteId

 12:         {

 13:             get

 14:             {

 15:                 return _noteId;

 16:             }

 17:             set

 18:             {

 19:                 if (_noteId == value)

 20:                 {

 21:                     return;

 22:                 }

 23:                 _noteId = value;

 24:                 RaisePropertyChanged("NoteId");

 25:             }

 26:         }

 27:

 28:         private string _name;

 29:         [Column]

 30:         public string Name

 31:         {

 32:             get

 33:             {

 34:                 return _name;

 35:             }

 36:             set

 37:             {

 38:                 if (_name == value)

 39:                 {

 40:                     return;

 41:                 }

 42:                 _name = value;

 43:                 RaisePropertyChanged("Name");

 44:             }

 45:         }

 46:

 47:         private string _text;

 48:         [Column]

 49:         public string Text

 50:         {

 51:             get { return _text; }

 52:             set

 53:             {

 54:                 if (_text == value)

 55:                 {

 56:                     return;

 57:                 }

 58:                 _text = value;

 59:                 RaisePropertyChanged("Text");

 60:             }

 61:         }

 62:

 63:     }

 64: }

We should customize our model and properties with the SqlCE attributes to use Windows Phone database – current version of WpScaffolding supports only using WP local database.

6. Scaffold your application with the created Note model using Visual Studio package console:

PM> Scaffold MVVM Note

Lets see what WpScaffolding did with our application:

Added database context ‘Models\NotesApplicationContext.cs’  – our database SQL CE context
Added ‘Notes’ to database context ‘NotesApplication.Models.NotesApplicationContext’ – database context Notes collection
Added ViewModel ViewModels\NotesListViewModel.cs – ViewModel with Notes entities listing functionality
Added ViewModel ViewModels\NoteDetailsViewModel.cs – ViewModel with single Note entity details info
Added ViewModel ViewModels\NoteCreateOrEditViewModel.cs – ViewModel with Create and Edit operations for adding and editing Note entities
Added View Views\NotesListView.xaml – View with Notes list vizualization bound to NotesListViewModel
Added View CodeBehind Views\NotesListView.xaml.cs – Notes list view code behind
Added View Views\NoteDetailsView.xaml – View with Note entity details info bound to Note details view model
Added View CodeBehind Views\NoteDetailsView.xaml.cs – Note details view code behind
Added View Views\NoteCreateOrEditViewControl.xaml – Note create or edit control used with Note create or edit viewmodel
Added View CodeBehind Views\NoteCreateOrEditViewControl.xaml.cs – view code behind
Added View Views\NoteCreateView.xaml – Page that contains NoteCreateOrEdit view control and Create functionality when the Note entity is new
Added View CodeBehind Views\NoteCreateView.xaml.cs – view code behind
Added View Views\NoteEditView.xaml  – Page that contains NoteCreateOrEdit view control when the Note entity is edited
Added View CodeBehind Views\NoteEditView.xaml.cs –view code behind

WpScaffolding give us a clue what to do for running and using our app as easy as possible:

TO DO:
Put the following HyperlinkButton on the MainPage to easily navigate to Notes list page

<HyperlinkButton Content=”Notes list” NavigateUri=”/Views/NotesListView.xaml”/>

 

7. Add the Notes list hyperlink to the MainPage and run the application:

        <!–ContentPanel – place additional content here–>

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
                      <HyperlinkButton Content="Notes list" NavigateUri="/Views/NotesListView.xaml"/>
        </Grid>

8. Run NotesApplication and see how app is organizaed
- Screen with the MainPage and our Payments list:
01-started-app
- list entered notes:

03-create-note-view

-Create new note

image

– Edit selected item:

image

-Note details:

image

– Delete features:

05-delete-entered

Here is the generated NotesApplication Source code

More about WpScaffolding: http://wpscaffolding.codeplex.com/

Advertisements
Posted in C#, SqlCE, Visual Studio, Windows Phone, WpScaffolding | Tagged , , , | 2 Comments

SilverlightShow’s ECO Contest

I’ve participated in the SilverlightShow’s ECO Contest 2011. The contest subject  was  the International year of forest and the object was to create an web application with Microsoft Silverlight technology that helps raise social awareness of saving the forest.  The prizes were more than great – Telerik controls and  3 MIX 11 tickets! Sponsors were Telerik and Completit

The contest submission period was from 12:01 am PST on January 7th and until 11:59 pm PST on March 6th.  I’ve decided my app subject one week before the end date as usual.

My application was “Save the earth – plant a tree” – Plant A tree and share your green message(switch to full screen):

Continue reading

Posted in Silverlight | Tagged , | 1 Comment

Създаване на нов ASP.NET Web Application за Windows Azure.

Сега ще покажа как се създава ново приложение и как да го качим в Windows Azure, така че всички да могат да го видждат.

Първото нещо, което трябва да направим е да си изтеглим Windows Azure Tools за Visual Studio и да ги инсталираме.
Вече може да създадем нов проект за Azure.

От File->New->Project->Cloud Избираме Windows Azure Cloud Service

Continue reading

Posted in ASP.NET, Azure, Visual Studio | Leave a comment

Създаване на нов сървис в Windows Azure

Сега ще покажа колко лесно се добавя нов сървис в Azure-а.

Влизаме в Azure акаунта на http://windows.azure.com и избираме “New Hosted Service”:

Continue reading

Posted in Azure | Tagged , | 1 Comment

Свързване към SQL Azure database в SQL Management Studio

На PDC Local 2010 в София имаше безплатни тестови акаунти за Windows Azure  и имам възможност да си поиграя с него. Сега ще покажа как да направим връзка с SQL Azure в SQL Management Studio.

1.Трябва да се добави изключение  в защитната стена на database server-a в Windows Azure акаунта, с IP адреса на компютъра, от който се сързвате.

Continue reading

Posted in Azure | Tagged , | 2 Comments

Промяна на text encoding на файл във VisualStudio

Трябваше да направя малък проект  по „Програмни езици“ и реших да го направя на Silverlight, като използвам известния темплейт  „Silverlight Navigation with Cosmopolitan Theme“ (по подразбиране не е добавен във Visual Studio, но е сред първите темплейти в “Online Templates->Silverlight”). Създадох нов проект и започнах да променям label-ите на български. При Build-а даде следната грешка:

“Error    1              Cannot resolve reference assemblies. Please check the reference assemblies. Invalid character in the given encoding. Line 11, position 30.   ”

Проблема е, че encoding-а на файла не съдържа символите, които съм въвел. Най-вероятно същият „проблем“ ще се появи и при някой друг, който използва същия темплейт. Решението на този проблем е да се промени Encoding-a на файла. Ето как става:

1)      Отваряме проблемния файл – в случая About.xaml

2)      File -> Advanced Save Options

3)      Най-добре е да изберем UTF-8, за да нямаме проблеми и с други символи и езици

4)      “Build succeеded”

Posted in Visual Studio | Tagged , | Leave a comment

Silverilght with .Net 4.0, WCF RIA Services and IIS error NotFound – A deploy nightmare

When we first deploy our Silveright , RIA Services enabled application we may can some errors trying to get data from the services.

I got the folliwng error:

Load operation failed for query ‘GetUser’. The remote server returned an error: NotFound.

After 3 days reading posts and tutorials and fighting with WCF RIA services, I’ve succeeded to run my application.

As I understood the error was caused by number of problems.

1) I had to Disable “Windows authentication” from IIS->MyApplication->Authentication:

In many post this action saved the problems of other users, but in my case it didn’t help. However without it after making the other steps there was no success.

2) Second step was to include “Windows Comunication Foundation HTTP Activation ” and “Windows Comunication Foundation Non -HTTP Activation ” from Windows Features.

3) I got another error after installing the features above

Could not load type ‘System.ServiceModel.Activation.HttpModule’ from assembly ‘System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’.

This error appears  if ASP.Net 4. Is not installed.

Fix the problem by installing ASP.Net

c:\WIndows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -iru

Start installing ASP.NET (4.0.30319).

……………….

Finished installing ASP.NET (4.0.30319).

The –iru option of aspnet_regiis.exe Is required because of  “-iru   Install this version of ASP.NET. If there are any existing  applications that uses ASP.NET, it will not change IIS”

Now it works !

I hope this post will save someone 3 days 🙂

Posted in RIA Services, Silverlight | 1 Comment