Ray Yagubyan

 

Building the Bing apps for Windows 8

Overview

For Windows 8, the Bing team built News, Weather, Finance, Sports, Travel and Maps apps. This technical overview provides insight on the architecture of these apps, key Windows 8 features and the contracts they use, common controls they employ, and world readiness more generally.

Integrating your cloud service with the file picker contracts

In the past, users organized, shared, and maintained their documents, photos, videos, and music on the local PC. But the cloud is quickly providing users with much richer ways to access, experience, and manage the files they care about. Windows 8 embraces these new scenarios by allowing you to deeply integrate cloud services directly into your apps to create completely new experiences that were not possible before.

Building your own Windows Runtime components to deliver great Metro style apps


For Windows 8, we completely reimagined the platform, allowing you to choose the programming language and technologies you already know to build apps tailored to the device and form factor. With the Windows Runtime, you can even easily use multiple languages within a single app. You can build a great Metro style app with HTML and JavaScript that can interact with the Xbox 360 controller through building your own Windows Runtime component in C++. You can build reusable XAML controls exposed via Windows Runtime components that are instantly consumable by Metro style apps written in both C++ and C#. Essentially, we have let you build apps on the Windows 8 platform using the languages of your choice with no comprises.

In this blog post, we talk about what you need to know to build your own Windows Runtime components.

The basics

The Windows Runtime is at the heart of empowering language choice. It exposes so that you can call them from JavaScript, C++, C# and Visual Basic in a way that’s natural and familiar. This same foundation is available to you when building your own APIs too.

A Windows Runtime component that you build and package in your app is typically referred to as a 3rd party Windows Runtime component. This differs from 1st party components that are already part of the Windows 8 platform. You can write these 3rd party Windows Runtime components in C++, C# or Visual Basic. You can call into the APIs they expose from anywhere, including other Windows Runtime components packaged into your app. You can also call into the APIs exposed via Windows Runtime components from any language.

The Windows Runtime components that you write for your app can use Windows Runtime APIs, Win32, COM, .NET APIs or 3rd party libraries as long as they are supported for Metro style app development. Note that the Windows Runtime components that you build are different from what you traditionally know as C++ DLLs or .NET assemblies that expose APIs. Creating a class library in .Net or a standalone DLL in C++ is not the same as building a Windows Runtime component. Windows Runtime components are declared in .wnmd files that expose Windows Runtime metadata and enable languages such as JavaScript to naturally consume Windows Runtime APIs (for example, pascalCasedNames support for APIs exposed to JavaScript). The Windows Runtime metadata also enables Visual Studio to provide great tooling capabilities such as IntelliSense support.

Why build your own Windows Runtime components

Creating Windows Runtime components can help you architect for reusability and language interoperability. Let’s take a look at some app scenarios that showcase how you can use 3rd party Windows Runtime components to build better experiences.

    Figure1: Xbox 360 Controller

Using Win32 and COM APIs in your Metro style app

The platform provided by Internet Explorer 10 enables you to create great Metro style app experiences using HTML, CSS and JavaScript. But what if you have built a game using HTML5 canvas and want to integrate with the Xbox 360 controller for Windows? The XInput API, which allows apps to receive input from the controller, exposes Win32 APIs that are not available directly to JavaScript.

This is a great example of where creating a Windows Runtime component can solve this problem and give you the ability to use the XInput APIs in your HTML based Metro style app. The XInput and JavaScript controller sketch sample showcases exactly that. The sample app contains a game controller Windows Runtime component written in C++ which wraps the functionality exposed by the XInput APIs. The controller sketch HTML-based app uses the game controller C++ Windows Runtime component to enable the interaction with the Xbox 360 controller.

This scenario, impossible to accomplish using HTML and JavaScript alone, is a perfect example of where creating a 3rd party Windows Runtime component allows you to complete a complex scenario that you otherwise wouldn’t be able to.

Computationally Intensive Operations

