Grid Events and oldValue versus newValue - ignite

When updating entities in my cache, the oldValue=newValue in the event, unless I do a put with the original object instance. This is of course not always possible.
Here is a simplified example.
IgnitePredicate<CacheEvent> locLsnr = evt -> {
// do something
};
ignite.events().localListen(locLsnr,EventType.EVT_CACHE_OBJECT_PUT);
IgniteCache<TradeKey, Trade> cache = ignite.getOrCreateCache("MyCache");
Trade trade1 = new Trade();
trade1.setId(1);
trade1.setSize(10);
cache.put(new TradeKey(trade.getId()), trade1);
// event is generated
//evt.oldValue is null, no problem
trade1.setSize(20);
cache.put(new TradeKey(trade.getId()), trade1);
// event is generated
// evt.oldValue().getSize() is 10, evt.newValue().getSize() is 20, this is GOOD
But, if I retrieve the trade from the cache again before updating (from another part of the application for example), I am not able to see what the old value was in the event. Old value will just show the new value.
IgnitePredicate<CacheEvent> locLsnr = evt -> {
// do something
};
ignite.events().localListen(locLsnr,EventType.EVT_CACHE_OBJECT_PUT);
IgniteCache<TradeKey, Trade> cache = ignite.getOrCreateCache("MyCache");
Trade trade1 = new Trade();
trade1.setId(1);
trade1.setSize(10);
cache.put(new TradeKey(trade.getId()), trade1);
// event is generated
//evt.oldValue is null, no problem
trade1 = cache.get(new TradeKey(1)); // or could be a query or any search on the cache
trade1.setSize(20);
cache.put(new TradeKey(trade.getId()),trade1);
// event is generated
// evt.oldValue().getSize() is 20, evt.newValue().getSize() is 20, this is BAD
Any advice?
Thanks.

This is also discussed on Apache Ignite user forum: http://apache-ignite-users.70518.x6.nabble.com/Grid-Events-and-oldValue-versus-newValue-td10577.html

Related

How to keep HTTP/2 connection alive till the request / response session is complete?

