7 May 2014

Using Windows Azure to Store Windows Phone 8 App Data

Options for Storing Mobile Data to Azure

Windows® Azure™ provides multiple options for data storage and its persistence. I delve into this discussion in my article published at Developer.com:
http://www.developer.com/ws/using-windows-azure-to-store-windows-phone-8-app-data.html

11 Mar 2014

Dependency Injection Best Practices


Sometimes if we don't implement software application's layer separation correctly, it leads to many code issues. This is even more important when we are dealing with an enterprise scale solution. So check out my articles published recently on Developer.com which dig deep into common IoC design issues and its resolution:

Dependency Injection Best Practices in an N-tier Modular Application   
In this article, you will learn some of the best design practices in implementing an Inversion of Control (IoC) / Dependency Injection (DI) pattern to create a loosely coupled system in .NET Framework, while keeping the data and business layers abstracted.



27 Jan 2014

Windows Phone 8 App Development Part-3: Testing/Publishing

This post is part-3 of the article on windows phone 8 app developments -  Quick Start-up guide with best practicesThis whole series is in 3 parts:
Part-1: Planning and Environment Setup
Part-2: App Development, best design practices, and some challenges 
Part-3: Testing/QA of the App and the process of publishing it to store

In case if you haven’t checked the part-1 and part-2, I strongly recommend you to go through them first. 

Now I will discuss about the testing/QA challenges and the process of your app certification and publication to windows phone store.


Testing/QA

Through Emulator: Emulator is a virtualized environment in which you can debug and test Windows Phone apps without a physical device. The default emulator image in Visual Studio is 'Emulator WVGA 512MB'. This default selection targets the largest possible market.  Emulator is used continuously for testing during development or QA. 
Various emulator options: 

With real phone device: Although emulator provides a comparable performance to a real device, I strongly recommend you to test your app on multiple devices (like 1 high end-Lumia 920 and 1 low end - Lumia 520). 
Even I found some differences between emulator and device such as problem in detecting network or limitations with memory utilization issues. The testing against device will help you to find few critical issues which may not come up in Emulator.
Deployment to a device is real easy as we just need to connect device using USB while Win 8 VM is maximized, select Device in-place of Emulator, and run/debug the App in Visual Studio. App will get installed in the device. We can also debug against the device, and there is no need to worry as nothing would happen to your phone.


Creating a developer account

You will need a paid developer account to publish your app to windows store. You can register as individual or a company. You would also need to associate a Microsoft account with this developer account. Following are the differences between individual and company account:
Individual
  • Restricted from using certain app capabilities
  • Cannot list desktop apps in the Windows Store
  • Costs approximately $19 USD
Company 
  • Requires additional verification through Symantec
  • Costs approximately $99 USD
Both of these accounts will give the ability to publish to windows phone and store, and would need Credit card for verification.
Useful links:
Setting up payout account: In case you app is a paid one or you expect some revenue from in-app advertisements. Follow this link to setup this.

Publishing to store

I would say, publishing an app to windows phone store is not very difficult task, but at the same time for the first timers, it would look little daunting because of the following steps involved:

Technical certification requirements for Windows Phone

Ideally it is like a third party acting as QA and verifying your application against some predefined certification requirements. From my experience, I think they don’t focus a lot on testing your app features but the bottlenecks such as app reliability (should not crash), performance, app functionality, non-blocking ease of use, content validations like app text and icons are visible in light or dark background or in various themes like red, green etc, or whether app tile images or app listing details are fine.