Apps created for fields like science, engineering, and maps/geography often have computationally intensive operations. These intensive operations typically require powerful parallel processing and are well suited for C++ to achieve optimal performance. In Developing Bing Maps Trip Optimizer, a Metro style app in JavaScript and C++ , we see another scenario where creating a Windows Runtime component in C++ allows us to create the best experience in our app.

You wonder why anyone would want to calculate a trip route on local data at all when we could run this computationally intensive task in the cloud on Bing servers. Bing Maps exposes JavaScript APIs to do this, but sometimes an app must run offline. And we also want the user to drag and change the route in real time with touch. If we can run these intense operations locally, we create an even better experience.

By writing our compute-intensive operation in C++ using the parallel task library, we can harness the power of the client to create a great experience for users. Windows Runtime is a great fit for this scenario, allowing us to create our rich client User Interface (UI) in HTML and JavaScript with the Bing Maps AJAX control while running all of our intensive route operations using C++ code that calculates quickly using parallelization.

Libraries

The community is filled with great libraries that developers put together and shared for everyone to use. In the past, you may have found it challenging to reuse some of these libraries if they didn’t match the programming language your app was implemented in. For example, you built a great .NET app, but couldn’t use a library written in C++ without going through painful interop hoops like PInvoke.

Windows Runtime bridges the language gap in Windows 8, making it possible for a single Windows Runtime component library with a single code base to reach a broader set of developers irrespective of the component’s language or your app’s primary programming language.

You can now create a single Windows Runtime-exposed XAML library of custom controls that both C++ and C# app developers can consume. And you can use various data storage Windows Runtime libraries shared out by developers in your XAML or HTML based Metro style apps. All of these scenarios are possible without the burden of writing any interop code.

We think Windows Runtime will be a boon to the libraries that developers create and share broadly for the community of Metro style app developers. Let’s now take a look at two concrete examples showing the basics of building a 3rd party Windows Runtime component in C++/CX and C#.

Scenario 1: Enhancing your app with native audio

Say we are building a software synthesizer app using XAML backed by app logic written in C#. To add filter support to our music app, we would like to use XAudio to have direct control of audio buffers.

Adding the Windows Runtime component to our solution

Using Visual Studio, we add a new C++ Windows Runtime component project to our existing solution. This Windows Runtime component wraps the music processing functionality:

Figure 2: Adding a new C++ Windows Runtime Component

Visual Studio created a C++ project for us to expose APIs for which the implementation will be packaged in a DLL and the Windows Runtime metadata in a winmd file. Both are made available to our C# project.

Defining the class exposed to our XAML C# project

We use C++/CX to build the APIs that will be exposed to our C# project, but you also can use the Windows Runtime C++ Template Library (WRL). We start by defining a fairly basic class to encapsulate the XAudio functionality:

XAudioWrapper.h

#pragma once #include “mmreg.h” #include< vector> #include <memory> namespace XAudioWrapper { public ref class XAudio2SoundPlayer sealed { public: XAudio2SoundPlayer(uint32 sampleRate); virtual ~XAudio2SoundPlayer(); void Initialize(); bool PlaySound(size_t index); bool StopSound(size_t index); bool IsSoundPlaying(size_t index); size_t GetSoundCount(); void Suspend(); void Resume(); private: interface IXAudio2* m_audioEngine; interface IXAudio2MasteringVoice* m_masteringVoice; std::vector<std::shared_ptr<ImplData>> m_soundList; }; }

You will first notice the usage of the public, ref and sealed keywords in the class declaration. For a class to be instantiated from another language such as JavaScript or C# in a Metro style app, the class must be declared as public ref class sealed.

The public functionality (methods, properties …) of the class are limited to C++ built-in types or Windows Runtime types. Those are the only types allowed for crossing the language boundary in Windows Runtime components. That being said, you can use the regular C++ library (i.e.: Standard Template Library collections) for the private data members of your class as shown in this code snippet. Those private data members don’t have to follow the rules associated with crossing the language boundary. The Visual Studio compiler emits error messages and provides guidance if you use unsupported constructs.

Implementing the class exposed in our Windows Runtime component

Now that we have defined the basic interface for our class, let’s take a look at some of the implemented methods:

XAudioWrapper.cpp

