How can I apply a transaction to a ledger? - xrp

I have an STTx and a Ledger. How can I get a new Ledger with the transaction applied (or even just a ReadView such that .info().accountHash is up-to-date)?

# include <ripple/app/ledger/BuildLedger.h>
# include <ripple/app/misc/CanonicalTXSet.h>
# include <ripple/consensus/LedgerTiming.h> // ledgerDefaultTimeResolution
// Start with what you have.
Application const& app = ...
beast::Journal journal = ...
std::shared_ptr<Ledger const> const& parent = ...
std::shared_ptr<STTx const> const& transaction = ...
// Massage them into parameters for buildLedger.
NetClock::time_point const closeTime = app.timeKeeper().closeTime();
bool const closeTimeCorrect = false;
NetClock::duration closeTimeResolution = ledgerDefaultTimeResolution;
CanonicalTXSet const transactions{parent->info().hash};
transactions.insert(transaction);
std::set<TXID> failedTransactions; // Leave empty.
std::shared_ptr<Ledger> child = buildLedger(
parent,
closeTime,
closeTimeCorrect ,
closeTimeResolution,
app,
transactions,
failedTransactions,
journal);

Related

How can I use Telescope.nvim to complete a path in insert mode?

Fzf.vim implements a fuzzy finder in insert mode, extending the native ins-completion functionality.
For example: in insert mode, we can map <c-x><c-f> to enable Fzf.vim to fuzzy find and insert file names with relative paths (fzf-complete-path). The same functionalities are implemented for words (fzf-complete-word) and lines (fzf-complete-line) completions.
Here are the Fzf.vim mapping example of these functions:
" Insert mode completion
imap <c-x><c-k> <plug>(fzf-complete-word)
imap <c-x><c-f> <plug>(fzf-complete-path)
imap <c-x><c-l> <plug>(fzf-complete-line)
How can I set the same behavior with Telescope.nvim?
You can define a custom action and map it to a key to execute it in Telescope.
I've written a set of actions for this task (to insert file paths in the current buffer): telescope-insert-path.nvim
You just need to make your custom mappings in the require'telescope'.setup().
local path_actions = require('telescope_insert_path')
require('telescope').setup {
defaults = {
mappings = {
n = {
["pi"] = path_actions.insert_relpath_i_insert,
["pI"] = path_actions.insert_relpath_I_insert,
["pa"] = path_actions.insert_relpath_a_insert,
["pA"] = path_actions.insert_relpath_A_insert,
["po"] = path_actions.insert_relpath_o_insert,
["pO"] = path_actions.insert_relpath_O_insert,
["Pi"] = path_actions.insert_abspath_i_insert,
["PI"] = path_actions.insert_abspath_I_insert,
["Pa"] = path_actions.insert_abspath_a_insert,
["PA"] = path_actions.insert_abspath_A_insert,
["Po"] = path_actions.insert_abspath_o_insert,
["PO"] = path_actions.insert_abspath_O_insert,
["<leader>pi"] = path_actions.insert_relpath_i_visual,
["<leader>pI"] = path_actions.insert_relpath_I_visual,
["<leader>pa"] = path_actions.insert_relpath_a_visual,
["<leader>pA"] = path_actions.insert_relpath_A_visual,
["<leader>po"] = path_actions.insert_relpath_o_visual,
["<leader>pO"] = path_actions.insert_relpath_O_visual,
["<leader>Pi"] = path_actions.insert_abspath_i_visual,
["<leader>PI"] = path_actions.insert_abspath_I_visual,
["<leader>Pa"] = path_actions.insert_abspath_a_visual,
["<leader>PA"] = path_actions.insert_abspath_A_visual,
["<leader>Po"] = path_actions.insert_abspath_o_visual,
["<leader>PO"] = path_actions.insert_abspath_O_visual,
-- Additionally, there's normal mode mappings for the same actions:
-- ["<leader><leader>pi"] = path_actions.insert_relpath_i_normal,
-- ...
}
}
}
}

OPC UA.NET custom Node Manager creating