So, it is strongly advised to test your app against the Windows App Certification Kit: The Windows SDK includes this kit. 
How to access in Visual Studio (Right click project and select "Open Store Test Kit":



Other preparations before publishing your app for certification:

Choose and reserve your app name: App name should be unique, so it is advisable to select few good names which doesn't exist in store.

Decide what age rating will apply to your app: It depends on the type of App.

Choose pricing: Free or paid. If paid then what would be the price.

Choose the countries and regions in which you want to sell your apps: All markets or some specific countries.

Write your app's description: The app description is kind of a summary of your published app’s capabilities. So a well-written description with to-the-point features details, can encourage your prospective users to download or buy your app.

Select Auto or Manual publish: In case of automatic publishing option, app will get published automatically once it passes certification. Once app passes certification, you will receive email confirmation. Even if “Auto” publish option is selected, it may take some time (few hours) before your app would be visible in the targeted store.

Submit App and then Track certification status: Once all details are filled correctly along with XAP file (build) and listing images, app can be submitted. In case after submission, you want to change something, you can cancel the submission and resubmit it again. Your every submission will go through certification process from start.

Microsoft's App submission/ tracking dashboard:


Tracking app submission

The certification process usually takes 5-7 days of time. If your app fails the certification, you will receive an email from Microsoft with detailed test report in PDF format. It will explain the expected and the actual result. These are generally standard tests outlined in their certification requirements. Correct these defects, and re-submit the new XAP file.

Some common blocks (tech or non-tech)

Network availability: Use following code to know network availability. You can add it as static property on App class to make it easy to access throughout the app.

public static bool IsNetworkAvailable
        {
            get
            {
                return NetworkInterface.GetIsNetworkAvailable();
            }
        }

Image for dark and light theme: In case if you have an image for dark background, don’t worry, we can use same image for light background too. Use following code to achieve this:



Out of memory issues: These issues are mostly caught while testing app through a phone device. Use memory intensive controls like browser or others very consciously.

Few Advance Scenarios:

Creating Live Tiles: It is quite easy to add a live tile for you app. Check out this article -  Live Tile Templates in Windows Phone 8

Push notifications: There can be local or remote notifications. Remote would definitely need some services like Microsoft Push Notification Service (MPNS) which send data from cloud.
     Local notifications: These can be tiles, toasts, alarm, reminder notifications on the phone. Check out this link - Local notifications for Windows Phone  
     Remote notifications: Push notifications for Windows Phone 

Integrating Facebook with app: This is a nice article to get started on this - Integrate Facebook to Your Windows Phone Application 

Integrating Azure with phone: MobileService can be used to communicate to Azure data or other services. Check out this link: Get started with Mobile Services. Very soon, I am going to publish one article around this. Stay tuned.

Summary

In this article series - part-1: planning and environment setup, part-2: Development, and this part-3: Testing and Publishing, I have tried to cover most of the pain points for starting windows phone 8 developments. I believe it would be quite useful for beginners. I would recommend you to check out the source code from part-2 which contains a jump-start project design with many of the best practices discussed. Please get in touch with me if you have any questions or feedback @ manoj.kumar[at]neudesic.com.


26 Jan 2014

Windows Phone 8 App Development Part-2: Developing an App

This article is the part-2 of the series of the article on windows phone 8 app developments -  Quick Start-up guide with best practices. This whole series is in 3 parts:
Part-1: Planning and Environment Setup
Part-2: App Development, best design practices, and some challenges 
Part-3: Testing/QA of the App and the process of publishing it to store
In case if you haven’t checked the part-1, I strongly recommend you to go through it first. 

Now I will discuss about the real app development challenges and some of the best practices to follow.

Language choice

This was one of the first confusion we had – whether to go with XAML/C# or HTML/JS
Although it depends on individual or team’s experience and liking, it seems that XAML/C# is clearly the most preferred choice for app development. I have listed down some of the reasons to choose one:-

XAML/C#: Windows Ecosystem, High Performance (Native), Resolution Independence, Easier UI Binding, Better Object Oriented Programming, Stateful (persistent state), Integration with Expression Blend, Easier debugging, better community knowledge support (coming from earlier Windows 7 days).

HTML5/JS: Multi-Platform, Lesser learning curve, JavaScript language flexibility, Easier styling thru CSS, Powerful query selection for elements, Better integration with Blend, Plugins. 

If you are new to XAML, then I would strongly recommend you to learn few basic concepts such as Xaml markups, Xaml Code behind, events, styles, behavior/triggers, binding (one time, one way, two-way etc)

App templates

There are many app templates available for win 8. 

If you really don’t care about template type, then let’s create a new Project for “Windows Phone Databound App” template.
If need more help, follow this link to create your first app: How to create your first app for Windows Phone

Design Considerations

The Windows phone application can be based on pure XAML or it can leverage the power of any MVVM framework. I always prefer to use MVVM framework with any XAML based application because of many advantages such as easy data binding or event handling, robust design with better SoC (Separation of Concerns), better testability etc.  
MVVM framework popular options: MVVMLight (Easy and very lightweight, good for Phone), Prism (More comprehensive and good for desktop or Windows store apps). 

The recently released free MVVMLight has support for Windows Phone 8. MVVMLight has following advantages:
- Very light weight (just around 50-60Kb in size)
- Inbuilt IoC (SimpleIoc)
- Decoupling of View Model by using publish/subscribe message based communication
- Relay Command: Less code behind.

In case you are new to MVVM pattern, please go through following link to understand it. It is used almost in every XAML app. Few concepts such as view models, data context, command, property change events etc are used extensively. 
Adding MVVMLight to the XAML project: Right click the project and select ‘Manage NuGet Packages’. Search ‘mvvmlight’ and install ‘MVVM Light’ (Toolkit). It will add few files and folders. If needs further help, follow these instructions: How to install MVVM Light Toolkit for Windows Phone

IoC implementation and importance

The SimpleIoc is really a great addition in GalaSoft MVVMLight. In most of the scenarios, view models are singleton objects and which can be easily managed by SimpleIoC and can be accessed anywhere in the application.
public class ViewModelLocator
    {
        /// 
        /// Initializes a new instance of the ViewModelLocator class.
        /// 
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (ViewModelBase.IsInDesignModeStatic)
            {
                // Create design time view services and models
                //SimpleIoc.Default.Register();
            }
            else
            {
                // Create run time view services and models
                SimpleIoc.Default.Register();
            }

            SimpleIoc.Default.Register();
        }

        public T GetInstance()
        {
            return ServiceLocator.Current.GetInstance();
        }
        
        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }

For easy access across application:

public static ViewModelLocator Locator
        {
            get
            {
                if (_locator == null)
                    _locator = new ViewModelLocator();

                return _locator;
            }
        }
Async/Await pattern

Asynchrony proves especially valuable for applications that access the UI thread because all UI-related activity usually shares one thread. Application can stop responding. Async/await is a Tasked-Based Asynchronous Pattern (TAP) which is much easier to implement than Event-based Asynchronous Pattern (EAP) which came in .Net 2.0. We can create an asynchronous method almost as easily as you create a synchronous method. Read more here:  Asynchronous Programming with Async and Await
async private void LoadItems(string query)
        {
            var items = await _data.GetItems(query);

            var itemVMs = items.Select(i => new ItemViewModel { ID = i.ID, LineOne = i.LineOne, LineThree = i.LineThree, LineTwo = i.LineTwo });
            this.Items = new ObservableCollection(itemVMs);
        }
Navigation

Windows Phone supports frame based navigation. The hardware back button makes navigation behave differently than desktop applications. Navigation can be based on “Data Template”, where depending upon current view model we can show view template registered with App resources. Data Template based navigation is quite common in WPF applications.
I suggest to use default frame based navigation. It is hassle free and provides automatic back navigation which is managed by the back stack. 
NavigationService available thru PhoneApplicationPage class (base class of every phone page).
// Navigate to the new page
NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + (MainLongListSelector.SelectedItem as ItemViewModel).ID, UriKind.Relative));

In case you need to handle hardware back button press differently, then follow this:
At App level in App.xaml.cs:
private void RootFrame_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //Some custom logic/ condition
If (true)
e.Cancel = true;
 else {}
        }

Or in page:
protected override void OnBackKeyPress(CancelEventArgs e)
{
    if(MessageBox.Show("Are you sure you want to exit?","Exit?", 
                            MessageBoxButton.OKCancel) != MessageBoxResult.OK)
    {
        e.Cancel = true; 

    }
}
Phone storage

User/App data can be stored in isolated phone storage. It would be good to add a utility class like AppSettings:
public class AppSettings
    {
        IsolatedStorageSettings settings;
        bool isDirty;
        public AppSettings()
        {
            //Get the settings for this application.
            settings = IsolatedStorageSettings.ApplicationSettings;
        }

        /// 
        /// Update a setting value for our application. If the setting does not
        /// exist, then add the setting.
        /// 
        /// 
        /// 
        /// 
        public void AddOrUpdateValue(string Key, Object value)
        {
            if (settings.Contains(Key))
            {
                settings[Key] = value;
            }
            // Otherwise create the key.
            else
            {
                settings.Add(Key, value);
            }
            isDirty = true;
        }

        public bool ContainsKey(string key)
        {
            return settings.Contains(key);
        }

        /// 
        /// Get the current value of the setting, or if it is not found, set the 
        /// setting to the default setting.
        /// 
        /// 
        /// 
        /// 
        /// 
        public T GetValue(string Key)
        {
            if (settings.Contains(Key))
            {
                return (T)settings[Key];
            }
            return default(T);
        }

        /// 
        /// Save the settings to isolated storage.
        /// 
        public void Save()
        {
            if (!isDirty)
                return;
            settings.Save();
            isDirty = false;
        }
    }