XAudio2SoundPlayer::XAudio2SoundPlayer(uint32 sampleRate) : m_soundList() { // Create the XAudio2 engine UINT32 flags = 0; XAudio2Create(&m_audioEngine, flags); // Create the mastering voice m_audioEngine->CreateMasteringVoice( &m_masteringVoice, XAUDIO2_DEFAULT_CHANNELS, sampleRate ); } void XAudio2SoundPlayer::Resume() { m_audioEngine->StartEngine(); } bool XAudio2SoundPlayer::PlaySound(size_t index) { // // Setup buffer // XAUDIO2_BUFFER playBuffer = { 0 }; std::shared_ptr<ImplData> soundData = m_soundList[index]; playBuffer.AudioBytes = soundData->playData->Length; playBuffer.pAudioData = soundData->playData->Data; playBuffer.Flags = XAUDIO2_END_OF_STREAM; HRESULT hr = soundData->sourceVoice->Stop(); if (SUCCEEDED(hr)) { hr = soundData->sourceVoice->FlushSourceBuffers(); } // // Submit the sound buffer and (re)start (ignore any ‘stop’ failures) // hr = soundData->sourceVoice->SubmitSourceBuffer(&playBuffer); if (SUCCEEDED(hr)) { hr = soundData->sourceVoice->Start(0, XAUDIO2_COMMIT_NOW); } return SUCCEEDED(hr); }

In this code snippet, we are just using the XAudio2 COM APIs available for Metro style app development to wire up our audio engine, play sound and resume the engine. Additionally, we can use C++ constructs and types beyond just the Windows Runtime types to implement the necessary functionality.

Adding and consuming the Windows Runtime component

After we define and implement our basic class, we use Visual Studio to add the XAudioWrapper Windows Runtime component to our C++ project from our C# project:

Figure 3: Adding the XAudioWrapper Windows Runtime Component to our music app

As a result, the class that we expose from our C++ project becomes available to our C# project:

MainPage.cs

using XAudioWrapper; namespace BasicSoundApp { public sealed partial class MainPage : Page { XAudio2SoundPlayer _audioPlayer = new XAudio2SoundPlayer(48000); public MainPage() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { _audioPlayer.Initialize(); } private void Button_Click_1(object sender, RoutedEventArgs e) { _audioPlayer.PlaySound(0); } } }

As shown in the code snippet, we can interact with our XAudio wrapper from C# just as if it were a regular .NET component. We reference its namespace, instantiate the component and start invoking the various methods it exposes. All of this without requiring any DllImports to call into the native code!

Scenario 2: Using built-in APIs to open a zip file from your app

Say we are also building a file viewer app using HTML and want to add functionality to allow users of this app to pick zip files. We want to use the APIs already built-into Windows and exposed in the .NET platform for handling zip files.

Adding the Windows Runtime component to our solution

This is the same step as we have described for our music app, but we now pick the C# Windows Runtime component to wrap the zip processing functionality:

Figure 4: Adding a new C# Windows Runtime Component

Visual Studio has created a C# project for us to expose the APIs for which both the implementation and Windows Runtime metadata are packaged in a .winmd file and made available to our web project.

Implementing the class exposed in our Windows Runtime component

We use C# to build the APIs that will be exposed to our web project, but you can also use Visual Basic. We start by defining a simple C# class to encapsulate the zip functionality:

ZipWrapper.cs

using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Foundation; using Windows.Storage; public sealed class ZipWrapper { public static IAsyncOperationWithProgress<IList<string>, double> EnumerateZipFileAsync(StorageFile file) { return AsyncInfo.Run(async delegate( System.Threading.CancellationToken cancellationToken, IProgress<double> progress) { IList<string> fileList = new List<string>(); progress.Report(0); using (var stream = await file.OpenStreamForReadAsync()) { using (var archive = new ZipArchive(stream)) { for (int i = 0; i < archive.Entries.Count; i++) { // add code for processing/analysis on the file // content here // add to our list and report progress fileList.Add(archive.Entries[i].FullName); double progressUpdate = ((i + 1) / ((double)archive.Entries.Count)) * 100; // percentage progress.Report(progressUpdate); } } } progress.Report(100.0); return fileList; }); } }

This class is public and sealed. Similarly to building C++ Windows Runtime components, this is necessary for other languages to instantiate the class. The static method exposed in the class uses a mixture of Windows Runtime types (such as StorageFile) and as .NET types (such as IList) in the method signature. The rule of thumb is to use Windows Runtime types for defining the public fields, parameters and return types that will be exposed to the other languages. That being said, you can use certain .NET fundamental types (i.e.: DateTimeOffset and Uri) and primitives (i.e.: IList) as is.

You will also notice that the method above leverages the Windows Runtime infrastructure for async and progress support that you can (and should) use when defining your Windows Runtime components. As far as the implementation for the Windows Runtime component or any private functionality in the class, you are not limited to only using Windows Runtime types and APIs; you are free to use any of the .NET API surface exposed for Metro app development as shown in the code snippet ZipArchive APIs.

Adding and consuming the Windows Runtime component

Now that we have implemented our zip tool wrapper, we use Visual Studio to add a reference to our C# project from our JavaScript project:

Figure 5: Adding the ZipUtil Windows Runtime component to our file viewer app

As a result, the class that we have exposed from our C# project becomes available to our web project:

program.js

function pickSinglePhoto() { // Create the picker object for picking zip files var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail; openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary; openPicker.fileTypeFilter.replaceAll([".zip"]); // Open the picker for the user to pick a file openPicker.pickSingleFileAsync().then(function (file) { if (file) { ZipUtil.ZipWrapper.enumerateZipFileAsync(file).then( function (fileList) { for (var i = 0; i < fileList.length; i++) document.getElementById(‘output’).innerHTML += ” ” + fileList[i]; }, function (prog) { document.getElementById(‘zipProgress’).value = prog; } ); } else { document.getElementById(‘output’).innerHTML = “an error occurred”; } }); };

As you can see, we can interact with our zip tool wrapper from JavaScript just as if it were a regular JavaScript object. We can call into the static method exposed in our Windows Runtime component, and we can do so using JavaScript’s async language constructs such as .then().

General guidance

Not every API you write for your Metro style app should be exposed as a 3rd party Windows Runtime component. In general, use Windows Runtime types when you are communicating between programming languages and use types and constructs that are built into the language that you are using for functionality that is not publicly exposed via a Windows Runtime component. Additionally, there are various language-specific features and rules around crossing the language boundary that you need to take into consideration when building your Windows Runtime component. This includes delegates and events, asynchronous operations, method overloading, handling specific data types such as collections, exception handling and debugging tips. You can dive into those topics further by visiting the section on building Windows Runtime components for your development language.

In closing

With Windows Runtime components, you can now mix programming languages and API technologies to build the apps you envision. Windows 8 is about no compromises. There are even no compromises during development, allowing you to mix and match the programming languages that best fit your scenario. We hope this allows you to spend more time thinking about innovation and less time being forced to learn a completely new programming language.

Happy app building!

Ray Yagubyan

 


Generate Entity Framework using SQL Azure

 

 
 
 
 
 
 
1 Vote

Ray Yagubyan

 

In this example I am going to show you how to generate your Entity Model edmx using SQl Azure database.

Before we start, first lets create a Sample database named called ContactDetail on SQl Azure database.

To create a SQL Azure database you can either Login directly to your SQL Azure account through web or you can Login to your Windows Azure Account, and from the Homepage you can navigate to the Database. In my example below I am using the Second option.

1. Login to your Windows Azure Account and Navigate to the Database, this will give you the below screen.

image_thumb

2. Now Select the Create Button to Create a new database, this will give you the following screen where you can enter your region and provide a new credentials which you will use with this new database.

image_thumb[1][1]

image_thumb[2][1]

3. Once done, Select Next this will provide you with the below screen where you can provide the firewall rule, this is just for extra security. Once you have provided the IP Address Range, you will not be able to connect from any other IP Address which does not fall in this Range.

image_thumb28[1]

4. If you are connecting through any other application which is Hosted on any other Windows Azure accounts then make sure to Select this option, this will allow your Windows Azure applications to connect to this SQL Azure Database.

image_thumb[3][1]

5. Once completed you can see your fully qualified server name in the Dashboard provided. This Server name is used to connect remotely to your Azure DB from your application or from VS 2010 Server Explorers, etc.

image_thumb26

6. Now lets create some sample database which we are going to use to generate our Entity Model, to create a new database you will have to first select the newly created server from the left hand side of the Windows Azure console, and select Create from the Menu, this will present you the windows where you have to provide your Database information. Based on your requirement you can select the Edition and Size, I am keeping my Database names as ContactDetail and Leaving rest as default and Select Ok.

image

7. Now I can see my New database in the Azure Console, select manage to manage the database objects like SP, Tables, etc. This will open the SQL Azure console.

image

8. SQL Azure console will prompt you for credentials, once you are thru, you will get the SQL Azure Dashboard, where once you have to select the Contact Detail Table –> Design – New Table

image

9. In the New Table I have provided the following information, for my Contact table and Click on Save, this will create my ContactDetail Table.

image

Now I am ready with the SQL Azure table, my next task will be to configure my Entity Framework to use this table, to use in my Application. Please note if you want to use any scripts which is used for your SQL Server database, then this will not work with your SQL Azure database, you can read more in the following link: http://blog.sqlauthority.com/2010/06/04/sql-server-generate-database-script-for-sql-azure/

10. Now lets get back to my application, where I am going to create a entity framework entity model, which I am going to configure with this SQL Azure DB, to perform this I am opening my .NET application where I want to add Entity Model, and Select Add New Item – Data –> ADO.NET Entity Data Model.

image

11. Select Next, in the Wizard, Select New Connection and enter the fully qualified Server name, and the credentials and Select Ok and then Next with default options selected.

image

12. You will get the list of your tables, views and Stored procedures, select the desired Database objects with the default options selected and Select Finish, you will get the Designer with the tables, stored procedures or views you have selected.

image

And that’s it, once done you can work like any other Entity Framework you have used to work with your SQL Server 2008/2005 databases.

 

Ray Yagubyan

 Handwriting recognition: The unsung hero of the Surface Pro

Ray Yagubyan
Ray Yagubyan

 

There are a lot of people out there who don’t “get” the Surface Pro. This isn’t their fault, or their problem, it’s up to Microsoft to help them understand the product. So far the team from Redmond hasn’t delivered on that. One of the biggest points that Microsoft should be focusing on, in my opinion, is the Pro’s absolutely stellar handwriting recognition driven by the combination of Windows 8 and the Wacom stylus.

We’ve reached a strange point, technologically, with input mechanisms. Every part of the ecosystem desperately wants to kill off the physical keyboard, but no one has really figured out what to replace it with. Most on-screen keyboards are relatively terrible, but they offer more screen real estate for other activities so we deal with them in the hopes that it will get better. Voice-to-text has made massive leaps in the last few years, but no one wants to be “that guy” walking around in public talking to their phone or computer. Microsoft made some improvements on this front with Windows Phone 8, but none of them made their way to Windows 8.

When you take a look at the Surface Pro, it’s a mash up of acceptable input tools, allowing you to pick which option will make you the least miserable when writing. The primary options are as follows:

  • You can use the on-screen keyboard, which either requires you to type while the tablet is awkwardly cradled in your lap or split into two smaller keyboards that are usable if you have giant hands with tiny thumbs.
  • You can use a fun-looking touch cover, which is only mildly less terrible than the on-screen keyboard.
  • You can use a tactile touch cover, if you’re a fan of a detachable keyboard that would have been considered embarrassing on a $300 netbook five years ago.

What many people don’t know is that there’s another option, and it is by far the best in the industry for what it is designed to accomplish.

Handwriting recognition surface pro

Handwriting recognition is not at all a new concept. In fact, when most people hear “handwriting recognition” they think about Graffiti from the old Palm days, some awful hybrid between writing actual words and tricking the computer into making them show up on the computer. Handwriting recognition practically disappeared from the world for a while, as we decided the stylus was a dirty thing that should be forgotten forever (resistive touch displays were partially to blame for this).

When you think about a stylus in current generation hardware, it’s usually a clumsy eraser tip style, which is horrible for just about everything. Microsoft’s decision to include a stylus with the Surface Pro comes off mostly as a tool for artists, or as a alternative form of navigation. If you are feeling brave enough to try writing with it, however, you’ll be pleasantly surprised.

Just like the regular virtual keyboard, you can use handwriting recognition anywhere in the OS. You write in the black box, and than insert the translation into a text field. You can write URLs, email addresses, even passwords with surprising accuracy. Whether you’re a far of print or cursive, you’ll find that even horrible penmanship is recognized. If a mistake is made, it’s really easy to fix. You tap on the are you need to correct, and an exploded view of the word allows you to go in and make whatever changes you need. The tutorial for the different editing gestures is easily the best laid out tutorial for the entirely of Windows 8, and really makes it so you can quickly use this tool as your default writing mechanism when curled up on the couch.

Handwriting is still not faster than typing, but it’s a comfortable alternative to input on the Surface Pro. This input mechanism is available on any Windows 8 install, but the combination of the stylus and the screen on the Surface Pro makes the experience really great. It’s this kind of thing that should be passed on to the rest of the Windows 8 ecosystem, encouraging an input mechanism that requires no learning and no effort, just a pen and a screen.

Can HTC beat the competition in 2013

 

 

 

It looks like HTC’s Windows Phone 8 is going to give the others a run for their money. In a new report released today by the mobile phone experts over at MyRatePlan.com, the HTC phone takes two of the top five spots on the list of “Best Windows Phone of 2013″ with its 8X and 8S models. According to the press release, the rankings were based on device features, tech specs, consumer buzz, customer demand and manufacturer sales history.

 

 

 

In the UK, HTC and Nokia have contributed to tripling Windows Phone 8′s market share over the last 12 months. HTC’s 8X and 8S models were so popular that initial supplies have been unable to meet the demand. Some of this might be due to other manufacturers like Samsung holding back to promote their other models, but we can expect to see continued growth for all of the manufacturers throughout the course of the year. In the U.S., Nokia outsells HTC, but there is evidence that since HTC Windows Phone 8 models like the HTC 8X are available on more carriers like T-Mobile, it’s racking up 50 percent more sales than devices available on certain networks.

 

 

 

Some are even going as far as to say that the HTC 8X is the clear winner of the Windows 8 launch devices and that the choice between premium devices really comes down to which operating system users prefer.

 

 

 

Leading alternatives include the iPhone 5 (iOS) and the Google Nexus 4 (Android Jelly Bean) but for those who have been long-time fans of Microsoft (or those who are looking to give something new a whirl), the Windows 8 devices are proving to pack as much punch in both processing power and user experience as either of its main competitors. The steep price tag of the iPhone 5 and current supply chain issues surrounding the Nexus 4 in the U.S., UK and Europe are giving consumers plenty of reasons to shop around and test out a Windows 8 phone it they haven’t already.

 

 

 

It looks like a bright future for HTC’s first foray into the Windows Phone 8 market. Taking two of the top five spots as “Best Windows Phones of 2013″ is no easy feat with such a tense market and fierce competition. HTC has done exceptionally well in stocking the devices with features consumers love, and countless reviews of the devices reaffirm that HTC only has big plans ahead.

 

 

 

Some of the core features of the flagship model (HTC 8X) include a powerful Qualcomm Dual-Core Snapdragon S4 processor, an 8-megapixel rear-facing camera, Beats Audio sound card, NFC Isis payment capabilities and seamless integration with XBox, Windows 8 and Skydrive. In the U.S., it’s available on T-Mobile, AT&T and Verizon’s networks, for now. In contrast, it’s smaller, less expensive counterpart (HTC 8S) is equipped with a 5-megapixel rear-facing camera, 4-inch touchscreen display, Beats Audio and a similar processor. This model also integrates beautifully with the XBox, Windows 8 and Skydrive.

 

 

Thanks

 

 

 
 
 
 
 
 
2 Votes

Ray Yagubyan

Ray Yagubyan

 

Introduction  

NoSqlJsonFile as the name implies, it is designed to be NoSQL-like document store in JSON format, similar to mongoDB. NoSqlJsonFile is designed to return enumerable/ generic list type, so you can utilise  C# LINQ/Lambda expression to manipulate data.

So Why NoSqlJsonFile?

File system based and Document-oriented.

  • Each table in relational database represents a directory in NoSqlJsonFile.
  • Each row in tradition database represents a file in NoSqlJsonFile.
  • It supports one to many relationship and recursive relationship.
  • The file is stored in JSON Formatted Document.
  • The benefit of file system based is that it requires no special program or engine on top.

Portable and lightweight

  • It is intended to be a single source code file so that the developer can copy it and modify it for different projects.

Simple Inheritance to use it

  • All you need to do is just to inherit the NoSqlJsonFile class and off you go!

Using the code

Here is a simple CRUD by using a simple customer detail as an example.

Create a document  

To create a new record, firstly, you need to create a class and then simply assign values to the properties as follows. Save() method is inherited from NoSqlJsonFile class, once Save() method is called, the Unique Id is generated and then the document is saved as a file under your project directory by default (can be changed by define FILE_PATH in your app.config).  The file will be named like “Customer94554F9D47E0425B97EBC13614F36CD5″ under NoSqlJsonFiles directory.

Collapse | Copy Code
Customer customer = new Customer();
customer.FirstName = "Anna";
customer.LastName = "Lee";
customer.Save();

For the scheme, here is a rule, you must inherit NoSqlJsonFile with the [DataContract] attribute. All fields must be attached with the [DataMember] attribute. If you do not specify it, the field will be ignored. Importantly the property name is strictly an Auto Property i.e., {get;set;}.

Collapse | Copy Code
[DataContract]
class Customer : NoSqlJsonFile<Customer>
{
  [DataMember]
  public string FirstName { get; set; }
  [DataMember]
  public string LastName { get; set; }
}

If you open up the file from your project bin/debug or bin/release. You can find the file from NoSqlJsonFiles\Customer94554F9D47E0425B97EBC13614F36CD5.  The file will be saved in JSON format.

Collapse | Copy Code
{"DateModfied":"\/Date(1363055984263+1100)\/","UniqueId":"Customer94554F9D47E0425B97EBC13614F36CD5","FirstName":"Anna","LastName":"Lee"}

 List documents

Simply call inherited List() or Enumerable() method.

Collapse | Copy Code
foreach (Customer c in Customer.List())
{
   Console.WriteLine( c.FirstName + " " + c.LastName);
}

Update a document

Collapse | Copy Code
var customer = Customer.Get("Customer94554F9D47E0425B97EBC13614F36CD5");
customer.FirstName = "Annie";
customer.Save();

Delete a document

Collapse | Copy Code
Customer.Delete("Customer94554F9D47E0425B97EBC13614F36CD5");

Or if it is an instance.

Collapse | Copy Code
customer.Delete();

One to many relationship

Collapse | Copy Code
Customer customer = new Customer();
customer.FirstName = "Anna";
customer.LastName = "Lee";
customer.Products = new List<Product><product>();
customer.Products.Add(new Product{ProductName = "Iphone4S", Price = "500.00"});
customer.Products.Add(new Product { ProductName = "HTC One", Price = "400.00" });
customer.Save();
Collapse | Copy Code
[DataContract]
class Customer : NoSqlJsonFile<Customer>
{
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string LastName { get; set; }
    [DataMember]
    public List<product> Products { get; set; }
}

[DataContract]
class Product : NoSqlJsonFile<Product>
{
    [DataMember]
    public string ProductName { get; set; }
    [DataMember]
    public string Price { get; set; }
}




Thanks

Ray Yagubyan

This free website was made using Yola.

No HTML skills required. Build your website in minutes.

Go to www.yola.com and sign up today!

Make a free website with Yola