These days JavaScript is everywhere, and now not simply in browsers. DocumentDB embraces JavaScript as a kind of present day day T-SQL and helps the transactional execution of JavaScript logic natively, right in the database engine. DocumentDB gives a programming version for executing JavaScript-based totally application common sense at once on the collections in phrases of saved tactics and triggers.
Let’s test an example in which we create a easy store method. Following are the stairs −
Step 1 − Create a brand new console programs.
Step 2 − Add within the .NET SDK from NuGet. We are the use of the .NET SDK here, because of this that we'll be writing a few C# code to create, execute, after which delete our stored manner, but the stored procedure itself receives written in JavaScript.
Step 3− Right-click at the mission in Solution explorer.
Step 4 − Add a new JavaScript file for the stored technique and phone it HelloWorldStoreProce.Js
Every stored process is just a JavaScript function so we're going to create a new function and naturally we'll additionally call this feature HelloWorldStoreProce. It would not count number if we provide the function a name at all. DocumentDB will handiest talk over with this saved manner by using the Id that we offer when we create it.
function HelloWorldStoreProce() {
var context = getContext();
var response = context.getResponse();
response.setBody('Hello, and welcome to DocumentDB!');
}
All the stored technique does is gain the response item from the context and make contact with its setBody approach to return a string to the caller. In C# code, we can create the stored system, execute it, after which delete it.
Stored processes are scoped per collection, therefore we will need the SelfLink of the gathering to create the stored technique.
Step 5 − First question for the myfirstdb database and then for the MyCollection series.
Creating a saved procedure is much like growing any other aid in DocumentDB.
private async static Task SimpleStoredProcDemo() {
var endpoint = "https://azuredocdbdemo.documents.azure.com:443/";
var masterKey =
"BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
using (var client = new DocumentClient(new Uri(endpoint), masterKey)) {
// Get database
Database database = client
.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'")
.AsEnumerable()
.First();
// Get collection
DocumentCollection collection = client
.CreateDocumentCollectionQuery(database.CollectionsLink, "SELECT * FROM
c WHERE c.id = 'MyCollection'")
.AsEnumerable()
.First();
// Create stored procedure
var sprocBody = File.ReadAllText(@"..\..\HelloWorldStoreProce.js");
var sprocDefinition = new StoredProcedure {
Id = "HelloWorldStoreProce",
Body = sprocBody
};
StoredProcedure sproc = await client.
CreateStoredProcedureAsync(collection.SelfLink, sprocDefinition);
Console.WriteLine("Created stored procedure {0} ({1})",
sproc.Id, sproc.ResourceId);
// Execute stored procedure
var result = await client.ExecuteStoredProcedureAsync(sproc.SelfLink);
Console.WriteLine("Executed stored procedure; response = {0}", result.Response);
// Delete stored procedure
await client.DeleteStoredProcedureAsync(sproc.SelfLink);
Console.WriteLine("Deleted stored procedure {0} ({1})",
sproc.Id, sproc.ResourceId);
}
}
Step 6 − First create a definition object with the Id for the brand new aid and then call one of the Create techniques at the DocumentClient item. In the case of a saved process, the definition consists of the Id and the real JavaScript code that you want to ship over to the server.
Step 7 − Call File.ReadAllText to extract the saved technique code out of the JS report.
Step 8 − Assign the saved manner code to the body property of the definition object.
As some distance as DocumentDB is worried, the Id we specify here, within the definition, is the call of the saved manner, regardless of what we definitely call the JavaScript characteristic.
Nevertheless when creating stored strategies and other server-side objects, it's far advocated that we name JavaScript capabilities and that the ones characteristic names do fit the Id that we've set within the definition for DocumentDB.
Step 9 − Call CreateStoredProcedureAsync, passing in the SelfLink for the MyCollection collection and the stored method definition. This creates the stored system and ResourceId that DocumentDB assigned to it.
Step 10 − Call the stored procedure. ExecuteStoredProcedureAsync takes a kind parameter which you set to the anticipated records type of the fee back by using the stored method, which you could specify in reality as an object if you want a dynamic item returned. That is an item whose houses could be certain at run-time.
In this case we recognize that our saved process is just returning a string and so we call ExecuteStoredProcedureAsync<string>.
Following is the complete implementation of Program.Cs file.
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DocumentDBStoreProce {
class Program {
private static void Main(string[] args) {
Task.Run(async () => {
await SimpleStoredProcDemo();
}).Wait();
}
private async static Task SimpleStoredProcDemo() {
var endpoint = "https://azuredocdbdemo.documents.azure.com:443/";
var masterKey =
"BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
using (var client = new DocumentClient(new Uri(endpoint), masterKey)) {
// Get database
Database database = client
.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'")
.AsEnumerable()
.First();
// Get collection
DocumentCollection collection = client
.CreateDocumentCollectionQuery(database.CollectionsLink,
"SELECT * FROM c WHERE c.id = 'MyCollection'")
.AsEnumerable()
.First();
// Create stored procedure
var sprocBody = File.ReadAllText(@"..\..\HelloWorldStoreProce.js");
var sprocDefinition = new StoredProcedure {
Id = "HelloWorldStoreProce",
Body = sprocBody
};
StoredProcedure sproc = await client
.CreateStoredProcedureAsync(collection.SelfLink, sprocDefinition);
Console.WriteLine("Created stored procedure {0} ({1})", sproc
.Id, sproc.ResourceId);
// Execute stored procedure
var result = await client
.ExecuteStoredProcedureAsync<string>(sproc.SelfLink);
Console.WriteLine("Executed stored procedure; response = {0}",
result.Response);
// Delete stored procedure
await client.DeleteStoredProcedureAsync(sproc.SelfLink);
Console.WriteLine("Deleted stored procedure {0} ({1})",
sproc.Id, sproc.ResourceId);
}
}
}
}
When the above code is accomplished, it produces the subsequent output.
Created stored procedure HelloWorldStoreProce (Ic8LAMEUVgACAAAAAAAAgA==)
Executed stored procedure; response = Hello, and welcome to DocumentDB!
As visible within the above output, the reaction belongings has the “Hello, and welcome to DocumentDB!” back by means of our stored manner.