It can be added to App class as static field for easy access across application:
public static AppSettings Settings
        {
            get
            {
                if (_settings == null)
                    _settings = new AppSettings();
                return _settings;
            }
        }
Windows Phone Toolkit

An important addition to the default App development ecosystem which has limited no of controls at our disposal. Toolkit has many useful components. To add this: Go to “Manage NuGet Package” and search “toolkit”. Install “Windows Phone Toolkit” from the available packages.
This toolkit has many new controls such as: AutoCompleteBox, ContextMenu, CustomMessageBox, DateTimeConverters, DateTimePickers, ExpanderView, ListPicker, LongListMultiSelector, Map extensions, RatingControl, ToggleSwitch, Navigation transitions.

Application Bar

It is an integral part of your app which enables easy navigation between pages. Add following lines of code with required menu items or icons in any page where you want to provide navigation options.

        
            
            
            
                
                
            
        
    
App bar:

Menu items can be hidden by setting "IsMenuEnabled " flag to false. The app bar can be in minimized state by setting “Mode” as “Minimized”.
Minimized app bar:

Phone page animated transition

It is quite easy to implement by adding following lines of code in page XAML. This is again possible because of toolkit. Even Effects such as SlideInEffect, TiltEffect and TurnstileFeatherEffect are possible thru use of toolkit.

For Page transition effect:

        
            
                
            
            
                
            
        
    
    
        
            
                
            
            
                
            
        
    

User Interface

The phone SDK provides some default theme and icons. It is highly recommended to use them as it matches the overall look and feel of phone. If needed new theme can be added or existing theme styles can be extended. It is good practice to keep these new styles in App XAML or a separate file. Expression blend can be used to efficiently create new styles.

SDK Path: C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0 
ICONs (Dark/Light): C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Icons
Adding custom styles at App level under:

    #FF000000
    #FFFFFFFF
    #666666
    
    40
    12,5,12,0
    
    
    
  
Source Control

I used online visual studio as source control. It is just as easy to configure as we can do in our favorite TFS (Team Foundation Server). A valid Microsoft account is required to access online visual studio. License: The free version supports upto 5 users.
Link: http://www.visualstudio.com/  (Go to 'Visual Studio Online')
Interface:

Source Code

I have developed a windows phone 8 solution which includes most of the best practices discussed above. It would be a great starting point for your application. 
Solution contains following:

Next

In next post - part-3 of this article series, I will discuss about testing/QA of the developed application and the process of publishing it to windows store.

25 Jan 2014

Windows Phone 8 App Development Part-1: Environment Setup

Introduction

With Windows 8, Microsoft has introduced major changes in the operating system and its user interface to improve overall user experience. Microsoft is positioning it as a next revolution in the technology of computer’s operating systems (OS) to compete with other tablet or mobile OS, including popular Android and iOS. Some of the key enhancements would be Speedy Boot Time, Live tiles based interface, Improved Search Function, Windows To Go (plug in, boot and go), or Windows Live Syncing. 

Read more about Windows 8: 
5 Reasons You Should Upgrade to Windows 8
5 Top Windows 8 Features You’ll Love

As there are significant changes in the platform, it is obvious that we need to unlearn some old ways and get used to all new windows 8 development environment. Although there are many changes in API, the best part is that we can still utilize the existing knowledge base - either we choose to develop in XAML/C# or HTML5/JS. 
Today I am going to discuss about the steps and challenges which any developer can face while starting windows phone 8 developments. These are the same experiences which I experienced when I started working on my first app.

I have divided this article Windows Phone 8 App Development - Quick Start-up guide with best practices in 3 parts:-
Part-1: Planning and Environment Setup
Part-2: App Development, best design practices, and some challenges 
Part-3: Testing/QA of the App and the process of publishing it to store

Background

