Inserting some 200 records in Apex? - list

How to insert 200+ records in an object while using List in apex? Do I have to run the loop 200+ times? I inserted 2 records so I run the loop 2 times. Is this approach correct?
public class ContactRecord {
public static void ConRecord(){
List<Contact> InsertContactRecord = new List<Contact>();
for(Integer i=0; i<2;i++){
Contact conobj = new Contact();
conobj.FirstName = 'Rashmi11';
conobj.LastName = 'Kumari';
conobj.Credit_Card__c ='9857-9707-8788';
conobj.Email = 'rashmi11' + '#gmail.com';
InsertContactRecord.Add(conobj);
Contact conobj1 = new Contact();
conobj1.FirstName = 'Saloni11';
conobj1.LastName = 'Mangal';
conobj1.Credit_Card__c ='9316-8767-8005';
conobj1.Email = 'saloni11' + '#gmail.com';
InsertContactRecord.Add(conobj1);
break;
}
if(!InsertContactRecord.isEmpty())
insert InsertContactRecord;

Related

Unit Test for Apex Trigger that Concatenates Fields

I am trying to write a test for a before trigger that takes fields from a custom object and concatenates them into a custom Key__c field.
The trigger works in the Sandbox and now I am trying to get it into production. However, whenever I try and do a System.assert/assertEquals after I create a purchase and perform DML, the value of Key__c always returns null. I am aware I can create a flow/process to do this, but I am trying to solve this with code for my own edification. How can I get the fields to concatenate and return properly in the test? (the commented out asserts are what I have tried so far, and have failed when run)
trigger Composite_Key on Purchases__c (before insert, before update) {
if(Trigger.isBefore)
{
for(Purchases__c purchase : trigger.new)
{
String eventName = String.isBlank(purchase.Event_name__c)?'':purchase.Event_name__c+'-';
String section = String.isBlank(purchase.section__c)?'':purchase.section__c+'-';
String row = String.isBlank(purchase.row__c)?'':purchase.row__c+'-';
String seat = String.isBlank(String.valueOf(purchase.seat__c))?'':String.valueOf(purchase.seat__c)+'-';
String numseats = String.isBlank(String.valueOf(purchase.number_of_seats__c))?'':String.valueOf(purchase.number_of_seats__c)+'-';
String adddatetime = String.isBlank(String.valueOf(purchase.add_datetime__c))?'':String.valueOf(purchase.add_datetime__c);
purchase.Key__c = eventName + section + row + seat + numseats + adddatetime;
}
}
}
#isTest
public class CompositeKeyTest {
public static testMethod void testPurchase() {
//create a purchase to fire the trigger
Purchases__c purchase = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c=1.0,number_of_seats__c='test',add_datetime__c='test');
Insert purchase;
//System.assert(purchases__c.Key__c.getDescribe().getName() == 'testesttest1testtest');
//System.assertEquals('testtesttest1.0testtest',purchase.Key__c);
}
static testMethod void testbulkPurchase(){
List<Purchases__c> purchaseList = new List<Purchases__c>();
for(integer i=0 ; i < 10; i++)
{
Purchases__c purchaserec = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c= i+1.0 ,number_of_seats__c='test',add_datetime__c='test');
purchaseList.add(purchaserec);
}
insert purchaseList;
//System.assertEquals('testtesttest5testtest',purchaseList[4].Key__c,'Key is not Valid');
}
}
You need to requery the records after inserting them to get the updated data from the triggers/database

Performance Issue when retrieving transaction details from Quorum Blockchain

