/// <summary> /// /// This method will iterate through the DataRows inside this Group in order to form /// the appropriate repeating composite bodies as its correct XML amalgamation. /// /// For example, in the case of an Account group with two rows, it could then /// generate XML like the following: /// /// <Account> /// <AccountType><![CDATA[Checking]]></AccountType> /// <Currency><![CDATA[Ethereum]]></Currency> /// <Amount><![CDATA[10.5]]></Amount> /// </Account> /// <Account> /// <AccountType><![CDATA[Savings]]></AccountType> /// <Currency><![CDATA[USD]]></Currency> /// <Amount><![CDATA[20.5]]></Amount> /// </Account> /// /// </summary> /// <returns>The serialized Wonka XML that represents this Product Group</returns> public string AssembleGroupXml() { WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); StringBuilder GroupBuilder = new StringBuilder(); foreach (WonkaPrdGroupDataRow TempDataRow in this) { GroupBuilder.Append("<" + this.MasterGroup.GroupName + ">"); foreach (int nTempAttrId in TempDataRow.Keys) { WonkaRefAttr TempAttribute = RefEnv.GetAttributeByAttrId(nTempAttrId); string sTempAttrValue = TempDataRow[nTempAttrId]; if (!String.IsNullOrEmpty(sTempAttrValue)) { GroupBuilder.Append("\t<" + TempAttribute.AttrName + ">" + WrapWithCDATA(sTempAttrValue) + "</" + TempAttribute.AttrName + ">"); } } GroupBuilder.Append("</" + this.MasterGroup.GroupName + ">"); } return(GroupBuilder.ToString()); }
public void Execute() { WonkaRefEnvironment RefEnv = WonkaRefEnvironment.CreateInstance(false, moMetadataSource); WonkaRefAttr AccountStsAttr = RefEnv.GetAttributeByAttrName("AccountStatus"); WonkaProduct NewProduct = GetNewProduct(); string sStatusValueBefore = GetAttributeValue(NewProduct, AccountStsAttr); /* * NOT YET READY * * // Cue the rules engine * WonkaBreRulesEngine RulesEngine = * new WonkaBreRulesEngine(CONST_SIMPLE_RULES_FILEPATH, moMetadataSource); * * RulesEngine.GetCurrentProductDelegate = GetOldProduct; * * WonkaBre.Reporting.WonkaBreRuleTreeReport Report = RulesEngine.Validate(NewProduct); * * string sStatusValueAfter = GetAttributeValue(NewProduct, AccountStsAttr); * * if (Report.GetRuleSetFailureCount() > 0) * { * throw new Exception("Oh heavens to Betsy! Something bad happened!"); * } */ }
/// <summary> /// /// This method will iterate through a list of Products and apply the default value to every instance /// of an empty Attribute (i.e., in every DataRow of its Group). /// /// <param name="poProducts">The product list that we are iterating through</param> /// <param name="poDefaultValues">The default values for Attributes</param> /// <returns>None</returns> /// </summary> public static void ApplyDefaults(List <WonkaProduct> poProducts, Dictionary <int, string> poDefaultValues) { foreach (WonkaProduct TempProduct in poProducts) { var iDefaultValEnumerator = poDefaultValues.GetEnumerator(); while (iDefaultValEnumerator.MoveNext()) { int nDefaultAttrId = iDefaultValEnumerator.Current.Key; string sDefaultAttrValue = iDefaultValEnumerator.Current.Value; WonkaRefAttr TempAttr = WonkaRefEnvironment.GetInstance().GetAttributeByAttrId(nDefaultAttrId); WonkaPrdGroup TargetGroup = TempProduct.GetProductGroup(TempAttr.GroupId); foreach (WonkaPrdGroupDataRow TempDataRow in TargetGroup) { string sTempValue = TempDataRow[TempAttr.AttrId]; if (String.IsNullOrEmpty(sTempValue)) { TempDataRow.SetData(TempAttr.AttrId, sDefaultAttrValue); } } } } }
/// <summary> /// /// This method will serialize a ProductGroup within a Product instance. /// /// </summary> /// <param name="poTmpPrdGroup">The target ProductGroup being serialized</param> /// <param name="poProductListBuilder">The buffer that is holding the written WONKA-XML message</param> /// <returns>None</returns> private void AppendProductGroup(WonkaPrdGroup poTmpPrdGroup, StringBuilder poProductListBuilder) { WonkaRefEnvironment WonkaRefEnv = WonkaRefEnvironment.GetInstance(); if (poTmpPrdGroup.GetRowCount() > 0) { string sTmpAttrValue = null; foreach (WonkaPrdGroupDataRow TempDataRow in poTmpPrdGroup) { poProductListBuilder.Append("\n <" + poTmpPrdGroup.MasterGroup.GroupName + ">"); foreach (int nTmpAttrId in TempDataRow.Keys) { sTmpAttrValue = TempDataRow[nTmpAttrId]; if (!String.IsNullOrEmpty(sTmpAttrValue)) { WonkaRefAttr TempAttribute = WonkaRefEnv.GetAttributeByAttrId(nTmpAttrId); poProductListBuilder.Append("\n <" + TempAttribute.AttrName + ">"); poProductListBuilder.Append(WrapWithCData(sTmpAttrValue)); poProductListBuilder.Append("</" + TempAttribute.AttrName + ">"); } } poProductListBuilder.Append("\n </" + poTmpPrdGroup.MasterGroup.GroupName + ">"); } } }
public WonkaProduct GetNewProduct() { WonkaRefEnvironment WkaRefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr NewSalesTransSeqAttr = WkaRefEnv.GetAttributeByAttrName("NewSalesTransSeq"); WonkaRefAttr NewSaleEANAttr = WkaRefEnv.GetAttributeByAttrName("NewSaleEAN"); WonkaRefAttr NewSaleVATRateDenomAttr = WkaRefEnv.GetAttributeByAttrName("NewSaleVATRateDenom"); WonkaRefAttr NewSaleItemTypeAttr = WkaRefEnv.GetAttributeByAttrName("NewSaleItemType"); WonkaRefAttr CountryOfSaleAttr = WkaRefEnv.GetAttributeByAttrName("CountryOfSale"); WonkaRefAttr NewSalePriceAttr = WkaRefEnv.GetAttributeByAttrName("NewSalePrice"); WonkaRefAttr PrevSellTaxAmountAttr = WkaRefEnv.GetAttributeByAttrName("PrevSellTaxAmount"); WonkaRefAttr NewSellTaxAmountAttr = WkaRefEnv.GetAttributeByAttrName("NewSellTaxAmount"); WonkaRefAttr NewVATAmountForHMRCAttr = WkaRefEnv.GetAttributeByAttrName("NewVATAmountForHMRC"); WonkaProduct NewProduct = new WonkaProduct(); NewProduct.SetAttribute(NewSalesTransSeqAttr, "123456789"); NewProduct.SetAttribute(NewSaleEANAttr, "9781234567890"); NewProduct.SetAttribute(NewSaleVATRateDenomAttr, "2"); NewProduct.SetAttribute(NewSaleItemTypeAttr, "Widget"); NewProduct.SetAttribute(CountryOfSaleAttr, "UK"); NewProduct.SetAttribute(NewSalePriceAttr, "200"); NewProduct.SetAttribute(PrevSellTaxAmountAttr, "5"); NewProduct.SetAttribute(NewSellTaxAmountAttr, "0"); NewProduct.SetAttribute(NewVATAmountForHMRCAttr, "0"); return(NewProduct); }
public static void AddNethereumERC20GetBalanceRule(this WonkaBizRuleSet poRuleSet, WonkaRefEnvironment poRefEnv, Web3 poWeb3, WonkaRefAttr poTargetAttr, string psAddRuleDesc, string psTargetOwner, string psERC20ContractAddress) { WonkaBizRule NewRule = null; WonkaBizSource DummySource = new WonkaBizSource("ERC20", psERC20ContractAddress, "", "", "", "", "", null); WonkaEthCustomOpRule CustomOpRule = new WonkaEthCustomOpRule(mnRuleCounter++, TARGET_RECORD.TRID_NEW_RECORD, poTargetAttr.AttrId, CONST_ERC20_GET_BALANCE_OP, null, DummySource); CustomOpRule.OwnerWeb3 = poWeb3; CustomOpRule.PrimaryContractAddress = psERC20ContractAddress; CustomOpRule.CustomOpDelegate = CustomOpRule.InvokeERC20GetBalance; CustomOpRule.AddDomainValue(psTargetOwner, true, TARGET_RECORD.TRID_NONE); if (!String.IsNullOrEmpty(psAddRuleDesc)) { NewRule.DescRuleId = psAddRuleDesc; } poRuleSet.AddRule(NewRule); }
static void Main(string[] args) { var ownerAddress = "0x12890d2cce102216644c59daE5baed380d84830c"; var password = "******"; var destinationAddress = "0x6C547791C3573c2093d81b919350DB1094707011"; var web3 = GetWeb3(ownerAddress, password, CONST_ONLINE_TEST_CHAIN_URL); var erc20TokenDeployment = new ERC20TokenDeployment() { DecimalUnits = 18, TokenName = "TST", TokenSymbol = "TST", InitialAmount = Web3.Convert.ToWei(10000) }; //Deploy our custom token var tokenDeploymentReceipt = ERC20TokenService.DeployContractAndWaitForReceiptAsync(web3, erc20TokenDeployment).Result; //Creating a new service var tokenService = new ERC20TokenService(web3, tokenDeploymentReceipt.ContractAddress); //Creating the rules engine, using the default set of rules var wonkaERC20Service = new WonkaERC20Service(ownerAddress, password, tokenDeploymentReceipt.ContractAddress, new StringBuilder(CONST_WONKA_DEFI_RULES), new WonkaDeFiDefaultMetadata(), null, false, CONST_ONLINE_TEST_CHAIN_URL); var RefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr OwnerAddressAttr = RefEnv.GetAttributeByAttrName("OwnerAddress"); WonkaRefAttr VaultAddressAttr = RefEnv.GetAttributeByAttrName("VaultAddress"); WonkaRefAttr TokenTrxAmtAttr = RefEnv.GetAttributeByAttrName("TokenTransferAmt"); WonkaRefAttr VaultYieldRateAttr = RefEnv.GetAttributeByAttrName("VaultYieldRate"); var trxData = new WonkaProduct(); trxData.SetAttribute(OwnerAddressAttr, ownerAddress); trxData.SetAttribute(VaultAddressAttr, destinationAddress); trxData.SetAttribute(TokenTrxAmtAttr, "12"); // Must specify the amount in hex form var currentBalance = tokenService.BalanceOfQueryAsync(ownerAddress).Result; for (int i = 0; (i < 1000) && (currentBalance.CompareTo(0) > 0); ++i) { trxData.SetAttribute(VaultYieldRateAttr, GetCurrentInterestRate()); wonkaERC20Service.Execute(trxData); currentBalance = tokenService.BalanceOfQueryAsync(ownerAddress).Result; var vaultBalance = tokenService.BalanceOfQueryAsync(destinationAddress).Result; Thread.Sleep(5000); } }
public string RetrieveValueMethod(WonkaBre.RuleTree.WonkaBreSource poTargetSource, string psAttrName) { WonkaRefEnvironment WkaRefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr TargetAttr = WkaRefEnv.GetAttributeByAttrName(psAttrName); return(moProduct.GetAttributeValue(TargetAttr)); }
public void SetAttribute(WonkaProduct poTargetProduct, WonkaRefAttr poTargetAttr, string psTargetValue) { if (poTargetProduct.GetProductGroup(poTargetAttr.GroupId).GetRowCount() <= 0) { poTargetProduct.GetProductGroup(poTargetAttr.GroupId).AppendRow(); } poTargetProduct.GetProductGroup(poTargetAttr.GroupId)[0][poTargetAttr.AttrId] = psTargetValue; }
public IMetadataRetrievable ImportSource(Type poDataStructType, object poDataStructure = null) { WonkaImportSource NewImportSource = new WonkaImportSource(); PropertyInfo[] Props = poDataStructType.GetProperties(); foreach (PropertyInfo TmpProperty in Props) { Type AttrType = TmpProperty.PropertyType; string sAttrName = TmpProperty.Name; WonkaRefAttr TmpWonkaAttr = new WonkaRefAttr(); TmpWonkaAttr.AttrId = GenerateNewAttrId(); TmpWonkaAttr.AttrName = sAttrName; TmpWonkaAttr.ColName = sAttrName; TmpWonkaAttr.TabName = poDataStructType.FullName; if (poDataStructure != null) { object oTmpValue = TmpProperty.GetValue(poDataStructure); TmpWonkaAttr.DefaultValue = Convert.ToString(oTmpValue); } TmpWonkaAttr.Description = ""; TmpWonkaAttr.IsDate = IsTypeDate(AttrType.Name); TmpWonkaAttr.IsNumeric = IsTypeNumeric(AttrType.Name); TmpWonkaAttr.IsDecimal = IsTypeDecimal(AttrType.Name); // NOTE: These values are simply defaults and have no real meaning if (TmpWonkaAttr.IsNumeric) { TmpWonkaAttr.Precision = 9; TmpWonkaAttr.Scale = 0; } else if (TmpWonkaAttr.IsDecimal) { TmpWonkaAttr.Precision = 9; TmpWonkaAttr.Scale = 9; } // TmpWonkaAttr.MaxLength = ?; TmpWonkaAttr.FieldId = TmpWonkaAttr.AttrId + 1000; TmpWonkaAttr.GroupId = CONST_DEFAULT_GROUP_ID; TmpWonkaAttr.IsAudited = true; TmpWonkaAttr.IsKey = (TmpWonkaAttr.AttrName.EndsWith("ID") || TmpWonkaAttr.AttrName.EndsWith("Id")); NewImportSource.AddAttribute(TmpWonkaAttr); } return(NewImportSource); }
/// <summary> /// /// This method will update the contents of a row (at index 'pnRowIndex') with the values from the supplied DataRow /// (via matching on the key), but only for the Attributes of a given Field. In addition, if any Attribute inside /// the updated Field has an associated AttrModDt, we will set that Attribute with the timestamp of CurrTimeStamp. /// /// NOTE: This code assumes that only 1 AttrModDt will be updated per call of updateField(...) /// /// <param name="poThatGroup">The Group that we are using to update this one</param> /// <param name="poTargetField">The Field that possesses the Attribute list of interest</param> /// <param name="psCurrTimeStamp">The current Timestamp that we will use to set any associated AttrModDdt</param> /// <returns>The AttrID of the AttrModDt which has been updated with the CurrTimeStamp</returns> /// </summary> public int UpdateField(WonkaPrdGroup poThatGroup, WonkaRefCadre poTargetField, string psCurrTimeStamp = null) { int nUpdatedModDtAttrId = 0; HashSet <int> FieldAttrIds = WonkaRefEnvironment.GetInstance().GetAttrIdsByFieldId(poTargetField.CadreId); string sTimeStamp = (!String.IsNullOrEmpty(psCurrTimeStamp)) ? psCurrTimeStamp : DateTime.Now.ToString("yyyyMMddHHmmss"); foreach (WonkaPrdGroupDataRow ThatRow in poThatGroup) { WonkaPrdGroupDataRow ThisRow = (this.GetRowIndex(ThatRow.GetKey()) >= 0) ? this.GetRow(ThatRow.GetKey()) : AppendRow(); foreach (int nTempAttrId in FieldAttrIds) { string sThatValue = ThatRow[nTempAttrId]; if (!String.IsNullOrEmpty(sThatValue)) { WonkaRefAttr TempAttr = WonkaRefEnvironment.GetInstance().GetAttributeByAttrId(nTempAttrId); ThisRow[nTempAttrId] = sThatValue; if (TempAttr.AttrModDtFlag) { try { WonkaRefAttr TempAttrModDt = WonkaRefEnvironment.GetInstance().GetAttributeByAttrName(TempAttr.AttrModDt); string sThatAttrModDtValue = ThatRow[TempAttrModDt.AttrId]; // NOTE: We will only use the CurrentTimestamp if there isn't already a timestamp value // in the provided DataRow of ThatGroup if (String.IsNullOrEmpty(sThatAttrModDtValue)) { ThisRow[TempAttrModDt.AttrId] = sTimeStamp; if (nUpdatedModDtAttrId == 0) { nUpdatedModDtAttrId = TempAttrModDt.AttrId; } } } catch (Exception ex) { throw new Exception("ERROR! Cannot set the ATTR_MOD_DT sibling (" + TempAttr.AttrModDt + ") for ATTRIBUTE (" + TempAttr.AttrName + ")."); } } } } } return(nUpdatedModDtAttrId); }
public WonkaPrdException(WonkaRefAttr poAttribute, string psErrorMessage) { if (poAttribute == null) { throw new Exception("Provided Attribute is null!"); } AttrId = poAttribute.AttrId; Msg = psErrorMessage; }
/// <summary> /// /// This method will compare two values of the same Attribute type. It will then use the /// Attribute information to help determine if the two values are the same. For example, /// if the Attribute metadata specifies that they're decimal values, then they will be /// converted to Decimal types and then compared that way. /// /// <param name="poAttr">The Attribute type of the two values</param> /// <param name="psThisValue">The left-hand value being compared</param> /// <param name="psThatValue">The right-hand value being compared</param> /// <returns>The bool indicating whether or not the two values are actually the same</returns> /// /// </summary> public bool Compare(WonkaRefAttr poAttr, string psThisValue, string psThatValue) { bool bResult = true; if (!String.IsNullOrEmpty(psThisValue) && String.IsNullOrEmpty(psThatValue)) { bResult = false; } else if (poAttr.IsNumeric) { if (poAttr.IsDecimal) { try { // NOTE: Do we need to do any rounding here? decimal fThisValue = Convert.ToDecimal(psThisValue); decimal fThatValue = Convert.ToDecimal(psThatValue); if (fThisValue != fThatValue) { bResult = false; } } catch (Exception ex) { bResult = false; } } else { try { // NOTE: Do we need to do any rounding here? long nThisValue = Convert.ToInt64(psThisValue); long nThatValue = Convert.ToInt64(psThatValue); if (nThisValue != nThatValue) { bResult = false; } } catch (Exception ex) { bResult = false; } } } else { bResult = false; } return(bResult); }
private WonkaProduct AssembleProduct(Dictionary <string, string> poAttrData) { var NewProduct = new Wonka.Product.WonkaProduct(); foreach (string sTmpAttrName in poAttrData.Keys) { WonkaRefAttr TargetAttr = refEnvHandle.GetAttributeByAttrName(sTmpAttrName); NewProduct.SetAttribute(TargetAttr, poAttrData[sTmpAttrName]); } return(NewProduct); }
public static bool SetAttribute(this WonkaProduct poTargetProduct, WonkaRefAttr poTargetAttr, string psTargetValue) { bool bSuccess = true; if (poTargetProduct.GetProductGroup(poTargetAttr.GroupId).GetRowCount() <= 0) { poTargetProduct.GetProductGroup(poTargetAttr.GroupId).AppendRow(); } poTargetProduct.GetProductGroup(poTargetAttr.GroupId)[0][poTargetAttr.AttrId] = psTargetValue; return(bSuccess); }
/// <summary> /// /// This method will compare two Groups to see if they are equal, but it will /// only compare those Attributes mentioned in the target Field. /// /// NOTE: The auditing containers 'poThisAttrValues' and 'poThatAttrValues' will only /// work correctly with a group that only has one row. /// /// <param name="poThatGroup">The group being compared against (usually representing old data from the DB)</param> /// <param name="poTargetField">The Field that has the Attribute list of interest</param> /// <param name="poIgnoreAttrIds">The list of Attributes that should be ignored when comparisons are done</param> /// <param name="poThisAttrValues">Storage for the values different from "this" group</param> /// <param name="poThatAttrValues">Storage for the values different from "that" group</param> /// <returns>Bool that indicates whether or not the two Groups are equal</returns> /// </summary> public bool Equals(WonkaPrdGroup poThatGroup, WonkaRefCadre poTargetField, HashSet <int> poIgnoreAttrIds, Dictionary <int, string> poNewAttrValues, Dictionary <int, string> poOldAttrValues) { bool bResult = true; foreach (WonkaPrdGroupDataRow ThisRow in this.DataRowVector) { int nThatRowIndex = poThatGroup.GetRowIndex(ThisRow.GetKey()); if (nThatRowIndex != -1) { WonkaPrdGroupDataRow ThatRow = poThatGroup[nThatRowIndex]; HashSet <int> FieldAttrIds = WonkaRefEnvironment.GetInstance().GetAttrIdsByFieldId(poTargetField.CadreId); foreach (int nAttrId in FieldAttrIds) { WonkaRefAttr TempAttr = WonkaRefEnvironment.GetInstance().GetAttributeByAttrId(nAttrId); if (poIgnoreAttrIds.Contains(nAttrId)) { continue; } if (poTargetField.MergeNullAttrFlag || !String.IsNullOrEmpty(ThisRow[nAttrId])) { string sThisValue = ThisRow[nAttrId]; string sThatValue = ThatRow[nAttrId]; if (sThisValue != sThatValue) { // NOTE: Need to record these values, maybe for auditing if (TempAttr.IsAudited) { poNewAttrValues[TempAttr.AttrId] = sThisValue; poOldAttrValues[TempAttr.AttrId] = sThatValue; } bResult = Compare(TempAttr, sThisValue, sThatValue); } } } } } return(bResult); }
public WonkaSimpleNethereumTest(string psSenderAddress, string psPassword, string psContractAddress) { msSenderAddress = psSenderAddress; msPassword = psPassword; msContractAddress = psContractAddress; // Create an instance of the class that will provide us with PmdRefAttributes (i.e., the data domain) // that define our data records moMetadataSource = new WonkaMetadataTestSource(); var TmpAssembly = Assembly.GetExecutingAssembly(); // Read the ABI of the Ethereum contract which holds our old (i.e., existing) data record using (var AbiReader = new StreamReader(TmpAssembly.GetManifestResourceStream("WonkaSystem.TestData.WonkaEngine.abi"))) { msAbiWonka = AbiReader.ReadToEnd(); } // Read the bytecodes of the Ethereum contract which holds our old (i.e., existing) data record using (var ByteCodeReader = new StreamReader(TmpAssembly.GetManifestResourceStream("WonkaSystem.TestData.WonkaEngine.bin"))) { msByteCodeWonka = ByteCodeReader.ReadToEnd(); } // Read the XML markup that lists the business rules using (var RulesReader = new StreamReader(TmpAssembly.GetManifestResourceStream("WonkaSystem.TestData.SimpleAccountCheck.xml"))) { msRulesContents = RulesReader.ReadToEnd(); } // Using the metadata source, we create an instance of a defined data domain WonkaRefEnvironment WonkaRefEnv = WonkaRefEnvironment.CreateInstance(false, moMetadataSource); WonkaRefAttr AccountIDAttr = WonkaRefEnv.GetAttributeByAttrName("BankAccountID"); WonkaRefAttr AccountNameAttr = WonkaRefEnv.GetAttributeByAttrName("BankAccountName"); WonkaRefAttr AccountStsAttr = WonkaRefEnv.GetAttributeByAttrName("AccountStatus"); WonkaRefAttr AccountCurrValAttr = WonkaRefEnv.GetAttributeByAttrName("AccountCurrValue"); WonkaRefAttr AccountTypeAttr = WonkaRefEnv.GetAttributeByAttrName("AccountType"); WonkaRefAttr AccountCurrencyAttr = WonkaRefEnv.GetAttributeByAttrName("AccountCurrency"); // We create a target list of the Attributes of the old (i.e., existing) record that currently exists on the blockchain // and which we want to pull back during the engine's execution moTargetAttrList = new List <WonkaRefAttr>(); moTargetAttrList = new List <WonkaRefAttr>() { AccountIDAttr, AccountNameAttr, AccountStsAttr, AccountCurrValAttr, AccountTypeAttr, AccountCurrencyAttr }; }
public static string GetAttributeValue(this WonkaProduct poTargetProduct, WonkaRefAttr poTargetAttr) { string sAttrValue = ""; if (poTargetProduct.HasProductGroup(poTargetAttr.GroupId)) { if (poTargetProduct.GetProductGroup(poTargetAttr.GroupId)[0].ContainsKey(poTargetAttr.AttrId)) { sAttrValue = poTargetProduct.GetProductGroup(poTargetAttr.GroupId)[0][poTargetAttr.AttrId]; } } return(sAttrValue); }
private void Init(T poCommand, OrchestrationInitData poOrchInitData) { WonkaRefEnvironment WonkaRefEnv = null; if (poOrchInitData == null) { throw new WonkaOrchestratorException("ERROR! Initialization for orchestration has not been provided."); } if (poOrchInitData.AttributesMetadataSource == null) { throw new WonkaOrchestratorException("ERROR! Initialization data for metadata retrieval has not been provided."); } if ((poOrchInitData.BlockchainDataSources == null) || (poOrchInitData.BlockchainDataSources.Count == 0)) { if (poOrchInitData.DefaultBlockchainDataSource != null) { Dictionary <string, WonkaBizSource> BlockchainDataSources = new Dictionary <string, WonkaBizSource>(); Dictionary <PropertyInfo, WonkaRefAttr> PropMap = poCommand.GetPropertyMap(); // Set Commentary Attributes foreach (PropertyInfo TmpProperty in PropMap.Keys) { WonkaRefAttr TempAttr = PropMap[TmpProperty]; BlockchainDataSources[TempAttr.AttrName] = poOrchInitData.DefaultBlockchainDataSource; } poOrchInitData.BlockchainDataSources = BlockchainDataSources; } } if ((poOrchInitData.BlockchainDataSources == null) || (poOrchInitData.BlockchainDataSources.Count == 0)) { throw new WonkaOrchestratorException("ERROR! Initialization for data retrieval metadata has not been provided."); } try { WonkaRefEnv = WonkaRefEnvironment.GetInstance(); } catch (Exception ex) { WonkaRefEnv = WonkaRefEnvironment.CreateInstance(false, poOrchInitData.AttributesMetadataSource); // NOTE: Should/could contract be deployed here along with metadata (i.e., Attributes)? } }
public async void ShouldInvokeERC20WonkaService() { var ownerAddress = "0x12890d2cce102216644c59daE5baed380d84830c"; var destinationAddress = "0x6C547791C3573c2093d81b919350DB1094707011"; //Using ropsten infura if wanted for only a tests //var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Ropsten); var web3 = _ethereumClientIntegrationFixture.GetWeb3(); var erc20TokenDeployment = new ERC20TokenDeployment() { DecimalUnits = 18, TokenName = "TST", TokenSymbol = "TST", InitialAmount = Web3.Convert.ToWei(10000) }; //Deploy our custom token var tokenDeploymentReceipt = await ERC20TokenService.DeployContractAndWaitForReceiptAsync(web3, erc20TokenDeployment); //Creating a new service var tokenService = new ERC20TokenService(web3, tokenDeploymentReceipt.ContractAddress); //Creating the rules engine, using the default set of rules var wonkaERC20Service = new WonkaERC20Service("0x12890d2cce102216644c59daE5baed380d84830c", "0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7", tokenDeploymentReceipt.ContractAddress); var RefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr OwnerAddressAttr = RefEnv.GetAttributeByAttrName("OwnerAddress"); WonkaRefAttr VaultAddressAttr = RefEnv.GetAttributeByAttrName("VaultAddress"); WonkaRefAttr TokenTrxAmtAttr = RefEnv.GetAttributeByAttrName("TokenTransferAmt"); var trxData = new WonkaProduct(); trxData.SetAttribute(OwnerAddressAttr, ownerAddress); trxData.SetAttribute(VaultAddressAttr, destinationAddress); trxData.SetAttribute(TokenTrxAmtAttr, "12"); // Must specify the amount in hex form var ownerBalance = await tokenService.BalanceOfQueryAsync(ownerAddress); var beforeBalance = await tokenService.BalanceOfQueryAsync(destinationAddress); wonkaERC20Service.Execute(trxData); //validate the current balance (in decimal form) var afterBalance = await tokenService.BalanceOfQueryAsync(destinationAddress); Assert.Equal(18, afterBalance); }
public WonkaPrdGroupDataRow(WonkaRefGroup poGroup, Dictionary <string, string> poDataRow) : this(poGroup) { if ((poDataRow != null) && (poDataRow.Count > 0)) { foreach (string sTmpAttrName in poDataRow.Keys) { string sTmpValue = poDataRow[sTmpAttrName]; WonkaRefAttr TmpAttribute = WonkaRefEnvironment.GetInstance().GetAttributeByAttrName(sTmpAttrName); this[TmpAttribute.AttrId] = sTmpValue; } } }
public List <WonkaRefAttr> GetAttrCache() { List <WonkaRefAttr> AttrCache = new List <WonkaRefAttr>(); XmlSerializer AttrSerializer = new XmlSerializer(typeof(WonkaRefAttr)); XmlNodeList AttrNodeList = moXmlDoc.GetElementsByTagName("Attr"); foreach (XmlNode AttrNode in AttrNodeList) { WonkaRefAttr TempAttr = (WonkaRefAttr)AttrSerializer.Deserialize(new StringReader(AttrNode.OuterXml)); AttrCache.Add(TempAttr); } return(AttrCache); }
public string GetAttributeValue(WonkaProduct poTargetProduct, WonkaRefAttr poTargetAttr) { if (poTargetProduct.GetProductGroup(poTargetAttr.GroupId).GetRowCount() <= 0) { throw new Exception("ERROR! Provided incoming product has empty group."); } string sAttrValue = poTargetProduct.GetProductGroup(poTargetAttr.GroupId)[0][poTargetAttr.AttrId]; if (String.IsNullOrEmpty(sAttrValue)) { throw new Exception("ERROR! Provided incoming product has no value for needed key(" + poTargetAttr.AttrName + ")."); } return(sAttrValue); }
public void Execute() { // Using the metadata source, we create an instance of a defined data domain WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); // To test whether the data domain has been created, we plan on retrieving the value // of the "AccountStatus" Attribute WonkaRefAttr AccountStsAttr = RefEnv.GetAttributeByAttrName("AccountStatus"); // Creating an instance of the rules engine using our rules and the metadata WonkaBreRulesEngine RulesEngine = new WonkaBreRulesEngine(new StringBuilder(msRulesContents), moMetadataSource); // Gets a predefined data record that will be our analog for new data coming into the system WonkaProduct NewProduct = GetNewProduct(); // Check that the data has been populated correctly on the "new" record - also, we will use // it later for comparison purposes string sStatusValueBefore = GetAttributeValue(NewProduct, AccountStsAttr); // Since the rules can reference values from different records (like O.Price for the existing // record's price and N.Price for the new record's price), we need to provide the delegate // that can pull the existing (i.e., old) record from the blockchain using a key RulesEngine.GetCurrentProductDelegate = GetOldProduct; // Validate the new record using our rules engine and its initialized RuleTree WonkaBre.Reporting.WonkaBreRuleTreeReport Report = RulesEngine.Validate(NewProduct); // Now retrieve the AccountStatus value and see if the rules have altered it (which should // not be the case) string sStatusValueAfter = GetAttributeValue(NewProduct, AccountStsAttr); // We will evaluate whether or not any failures of the rules were detected during the engine's execution if (Report.OverallRuleTreeResult == ERR_CD.CD_SUCCESS) { // If successful, we will write the record back into the contract on the blockchain Serialize(NewProduct); } else if (Report.GetRuleSetFailureCount() > 0) { throw new Exception("Oh heavens to Betsy! Something bad happened!"); } else { throw new Exception("What in the world is happening?!"); } }
public RuleTreeReport ExecuteWithReport(WonkaBizRulesEngine poRulesEngine, bool pbValidateWithinTransaction) { WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr CurrValueAttr = RefEnv.GetAttributeByAttrName("AccountCurrValue"); WonkaRefAttr ReviewFlagAttr = RefEnv.GetAttributeByAttrName("AuditReviewFlag"); Dictionary <string, string> PrdKeys = new Dictionary <string, string>(); var contract = GetContract(); var senderAddress = moEthEngineInit.EthSenderAddress; var executeWithReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_EXEC_RPT); RuleTreeReport ruleTreeReport = null; if (pbValidateWithinTransaction) { var FlagSource = poRulesEngine.SourceMap[ReviewFlagAttr.AttrName]; var CurrValSource = poRulesEngine.SourceMap[CurrValueAttr.AttrName]; var executeGetLastReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_GET_LAST_RPT); WonkaProduct OrchContractCurrValues = poRulesEngine.AssembleCurrentProductFromChainSources(new Dictionary <string, string>(), CONST_ONLINE_TEST_CHAIN_URL); // Before invoking the RuleTree, the storage contract should have Review Flag as "" and CurrVal as "999" string sFlagBeforeOrchestrationAssignment = RetrieveValueMethod(FlagSource, ReviewFlagAttr.AttrName); string sValueBeforeOrchestrationAssignment = RetrieveValueMethod(CurrValSource, CurrValueAttr.AttrName); var EthRuleTreeReport = new Wonka.Eth.Extensions.RuleTreeReport(); poRulesEngine.ExecuteOnChain(moEthEngineInit, EthRuleTreeReport); // After invoking the RuleTree, the storage contract should have Review Flag as "???" and CurrVal as "1014" string sFlagAfterOrchestrationAssignment = RetrieveValueMethod(FlagSource, ReviewFlagAttr.AttrName); string sValueAfterOrchestrationAssignment = RetrieveValueMethod(CurrValSource, CurrValueAttr.AttrName); ruleTreeReport = executeGetLastReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>().Result; } else { ruleTreeReport = executeWithReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>(senderAddress).Result; } return(ruleTreeReport); }
public async Task <RuleTreeReport> ExecuteWithReportAsync(WonkaBizRulesEngine poRulesEngine, bool pbValidateWithinTransaction) { WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr CurrValueAttr = RefEnv.GetAttributeByAttrName("AccountCurrValue"); WonkaRefAttr ReviewFlagAttr = RefEnv.GetAttributeByAttrName("AuditReviewFlag"); var contract = GetContract(); var senderAddress = moEthEngineInit.EthSenderAddress; var executeWithReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_EXEC_RPT); RuleTreeReport ruleTreeReport = null; if (pbValidateWithinTransaction) { var FlagSource = poRulesEngine.SourceMap[ReviewFlagAttr.AttrName]; var CurrValSource = poRulesEngine.SourceMap[CurrValueAttr.AttrName]; var executeGetLastReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_GET_LAST_RPT); // Before invoking the RuleTree, the storage contract should have Review Flag as "" and CurrVal as "999" string sFlagBeforeOrchestrationAssignment = await RetrieveValueMethodAsync(FlagSource, ReviewFlagAttr.AttrName).ConfigureAwait(false); string sValueBeforeOrchestrationAssignment = await RetrieveValueMethodAsync(CurrValSource, CurrValueAttr.AttrName).ConfigureAwait(false); var EthRuleTreeReport = new Wonka.Eth.Extensions.RuleTreeReport(); await poRulesEngine.ExecuteOnChainAsync(moEthEngineInit, EthRuleTreeReport).ConfigureAwait(false); // After invoking the RuleTree, the storage contract should have Review Flag as "???" and CurrVal as "1014" string sFlagAfterOrchestrationAssignment = await RetrieveValueMethodAsync(FlagSource, ReviewFlagAttr.AttrName).ConfigureAwait(false); string sValueAfterOrchestrationAssignment = await RetrieveValueMethodAsync(CurrValSource, CurrValueAttr.AttrName).ConfigureAwait(false); ruleTreeReport = await executeGetLastReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>().ConfigureAwait(false); } else { ruleTreeReport = await executeWithReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>(senderAddress).ConfigureAwait(false); } return(ruleTreeReport); }
public bool Execute() { // Using the metadata source, we create an instance of a defined data domain WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); // To test whether the data domain has been created, we plan on retrieving the value // of the "AccountStatus" Attribute WonkaRefAttr AccountStsAttr = RefEnv.GetAttributeByAttrName("AccountStatus"); // This collection represents the product key(s) for the record being sought - for now, // we do not need to specify one Dictionary <string, string> PrdKeys = new Dictionary <string, string>(); // Gets a predefined data record that will be our analog for new data coming into the system WonkaProduct NewProduct = GetNewProduct(); // Check that the data has been populated correctly on the "new" record - also, we will use // it later for comparison purposes string sStatusValueBefore = GetAttributeValue(NewProduct, AccountStsAttr); // Write the product to the contract, which will then be used by the rules engine on the // blockchain during the engine's execution SerializeProduct(NewProduct); /** ** Now execute the rules engine on the blockchain. ** ** NOTE: We are only issuing a call() now when we execute the rules engine, ** since we are only looking to validate here. However, there is a chance ** that sendTransaction() might be used in the future because we wish for ** the rules engine to alter the record. In that case, we might want to ** pull back the record afterwards with a subsequent function call, in order ** to examine the record here. **/ bool bProductIsValid = ExecuteRulesEngineOnTheBlockchain(); // Now we pull back the product from the blockchain WonkaProduct ProductOnBlockchain = GetBlockchainRecord(PrdKeys); // Now retrieve the AccountStatus value and see if the rules have altered it string sStatusValueAfter = GetAttributeValue(NewProduct, AccountStsAttr); return(bProductIsValid); }
public RuleTreeReport ExecuteWithReport(WonkaBreRulesEngine poRulesEngine, bool pbValidateWithinTransaction, WonkaBreSource poFlagSource) { WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr CurrValueAttr = RefEnv.GetAttributeByAttrName("AccountCurrValue"); WonkaRefAttr ReviewFlagAttr = RefEnv.GetAttributeByAttrName("AuditReviewFlag"); Dictionary <string, string> PrdKeys = new Dictionary <string, string>(); var contract = GetContract(); var executeWithReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_EXEC_RPT); RuleTreeReport ruleTreeReport = null; if (pbValidateWithinTransaction) { var executeGetLastReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_GET_LAST_RPT); // NOTE: Caused exception to be thrown // var gas = executeWithReportFunction.EstimateGasAsync(msSenderAddress).Result; var gas = new Nethereum.Hex.HexTypes.HexBigInteger(1000000); WonkaProduct OrchContractCurrValues = poRulesEngine.AssembleCurrentProduct(new Dictionary <string, string>()); string sFlagBeforeOrchestrationAssignment = RetrieveValueMethod(poFlagSource, ReviewFlagAttr.AttrName); string sValueBeforeOrchestrationAssignment = RetrieveValueMethod(poFlagSource, CurrValueAttr.AttrName); var receiptAddAttribute = executeWithReportFunction.SendTransactionAsync(msSenderAddress, gas, null, msSenderAddress).Result; string sFlagAfterOrchestrationAssignment = RetrieveValueMethod(poFlagSource, ReviewFlagAttr.AttrName); string sValueAfterOrchestrationAssignment = RetrieveValueMethod(poFlagSource, CurrValueAttr.AttrName); ruleTreeReport = executeGetLastReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>().Result; } else { ruleTreeReport = executeWithReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>(msSenderAddress).Result; } return(ruleTreeReport); }
/// <summary> /// /// This method will assemble the new product by iterating through each specified source /// and retrieving the data from it. /// /// <param name="poKeyValues">The keys for the product whose data we wish to extract/param> /// <returns>Contains the assembled product data that represents the current product</returns> /// </summary> public WonkaProduct AssembleCurrentProduct(Dictionary <string, string> poKeyValues) { WonkaProduct CurrentProduct = new WonkaProduct(); // NOTE: Do work here if (SourceMap != null) { foreach (string sTmpAttName in SourceMap.Keys) { WonkaBreSource TmpSource = SourceMap[sTmpAttName]; WonkaRefAttr TargetAttr = RefEnvHandle.GetAttributeByAttrName(sTmpAttName); string sTmpValue = TmpSource.RetrievalDelegate.Invoke(TmpSource, TargetAttr.AttrName); CurrentProduct.SetAttribute(TargetAttr, sTmpValue); } } return(CurrentProduct); }
/// <summary> /// /// This method will assemble the new product by iterating through the known Attributes /// and retrieving the data via the Wonka engine on the chain (acting as a proxy). /// /// <param name="poEngineSource">The address that represents the instance on the chain</param> /// <param name="psWeb3Url">The URL for the Ethereum client to which we want to connect</param> /// <returns>Contains the assembled product data that represents the current product</returns> /// </summary> public static WonkaProduct AssembleCurrentProductFromChainWonka(this Wonka.Eth.Init.WonkaEthSource poEngineSource, string psWeb3Url = "") { var RefEnv = WonkaRefEnvironment.GetInstance(); WonkaProduct CurrentProduct = new WonkaProduct(); var AllAttributes = new HashSet <string>(); RefEnv.AttrCache.ForEach(x => AllAttributes.Add(x.AttrName)); var CurrRecordOnChain = poEngineSource.GetAttrValuesViaChainEngine(AllAttributes, psWeb3Url); foreach (string sTmpAttrName in CurrRecordOnChain.Keys) { WonkaRefAttr TargetAttr = RefEnv.GetAttributeByAttrName(sTmpAttrName); CurrentProduct.SetAttribute(TargetAttr, CurrRecordOnChain[sTmpAttrName]); } return(CurrentProduct); }