DocumentDB Rest API - create document needs id for new documents - azure-cosmosdb

I'm trying to use the DocumentDB Rest API to create a new document and autogenerate the id for me.
The Create Document documentation says that id is a required property of the body, but the node.js SDK and the Azure Portal Document Explorer will both generate ID's when no id is provided in the input.
Here's the response from the server:
{ code: 'BadRequest',
message: 'Message: {"Errors":["The input content is invalid because the required properties - \'id; \' - are missing","The request payload is invalid. Ensure to provide a valid request pa
yload."]}\r\nActivityId: 6b718b3d-01bc-403f-82e6-266254aad952, Request URI: /apps/4c8d65d7-216b-46b4-abb7-52c1a0c7123f/services/0e58e0c6-ff02-4523-a94b-204abd0d2179/partitions/6bf7ec3e-d850
-440e-bbcb-50d949389f3e/replicas/131469737377192972p' }

I just noticed that the DocumentDB node.js SDK generates its own id's, this is not something handled by the database.
Here is the code that they use to generate unique id's, packaged for independent use:
function generateGuidId () {
var id = "";
for (var i = 0; i < 8; i++) {
id += getHexaDigit();
}
id += "-";
for (var i = 0; i < 4; i++) {
id += getHexaDigit();
}
id += "-";
for (var i = 0; i < 4; i++) {
id += getHexaDigit();
}
id += "-";
for (var i = 0; i < 4; i++) {
id += getHexaDigit();
}
id += "-";
for (var i = 0; i < 12; i++) {
id += getHexaDigit();
}
return id;
}
function getHexaDigit () {
return Math.floor(Math.random() * 16).toString(16);
}

DocumentDb supports two addressing modes SelfLink (a.ka. RID) and AltLink (a.k.a. named). SelfLink is server generated. 'id' property is an opportunity for named addressing (ex: /dbs/ToDoList/colls/items/docs/user1).
SDK just tries to fill them with UNIQ values in-case of unavailability. I suggest strongly to specify the name.

Related

Meteor collection insert from input element

This code is trying to insert the data from input elements on the page into a Meteor Collection Task1
I am getting "App is crashing error" because of the Tasks1.insert line. Why and how can I fix it?
I need to get the element name and value as the key:value pair for the Document being inserted. Thanks
Template.footer.events({
'click button': function () {
if ( this.text === "SUBMIT" ) {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
Tasks1.insert({inputs[i].name: inputs[i].value});
}
}
}
});
inputs[i].name cannot be used as a key of an object literal, because it's a variable and we can only use strings for defining properties in an object literal.
Like this it should work (it's the most common workaround):
for (var i = 0; i < inputs.length; i++) {
// First define a variable
var params = {};
// Then you can use a variable (or a function) to set the key
params[inputs[i].name] = inputs[i].value;
Tasks1.insert(params);
}

Google Calendar API: New event properties

I'm developing an Android APP that connects to Google Calendar using GData API for Google Calendar in Java. So far I've managed to create events but I could only set the title, description and time.
Does anybody know where I can find a reference or a sample with all the parameters I can set to an event?
I leave you some code of what I've achieved so far.
CalendarService calendarService = new CalendarService("CalendarAPP");
calendarService.setUserCredentials(<username>, <password>);
URL postUrl = new URL("https://www.google.com/calendar/feeds/<GMAIL ACCOUNT>/private/full");
CalendarEventEntry myEntry = new CalendarEventEntry();
myEntry.setTitle(new PlainTextConstruct("Tennis with Beth"));
myEntry.setContent(new PlainTextConstruct("Meet for a quick lesson."));
DateTime startTime = DateTime.now();
DateTime endTime = DateTime.now();
When eventTimes = new When();
eventTimes.setStartTime(startTime);
eventTimes.setEndTime(endTime);
myEntry.addTime(eventTimes);
CalendarEventEntry insertedEntry = connection.getCalendarService().insert(postUrl, myEntry);
Thanks in advance.
Mikywan.
GData for Google Calendar it's pretty damn good. For every property you may want to set or get, there is a Getter and a Setter defined. You just have to look for the setter/getter on the event entry that suits the data you want access.
I leave an example of how to show on the console almost all the data you may want to.
Enjoy!
private static void showCalendarEventEntry(CalendarEventEntry entry) {
assert entry != null;
System.out.println("-------------------------------------------");
System.out.println("START showCalendarEventEntry");
System.out.println("");
System.out.println("ID: " + entry.getId());
System.out.println("TITLE: "+entry.getTitle().getPlainText());
System.out.println("DESCRIPTION: "+entry.getPlainTextContent());
System.out.println("LOCATION: "+entry.getLocations().get(0).getValueString());
System.out.println("");
System.out.println("TIMES");
if (entry.getTimes().size() > 0) {
When eventTimes = entry.getTimes().get(0);
if (eventTimes.getStartTime().isDateOnly()) {
System.out.println("\tWHEN: ALL DAY");
} else {
System.out.println("\tWHEN: TIME");
}
if (entry.getRecurrence() != null)
System.out.println("\tRECURRENCE: "+entry.getRecurrence().toString());
System.out.println("\tSTART TIME: "+eventTimes.getStartTime());
System.out.println("\tEND TIME: "+eventTimes.getEndTime());
}
System.out.println("");
System.out.println("PARTICIPANTS");
System.out.println("\t"+(entry.getParticipants().size()) + " PARTICIPANTS");
if (entry.getParticipants().size() > 0){
for (int i=0; i<entry.getParticipants().size(); i++) {
EventWho participant = entry.getParticipants().get(i);
System.out.println("\t\tPARTICIPANT "+participant.getValueString());
System.out.println("\t\t\tTYPE: "+participant.getAttendeeType());
System.out.println("\t\t\tSTATUS: "+participant.getAttendeeStatus());
}
if (entry.isGuestsCanInviteOthers())
System.out.println("\tGUESTS CAN INVITE OTHERS: ");
if (entry.isGuestsCanModify())
System.out.println("\tGUESTS CAN MODIFY");
if (entry.isGuestsCanSeeGuests())
System.out.println("\tGUESTS CAN SEE GUESTS");
}
//REMINDERS
System.out.println("");
System.out.println("REMINDERS");
System.out.println("\t"+entry.getReminder().size()+" REMINDERS");
if (entry.getReminder().size() > 0) {
for (int i=0; i<entry.getReminder().size(); i++) {
Reminder reminder = entry.getReminder().get(i);
System.out.println("\t\tREMINDER "+i);
System.out.println("\t\t\tMETHOD: "+reminder.getMethod().toString());
System.out.println("\t\t\tDAYS: "+reminder.getDays());
System.out.println("\t\t\tHOURS: "+reminder.getHours());
System.out.println("\t\t\tMINUTES: "+reminder.getMinutes());
}
}
//VISIBILITY
System.out.println("");
System.out.println("VISIBILITY: "+entry.getVisibility().getValue());
System.out.println("");
System.out.println("END showCalendarEventEntry");
System.out.println("-------------------------------------------");
}

asp.net logic for fixing relative urls to full urls

i have a function that pulls URLs from various web resources. needless to say some are full valid URLS and some are relative as per the HTML of the page. below is my asp.net/ c# logic i derived for examining the URL and then generate a full usable URL from whats pulled from the site...
I have have not looked at this code in some time but i remember it was working well some months ago and now it needed many tweaks to get running - especially with relative paths and the regeneration of a FULL url from various relative variations.
is there a simpler way or method to accomplish this seemingly routing boilerplate task than what i have here?
NOTE:
origianlurl is the full url of the first searched page, and relativeUrl is a url found within the searched page (it can be a full www.site.com or a /contactus.html)
private string ResolveRelativePaths(string relativeUrl, string originatingUrl)
{
if (relativeUrl.StartsWith("http") || relativeUrl.StartsWith("www"))
return relativeUrl;
if (relativeUrl.StartsWith("/"))
{
//get main url something.com
Uri myURI = new Uri(originatingUrl);
//add the relative page to the end
return myURI.Host + relativeUrl;
}
string resolvedUrl = String.Empty;
string[] relativeUrlArray = relativeUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string[] originatingUrlElements = originatingUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
int indexOfFirstNonRelativePathElement = 0;
for (int i = 0; i <= relativeUrlArray.Length - 1; i++)
{
if (relativeUrlArray[i] != "..")
{
indexOfFirstNonRelativePathElement = i;
break;
}
}
int countOfOriginatingUrlElementsToUse = originatingUrlElements.Length - indexOfFirstNonRelativePathElement - 1;
//for (int i = 0; i <= countOfOriginatingUrlElementsToUse - 1; i++)
for (int i = 0; i <= countOfOriginatingUrlElementsToUse ; i++)
{
if (originatingUrlElements[i] == "http:" || originatingUrlElements[i] == "https:")
resolvedUrl += originatingUrlElements[i] + "//";
else
resolvedUrl += originatingUrlElements[i] + "/";
}
for (int i = 0; i <= relativeUrlArray.Length - 1; i++)
{
if (i >= indexOfFirstNonRelativePathElement)
{
resolvedUrl += relativeUrlArray[i];
if (i < relativeUrlArray.Length - 1)
resolvedUrl += "/";
}
}
return resolvedUrl;
}
The Uri class has a constructor that you can use for that exactly. Given a base uri, which is your originatingUrl and a string (the relative part) it generates the full url. As far as I can see there is not a single thing in your method that cannot be done using the Uri class (maybe a few instances). My guess is that you could rewrite it to 5-10 LOC.

Create HTML table out of object array in Javascript

I am calling a web Method from javascript. The web method returns an array of customers from the northwind database. The example I am working from is here: Calling Web Services with ASP.NET AJAX
I dont know how to write this javascript method: CreateCustomersTable
This would create the html table to display the data being returned. Any help would be appreciated.
My javascript
function GetCustomerByCountry() {
var country = $get("txtCountry").value;
AjaxWebService.GetCustomersByCountry(country, OnWSRequestComplete, OnWSRequestFailed);
}
function OnWSRequestComplete(results) {
if (results != null) {
CreateCustomersTable(results);
//GetMap(results);
}
}
function CreateCustomersTable(result) {
alert(result);
if (document.all) //Filter for IE DOM since other browsers are limited
{
// How do I do this?
}
}
else {
$get("divOutput").innerHTML = "RSS only available in IE5+"; }
}
My web Method
[WebMethod]
public Customer[] GetCustomersByCountry(string country)
{
NorthwindDALTableAdapters.CustomersTableAdapter adap =
new NorthwindDALTableAdapters.CustomersTableAdapter();
NorthwindDAL.CustomersDataTable dt = adap.GetCustomersByCountry(country);
if (dt.Rows.Count <= 0)
{
return null;
}
Customer[] customers = new Customer[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
NorthwindDAL.CustomersRow row = (NorthwindDAL.CustomersRow)dt.Rows[i];
customers[i] = new Customer();
customers[i].CustomerId = row.CustomerID;
customers[i].Name = row.ContactName;
}
return customers;
}
Try to look what is the result variable value in debug mode. If the structure seems the structure that i'm imagining, something like this could work:
function CreateCustomersTable(result) {
var str = '<table>';
str += '<tr><th>Id</th><th>Name</th></tr>';
for ( var i=0; i< result.length; i++){
str += '<tr><td>' + result[i].CustomerId + '</td><td>' + result[i].Name + '</td></tr>';
}
str += '</table>';
return str;
}
And then You can do somethig like this:
var existingDiv = document.getElementById('Id of an existing Div');
existingDiv.innerHTML = CreateCustomersTable(result);
I wish this help you.
Something like this, assuming you have JSON returned in the "result" value. The "container" is a div with id of "container". I'm cloning nodes to save memory, but also if you wanted to assign some base classes to the "base" elements.
var table = document.createElement('table');
var baseRow = document.createElement('tr');
var baseCell = document.createElement('td');
var container = document.getElementById('container');
for(var i = 0; i < results.length; i++){
//Create a new row
var myRow = baseRow.cloneNode(false);
//Create a new cell, you could loop this for multiple cells
var myCell = baseCell.cloneNode(false);
myCell.innerHTML = result.value;
//Append new cell
myRow.appendChild(myCell);
//Append new row
table.appendChild(myRow);
}
container.appendChild(table);
You should pass the array as JSON or XML instead of just the toString() value of it (unless that offcourse is returns either JSON oR XML). Note that JSOn is better for javascript since it is a javascript native format.
Also the person who told you that browser other then IE can not do DOM manipulation should propably have done horrible things to him/her.
If your format is JSON you can just for-loop them and create the elements and print them. (once you figured out what format your service returns we can help you better.)