I am currently using HttpDeclarePushto exploit the Server Push feature in HTTP/2.
I am able to successfully create all the parameters that this function accepts. But the issue is when HttpDeclarePushexecutes it returns a value of 1229 (ERROR_CONNECTION_INVALID) - https://learn.microsoft.com/en-us/windows/desktop/debug/system-error-codes--1000-1299-.
On further investigation I found that the HttpHeaderConnection in _HTTP_HEADER_ID (https://learn.microsoft.com/en-us/windows/desktop/api/http/ne-http-_http_header_id) is actually passed in the function as 'close'. That implies that on every request response the server closes the connection and that is also happening in my case, I checked it in the log.
Here is the code.
class http2_native_module : public CHttpModule
{
public:
REQUEST_NOTIFICATION_STATUS OnBeginRequest(IN IHttpContext * p_http_context, IN IHttpEventProvider * p_provider)
{
HTTP_REQUEST_ID request_id;
const HTTPAPI_VERSION version = HTTPAPI_VERSION_2;
auto pHttpRequest = p_http_context->GetRequest();
auto phttpRequestRaw = pHttpRequest->GetRawHttpRequest();
HANDLE p_req_queue_handle = nullptr;
auto isHttp2 = phttpRequestRaw->Flags;
try {
const auto request_queue_handle = HttpCreateRequestQueue(version, nullptr, nullptr, NULL, &p_req_queue_handle);
const auto verb = phttpRequestRaw->Verb;
const auto http_path = L"/polyfills.0d74a55d0dbab6b8c32c.js"; //ITEM that I want to PUSH to client
const auto query = nullptr;
request_id = phttpRequestRaw->RequestId;
auto headers = phttpRequestRaw->Headers;
auto connId = phttpRequestRaw->ConnectionId;
WriteEventViewerLog(L"OnBeginRequest - Entering HTTPDECLAREPUSH");
headers.KnownHeaders[1].pRawValue = NULL;
headers.KnownHeaders[1].RawValueLength = 0;
const auto is_success = HttpDeclarePush(p_req_queue_handle, request_id, verb, http_path, query, &headers);
sprintf_s(szBuffer, "%lu", is_success);
Log("is_success value", szBuffer); //ERROR CODE 1229 here
HttpCloseRequestQueue(p_req_queue_handle);
}
catch (std::bad_alloc & e)
{
auto something = e;
}
return RQ_NOTIFICATION_CONTINUE;
}
I even tried to update the header connection value as below but it still gives me 1229.
headers.KnownHeaders[1].pRawValue = NULL;
headers.KnownHeaders[1].RawValueLength = 0;
I understand from https://http2.github.io/http2-spec/ that HTTP/2 actually ignores the content in HTTP HEADERs and uses some other mechanism as part of its FRAME.
This brings us to the next question on how we can keep the connection OPEN and is it something related to the FRAME (similar to HEADER) that HTTP2 uses, if so, how C++ or rather Microsoft helps us to play and exploit with the FRAME in HTTP2?

Createjs. Line follow element fiddle

I created this jsfiddle.
A line i connecting two elements, and I want the line to stay connected to both elements no matter where they go.
I've sort of succeeded, but with one pretty obvious error. It keeps drawing new lines instead of redrawing the existing line. Please help me on how to make it update the line position instead.
var stage = new createjs.Stage("canvas");
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", tick);
var arrDots = [];
var arrLines = [];
var circle1 = new createjs.Shape().set({
x: stage.canvas.width/2,
y: 50,
cursor: "pointer",
name:"target"
});
circle1.graphics.f(createjs.Graphics.getRGB(Math.random()*0xFFFFFF))
.dc(0,0,20);
stage.addChild(circle1);
arrDots.push(circle1);
var circle2 = new createjs.Shape().set({
x: stage.canvas.width/2,
y: stage.canvas.height - 50,
cursor: "pointer",
name:"target"
});
circle2.graphics.f(createjs.Graphics.getRGB(Math.random()*0xFFFFFF))
.dc(0,0,20);
stage.addChild(circle2);
arrDots.push(circle2);
var line = new createjs.Shape().set({
graphics: new createjs.Graphics().s("#00f").mt(arrDots[0].x,
arrDots[0].y).lt(arrDots[1].x, arrDots[1].y)
});
stage.addChild(line);
arrLines.push([arrDots[0], arrDots[1], line]);
createjs.Tween.get(circle1, {loop: true}).to({x:50},
3000).to({x:stage.canvas.width/2}, 3000);
function tick(event) {
keepLineConnection();
stage.update();
}
function keepLineConnection() {
for(var i = 0; i < arrLines.length; i++) {
arrLines[i][2].graphics.mt(arrLines[i][0].x, arrLines[i][0].y).lt(arrLines[i][1].x, arrLines[i][1].y);
}
}
The reason it keeps drawing is because you keep adding commmands to the graphics. Basically, you are doing this:
graphics.mt().lt().mt().lt().mt().lt().mt().etc();
Since you are just adding new instrucitons, they will pile up over time,
and will eventually kill your processor.
An easy fix for that is to clear the graphics first before adding new ones:
graphics.clear().mt().lt();
A better approach is to use commands. Since EaselJS 0.7.0, all graphics commands are objects, and at any time you can update properties of those objects directly. For example, the MoveTo and LineTo commands both have an x and y property. Here is more info on Commands: http://blog.createjs.com/update-width-height-in-easeljs/
Here is a modified fiddle that stores of commands on the line, and then updates them on tick. I also made a few other updates, such as changing the timing mode to RAF, which is smoother than using interval-based timers at 60FPS.
https://jsfiddle.net/tck7x8u2/
// Store commands:
line.cmd1 = line.graphics.mt(0,0).command;
line.cmd2 = line.graphics.lt(0,0).command;
// Update commands:
var instr = arrLines[i],
line = instr[2];
line.cmd1.x = instr[0].x;
line.cmd1.y = instr[0].y;
line.cmd2.x = instr[1].x;
line.cmd2.y = instr[1].y;
Cheers!
Edit: Here is are some demos using that idea that I made a while back:
https://lab.gskinner.com/connections
http://jsfiddle.net/lannymcnie/2xoL08bx/
http://jsfiddle.net/lannymcnie/6rh7P/

Why does cacheTimeout setting of renderView() in ColdBox application have no effect?

I'm developing a ColdBox application with modules and wanted to use it's caching functionality to cache a view for some time.
component{
property name="moduleConfig" inject="coldbox:moduleConfig:mymodule";
...
function widget(event, rc, prc){
var viewData = this.getData();
return renderView(
view = "main/widget",
args = viewData,
cache = true,
cacheSuffix = ":" & moduleConfig.entryPoint,
cacheTimeout = 2
);
}
}
I tried to set the default caching config by adding the following info to my Cachebox.cfc and removed the cacheTimeout from the code above:
cacheBox = {
defaultCache = {
objectDefaultTimeout = 1, //two hours default
objectDefaultLastAccessTimeout = 1, //30 minutes idle time
useLastAccessTimeouts = false,
reapFrequency = 5,
freeMemoryPercentageThreshold = 0,
evictionPolicy = "LRU",
evictCount = 1,
maxObjects = 300,
objectStore = "ConcurrentStore", //guaranteed objects
coldboxEnabled = false
},
caches = {
// Named cache for all coldbox event and view template caching
template = {
provider = "coldbox.system.cache.providers.CacheBoxColdBoxProvider",
properties = {
objectDefaultTimeout = 1,
objectDefaultLastAccessTimeout = 1,
useLastAccessTimeouts = false,
reapFrequency = 5,
freeMemoryPercentageThreshold = 0,
evictionPolicy = "LRU",
evictCount = 2,
maxObjects = 300,
objectStore = "ConcurrentSoftReferenceStore" //memory sensitive
}
}
}
};
Though that didn't have any influence on the caching. I've also tried to add the config above to my Coldbox.cfc.
Even if I create a completely new test app via CommandBox via coldbox create app MyApp, then only set the the caching in Cachebox.cfc to one minute, set viewCaching = true in Coldbox.cfc, and set event.setView( view="main/index", cache=true ) in the Main.cfc, it doesn't work as expected.
No matter what I do, the view is always cached for at least 5 minutes.
Is there something I am missing?
Make sure you have enabled view caching in your ColdBox configuration. Go to the /config/ColdBox.cfc file and add this key:
coldbox = {
// Activate view caching
viewCaching = true
}
Also, did you mistype the name of the CFC you changed for the caching above? Those changes should be in the /config/CacheBox.cfc file, not in /config/ColdBox.cfc.
Obviously, also the the reapFrequency in the /config/ColdBox.cfc needs to be set to a smaller value in order to let the cache entry be removed earlier.
Though, as the documentation states:
The delay in minutes to produce a cache reap (Not guaranteed)
It is not guaranteed that the cached item it really removed after that time, so it can be that the cache is empty after 3 minutes even when reapFrequency is set to 1.

EPiServer 9 - Add block to new page programmatically

I have found some suggestions on how to add a block to a page, but can't get it to work the way I want, so perhaps someone can help out.
What I want to do is to have a scheduled job that reads through a file, creating new pages with a certain pagetype and in the new page adding some blocks to a content property. The blocks fields will be updated with data from the file that is read.
I have the following code in the scheduled job, but it fails at
repo.Save((IContent) newBlock, SaveAction.Publish);
giving the error
The page name must contain at least one visible character.
This is my code:
public override string Execute()
{
//Call OnStatusChanged to periodically notify progress of job for manually started jobs
OnStatusChanged(String.Format("Starting execution of {0}", this.GetType()));
//Create Person page
PageReference parent = PageReference.StartPage;
//IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
//var repository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//var slaegtPage = repository.GetDefault<SlaegtPage>(ContentReference.StartPage);
IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
SlaegtPage slaegtPage = contentRepository.GetDefault<SlaegtPage>(parent, contentTypeRepository.Load("SlaegtPage").ID);
if (slaegtPage.MainContentArea == null) {
slaegtPage.MainContentArea = new ContentArea();
}
slaegtPage.PageName = "001 Kim";
//Create block
var repo = ServiceLocator.Current.GetInstance<IContentRepository>();
var newBlock = repo.GetDefault<SlaegtPersonBlock1>(ContentReference.GlobalBlockFolder);
newBlock.PersonId = "001";
newBlock.PersonName = "Kim";
newBlock.PersonBirthdate = "01 jan 1901";
repo.Save((IContent) newBlock, SaveAction.Publish);
//Add block
slaegtPage.MainContentArea.Items.Add(new ContentAreaItem
{
ContentLink = ((IContent) newBlock).ContentLink
});
slaegtPage.URLSegment = UrlSegment.CreateUrlSegment(slaegtPage);
contentRepository.Save(slaegtPage, EPiServer.DataAccess.SaveAction.Publish);
_stopSignaled = true;
//For long running jobs periodically check if stop is signaled and if so stop execution
if (_stopSignaled) {
return "Stop of job was called";
}
return "Change to message that describes outcome of execution";
}
You can set the Name by
((IContent) newBlock).Name = "MyName";

How to add extra data to a member in MDS?

I'm running MDS on a virtual machine and trying to access the service from my host OS.
I've been able to add something to the database but my data is all over the place and in the Master Data Manager (website) I don't see the new member.
I suppose I shouldn't be using Attributes but something else but what and how? Are there tutorials because I can't find any ...?
Here's the code I'm using:
International international = new International();
EntityMembers entityMembers = new EntityMembers();
// Set the modelId, versionId, and entityId.
entityMembers.ModelId = new Identifier { Name = modelName };
entityMembers.VersionId = new Identifier { Name = versionName };
entityMembers.EntityId = new Identifier { Name = entityName };
entityMembers.MemberType = memberType;
Collection<Member> members = new Collection<Member>();
Member aNewMember = new Member();
aNewMember.MemberId = new MemberIdentifier() { Name = employee.FullName, Code = aNewCode, MemberType = memberType };
Collection<MDS.Attribute> attributes = new Collection<MDS.Attribute>();
MDS.Attribute attrOrgUnit = new MDS.Attribute();
attrOrgUnit.Identifier = new Identifier() { Name = "OrganizationalUnit" };
attrOrgUnit.Value = employee.OrganizationalUnit;
attrOrgUnit.Type = AttributeValueType.String;
attributes.Add(attrOrgUnit);
aNewMember.Attributes = attributes.ToArray();
members.Add(aNewMember);
entityMembers.Members = members.ToArray();
// Create a new entity member
OperationResult operationResult = new OperationResult();
clientProxy.EntityMembersCreate(international, entityMembers, false, out operationResult);
HandleOperationErrors(operationResult);
I have been able to fix my own problem.
First of all: creating separate variables with collections and converting them to arrays afterwards is not necessary. The code from the tutorials works but fails to mention that, when adding the service reference, you have to configure it (right-click on the service reference -> configure) to use Collections as "Collection type" instead of arrays and to generate message contracts.
Second, the code above with the attributes is correct and works perfectly. The problem I had which failed to add messages with attributes was unrelated. It was a connection/authentication problem between my Host OS and Guest OS.
Hope this helps someone.