How to pass a value from getInputData() to map() function in map reduce suitescript? - suitescript

I have made a suitelet that is running a map-reduce script and passing a parameter which is a date. Now what is required is to include that date object (coming from suitelet) in the map() function. So that the record that will be created in map() can have that date as trandate.
define(['N/record', 'N/search', 'N/runtime'], function (record, search, runtime) {
function getInputData() {
try {
var slfilter = runtime.getCurrentScript().getParameter({ name: 'custscript_searchfilter_date' });
slfilter.replace(/\\/g, "");
var dateSL = JSON.parse(slfilter);
log.debug('dateSL parsed', dateSL)
var date = dateSL['date'];
log.debug('date', date);
var savedSearch = search.load({ id: 'customsearch_wip_correction' });
var results = getResults(savedSearch.run())
log.debug('results:', results)
return results;
}
catch (e) {
log.error("GetInputData ", e);
}
}
function map(context) {
try {
// date is required here
var data = JSON.parse(context.value);
log.debug('map:' + context.key, context.value)
var amount = data.values['SUM(amount)'];
log.debug('amount', amount)
var location = data.values['GROUP(location)'][0].value;
log.debug('location', location)
}
catch (e) {
log.error("map", e)
}
}

Put runtime.getCurrentScript().getParameter in map section.
N/runtime can work in any endpoint either Client Script or User Events.

Related

How to get source and target of edge after any change on cell connect?

I'm programming a web application that use workflow. I used jgraph(Mxgraph) for designing workflow.
I will save workflow parts in database (activities, notifications, transitions).
I need to get source and target of transitions. So how should I catch any changes on transitions in client?
I used before from these three events but don't work always. For example when I change connection target.
Editor.graph.connectionHandler.addListener(mxEvent.CONNECT, function (sender, evt) {
console.log('connect');
});
Editor.graph.connectionHandler.addListener(mxEvent.START, function (sender, evt) {
console.log('start');
});
Editor.graph.connectionHandler.addListener(mxEvent.RESET, function (sender, evt) {
console.log('reset');
});
I found it.
We can use mxEvent.Change event for getting any change on graph model.
editor.graph.getModel().addListener(mxEvent.CHANGE, function (sender, evt) {
editor.graph.validateGraph();
var xml = getEditorXml(Editor);
$("#BpmnXml").val(xml);
//console.log(getCells_ByType("Start"));
// /console.log(getCells_ByType("Task"));
let connectors = getCells_ByType("Connector");
if (connectors != null && connectors.length > 0) {
connectors.forEach(element => {
var source = Editor.graph.getModel().getTerminal(element, true);
var target = Editor.graph.getModel().getTerminal(element, false);
setData(element, { FromActivityClientId: source.getId(), ToActivityClientId: target.getId() });
});
}
});
function getCells_ByType(TypeCell) { // dar report estafede mishavad
var AllCells = Editor.graph.getChildCells(Editor.graph.getDefaultParent(), true, true);
var result = $.grep(AllCells, function (s) { return s.getValue().localName == TypeCell; });
if (result.length != 0)
return result;
else
return null;
}

my action method returning {"success=true,message="work done"} ASP.net MVC 5

Here is my create action method. I want get alert form it when success is true.
public JsonResult Create(Student student ,HttpPostedFileBase img)
{
if (ModelState.IsValid)
{
if (img !=null)
{
var name = Path.GetFileNameWithoutExtension(img.FileName);
var ext = Path.GetExtension(img.FileName);
var filename = name + DateTime.Now.ToString("ddmmyyyff") + ext;
img.SaveAs(Server.MapPath("~/img/"+filename));
student.ImageName = filename;
student.Path = "~/img/" + filename;
}
db.Students.Add(student);
db.SaveChanges();
return Json(new { success = true, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
ViewBag.ClassID = new SelectList(db.Classes, "Id", "Name", student.ClassID);
return new JsonResult { Data = new { success = false, message = "data not saved" } };
}
Here is my ajax function :
function onsub(form) {
$.validations.unobtrusive.parse(form);
if (form.valid()) {
var ajaxConfig = {
type: "POST",
url: form.action,
data: new FormData(form),
success: function (response) {
if (response.success ) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
}
}
if ($(form).attr("enctype") == "multipart/form-data") {
ajaxConfig["contentType"] = false;
ajaxConfig["processData"] = false;
}
$.ajax(ajaxConfig);
}
return false;
}
How can I get an alert form it
without reloading the form. I also want to submit images and other files to create an action method.
This is the result that I get after submitting the form:
In your case you are calling Create action which returning the JSON Result and the same Json response is displayed in browser.
Their should be a View page from where you will call this method by using the Ajax call, then you will be able to see your alert message.

Cosmodb, why is this update not working?

I am trying to query orders and update them. I have been able to isolate my problem in a unit test:
[Fact(DisplayName = "OrderDocumentRepositoryFixture.Can_UpdateAsync")]
public async void Can_UpdateByQueryableAsync()
{
var order1 = JsonConvert.DeserializeObject<Order>(Order_V20170405_133926_9934934.JSON);
var orderId1 = "Test_1";
order1.Id = orderId1;
await sut.CreateAsync(order1);
foreach (var order in sut.CreateQuery())
{
order.Version = "myversion";
await sut.UpdateAsync(order);
var ordersFromDb = sut.GetByIdAsync(orderId1).Result;
Assert.Equal("myversion", ordersFromDb.Version);
}
}
where :
public IQueryable<T> CreateQuery()
{
return _client.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_databaseId, CollectionId));
}
With this code, orders are not updated.
If I replace the CreateQuery() by what follows, it does work:
[Fact(DisplayName = "OrderDocumentRepositoryFixture.Can_UpdateAsync")]
public async void Can_UpdateByQueryableAsync()
{
var order1 = JsonConvert.DeserializeObject<Order>(Order_V20170405_133926_9934934.JSON);
var orderId1 = "Test_1";
order1.Id = orderId1;
await sut.CreateAsync(order1);
var order = sut.GetByIdAsync(orderId1).Result;
order.Version = "myversion";
await sut.UpdateAsync(order);
var ordersFromDb = sut.GetByIdAsync(orderId1).Result;
Assert.Equal("myversion", ordersFromDb.Version);
}
where
public async Task<T> GetByIdAsync(string id)
{
try
{
var documentUri = UriFactory.CreateDocumentUri(_databaseId, CollectionId, id);
var document = (T) await ((DocumentClient) _client).ReadDocumentAsync<T>(documentUri);
return document;
}
catch (DocumentClientException e)
{
if (e.StatusCode == HttpStatusCode.NotFound) return null;
throw;
}
}
I've been trying to understand why this doesn't work. Obviously i could always do a GetByIdAsync before updating, but that seems overkill?
What can't I see?
Thanks!
You create your query, but you never execute it (CreateDocumentQuery just sets up the query). Try altering your call to something like:
foreach (var order in sut.CreateQuery().ToList())
{
//
}
Also note: if you are always querying for a single document, and you know the id, then ReadDocumentAsync() (your alternate code path) will be much more effecient, RU-wise.

Post data with free-jqgrid, what are the code in client and Web API side?

I am using ASP.NET MVC 6 Web API. In the View I use free-jqgrid.
Let's borrow Oleg's free jqgrid data to demonstrate my purpose. We already have the table shown.
Next I am going to add new Vendor. Please notify that there is primary key id(identity column) in the database. We don't want it displaying in the screen.
In VendorRespository.cs, I add the new Vendor as
public void AddVendor(Vendor item)
{
using (VendorDataContext dataContext = new VendorDataContext())
{
dataContext.Database.Connection.ConnectionString = DBUtility.GetSharedConnectionString(
"http://centralized.admin.test.com");
var newVendor = dataContext.Vendors.Create();
newVendor.Company = item.Company;
newVendor.ContactName = item.ContactName;
newVendor.ContactPhone = item.ContactName;
newVendor.UserName = item.UserName;
newVendor.UserKey = item.UserKey;
newVendor.Active = item.Active;
newVendor.FacilityId =item.FacilityId;
newVendor.ClientID = item.ClientID;
dataContext.SaveChanges();
}
}
My questions:
Not sure the script like?
<script>
API_URL = "/VendorManagement/";
function updateDialog(action) {
return {
url: API_URL
, closeAfterAdd: true
, closeAfterEdit: true
, afterShowForm: function (formId) { }
, modal: true
, onclickSubmit: function (params) {
var list = $("#jqgrid");
var selectedRow = list.getGridParam("selrow");
rowData = list.getRowData(selectedRow);
params.url += rowData.Id;
params.mtype = action;
}
, width: "300"
};
}
jQuery("#jqgrid").jqGrid('navGrid',
{ add: true, edit: true, del: true },
updateDialog('PUT'),
updateDialog('POST'),
updateDialog('DELETE')
);
In the controller, not sure what is the code?
// POST
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
My code has many compiling errors such as
'HttpRequest' does not contain a definition for 'CreateResponse' and the best extension method overload 'HttpRequestMessageExtensions.CreateResponse(HttpRequestMessage, HttpStatusCode, Vendor)' requires a receiver of type 'HttpRequestMessage'
Please help me to get rid of the error and inappropriate code.
EDIT:
I borrowed the code snippet from here.
I need add the code such as
[Microsoft.AspNet.Mvc.HttpGet]
public dynamic GetVendorById(int pkey)
{
return null;
}
And
// POST
[System.Web.Http.HttpPost]
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("/VendorManagement/GetVendorById", new { id = item.pkey });
response.Headers.Location = new Uri(uri);
return response;
}

Older asynchronous messages overwriting newer ones

We are developing a document collaboration tool in SignalR where multiple users can update one single WYSIWYG form.
We are struggling getting the app to work using the KeyUp method to send the changes back to the server. This causes the system to overwrite what the user wrote after his first key stroke when it sends the message back.
Is there anyway to work around this problem?
For the moment I tried to set up a 2 seconds timeout but this delays all updates not only the "writer" page.
public class ChatHub : Hub
{
public ChatHub()
{
}
public void Send(int id,string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(id,message); //id is for the document id where to update the content
}
}
and the client:
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//console.log("Declare a proxy to reference the hub.");
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (id, message) {
var encodedValue = $('<div />').text(id).html();
// Add the message to the page.
if (encodedValue == $('#hdnDocId').val()) {
$('#DiaplayMsg').text(message);
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message); //!!!
}
};
// Start the connection.
$.connection.hub.start().done(function (e) {
//console.log("Start the connection.");
if ($('#hdnDocId').val() != '') {
tinyMCE.activeEditor.onKeyUp.add(function (ed, e) {
var elelist = $(tinyMCE.activeEditor.getBody()).text();
var content = tinyMCE.get('txtContent').getContent();
function Chat() {
var content = tinyMCE.get('txtContent').getContent();
chat.server.send($('#hdnDocId').val(), content); //send a push to server
}
typewatch(Chat, 2000);
});
}
});
});
var typewatch = function () {
var timer = 0;
return function (Chat, ms) {
clearTimeout(timer);
timer = setTimeout(Chat, ms);
}
} ();
</script>
Hello, here is an update of the client KeyUp code. It seems to be working but I would like your opinion. I've used a global variable to store the timeout, see below:
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//console.log("Declare a proxy to reference the hub.");
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (id, message) {
var encodedValue = $('<div />').text(id).html();
var currenttime = new Date().getTime() / 1000 - 2
if (typeof window.istyping == 'undefined') {
window.istyping = 0;
}
if (encodedValue == $('#hdnDocId').val() && window.istyping == 0 && window.istyping < currenttime) {
function Update() {
$('#DiaplayMsg').text(message);
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message); //!!!
// tinyMCE.get('txtContent').setContent(message);
window.istyping = 0
}
Update();
}
};
// Start the connection.
$.connection.hub.start().done(function (e) {
//console.log("Start the connection.");
if ($('#hdnDocId').val() != '') {
tinyMCE.activeEditor.onKeyUp.add(function (ed, e) {
var elelist = $(tinyMCE.activeEditor.getBody()).text();
var content = tinyMCE.get('txtContent').getContent();
function Chat() {
//alert("Call");
var content = tinyMCE.get('txtContent').getContent();
chat.server.send($('#hdnDocId').val(), content);
window.istyping = new Date().getTime() / 1000;
}
Chat();
});
}
});
});
var typewatch = function () {
var timer = 0;
return function (Chat, ms) {
clearTimeout(timer);
timer = setTimeout(Chat, ms);
}
} ();
Thanks,
Roberto.
Is there anyway to work around this problem?
Yes, by not sending the entire document to the server, but document elements like paragraphs, table cells, and so on. You can synchronize these after the user has stopped typing for a period, or when focus is lost for example.
Otherwise add some incrementing counter to the messages, so older return values don't overwrite newer ones arriving earlier.
But you're basically asking us to solve a non-trivial problem regarding collaborated document editing. What have you tried?
"This causes the system to overwrite what the user wrote"
that's because this code isn't making any effort to merge changes. it is just blindly overwriting whatever is there.
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message);
as #CodeCaster hinted, you need to be more precise in the messages you send - pass specific changes back and forth rather re-sending the entire document - so that changes can be carefully merged on the receiving side

Resources