I'm trying to use UA-.NETStandardLibrary by OPC Foundation to create my own OPC UA Server that will maintain some variables.
I've created a server class inherited from StandardServer and node manager inherited from CustomNodeManager2.
There were some node managers in their examples, I removed them and add my own one. The server starts normally and doesn't contain any nodes except from standard ones, as planned. So, my problem is how to create my own variable node from code (not from xml, as in examples) and be able update its value on demand.
For example, I want to add a folder with couple of nodes inside.
Does anyone have a code snippet which demonstrates how to do it? I don't want anybody write it for me, I will appreciate only if you just tell me about a right way to make it.
Thanks a lot.
I am pretty sure the snippets you are looking for are included. Here is my testing code and I am 100% positive, I didn't write the second piece of code. Anyway, if this helps you...
{
var ticker_seq = createVariable(myFolder, "MyFolder/Ticker", "Ticker", BuiltInType.UInt64, ValueRanks.Scalar);
variables.Add(ticker_seq);
subscriptions.Add(clock.Ticker.Subscribe(val =>
{
lock (Lock)
{
ticker_seq.Value = val;
ticker_seq.Timestamp = DateTime.UtcNow;
ticker_seq.ClearChangeMasks(SystemContext, false);
}
}));
}
and creation
private BaseDataVariableState createVariable(NodeState parent, string path, string name, NodeId dataType, int valueRank)
{
BaseDataVariableState variable = new BaseDataVariableState(parent);
variable.SymbolicName = name;
variable.ReferenceTypeId = ReferenceTypes.Organizes;
variable.TypeDefinitionId = VariableTypeIds.BaseDataVariableType;
variable.NodeId = new NodeId(path, NamespaceIndex);
variable.BrowseName = new QualifiedName(path, NamespaceIndex);
variable.DisplayName = new LocalizedText("en", name);
variable.WriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
variable.UserWriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
variable.DataType = dataType;
variable.ValueRank = valueRank;
variable.AccessLevel = AccessLevels.CurrentReadOrWrite;
variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite;
variable.Historizing = false;
variable.Value = 0;
variable.StatusCode = StatusCodes.Good;
variable.Timestamp = DateTime.UtcNow;
if (parent != null)
{
parent.AddChild(variable);
}
return variable;
}
creating the folder:
private FolderState CreateFolder(NodeState parent, string path, string name)
{
FolderState folder = new FolderState(parent);
folder.SymbolicName = name;
folder.ReferenceTypeId = ReferenceTypes.Organizes;
folder.TypeDefinitionId = ObjectTypeIds.FolderType;
folder.NodeId = new NodeId(path, NamespaceIndex);
folder.BrowseName = new QualifiedName(path, NamespaceIndex);
folder.DisplayName = new LocalizedText("en", name);
folder.WriteMask = AttributeWriteMask.None;
folder.UserWriteMask = AttributeWriteMask.None;
folder.EventNotifier = EventNotifiers.None;
if (parent != null)
{
parent.AddChild(folder);
}
return folder;
}

Apex class is called in a trigger based on some conditions.Test class passes the test but code coverage is stil 0%