I have experienced performance issue when retrieving transaction details such as transaction originator and transaction recipient
from the Quorum blockchain.
The Javascript For loop and Web3.eth.contract(abi).at(address2).totalTransactions is used to retrieve transaction details and
then append to HTML table.
My performance problem is that the retrieval of few lines of transaction data from Quorum blockchain takes about 30 seconds.
Moreover, I am using web3-quorum#0.1.1 and quorum-js#0.3.0.
$('#get-tran').click(() => {
// Get Tran History
var tranId = 0;
let w2Contract=web3w2.eth.contract(abi).at(address2);
let tottr = w2Contract.totalTransactions();
//Clear the old table content first
$("#t02 tr").remove();
var i=0;
for (i = 0; i <= w2Contract.totalTransactions()-1; i++) {
tranId = i;
let tranHash = w2Contract.transactionIDs(i);
let trDetails1 = w2Contract.transactions(tranHash);
console.log(`Tran details ${trDetails1}`);
console.log(`Tran Detail 1: ${trDetails1[1]}`);
console.log(`Tran Detail 2: ${trDetails1[2]}`);
console.log(`Tran Detail 0: ${trDetails1[0]}`);
var tableRef = document.getElementById('t02').getElementsByTagName('tbody')[0];
// Insert a row at the end of the table
let newRow = tableRef.insertRow(-1);
// Insert a cell in the row at index 0
let newCell = newRow.insertCell(0);
// Append a text node to the cell
let newText = document.createTextNode(`${tranId}`);
newCell.appendChild(newText);
// Insert a cell in the row at index 1
let newCell1 = newRow.insertCell(1);
// Append a text node to the cell
let newText1 = document.createTextNode(`${trDetails1[1]}`);
console.log(`newText1 at index 1 ${newText1}`);
// w2 > w1
if ((trDetails1[1] == '0xf9a2cb34b6b5fd7a2ac0c2e9b2b9406d6daffbd4') &&
(trDetails1[2] == '0x180893a0ec847fa8c92786791348d7d65916acbb')) {
newText1.textContent = 'Stock In'
} else if
(trDetails1[1] == '0x180893a0ec847fa8c92786791348d7d65916acbb') {
newText1.textContent = 'Pier Company'
} else if (trDetails1[1] == '0xf9a2cb34b6b5fd7a2ac0c2e9b2b9406d6daffbd4') {
newText1.textContent = 'Warehouse Company'
}
newCell1.appendChild(newText1);
// Insert a cell in the row at index 2
let newCell2 = newRow.insertCell(2);
// Append a text node to the cell
let newText2 = document.createTextNode(`${trDetails1[2]}`);
console.log(`newText1 at index 2 ${newText1}`);
if (trDetails1[2] == '0xf9a2cb34b6b5fd7a2ac0c2e9b2b9406d6daffbd4') {
newText2.textContent = 'Warehouse Company'
}
if (trDetails1[2] == '0x180893a0ec847fa8c92786791348d7d65916acbb') {
newText2.textContent = 'Pier Company'
}
if (trDetails1[2] == '0xc8f717ba9593dc9d45c4518cf444d2cbd08af24d') {
newText2.textContent = 'Removal'
}
newCell2.appendChild(newText2);
// Insert a cell in the row at index 3
let newCell3 = newRow.insertCell(3);
// Append a text node to the cell
let newText3 = document.createTextNode(`${trDetails1[0]}`);
console.log(`newText3 at index 3 ${newText3}`);
newCell3.appendChild(newText3);
// Insert a cell in the row at index 4
let newCell4 = newRow.insertCell(4);
// Append a text node to the cell
let newText4 = document.createTextNode(`${trDetails1[3]}`);
console.log(`newText1 at index 4 ${newText4}`);
if (trDetails1[3] ) {
newText4.textContent = 'Confirmed'
} else {
newText4.textContent = 'Pending'
}
newCell4.appendChild(newText4);
}
});

how to add extra price to cart programmatically in prestahop 1.7

Am new to prestashop 1.7. I want to add extra cost for customization product on adding to cart in prestashop 1.7. Please any body help me.
add own customization data to cart.
$idProduct = Tools::getValue('pid'); // for me it's always one
$qty=Tools::getValue('qty'); // always add one item
$token = Tools::getValue('token');
$customData_front = Tools::getValue('front_view');
$customData_back = Tools::getValue('back_view');
$customData = Tools::getValue('customdata');
$attribute =Tools::getValue('id_product_attribute')
if (is_null($this->context->cart->id)) {
$this->context->cart->add();
$this->context->cookie->__set('id_cart', $this->context->cart->id);
}
// get cart id if exists
if ($this->context->cookie->id_cart)
{
$cart = new Cart($this->context->cookie->id_cart);
}
// create new cart if needed
if (!isset($cart) OR !$cart->id)
{
$cart = new Cart($this->context->cookie->id_cart);
$cart->id_customer = (int)($this->context->cookie->id_customer);
$cart->id_address_delivery = (int) (Address::getFirstCustomerAddressId($cart->id_customer));
$cart->id_address_invoice = $cart->id_address_delivery;
$cart->id_lang = (int)($this->context->cookie->id_lang);
$cart->id_currency = (int)($this->context->cookie->id_currency);
$cart->id_carrier = 1;
$cart->recyclable = 0;
$cart->gift = 0;
$cart->add();
$this->context->cookie->id_cart = (int)($cart->id);
}
$product = new Product((int)$idProduct);
if ($attribute > 0) {
$minimal_quantity = (int)Attribute::getAttributeMinimalQty($this->id_product_attribute);
} else {
$minimal_quantity = (int)$product->minimal_quantity;
}
// add customizatated text
$check =serialize($customData);
$id_address_delivery = $cart->id_address_delivery;
$customization = $this->context->cart->addTextFieldToProduct((int)($idProduct), 9, Product::CUSTOMIZE_TEXTFIELD, serialize($customData));
$exising_customization = Db::getInstance()->executeS('SELECT id_customization FROM '._DB_PREFIX_.'customized_data ORDER BY id_customization DESC LIMIT 0,1');
$customization = $exising_customization[0]['id_customization'];
Db::getInstance()->execute('UPDATE ps_customization SET in_cart = 1, id_product_attribute = '.$attribute.',id_address_delivery='.$id_address_delivery.',quantity='.$minimal_quantity.' WHERE id_customization = ' .$customization);
// get product to add into cart
$productToAdd = new Product((int)($idProduct), true, (int)($this->context->cookie->id_lang));
$cart->update();
$this->context->cart->updateQty((int)($qty),(int)($idProduct),(int)($attribute),$customization,'up',(int)($id_address_delivery));
$cart->update();
In that I want add additional cost every customization.

