Hi i have a sample stored procedure created like this
Bulk insert
function bulkImport(items) {
var container = getContext().getCollection();
var containerLink = container.getSelfLink();
var items=[{
"UserAccountID":"1236",
"FirstName": "Sanjeev",
},{
"UserAccountID":"1235",
"FirstName": "Sanjeev",
}];
// The count of imported items, also used as current item index.
var count = 0;
// Validate input.
if (!items) throw new Error("The array is undefined or null.");
var itemsLength = items.length;
if (itemsLength == 0) {
getContext().getResponse().setBody(0);
}
// Call the create API to create an item.
tryCreate(items[count], callback);
function tryCreate(item, callback) {
var isAccepted = container.createDocument(containerLink, item, callback);
if (!isAccepted) getContext().getResponse().setBody(count);
}
function callback(err, item, options) {
if (err) throw err;
// One more item has been inserted, increment the count.
count++;
if (count >= itemsLength) {
// If we created all items, we are done. Just set the response.
getContext().getResponse().setBody(count);
} else {
// Create next document.
tryCreate(items[count], callback);
}
}
}
How to execute this sp in the cosmos emulator. How to set the partition key uniquely for each of the item.
Since the partition key should be unique we cannot provide a single partition key while executing.
Firstly,you could create non-partitioned collection in the cosmos db if you do not need it. The portal has some limitations but the sdk allows it. You could refer to my previous case:Is it still a good idea to create comos db collection without partition key?.
Secondly, the bulk import of stored procedure is not suitable for the partitioned collection because you need to provide the pk for every execution of a stored procedure. Please refer to this link: Azure Cosmos DB asking for partition key for stored procedure
Finally,there are also many other solutions to import data into cosmos db,such as Azure Cosmos DB Data migration tool which is worth trying for you.
Related
I'm creating oData using the createEntry() method of the oData model (v2),
Then, on submitChanges(), I'm retrievinvg the newly created data with this.getPageBlocks() below.
However, intermittently, this.getPageBlocks() does not return the newly created entry, meaning the data is not refreshed correctly for the end-user.
Why is that? At what point does submitChanges() execute? I'm guessing it's executing before the actual backend data has been created, which would explain why it's not there when I run this.getPageBlocks()
pageModel.createEntry("/PageBlocks", {
...
...
}
then....
pageModel.submitChanges({
success: function (oData) {
this.getPageBlocks();
}
Actually, after submitChanges your entry should get updated. If you want to get the newly created entry, you should do the following:
_createEntry() {
const oModel = this.getView().getModel();
this._oEntry = oModel.createEntry("/PageBlocks", {...})
}
onSubmitButtonPress() {
const oModel = this.getView().getModel();
oModel.submitChanges({
success() {
this._oEntry.getObject() // Will return the newly created entry
}
})
}
I use NReco.Data in my Asp.NetCore Application to make db-calls, because I don't want to use EF and DataTable isn't supported yet.
Now I need to call a StoredProcedure and get Multiple RecordSets (or Dictionarylists).
At the moment I called this:
dbAdapter.Select($"STOREDNAME #{nameof(SQLPARAMETER)}", SQLPARAMETER).ToRecordSet()
But the stored gives me more than 1 recordset, can anyone help me to get the others?
Currently NReco.Data.DbDataAdapter has no API for processing multiple result sets returned by single IDbCommand.
You can compose IDbCommand by yourself, execute data reader and read multiple result sets in the following way:
IDbCommand spCmd; // lets assume that this is DB command for 'STOREDNAME'
RecordSet rs1 = null;
RecordSet rs2 = null;
spCmd.Connection.Open();
try {
using (var rdr = spCmd.ExecuteReader()) {
rs1 = RecordSet.FromReader(rdr);
if (rdr.NextResult())
rs2 = RecordSet.FromReader(rdr);
}
} finally {
spCmd.Connection.Close();
}
As NReco.Data author I think that support for multiple result sets may be easily added to DbDataAdapter API (I've just created an issue for that on github).
-- UPDATE --
Starting from NReco.Data v.1.0.2 it is possible to handle multiple result sets in the following way:
(var companies, var contacts) = DbAdapter.Select("exec STOREDNAME").ExecuteReader(
(rdr) => {
var companiesRes = new DataReaderResult(rdr).ToList<CompanyModel>();
rdr.NextResult();
var contactsRes = new DataReaderResult(rdr).ToList<ContactModel>();
return (companiesRes, contactsRes);
});
In the same manner DataReaderResult can map results to dictionaries or RecordSet if needed.
My application displays data to my users via the Parse.com. I am using their iOS sdk with their cloud code. I am required to use cloud code to add an object to my user. What I'm looking for is something like:
[PFCloud callFuction:#"addObjectToUser" withParameters:params];
And my parameters would be the userID and the the object ID of the object I want associated with that user ID.
How would I achieve this in JavaScript?
In order to change anything on a user object in parse (without being changed by the user themselves) it must be done through cloud code and by using the useMasterKey(). Assuming that you have set up your params like this:
NSDictionary *params = #{userID: #"12345", objectID: #"67890"};
You can save objects to a user with the master key like this:
//Add Object To User's "objectsAddedToUser" array
Parse.Cloud.define("addObjectToUser", function(request, response) {
// (1)
var userID = request.params.userID;
var objectID = request.params.objectID;
// (2)
var query = new Parse.Query(Parse.User);
query.equalTo("userID", userID);
query.first().then(function (user) {
// (3)
Parse.Cloud.useMasterKey();
// (4)
user.add("objectsAddedToUser", objectID);
// (5)
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
}, function (error) {
response.error(error);
});
});
(1) Get the parameters that you passed in.
(2) Query the database and retrieve the user that needs to be updated.
(3) IMPORTANT Use the master key to unlock privileges.
(4) Add the objectID to the user.
(5) Save to Parse.
Adding cloud function is explain in detail here, there is an example as well which explain how you can write java-script function to manipulate or add data.
Iam trying to apply Pagination to my MVC application. Iam using Azure table storage
Here is what I have tried:-
public List<T> GetPagination(string partitionKey, int start, int take)
{
List<T> entities = new List<T>();
TableQuery<T> query = new TableQuery<T>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey.ToLower()));
entities = Table.ExecuteQuery(query).Skip(start).Take(take).ToList();
return entities;
}
Controller:-
public ActionResult Index()
{
key= System.Web.HttpContext.Current.Request[Constants.Key];
if (String.IsNullOrEmpty(key))
return RedirectToAction("NoContext", "Error");
var items= _StorageHelper.GetPagination(key,0,3);
ItemCollection itemCollection = new ItemCollection();
itemCollection .Items= Mapper.Map<List<ItemChart>, List<ItemModel>>(items);
itemCollection .Items.ForEach(g => g.Object = g.Object.Replace(key, ""));
return View(itemCollection);
}
This currently gives me the first 3 entries from my data. Now how can I show and implement the "Previous" and "Next" to show the rest of the entries on next page? How do I implement the rest of the controller and HTML page?
Any help is appreciated.
When it comes to pagination, there are a few things to consider:
Not all LINQ operators (and in turn OData query options) are supported for Table Service. For example Skip is not supported. For a list of supported operators, please see this link: https://msdn.microsoft.com/en-us/library/azure/dd135725.aspx.
The way pagination works with Table Service is that when you query your table to fetch some data, maximum number of entities that can be returned by table service is 1000. There's no guarantee that always 1000 entities will be returned. It may be less than 1000 or even 0 depending on how you're querying. However if there are more results available, Table Service returns something called a Continuation Token. You must use this token to fetch next set of results from table service. Please see this link for more information on query timeout and pagination: https://msdn.microsoft.com/en-us/library/azure/dd135718.aspx.
Taking these two factors into consideration, you can't really implement a paging solution where a user can directly jump to a particular page (for example, user is sitting on page 1 and then the user can't go to page 4). At the most you can implement next page, previous page and first page kind of functionality.
To implement next page kind of functionality, store the continuation token returned by table service and use that in your query.
To implement previous page kind of functionality, you must store all the continuation tokens returned in an array or something and keep track of which page a user is on currently (that would be the current page index). When a user wants to go to previous page, you just get the continuation token for the previous index (i.e. current page index - 1) and use that in your query.
To implement first page kind of functionality, just issue your query without continuation token.
Do take a look at ExecuteQuerySegmented method in Storage Client Library if you want to implement pagination.
UPDATE
Please see the sample code below. For the sake of simplicity, I have only kept first page and next page functionality:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Table;
namespace TablePaginationSample
{
class Program
{
static string accountName = "";
static string accountKey = "";
static string tableName = "";
static int maxEntitiesToFetch = 10;
static TableContinuationToken token = null;
static void Main(string[] args)
{
var cloudStorageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
var cloudTableClient = cloudStorageAccount.CreateCloudTableClient();
var table = cloudTableClient.GetTableReference(tableName);
Console.WriteLine("Press \"N\" to go to next page\nPress \"F\" to go first page\nPress any other key to exit program");
var query = new TableQuery().Take(maxEntitiesToFetch);
var continueLoop = true;
do
{
Console.WriteLine("Fetching entities. Please wait....");
Console.WriteLine("-------------------------------------------------------------");
var queryResult = table.ExecuteQuerySegmented(query, token);
token = queryResult.ContinuationToken;
var entities = queryResult.Results;
foreach (var entity in entities)
{
Console.WriteLine(string.Format("PartitionKey = {0}; RowKey = {1}", entity.PartitionKey, entity.RowKey));
}
Console.WriteLine("-------------------------------------------------------------");
if (token == null)//No more token available. We've reached end of table
{
Console.WriteLine("All entities have been fetched. The program will now terminate.");
break;
}
else
{
Console.WriteLine("More entities available. Press \"N\" to go to next page or Press \"F\" to go first page or Press any other key to exit program.");
Console.WriteLine("-------------------------------------------------------------");
var key = Console.ReadKey();
switch(key.KeyChar)
{
case 'N':
case 'n':
continue;
case 'F':
case 'f':
token = null;
continue;
default:
continueLoop = false;
break;
}
}
} while (continueLoop);
Console.WriteLine("Press any key to terminate the application.");
Console.ReadLine();
}
}
}
I am developing a Single Page App using Hot Towel Template, using breeze...and I have come across a peculiar problem, and I am unable to figure out the internal working which causes it...
I have a Programmes table, and the Programmes table has a foreign key to Responses, so the structure of Programmes is:
Id, ResponseID, Name and Date
and the Page has Name and Date, the foreign comes from RouteData.
and for one ResponseId in Programmes table, I want to save only on Programme.
So, when user comes to this page, it check the Programmes table that if it has an Entry for that particular Response Id, if yes, it goes in Edit case and if not it goes to Add a new entry case.
To achieve this, what I am doing is below:
var objTempProgramme = ko.observable();
var objProgramme = ko.observable();
function activate(routeData) {
responseId = parseInt(routeData.responseId);
// Create a Programme Entity
objProgramme(datacontext.createProgramme());
// Fill in a Temporary Observable with Programmes data
datacontext.getEntitiesDetailsByRelativeId('responseID', responseId , 'Programmes', objTempProgramme, true).then(function(){
// Check if Programmes Exists
if (objTempProgramme() != null && objTempProgramme() != undefined) {
// What I am doing here is filling my Programmes Entity with data coming from database (if it is there)
objProgramme(objTempProgramme());
} else {
// The Else Part assigns the Foreign Key (ResponseId) to my Entity Created above
objProgramme().responseID(responseId);
}
});
}
In datacontext.js:
var createProgramme = function () {
return manager.createEntity(entityNames.programme);
}
var getEntitiesDetailsByRelativeId = function (relativeIdName, relativeId, lookupEntity, observable, forceRefresh) {
var query = entityQuery.from(lookupEntity).where(relativeIdName, "==", relativeId);
return executeGetQuery(query, observable, forceRefresh);
};
Now when I call manager.saveChanes on my page, I would Expect objProgramme to be saved, in any case, be it edit or be it save,
but what breeze is doing here is that though it is filling objTempProgramme in objProgramme, but it is also leaving the entity objProgramme unreferenced with its manager, so that when I call save, it tries to save that entity too (2 entities in total, objProramme and one unreferenced one), but that entity does not have foreign key set and it fails..but my question is why?
Assigning one entity to another does not mean all its properties get assigned to another? And why is that unreferenced entity present?