You are seasoned application developer with experience on Microsoft platform (C#, WPF/Silverlight, .Net, JavaScript).

Motivation

Learn Windows 8 development ecosystem and in the process create and publish a real time application on Windows Phone 8 apps store for millions of potential users / customers in hundreds of markets around the world.

Planning

I am hoping that, since you have landed to this post and reading this article, you already have some application idea and you are looking for ways to jump-start the development. In case, you have not, the good news is that it's not late. We are in planning phase. This is the time when we should start visualizing our application. I am going to share my experience when we started and came to this stage.

Steps: (I worked with one more team member)

  1. Kick-off: We noted down all the points whichever came to our mind separately. We collated all the findings and finalized a priority list. This exercise was great as both of us came with very different requirements / blocks. It would be impossible to get in case of a discussion as our thought process would not have been so independent and could be obstructed by other’s point of view.
  2. Came up with some rough documentation.
  3. Planned the next steps. First and the biggest one were to setup the environment, and then dive deep into the world of windows 8 development.

Environment setup

Our minimum need was to have a Windows 8 OS VM with Visual Studio 2013 installed. So we started in following manner:
Note: Before downloading any software, please check with your IT department whether they already have.

OS (Operating System): Downloaded Windows 8.1 enterprise edition (90 day trial) from http://technet.microsoft.com/en-in/evalcenter/hh699156.aspx (64 -bit) [more than 2GB in size]
Visual Studio 2013: Ultimate with 90 days extended free trial. 30 days default, but which gets extended by 60 days on login with Microsoft Account through visual studio. [more than 2GB in size]. Link: http://www.microsoft.com/en-in/download/details.aspx?id=40778

Virtual Machine Host: Need to have VMWare Workstation. I had Oracle Virtual Box, so I setup my Windows 8.1 OS VM using this client, but only to regret later when emulator installation failed during Visual Studio setup. We can’t imagine a developer life without emulator. Fortunately we came to know that emulator works fine with VMWare Workstation. So we downloaded VMWare Workstation 10 and recreated my Win 8 VM. VMWare Download Link: https://my.vmware.com/web/vmware/info/slug/desktop_end_user_computing/vmware_workstation/10_0

Steps for creating VM: System Req: 64 bit system, 8 GB of RAM, 40GB Free Space, System should Support Hyper-V for Emulator to work.Follow steps defined in this article to create VM. It is very well explained. http://developer.nokia.com/Community/Wiki/Windows_Phone_8_SDK_on_a_Virtual_Machine_with_Working_Emulator
Note: Follow the Hyper-V related changes carefully. It is mandatory for phone Emulator installation.

Once VM is created: Install Visual Studio 2013. It already has Windows Phone 8 SDK. Select all features while installation.

Next

That’s it. In part-2 of this article I will discuss about the application development process and some of the initial challenges.


12 Nov 2013

N-Tier Application Architecture

Software application architecture is an interesting and broadly discussed topic. In this presentation, I am discussing N-Tier application architecture. Going to investigate: What is architecture? Kinds of N-Tier application architecture and its advantage and disadvantage. 
There is also a very basic quiz towards the end of the discussion.


Microsoft BizTalk Server Fundamentals

Microsoft BizTalk Server Orchestration Fundamentals

10 Nov 2013

WPF 2 Dimensional Editable Grid

Problem

Two dimensional (2D) grid is not supported out-of-box in WPF. It is also not very trivial to create one. In this article, I will dive into a way we can create reusable generic 2D grid which is bound to object collections. This can be easily customized by setting appropriate attributes.  
Let’s look at the general grid requirements:
  1. Grid should have flexible design / layout.
  2. X-Axis or Y-Axis headers should not scroll with content.
  3. All binding should be done against object collections, so that we have more control over the data which is being displayed and on any user interactions.
  4. Easy to customize the data display and UI look and feel.
  5. Grid can be readonly or editable.
Grid Examples: In short we might need grids like: 
Grid 1: Notebook price (editable) by Brand and City
Grid 2: Notebook price (editable) with readonly notebook details by Brand and City - With auto scroll bars
Let's see how we can create an Editable or ReadOnly 2 D (Two Dimensional) generic grid in WPF which will be bound to objects directly.

Solution

We can design using various WPF controls. As shown in following figure, we can divide grid into 3 major areas – Column Headers, Row Headers, and Body cells. We can use panels to layout these and achieve structure of a grid.
Assuming this layout, let’s see how we can achieve this through code:
For this to demo: I will use following models:
Our final goal is to visualize product (Notebook in this case) information in a 2D grid where product price is shown by Brand name and City name. Product price should be editable. As shown in this grid:
To achieve this grid layout, we would need following collections:
Column Headers: IEnumerable<object> Columns
Row Headers: ObservableCollection<object> RowsHeader
Rows: ObservableDictionary<object, ObservableCollection<object>> RowsByYAxis
*RowsHeader collection will be generated from RowsByYAxis dictionary. So, ideally we would need only 2 collections.
Let's dive into the code:
Solution design:
The solution contains two projects:
WpfGenericGrid: A class library for generic grid (User Control, View Model, Converters, Messages).
WpfGeneric2DGrid: A client WPF application which consumes above class library to demo 2D editable grid.
In this WPF project, I have used GalaSoft.MvvmLight.WPF4 package for making it easy to implement MVVM pattern. It is a light weight solution which supports generic RelayCommand and Asynchronous Messaging to facilitate communication between view models.
Now we can peek into the real code to create this generic grid:
GenericGrid.xaml (User control)


    
        
        
    

    
        
            
            
        
        
            
            
        
        
            
                
                    
                    
                
            
        
        
            
                
                    
                        
                    
                
                
                    
                        
                            
                                
                                
                            
                        
                    
                
            
        
        
            
                
                    
                        
                            
                            
                                
                                
                            
                        
                    
                
            
        
        
            
                
                    
                        
                            
                                
                                    
                                        
                                    
                                
                                
                                    
                                        
                                            
                                                
                                                    
                                                
                                            
                                        
                                    
                                
                            
                        
                    
                
            
        
    
GenericGrid.xaml.cs (To handle some of the events like synchronize scroll between body and header or validations)
public partial class GenericGrid : UserControl
    {
        public GenericGrid()
        {
            InitializeComponent();
        }

        private void SvGridCells_OnScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (e.HorizontalChange != 0.0f)
            {
                try
                {
                    SvColHeaders.ScrollToHorizontalOffset(e.HorizontalOffset);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                SvRowYAxis.ScrollToVerticalOffset(e.VerticalOffset);
            }
        }

        private void CellTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
            e.Handled = regex.IsMatch(e.Text);
        }
    }