How to delete all the items from all tables of Amazon's dynamo db?

Just like backing up all the tables of dynamo db, i also want clear all the tables of my test environment after testing without deleting tables.
We used backup service such a way that we don't want schema structure or java object of table schema as below:
Map<String, AttributeValue> exclusiveStartKey = null;
do {
// Let the rate limiter wait until our desired throughput "recharges"
rateLimiter.acquire(permitsToConsume);
ScanSpec scanSpec = new ScanSpec().withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.withMaxResultSize(25);
if(exclusiveStartKey!=null){
KeyAttribute haskKey = getExclusiveStartHashKey(exclusiveStartKey, keySchema);
KeyAttribute rangeKey = getExclusiveStartRangeKey(exclusiveStartKey, keySchema);
if(rangeKey!=null){
scanSpec.withExclusiveStartKey(haskKey, rangeKey);
}else{
scanSpec.withExclusiveStartKey(haskKey);
}
}
Table table = dynamoDBInstance.getTable(tableName);
ItemCollection<ScanOutcome> response = table.scan(scanSpec);
StringBuffer data = new StringBuffer();
Iterator<Item> iterator = response.iterator();
while (iterator.hasNext()) {
Item item = iterator.next();
data.append(item.toJSON());
data.append("\n");
}
logger.debug("Data read from table: {} ", data.toString());
if(response.getLastLowLevelResult()!=null){
exclusiveStartKey = response.getLastLowLevelResult().getScanResult().getLastEvaluatedKey();
}else{
exclusiveStartKey = null;
}
// Account for the rest of the throughput we consumed,
// now that we know how much that scan request cost
if(response.getTotalConsumedCapacity()!=null){
double consumedCapacity = response.getTotalConsumedCapacity().getCapacityUnits();
if(logger.isDebugEnabled()){
logger.debug("Consumed capacity : " + consumedCapacity);
}
permitsToConsume = (int)(consumedCapacity - 1.0);
if(permitsToConsume <= 0) {
permitsToConsume = 1;
}
}
} while (exclusiveStartKey != null);
is it possible to delete all items without knowing table schema? can we do it using DeleteItemSpec

how to generate fake data using moq for unit test?

I need to generate some data to unit test my repositories. i was using a loop to generate a list of objects, see codes below. I learned moq is a great mocking library, Can I use moq to generate that and how do I do it?
public IQueryable<Category> GetCategories()
{
IList<Category> result = new List<Category>();
for (int i = 1; i <= 2; i++)
{
Category c = new Category();
c.ID = i;
c.Name = "Parent" + i.ToString();
c.ParentID = 0;
for (int x = i*10; x < i*10+5; x++)
{
Category sub = new Category();
sub.ID = x;
sub.Name = "Sub" + x.ToString();
sub.ParentID = i;
result.Add(sub);
}
result.Add(c);
}
return result.AsQueryable<Category>();
}
You can't use Moq to create the data, but you can use AutoFixture:
public IQueryable<Category> GetCategories()
{
return fixture.CreateMany<Category>().AsQueryable();
}
However, this will not give you a hierarchical tree. It will return objects like this:
Object 1:
- ID = 0
- ParentID = 1
Object 2:
- ID = 2
- ParentID = 3
etc.
If you really need to have this hierarchical data, you would need to use the following code:
public IQueryable<Category> GetCategories()
{
var result = new List<Category>();
// Create the parents
var parents = fixture.Build<Category>()
.Without(x => x.ParentID)
.CreateMany());
result.AddRange(parents);
result.AddRange(parents.SelectMany(p => fixture.Build<Category>()
.With(x => x.ParentID, p.ID)
.CreateMany()));
return result.AsQueryable();
}
This will add multiple parents with multiple subs for each parent.
You can use faker.net to generate fake data. for Example: for dotnet core project its Faker.NETCore.
dotnet add package Faker.NETCore -v 1.0.1
and then use the same in your code in the following manner:-
public void GetStudent()
{
var st = new Student()
st.FirstName = Faker.Name.First();
st.LastName = Faker.Name.Last();
st.Mobile = Faker.Phone.Number();
}