In DAML, what to return when a choice could lead to different new contracts to be created - daml

In DAML, if I have a choice called submit and it could lead to new contract approvedRequest or rejectedRequest. How should I manage the return value in the choice?
template Request
with
content : Text
anyone : Party
where
signatory anyone
--what to return ? ApprovedRequest or RejectedRequest
controller anyone can
Submit : ContractId ApprovedRequest
do
-- passed all the checks and approved
create ApprovedRequest with request = Request

Perhaps Maybe (ContractId ApprovedRequest) will work here? Alternatively, perhaps Either (ContractId RejectedRequest, ContractId ApprovedRequest)?

Related

DAML: Create a template in scenario requiring a ContractId as input and exercise a choice automatically after submit

I have 2 questions regarding DAML the possibility of automated choices and scenario.
I have this template that requires the input of a ContractId:
template Create_Creation
with
current_login : Party
artist : Party
title : Text
votingRight : Set Party
observers_list_id : ContractId Observers
where
signatory current_login
I need to create some of these templates in scenario, but am unable to specify a ContractId (like #0:0), giving me errors such as: Couldn't match expected type 'ContractId Observers' with actual type 'Text' Is it possible to specify a ContractId in scenario?
Next, in the above template I have a choice defined called Load_all_creation_observers that creates a template Creation and loads the observers specified in template Observers into it as observers:
choice Load_all_creation_observers : ContractId Creation
controller current_login
do
observers_list <- fetch observers_list_id
create Creation with created_by = current_login; artist = artist; title = title;
votingRight = votingRight; observers_list_id = observers_list_id; observers = observers_list.observers
template Observers
with
superuser : Party
observers : Set Party
where
signatory superuser
observer observers
As the code stands now, when a user creates a Create_Creation template he is required to perform the Load_all_creation_observers choice to create the Creation template with all the observers loaded into it. Is it possible to perform this choice automatically when a user submits the Create_Creation template? or maybe not make it a choice at all and define it as automated functionality like you would do in normal programming languages (if statements). You can only seem to define do functions in choices.
Given that the question about contract ids has already been answered, I’ll focus on your second question.
You cannot execute a choice automatically (you could have some off-ledger automation, e.g. a DAML trigger that does that but you don’t get any atomicity guarantees in that case). The way I would solve this problem is to define a new template with a single choice and then call that choice using CreateAndExercise on the ledger API. This is pretty much equivalent to defining a top-level function. For your example this would look something like the following
template CreateCreationTemplate
with
p : Party
where
signatory p
choice CreateCreation : ContractId Creation
with
observers_list_id : ContractId Observers
artist : Party
title : Text
votingRight : Set Party
do observers_list <- fetch observers_list_id
create Creation with
created_by = p
artist = artist
title = title
votingRight = votingRight
observers_list_id = observers_list_id
observers = observers_list.observers
You could have some of the fields of the choice as fields of a template but as a general guideline, I tend to only have the party as a field of the template when emulating top-level functions.
Depending on your usage, it is also possible to have a single “factory” template with a non-consuming CreateCreation choice.
In a scenario, the only contracts that exist on the ledger are those that have been created thus far in that scenario. So if there is an Observers contractId an Observers contract must have been created at some previous point in the scenario.
ContractIds are opaque and definitely not predictable, so it makes no sense to think of a contract-id literal. Instead, when the contract is created, bind the resulting id at that point. Ie.
test = scenario do
su <- getParty "Super User"
obsId <- su submit create Observers with ...
p1 <- getParty "Party 1"
ccId <- p1 submit create Create_Creation with ...; observers_list_id = obsId

RXSwift eventlistener

I´m kind of new to the reactive pattern and now I have my first bigger question.
I have done a few asychronous requests in the reactive way. But what I wan´t to do now is a "Eventlistener".
I have a Session object, at the moment I have an SessionEventListener protocol. The Session has a list of listeners and informs all of them about a successfull login and an logout. This Listeners can subscribe and unsubscribe. This thing I want to create reactive now.
How would you do that?
My Idea is to define a BehaviourSubject:
public let loginEventBehaviourSubject = BehaviorSubject(value: true)
now I can send onNext true if the session logged in, and false if it was logged out:
loginEventBehaviourSubject.onNext(true) // on login
loginEventBehaviourSubject.onNext(false) // on logout
And my "listeners" can subscribe to it.
But I would prefere to have subjects for every event:
public let loginEventBehaviourSubject = BehaviorSubject(value: )
public let logoutEventBehaviourSubject = BehaviorSubject(value: )
But then I wouldn´t need the bool. Can I make a kind of "empty" Subject, that only fire "events" without submitting really data.
And then my last question:
Why do I have to add an instance to the initializer of the Subject. Why can´t I create it like: BehaviourSubject<Bool>()?
You need to give an initial value to behavior subject because of it's API. Indeed, it defines BehaviorSubject<T>.value() method, which returns a T. And it would not make sense to call value without a proper initial value. In the presented case, I think PublishSubject is a better representation of the task at hand. You can find more documentation on the available kinds of subjects on the reactivex website.
If you are only interested in the .next event of your subjects, you can do let loginSubject = PublishSubject<Void>() (using behavior subject, you could have written BehaviorSubject<Void>(value: ())) and will the be able to call loginSubject.onNext().
Note though that using any subject is often an anti-pattern. Indeed, subject are most of the time intended to bridge from the imperative to the reactive world and you can very often create things like loginEventObservable as a combination of other observables. For more information on this, I recommend reading To Use Subject Or Not To Use Subject?. It is written using the .Net implementation of Rx, but the theory stays the same.

REST: Updating multiple records

I need to update multiple records using a single HTTP request. An example is selecting a list of emails and marking them as 'Unread'. What is the best (Restful) way to achieve this?
The way I doing right now is, by using a sub resource action
PUT http://example.com/api/emails/mark-as-unread
(in the body)
{ids:[1,2,3....]}
I read this site - http://restful-api-design.readthedocs.io/en/latest/methods.html#actions - and it suggests to use an "actions" sub-collection. e.g.
POST http://example.com/api/emails/actions
(in the body)
{"type":"mark-as-unread", "ids":[1,2,3....]}
Quotes from the referenced webpage:
Sometimes, it is required to expose an operation in the API that inherently is non RESTful. One example of such an operation is where you want to introduce a state change for a resource, but there are multiple ways in which the same final state can be achieved, ... A great example of this is the difference between a “power off” and a “shutdown” of a virtual machine.
As a solution to such non-RESTful operations, an “actions” sub-collection can be used on a resource. Actions are basically RPC-like messages to a resource to perform a certain operation. The “actions” sub-collection can be seen as a command queue to which new action can be POSTed, that are then executed by the API. ...
It should be noted that actions should only be used as an exception, when there’s a good reason that an operation cannot be mapped to one of the standard RESTful methods. ...
Create an algorithm-endpoint, like
http://example.com/api/emails/mark-unread
bulk-update is an algorithm name, a noun. It gets to be the endpoint name in REST, the list of ids are arguments to this algorithm. Typically people send them as URL query arguments in the POST call like
http://example.com/api/emails/mark-unread?ids=1,2,3,4
This is very safe, as POST is non-idempotent and you need not care about any side effects. You might decide differently and if your bulk update carries entire state of such objects opt for PUT
http://example.com/api/emails/bulk-change-state
then you would have to put the actual state into the body of the http call.
I'd prefer a bunch of simple algo like mark-unread?ids=1,2,3,4 rather than one monolithic PUT as it helps with debugging, transparent in logs etc
It a bit complicated to get array of models into an action method as argument. The easiest approach is to form a json string from your client and POST all that to the server (to your action mehtod). You can adopt the following approach
Say your email model is like this:
public class Email
{
public int EmailID {get; set;}
public int StatusID {get; set;}
// more properties
}
So your action method will take the form:
public bool UpdateAll(string EmailsJson)
{
Email[] emails = JsonConvert.DeserializeObject<Emails[]>(EmailsJson);
foreach(Email eml in emails)
{
//do update logic
}
}
Using Json.NET to help with the serialization.
On the client you can write the ajax call as follows:
$.ajax({
url: 'api/emailsvc/updateall',
method: 'post',
data: {
EmailsJson: JSON.stringify([{
ID: 1,
StatusID:2,
//...more json object properties.
},
// more json objects
])
},
success:function(result){
if(result)
alert('updated successfully');
});

BadlyFormattedFlowExecutionKeyException in grails webflow

I'm getting grails "BadlyFormattedFlowExecutionKeyException" exception when I change the execution param value in address bar!! Does anyone know how to handle such Exceptions?
Cheers!
I had the same problem. After a lot of googling, i made a filter for each flow.
And In 'before' closure i read params.execution, if params.execution is not null i test the state with getFlowStateName function:
Accessing flow state name from filter
if is a invalid state (the function return null) i redirect to the begin of flow (redirect controller: 'xx', action: 'yy').
Best Regards!

Is there a way to use google analytics to track calls to a json response?

I am working on a app that uses a json response from my Zend Framework 1.10 website. I want to track how many times the Json Action is hit?
If there is no true way to do this from just the action that is not reflected the json response.
I would suppose you are using Jquery to illustrate my idea ,
I would track both success and error function of jquery using google analytics events
example : pageTracker._trackEvent(category, action, opt_label, opt_value );
Guide : http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html
$.ajax({
......... some jquery code here .....
success:function(){
......... Jquery code ...........
/*lets show some magic */
pageTracker._trackEvent("JSON", "SUCCESS", "Loaded" , 1 );
},
error:function(){
.......... Jquery code ...........
pageTracker._trackEvent("JSON", "FAILD", "why it faild " , 0 );
}
})
at the end of the day , go to Events on you GA Account
you would see handy results as you would expect :)
you can track ( click , AJAX Request , Page load time , Banner & many other smart ideas )
another tip : you might use what GA Marketers used to do
this is the most easiest one to make
http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55578
just append it to your AJAX request and watch the magic :)
Twitter using this idea in the mailing notification
example :
http://twitter.com/*********?utm_campaign=newfollow20100823&utm_content=profile&utm_medium=email&utm_source=follow
You can track any action with GA by having a special page with tracking code for it that you load into an iframe when the action takes place.
If you need more actions you can have something like trackAction.php?action=myAction.
Regards,
Alin
Just use the measurement protocol from the back end, create a hash and post it.
The following parameters are required for each payload:
https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
v=1 // Version.
&tid=UA-XXXX-Y // Tracking ID / Property ID.
&cid=555 // Anonymous Client ID.
&t= // Hit Type.
p = {}
HTTParty.post('http://www.google-analytics.com/collect', body: p)