GenericGridViewModel.cs  (View Model for GenericGrid user control) This class contains all the necessary properties like:
CanDelete (True to enable row delete), ReadOnly (True/False, false for editable grid), Columns (XAxis column headers), GridHeight, GridWidth, RowHeight, XAxisHeight, YAxisWidth, ColumnWidth, ScrollBarVisibility. 
public class GenericGridViewModel : ViewModelBase
    {
        private ObservableDictionary<object, ObservableCollection<object>> _rowsByYAxis;
        private double _xAxisColumnWidth = 100;
        private double _yAxisWidth = 150;
        private double _xAxisHeight = 30;
        private double _rowHeight = 30;
        private double _gridWidth = 600;
        private double _gridHeight = 170;
        private string _gridName = string.Empty;
        private bool _isVerticalScrollVisible;
        private bool _isHorizontalScrollVisible;
        private double _gridXAxisHeaderWidth;
        private double _gridYAxisHeaderHeight;
        private double _gridBodyScrollHeight;
        private double _gridBodyScrollWidth;
        private ObservableCollection<object> _rowsHeader;
        private string _gridYAxisHeaderMargin;

        public GenericGridViewModel(string gridName)
        {
            _gridName = gridName;
            HorizontalScrollBarVisible = true;
            VerticalScrollBarVisible = true;
            DeleteRow = new RelayCommand<object>(rowIdentifier =>
            {
                if (!RowsByYAxis.ContainsKey(rowIdentifier)) return;
                var rowHeaderToRemove = RowsByYAxis[rowIdentifier];
                _rowsByYAxis.Remove(rowIdentifier);
                _rowsHeader.Remove(rowIdentifier);
                Messenger.Default.Send(
                    new GenericMessage<GridDataUpdateMessage>(new GridDataUpdateMessage()
                        {
                            RowHeader = rowHeaderToRemove,
                            ActionType = GridAction.RowDelete
                        }));
                RowsByYAxis = _rowsByYAxis;
            });
            Columns = new ObservableCollection<object>();
            RowsByYAxis = new ObservableDictionary<object, ObservableCollection<object>>();
        }

        protected void ComputeGridLayout(int colCount, int rowCount)
        {
            _isVerticalScrollVisible = GridHeight - RowHeight < rowCount * RowHeight;
            _isHorizontalScrollVisible = GridWidth - YAxisWidth < colCount * CellWidth;

            GridXAxisHeaderWidth = HorizontalScrollBarVisible ? _isHorizontalScrollVisible ? GridWidth - YAxisWidth : colCount * CellWidth : GridWidth - YAxisWidth;
            GridYAxisHeaderHeight = VerticalScrollBarVisible ? _isVerticalScrollVisible ? GridHeight - RowHeight : rowCount * RowHeight : GridHeight - RowHeight;

            GridBodyScrollWidth = _isVerticalScrollVisible ? GridXAxisHeaderWidth + 18 : GridXAxisHeaderWidth;
            GridBodyScrollHeight = _isHorizontalScrollVisible ? GridYAxisHeaderHeight + 18 : GridYAxisHeaderHeight;

            GridYAxisHeaderMargin = HorizontalScrollBarVisible || VerticalScrollBarVisible ? _isVerticalScrollVisible || _isHorizontalScrollVisible ? "0 -20 0 0" : "0" : "0";
        }

        public double XAxisColumnWidth
        {
            get { return _xAxisColumnWidth; }
            set { _xAxisColumnWidth = value; }
        }

        public double YAxisWidth
        {
            get { return _yAxisWidth; }
            set { _yAxisWidth = value; }
        }

        public double RowHeight
        {
            get { return _rowHeight; }
            set { _rowHeight = value; }
        }

        public double XAxisHeight
        {
            get { return _xAxisHeight; }
            set { _xAxisHeight = value; }
        }

        public double CellWidth
        {
            get { return XAxisColumnWidth + 1; }
        }
        public double GridWidth
        {
            get { return _gridWidth; }
            set { _gridWidth = value; }
        }

        public double GridHeight
        {
            get { return _gridHeight; }
            set { _gridHeight = value; }
        }

        public double GridXAxisHeaderWidth
        {
            get { return _gridXAxisHeaderWidth; }
            private set { _gridXAxisHeaderWidth = value; RaisePropertyChanged("GridXAxisHeaderWidth"); }
        }

        public double GridYAxisHeaderHeight
        {
            get { return _gridYAxisHeaderHeight; }
            private set { _gridYAxisHeaderHeight = value; RaisePropertyChanged("GridYAxisHeaderHeight"); }
        }

        public double GridBodyScrollHeight
        {
            get { return _gridBodyScrollHeight; }
            private set { _gridBodyScrollHeight = value; RaisePropertyChanged("GridBodyScrollHeight"); }
        }

        public double GridBodyScrollWidth
        {
            get { return _gridBodyScrollWidth; }
            private set { _gridBodyScrollWidth = value; RaisePropertyChanged("GridBodyScrollWidth"); }
        }

        public string YAxisHeaderText { get; set; }
        public bool IsReadOnly { get; set; }
        public bool CanDelete { get; set; }
        public bool HorizontalScrollBarVisible { get; set; }
        public bool VerticalScrollBarVisible { get; set; }
        public RelayCommand<object> DeleteRow { get; protected set; }
        public IEnumerable<object> Columns { get; set; }
        public string GridYAxisHeaderMargin
        {
            get { return _gridYAxisHeaderMargin; }
            private set { _gridYAxisHeaderMargin = value; RaisePropertyChanged("GridYAxisHeaderMargin"); }
        }
        public ObservableCollection<object> RowsHeader
        {
            get { return _rowsHeader; }
            private set { _rowsHeader = value; RaisePropertyChanged("RowsHeader"); }
        }
        public ObservableDictionary<object, ObservableCollection<object>> RowsByYAxis
        {
            get { return _rowsByYAxis; }
            set
            {
                _rowsByYAxis = value;
                if (_rowsByYAxis.Any())
                {
                    ComputeGridLayout(Columns.Count(), _rowsByYAxis.Count);
                    RowsHeader = new ObservableCollection<object>(_rowsByYAxis.Keys);
                }
                RaisePropertyChanged("RowsByYAxis");
            }
        }
    }