JsonArray in silverlight to javascript

I'm creating a JsonArray such as:
JsonArray jsonValues = new JsonArray();
for( int i = 0; i < values.Count; i++ )
{
var someSingleValue = values[i];
jsonValues.Add( string.Format( "Name: {0}", someSingleValue ) );
}
After that I'm shipping json values to my javascript in .aspx page via call:
HtmlPage.Window.Invoke("call", jsonValues);
The call works and it gets there, however I have no idea how to iterate over those values, i.e extract them.
I've tried: (in javascript)
for (var x in somevalues){ alert(somevalues); }
I also tried:
for(var i = 0; i < somevalues.length; i++) {
alert(somevalues[i]);
}
but it crashes.(in both cases)
any ideas?
Are you using the eval method to serialize the string to a JSON object?
function call(somevalues){
//somevalues is currently just a string.
var results = eval("(" + somevalues +")");
//results now should contain your array as a JSON object.
//and you should be able to iterate over it at this point.
for(var i = 0; i < results.length; i++){
alert(results[i]);
}
}
Assuming somevalues is truly an array, you do it like this:
for(var i = 0; i < somevalues.length; i++) {
// do something with somevalues[i]
}
What you did was tell JavaScript to iterate over the properties of the somevalues object, which is similar, but not the same, as the iteration using a regular for loop.
EDIT: I am willing to bet your variable, somevalues is a string. Just do alert(somevalues) and see what happens.

Resources