When work order updates to Completed then a new water meter reading record needs to created with two field values from work order and two from another object att. Both work order and water meter reading have a look up(workorder) and master detail relation(water meter reading) with att.Sorry for so much code,but I am really stuck and need help.
trigger CreateWaterMeterReading on sm1e__smWork_Order__c (after update)
{
if (Trigger.new.size() == 1)
{
sm1e__smWork_Order__c wo = Trigger.new[0];
if(wo.sm1e__WO_Type__c == 'Meter Read Move In/Out ' && wo.sm1e__Status__c == 'Completed')
reateNewWaterMeterRead.createWMRforMoveInOrOut(wo.Id);
}
}
--Apex class
public class CreateNewWaterMeterRead {
public static void createWMRforMoveInOrOut(string workorderId)
{
Work_Order__c wo = [Select Equipment__r.Name,Completion_Date__c,Meter_Reading__c from Work_Order__c where Id = : workorderId ];
Equipment__c att = [Select Id,Last_Water_Meter_Reading_Date__c,Last_Water_Meter_Reading__c from Equipment__c where Name = : wo.Equipment__r.Name ];
List<Water_Meter_Readings__c> newwmr = new List<Water_Meter_Readings__c>();
Water_Meter_Readings__c wmr = new Water_Meter_Readings__c();
wmr.Meter__c = att.Id;
wmr.Current_Meter_Reading__c = wo.Meter_Reading__c;
wmr.Current_Read_Date__c = wo.sm1e__Completion_Date__c;
wmr.Prior_Meter_Reading__c = att.Last_Water_Meter_Reading__c;
wmr.Prior_Read_Date__c = att.Last_Water_Meter_Reading_Date__c;
wmr.Source__c = 'Manual Read';
newwmr.add(wmr);
if(newwmr.size() >0)
insert newwmr;
}
--Test Class
isTest(SeeAllData = true)
public class CreateNewWaterMeterReadTest
{
static testmethod void createWMRforMoveInOrOut()
{
Work_Order__c wo = [Select Id,Equipment__r.Name,Completion_Date__c,Meter_Reading__c from Work_Order__c where sm1e__Status__c != 'Completed' AND sm1e__WO_Type__c = 'Meter Read Move In/Out' LIMIT 1];
Equipment__c att = [Select Id,Last_Water_Meter_Reading_Date__c,Last_Water_Meter_Reading__c from Equipment__c where Name = : wo.Equipment__r.Name ];
test.startTest();
wo.Meter_Reading__c = 1317;
wo.sm1e__Status__c = 'Completed';
update wo;
test.stopTest();
System.debug('updated wo');
Water_Meter_Readings__c wmr = new Water_Meter_Readings__c();
System.debug('wmr for test');
wmr.Meter__c= att.Id;
wmr.Current_Meter_Reading__c = wo.Meter_Reading__c;
wmr.Current_Read_Date__c = wo.Completion_Date__c;
System.debug('in between wmr');
wmr.Prior_Meter_Reading__c = att.Last_Water_Meter_Reading__c;
wmr.Prior_Read_Date__c = att.Last_Water_Meter_Reading_Date__c;
wmr.Source__c = 'Manual';
insert wmr;
You've written trigger on after update. But in your test class you're inserting a record and not updating it. That is why your code coverage is 0%. Refer to this link
For executing trigger you must do dml operation for which you've written a trigger. Also you can invoke your class method from test class by creating its instance. Refer above link for the same.

Implementing an OPC DA client from scratch

I would like to implement my own OPC DA client (versions 2.02, 2.05a, 3.00) from scratch but without using any third-party. Also I would like to make use of OPCEnum.exe service to get a list of installed OPC servers. Is there any kind of document that explains detailed and step by step the process to implement an OPC client?
I have a c# implementation but actually it's hard to fit it in here. I'll try to summarize the steps required.
Mostly you need to have OpcRcw.Comn.dll and OpcRcw.Da.dll from the OPC Core Components Redistributable package downloable for free from Opcfoundation.org. Once installed, the files are located in C:\Windows\assembly\GAC_MSIL. Create a reference in your project.
About coding, this is what you should do (there are three objects you want to implement, Server, Group and Item):
Let's start with server:
Type typeofOPCserver = Type.GetTypeFromProgID(serverName, computerName, true);
m_opcServer = (IOPCServer)Activator.CreateInstance(typeofOPCserver);
m_opcCommon = (IOPCCommon)m_opcServer;
IConnectionPointContainer icpc = (IConnectionPointContainer)m_opcServer;
Guid sinkGUID = typeof(IOPCShutdown).GUID;
icpc.FindConnectionPoint(ref sinkGUID, out m_OPCCP);
m_OPCCP.Advise(this, out m_cookie_CP);
I've striped a LOT of checking to fit it in here, take it as a sample...
Then you need a method on server to add groups:
// Parameter as following:
// [in] active, so do OnDataChange callback
// [in] Request this Update Rate from Server
// [in] Client Handle, not necessary in this sample
// [in] No time interval to system UTC time
// [in] No Deadband, so all data changes are reported
// [in] Server uses english language to for text values
// [out] Server handle to identify this group in later calls
// [out] The answer from Server to the requested Update Rate
// [in] requested interface type of the group object
// [out] pointer to the requested interface
m_opcServer.AddGroup(m_groupName, Convert.ToInt32(m_isActive), m_reqUpdateRate, m_clientHandle, pTimeBias, pDeadband, m_LocaleID, out m_serverHandle, out m_revUpdateRate, ref iid, out objGroup);
// Get our reference from the created group
m_OPCGroupStateMgt = (IOPCGroupStateMgt)objGroup;
Finally you need to create items:
m_OPCItem = (IOPCItemMgt)m_OPCGroupStateMgt;
m_OPCItem.AddItems(itemList.Length, GetAllItemDefs(itemList), out ppResults, out ppErrors);
Where itemlist is an array of OPCITEMDEF[]. I build the above using GetAllItemDefs from a structure of mine.
private static OPCITEMDEF[] GetAllItemDefs(params OpcItem[] opcItemList)
{
OPCITEMDEF[] opcItemDefs = new OPCITEMDEF[opcItemList.Length];
for (int i = 0; i < opcItemList.Length; i++)
{
OpcItem opcItem = opcItemList[i];
opcItemDefs[i].szAccessPath = "";
opcItemDefs[i].bActive = Convert.ToInt32(opcItem.IsActive);
opcItemDefs[i].vtRequestedDataType = Convert.ToInt16(opcItem.ItemType, CultureInfo.InvariantCulture);
opcItemDefs[i].dwBlobSize = 0;
opcItemDefs[i].pBlob = IntPtr.Zero;
opcItemDefs[i].hClient = opcItem.ClientHandle;
opcItemDefs[i].szItemID = opcItem.Id;
}
return opcItemDefs;
}
Finally, about enumerating Servers, I use this two functions:
/// <summary>
/// Enumerates hosts that may be accessed for server discovery.
/// </summary>
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public string[] EnumerateHosts()
{
IntPtr pInfo;
int entriesRead = 0;
int totalEntries = 0;
int result = NetServerEnum(
IntPtr.Zero,
LEVEL_SERVER_INFO_100,
out pInfo,
MAX_PREFERRED_LENGTH,
out entriesRead,
out totalEntries,
SV_TYPE_WORKSTATION | SV_TYPE_SERVER,
IntPtr.Zero,
IntPtr.Zero);
if (result != 0)
throw new ApplicationException("NetApi Error = " + String.Format("0x{0,0:X}", result));
string[] computers = new string[entriesRead];
IntPtr pos = pInfo;
for (int ii = 0; ii < entriesRead; ii++)
{
SERVER_INFO_100 info = (SERVER_INFO_100)Marshal.PtrToStructure(pos, typeof(SERVER_INFO_100));
computers[ii] = info.sv100_name;
pos = (IntPtr)(pos.ToInt32() + Marshal.SizeOf(typeof(SERVER_INFO_100)));
}
NetApiBufferFree(pInfo);
return computers;
}
/// <summary>
/// Returns a list of servers that support the specified specification on the specified host.
/// </summary>
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public string[] GetAvailableServers(Specification specification)
{
lock (this)
{
// connect to the server.
ArrayList servers = new ArrayList();
MULTI_QI[] results = new MULTI_QI[1];
GCHandle hIID = GCHandle.Alloc(IID_IUnknown, GCHandleType.Pinned);
results[0].iid = hIID.AddrOfPinnedObject();
results[0].pItf = null;
results[0].hr = 0;
try
{
// create an instance.
Guid srvid = CLSID;
CoCreateInstanceEx(srvid, null, CLSCTX.CLSCTX_LOCAL_SERVER, IntPtr.Zero, 1, results);
m_server = (IOPCServerList2)results[0].pItf;
// convert the interface version to a guid.
Guid catid = new Guid(specification.ID);
// get list of servers in the specified specification.
IOPCEnumGUID enumerator = null;
m_server.EnumClassesOfCategories(1, new Guid[] { catid }, 0, null, out enumerator);
// read clsids.
Guid[] clsids = ReadClasses(enumerator);
// release enumerator
if (enumerator != null && enumerator.GetType().IsCOMObject)
Marshal.ReleaseComObject(enumerator);
// fetch class descriptions.
foreach (Guid clsid in clsids)
{
try
{
string url = CreateUrl(specification, clsid);
servers.Add(url);
}
catch (Exception) { }
}
}
catch
{
}
finally
{
if (hIID.IsAllocated) hIID.Free();
if (m_server != null && m_server.GetType().IsCOMObject)
Marshal.ReleaseComObject(m_server);
}
return (string[])servers.ToArray(typeof(string));
}
}
I know I've striped a lot but maybe it can still help you ;)
Please mark the answer as correct if you think I've been clear ;)
Kind Regards,
D.

How do I test a trigger with an approval process?

I have a trigger which initiates an approval process when certain criteria are met:
trigger AddendumAfterIHMS on Addendum__c (after update) {
for (integer i = 0; i<Trigger.new.size(); i++){
if(Trigger.new[i].RecordTypeId != '012V0000000CkQA'){
if(Trigger.new[i].From_IHMS__c != null && Trigger.old[i].From_IHMS__c == null){
ID addendumId = Trigger.new[i].Id;
// Start next approval process
Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
request.setObjectId(addendumId);
Approval.ProcessResult requestResult = Approval.process(request);
}
}
}
}
It works perfectly, but now i need to create a test class for it. I have created a class which brings the code up to 75% coverage, which is the minimum, but I'm picky and like to have 100% coverage on my code. The test class I have now gets stuck on the line request.setObjectId(addendumId); and doesn't move past it. The error I receive is:
System.DmlException: Update failed. First exception on row 0 with id a0CV0000000B8cgMAC; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AddendumAfterIHMS: execution of AfterUpdate
Here is the test class that I have written so far, most of the class actually tests some other triggers, but the important line which is throwing the error is the very last line update addendumTierFeature;
#isTest
private class AddendumTest {
static testMethod void myUnitTest() {
// Query Testing Account, will need ID changed before testing to place into production
Account existingAccount = [SELECT Id FROM Account LIMIT 1];
Model__c existingModel = [SELECT Id FROM Model__c WHERE Active__c = TRUE LIMIT 1];
Pricebook2 existingPricebook = [SELECT Id,Name FROM Pricebook2 WHERE IsActive = TRUE LIMIT 1];
List<Contact> existingContacts = [SELECT Id,Name FROM Contact LIMIT 2];
Contact existingContactPrimary = existingContacts[0];
Contact existingContactSecondary = existingContacts[1];
Opportunity newOpportunity = new Opportunity(
Name = 'New Opportunity',
Account = existingAccount,
CloseDate = Date.today(),
Order_Proposed__c = Date.today(),
StageName = 'Branch Visit - Not Responding',
Opportunity_Follow_Up__c = 'Every 120 Days',
LeadSource = 'Farm Lists',
Source_Detail__c = 'FSBO',
Model_Name__c = existingModel.Id,
Processing_Fee__c = 100.50,
Site_State__c = 'OR',
base_Build_Zone__c = 'OR',
Pricebook_from_Lead__c = existingPricebook.Name
);
insert newOpportunity;
//system.assert(newOpportunity.Id != null);
ID newOppId = newOpportunity.Id;
OpportunityContactRole contactPrimary = new OpportunityContactRole(
Role = 'Primary',
IsPrimary = true,
OpportunityId = newOppId,
ContactId = existingContactPrimary.Id
);
OpportunityContactRole contactSecondary = new OpportunityContactRole(
Role = 'Primary',
IsPrimary = false,
OpportunityId = newOppId,
ContactId = existingContactPrimary.Id
);
insert contactPrimary;
insert contactSecondary;
newOpportunity.Name = 'Different - Updating';
newOpportunity.Order_Accepted__c = Datetime.now();
update newOpportunity;
Addendum__c addendumCustomOption = new Addendum__c(
RecordTypeId = '012V0000000CkQA', //Pre Priced Custom Option
Opportunity__c = newOppId,
Item_Pre_Priced_Description__c = 'a1eV00000004DNu',
Reason__c = 'This is a reason',
Item__c = 'This is an Item',
Quantity__c = 1
);
Addendum__c addendumTierFeature = new Addendum__c(
RecordTypeId = '012V0000000Cjks', //Tier Feature
Opportunity__c = newOppId,
Category__c = 'Countertops',
Reason__c = 'This is a reason',
Item__c = 'This is an Item',
Quantity__c = 1
);
insert addendumCustomOption;
insert addendumTierFeature;
addendumCustomOption.Quantity__c = 2;
addendumTierFeature.Quantity__c = 2;
update addendumCustomOption;
update addendumTierFeature;
update newOpportunity;
addendumTierFeature.To_IHMS__c = system.now();
update addendumTierFeature;
addendumTierFeature.From_IHMS__c = system.now();
update addendumTierFeature;
}
}
Any help on this matter would be greatly appreciated. I believe the problem is in the way I am testing the approval process start. Is there by chance a special testing function for this?
After fiddling around for a little while I discovered that the error was actually tied into my approval process. I kept digging into the error logs until I got to the error: caused by: System.DmlException: Process failed. First exception on row 0; first error: MANAGER_NOT_DEFINED, Manager undefined.: []. This phrase indicates that there is no one defined for the next step in my approval process.
When I created the opportunity, I did not set the owner and somehow this created an opportunity which had an owner without a manager. The addendum was also created without an owner/manager. So when I tried to launch the next approval process, there was no manager to send the approval to and an error was thrown.