Note: You would need ObservableDictionary to implement 2-way binding. This you can find in the linked source code.

GridDataUpdateMessage.cs (It is to communicate data edits or row deletion commands to view model)
public class GridDataUpdateMessage
    {
        public object CellData { get; set; }

        public object RowHeader { get; set; }

        public GridAction ActionType { get; set; }
    }
Few Utility classes: 
GridCellTextBox.cs (Custom text box control with extra bindable properties)
public class GridCellTextBox : TextBox
    {
        public static readonly DependencyProperty UniqueNameProperty =
            DependencyProperty.Register("UniqueName", typeof(string), typeof(GridCellTextBox));
        public static readonly DependencyProperty RowHeaderNameProperty =
            DependencyProperty.Register("RowHeaderName", typeof(string), typeof(GridCellTextBox));

        public string UniqueName
        {
            get { return (string)GetValue(UniqueNameProperty); }
            set { SetValue(UniqueNameProperty, value); }
        }

        public string RowHeaderName
        {
            get { return (string)GetValue(RowHeaderNameProperty); }
            set { SetValue(RowHeaderNameProperty, value); }
        }
    }
ColumnHeader.cs  (A class for binding columns headers)
public class ColumnHeader
    {
        public string Name { get; set; }

        public string Description { get; set; }
    }
RowHeader.cs  (A class for binding row headers)
public class RowHeader
    {
        public string Name { get; set; }

        public string Description { get; set; }
    }
We are done with important pieces of generic grid. If you want to dive more into details. I would advise to look into the source code.

Now let’s  see how to use all these to create grid in a WPF project: We need to add the reference of the WpfGenericGrid assembly to the client project, and then add reference of the user control to the view. As shown below:
MainWindow.xaml (View in the client app)

    
        
                
        
    

MainWindowViewModel.cs : Create sample product data and the view model instance for the grid. Set required properties appropriately.
class MainWindowViewModel : ViewModelBase
    {
        private GenericGridViewModel _gridViewModel;
        
        public MainWindowViewModel()
        {
            List<Product> products = CreateSampleData();

            var colHeaders = products.GroupBy(p => p.City).FirstOrDefault().Select(p => new ColumnHeader {Name = p.BrandName, Description = p.BrandName});
            
            var rowHeaders = products.GroupBy(p => p.BrandName).FirstOrDefault().Select(p => new RowHeader {Name = p.City, Description = p.City});

            var rowByYAxis = products.GroupBy(p => p.City).ToDictionary(p => p.Key, p => p.ToList());
            var observRowByYAxis = new ObservableDictionary<object, ObservableCollection<object>>();

            rowByYAxis.Keys.ToList().ForEach(key => observRowByYAxis.Add(rowHeaders.FirstOrDefault(r => r.Name == key), new ObservableCollection<object>(rowByYAxis[key])));

            GridViewModel = new GenericGridViewModel("productGrid")
            {
                RowHeight = 30,
                XAxisColumnWidth = 100,
                YAxisWidth = 120,
                GridHeight = 200,
                GridWidth = 700,
                Columns = colHeaders,
                RowsByYAxis = observRowByYAxis,
                CanDelete = true,
                HorizontalScrollBarVisible = true,
                VerticalScrollBarVisible = true,
                YAxisHeaderText = "City"
            };

            Messenger.Default.Register<GenericMessage<GridDataUpdateMessage>>(this, (a) =>
            {
                //Updated data
                var message = a.Content;
                if (message.ActionType == GridAction.CellUpdate)
                {
                    //Cell value change
                }
                else if (message.ActionType == GridAction.RowDelete) { 
                    //Row deleted
                }
            });
            Load = new RelayCommand(() =>
                {
                    //Run some logic
                });
        }

        public RelayCommand Load { get; set; }

        public GenericGridViewModel GridViewModel
        {
            get { return _gridViewModel; }
            private set 
            { 
                _gridViewModel = value;
            }
        }
    }
Once everything is put in place correctly, we can see following grid:
In case, if you want to see the running code, I would advise you to download it from the link and play with it.

Source Code

I have developed this generic grid as a class library which can be easily referenced and used in a WPF project. If needed, the same can be copied to any existing WPF project. This sample application demonstrates how to create both of the grids (Grid-1 and Grid-2) discussed in the problem statement. 
To run this application, you would need Visual Studio 2010.

Source code location: https://github.com/manoj-kumar1/WPF-2D-Editable-Grid

Conclusion

In this article, I have tried to demonstrate an easy way to create a 2D grid in WPF. This grid can be easily customized as one or two dimensional; or readonly or editable. Many of the customization can be achieved by setting appropriate properties in grid view model.
Please get in touch with me if you have any questions or you think otherwise @ manoj.kumar[at]neudesic.com.