I have multiple sortorder's list in an controller for 3 pages however when i sort on a table not in an index page. I am returned to the Index Page.
I thought changing the sortorder naming to make it different would work.
public async Task<ActionResult> DashBoard(string sortOrder, string currentFilter,string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var clinicalAssets = from s in db.ClinicalAssets.Include(c => c.ModelName) select s;
if (!String.IsNullOrEmpty(searchString))
{
clinicalAssets = clinicalAssets.Where(s => s.SerialNo.Contains(searchString)
|| s.PoNo.Contains(searchString));
}
switch (sortOrder)
{
case "name_desc":
clinicalAssets = clinicalAssets.OrderByDescending(s => s.PoNo);
break;
case "Date":
clinicalAssets = clinicalAssets.OrderBy(s => s.PurchaseDate);
break;
case "date_desc":
clinicalAssets = clinicalAssets.OrderByDescending(s => s.WarrantyEndDate);
break;
default:
clinicalAssets = clinicalAssets.OrderBy(s => s.ClinicalAssetID);
break;
}
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(await clinicalAssets.ToPagedListAsync(pageNumber, pageSize));
}
public async Task<ActionResult> Arjo(string sortOrder2, string currentFilter2, string searchString2, int? page)
{
ViewBag.CurrentSort = sortOrder2;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder2) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder2 == "Date" ? "date_desc" : "Date";
if (searchString2 != null)
{
page = 1;
}
else
{
}
ViewBag.CurrentFilter = searchString2;
var clinicalAssets = from s in db.ClinicalAssets
where (s.AssetTypeID.Equals (2) || s.AssetTypeID.Equals(3) )
select s;
if (!String.IsNullOrEmpty(searchString2))
{
clinicalAssets = clinicalAssets.Where(s => s.SerialNo.Contains(searchString2)
|| s.PoNo.Contains(searchString2));
}
switch (sortOrder2)
{
case "name_desc":
clinicalAssets = clinicalAssets.OrderByDescending(s => s.PoNo);
break;
case "Date":
clinicalAssets = clinicalAssets.OrderBy(s => s.PurchaseDate);
break;
case "date_desc":
clinicalAssets = clinicalAssets.OrderByDescending(s => s.WarrantyEndDate);
break;
default:
clinicalAssets = clinicalAssets.OrderBy(s => s.ClinicalAssetID);
break;
}
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(await clinicalAssets.ToPagedListAsync(pageNumber, pageSize));
}
public async Task<ActionResult> Index(string sortOrder1, string currentFilter1, string searchString1, int? page)
{
ViewBag.CurrentSort = sortOrder1;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder1) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder1 == "Date" ? "date_desc" : "Date";
if (searchString1 != null)
{
page = 1;
}
else
{
searchString1 = currentFilter1;
}
ViewBag.CurrentFilter = searchString1;
var clinicalAssets = from s in db.ClinicalAssets.Include(c => c.ModelName) select s;
if (!String.IsNullOrEmpty(searchString1))
{
clinicalAssets = clinicalAssets.Where(s => s.SerialNo.Contains(searchString1)
|| s.PoNo.Contains(searchString1));
}
switch (sortOrder1)
{
case "name_desc":
clinicalAssets = clinicalAssets.OrderByDescending(s => s.PoNo);
break;
case "Date":
clinicalAssets = clinicalAssets.OrderBy(s => s.PurchaseDate);
break;
case "date_desc":
clinicalAssets = clinicalAssets.OrderByDescending(s => s.WarrantyEndDate);
break;
default:
clinicalAssets = clinicalAssets.OrderBy(s => s.ClinicalAssetID);
break;
}
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(await clinicalAssets.ToPagedListAsync(pageNumber, pageSize));
}
I would have expected to see each page filter its own table not tables of other pages.
I was on the right track, i also needed to update the #html.Actionlink and the sortParm.
public async Task<ActionResult> Index(string sortOrder1, string currentFilter1, string searchString1, int? page1)
{
ViewBag.CurrentSort1 = sortOrder1;
ViewBag.NameSortParm1 = String.IsNullOrEmpty(sortOrder1) ? "name_desc" : "";
ViewBag.DateSortParm1 = sortOrder1 == "Date" ? "date_desc" : "Date";
if (searchString1 != null)
{
page1 = 1;
}
else
{
searchString1 = currentFilter1;
}
ViewBag.CurrentFilter1 = searchString1;
var clinicalAssets = from s in db.ClinicalAssets.Include(c => c.ModelName) select s;
if (!String.IsNullOrEmpty(searchString1))
{
clinicalAssets = clinicalAssets.Where(s => s.SerialNo.Contains(searchString1)
|| s.PoNo.Contains(searchString1));
}
switch (sortOrder1)
{
case "name_desc":
clinicalAssets = clinicalAssets.OrderByDescending(s => s.PoNo);
break;
case "Date":
clinicalAssets = clinicalAssets.OrderBy(s => s.PurchaseDate);
break;
case "date_desc":
clinicalAssets = clinicalAssets.OrderByDescending(s => s.WarrantyEndDate);
break;
default:
clinicalAssets = clinicalAssets.OrderBy(s => s.ClinicalAssetID);
break;
}
int pageSize = 10;
int pageNumber = (page1 ?? 1);
return View(await clinicalAssets.ToPagedListAsync(pageNumber, pageSize));
}
Related
public class Login : MonoBehaviour
{
[SerializeField] private string authenticationEndpoint = "http://146.190.226.27/api/login";
[SerializeField] private TMP_InputField usernameInputField;
[SerializeField] private TMP_InputField passwordInputField;
[SerializeField] private TextMeshProUGUI alertText;
[SerializeField] private Button loginButton;
public void OnLoginClick()
{
alertText.text = "Signing In...";
loginButton.interactable = false;
StartCoroutine(TryLogin());
}
private IEnumerator TryLogin()
{
string email = usernameInputField.text;
string password = passwordInputField.text;
if(email.Length < 15 || email.Length > 24)
{
alertText.text = "Invalid Username";
loginButton.interactable = true;
yield break;
}
if(password.Length < 3 || password.Length > 24)
{
alertText.text = "Invalid Password";
loginButton.interactable = true;
yield break;
}
else
{
alertText.text = "Locale is Required";
//Debug.Log("Locale is Required");
loginButton.interactable = true;
}
WWWForm form = new WWWForm();
form.AddField("email", email);
form.AddField("password", password);
UnityWebRequest request = UnityWebRequest.Post(authenticationEndpoint,form);
var handler = request.SendWebRequest();
float startTime = 0.0f;
while (!handler.isDone)
{
startTime += Time.deltaTime;
if(startTime > 10.0f)
{
break;
}
yield return null;
}
if(request.result == UnityWebRequest.Result.Success)
{
if (request.downloadHandler.text != "Invalid Credentials")
{
alertText.text = "Welcome";
loginButton.interactable = false;
}
else
{
alertText.text = "Invalid Credentials";
loginButton.interactable = true;
}
}
//Debug.Log($"{username}:{password}");
yield return null;
}
}
here is my code i have no idea how to call header or pass in unity here is API in json format
{
"msg": "Locale is required",
"data": {}
}
I need to test a function that requires the response as argument, I'm using mocha and sequelize in node environment with express framework. My code is scaffolded in multiple files, but I need to test only the superactivator istance. These are my files:
route.js
const express = require('express');
const router = express.Router();
const rcv_pcController = require('../controllers/rcv_pc.controller');
router.post('/', rcv_pcController.switchMode);
module.exports = router;
rcv_pc.controller.js
const superActivator = require('../helpers/superactivator');
...
const switchMode = async (req, res) => {
...
switch (tipo) {
case "1":
{
if (modo == "1") {
superActivator.checkLicense(license, hwId, oem, expire, nowDate, ip, allowedSerials, res)
}
else if (modo == "2") {
superActivator.generateLicense(license, hwId, reqCode, nowDate, ip, res);
}
else if (modo == "3") {
superActivator.registerLicense(license, hwId, reqCode, nowDate, customerName, referenteName, referentePhone, ip, res)
}
break;
}
}
}
module.exports.switchMode = switchMode;
superactivator.js
const pcRepo = require("../repositories/pc.server.repository");
const repository = require('../repositories/rcvpc.server.repository');
...
class SuperActivator {
...
checkLicense(license, hwId, oem, expDate, nowDate, ip, allowedSerials, res) {
repository.findLicense(license).then(key => {
// console.log(key[0]);
if (key[0]) {
if (!isset(key[0]['SS_ALLOWED_SERIALS']) || is_null(key[0]['SS_ALLOWED_SERIALS'])) {
key[0]['SS_ALLOWED_SERIALS'] = "";
}
if (this.updatePcRx(hwId, ip, nowDate) == 0) {
return res.send(this.licCheckResult.server_error);
}
if (this.checksetBanned(hwId) == 0) {
return res.send(this.licCheckResult.hwid_banned);
}
if (!isset(key[0]['SP_HW_ID'])) {
return res.send(this.licCheckResult.key_virgin);
}
if (key[0]['SS_STATUS'] < 1) {
return res.send(this.licCheckResult.key_unallowed);
}
if (key[0]['SP_HW_ID'] != hwId) {
if (this.setKeyMismatched(key[0]['SS_ID']) == 1) {
return res.send(this.licCheckResult.key_moved);
}
}
if ((strtotime(key[0]['SS_EXPIRE']) < strtotime(expDate))
|| (strtotime(nowDate) < strtotime(key[0]['SP_PC_DATE_TIME']))
|| (strtotime(nowDate) < time() - 60 * 60 * 24 * 2)) {
if (this.setKeyMismatched(key[0]['SS_ID']) == 1) {
return res.send(this.licCheckResult.dates_hacked);
} else {
return res.send(this.licCheckResult.server_error);
}
}
if ((key[0]['SS_OEM'] != oem)
|| (strtotime(key[0]['SS_EXPIRE']) > strtotime(expDate) || strcmp(key[0]['SS_ALLOWED_SERIALS'], this.decodeToMortal(allowedSerials)) != 0)) {
return res.send(this.licCheckResult.key_info_to_update);
}
if (strtotime(key[0]['SS_EXPIRE']) <= strtotime(nowDate)) {
return res.send(this.licCheckResult.key_expired);
}
return res.send(this.licCheckResult.key_ok);
} else {
return res.send(this.licCheckResult.key_insesistente);
}
}).catch(err => res.send(err.errors));
}
generateLicense(license, hwId, reqCode, nowDate, ip, res) {
pcRepo.updatePcRx(hwId, ip, nowDate);
repository.findOem(license, hwId)
.then((foundOem) => {
if (foundOem[0]) {
const keyCode = this.generateValidKey(this.decodeToMortal(reqCode));
let patchKey = keyCode;
if (keyCode.length != 10 || this.checkValidKey(keyCode, patchKey) == 'KO') {
return res.send(this.licCheckResult.invalid_reqcode);
} else {
let oem = '';
switch (foundOem[0]['SS_OEM']) {
case 0:
oem = 'thisisnotoem'
break;
case 1:
oem = 'thisisoem'
break;
case 2:
oem = 'thisisoemdoc'
break;
case 3:
oem = 'thisislock'
break;
case 10:
oem = 'thisisnotoem_lecu'
break;
case 11:
oem = 'thisisdemo_lecu'
break;
case 12:
oem = 'thisisoem_lecu'
break;
}
const keepDate = str_replace('-', "", foundOem[0]['SS_EXPIRE'])
const allowedSerials = this.getAllowedSerials(foundOem[0]['SS_ID'])
console.log(allowedSerials);
const key =
this.codeToGod(keyCode) + '|'
+ this.codeToGod(patchKey) + '|'
+ this.codeToGod(oem) + '|'
+ this.codeToGod(keepDate) + '|'
+ this.codeToGod(allowedSerials);
// console.log(key);
return res.send(key);
}
} else {
return res.send(this.licCheckResult.key_insesistente);
}
}).catch(err => res.send(err.errors));
}
registerLicense(license, hwId, reqKey, pcDate, customerName, referenteName, referentePhone, ip, res) {
pcRepo.findOne(hwId)
.then((pc) => {
let pcId = '';
if (!pc) {
const data = {
SP_HW_ID: hwId,
SP_LAST_RX: Date.now(),
SP_IP: ip,
SP_PC_DATE_TIME: new Date().toISOString().slice(0, 10)
}
pcRepo.create(data)
.then((newPc) => {
if (!newPc) {
return res.send(this.licCheckResult.server_error);
}
return pcId = newPc['SP_ID']
}).catch(err => res.send(err.errors));
} else {
pcId = pc['SP_ID']
}
console.log(pcId);
if (isset(pcId) || pcId.length == 0 || pcId == 0) {
return res.send(this.licCheckResult.server_error);
}
repository.updateLicense(pcId, customerName, referenteName, referentePhone, license)
.spread((results, metadata) => {
if (!results) {
return res.send(this.licCheckResult.server_error);
}
return this.generateLicense(license, hwId, reqKey, pcDate, ip, res);
}).catch(err => res.send(err.errors))
}).catch(err => res.send(err.errors));
}
}
...
const superActivator = new SuperActivator(licCheckResult);
module.exports = superActivator;
For the sake of clarity I omit all the Superactivator class methods. This is my test code:
superactivator.spec.js
...
const superactivator = require('../helpers/superactivator');
...
describe('checkLicense()', function () {
it('sks ', async function () {
// here I mock the request.body data
const ip = '127.0.0.1';
const license = "A2YyLM8i3G7feJt7Hlm8hxlYk";
const hwId = "123490EN40";
const oem = 12;
const expDate = "2019-10-10";
const nowDate = null; // "2018-09-05"
const allowedSerials = null;
const foundSks = await superactivator.checkLicensecheckLicense(license, hwId, oem, expDate, nowDate, ip, allowedSerials, res)
assert.equal(foundSks, '1');
});
});
I get the error
ReferenceError: res is not defined
at Context. (test\superactivator.spec.js:23:130)
because I do not have res in test files. How can I solve this problem? I need to simply mock the response to check the returned values.
Thanks for help!
Maybe for someone this quick solution will be helpful:
import { Response } from 'express';
const mockedResponse = {
// mock props, methods you use
setHeader: jest.fn(),
} as unknown as Response;
You can use Sinon to help you spy/stub res from express ie:
...
const superactivator = require('../helpers/superactivator');
const sinon = require('sinon'); // ----> use sinon
...
describe('checkLicense()', function () {
it('sks ', async function () {
// here I mock the request.body data
const ip = '127.0.0.1';
const license = "A2YyLM8i3G7feJt7Hlm8hxlYk";
const hwId = "123490EN40";
const oem = 12;
const expDate = "2019-10-10";
const nowDate = null; // "2018-09-05"
const allowedSerials = null;
const res = {
send: sinon.spy() // --> create spy for res.send method
}
const foundSks = await superactivator.checkLicensecheckLicense(license, hwId, oem, expDate, nowDate, ip, allowedSerials, res)
assert.equal(foundSks, '1');
});
});
Ref:
https://sinonjs.org/releases/v6.2.0/spies/
I'm checking, if a given user is part of a group by this code below. I'm getting
unauthorized exception
(0x80070005)
and I do not understand why? I'm using SPSecurity.RunWithElevatedPrivileges, so why it is giving me this exception!? Anybody a hint for me? Thanks in advance!
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
if (web.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = web.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
You need to create a new instance of SP Web inside elevated privileges. In your current implementation, you are reusing the web object which runs in current user context.
So, try and modify the below code as per your requirement :
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using(SPSite site = new SPSite(web.Site.ID))
{
using(SPWeb elevatedWeb = site.OpenWeb(web.ID))
{
if (elevatedWeb.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = elevatedWeb.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
}
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
we are using an extension to upload the products through csv files.
Its working fine for simple product. But its giving error when we try to upload configurable product.
Error : Skip import row, product with duplicate attribute combination
In the following code ,the above error message is present. I want to know what wrong in excel sheet, so that its giving this error :
for ($i = $totalProcessedRows + 1; $i <= sizeof($data); $i++) {
if(strtolower($data[$i][0]) != "configurable" && $data[$i][0] != "") {
$attributeOptionCheck[] = $data[$i][10];
$associatedSkuCheck[] = $data[$i][5];
$totalProcessedRows++;
} else {
if(count($attributeOptionCheck) != count(array_unique($attributeOptionCheck)))
$errors[] = Mage::helper('mpmassuploadaddons')->__('Skip import row, product with duplicate attribute combination');
elseif(count($associatedSkuCheck) != count(array_unique($associatedSkuCheck)))
$errors[] = Mage::helper('mpmassuploadaddons')->__('Skip import row,associated products with duplicate skus');
break;
}
}
This is complete function for configurable products
public function importConfigurableProducts($profileId,$rowCount) {
$helper = Mage::helper("mpmassuploadaddons");
$collection = Mage::getModel('mpmassuploadaddons/profilesession')->getCollection()
->addFieldToFilter('session_id',array('eq' => $profileId));
$result = array();
$data = array();
$csvFile = "";
$imgDir = "";
if (count($collection) > 0) {
foreach ($collection as $value) {
$csvFile = $value->getCsvFile();
$imgDir = $value->getImageFile();
}
$targetPath = Mage::getBaseDir('media')."/marketplace/massuploaded/".$profileId;
$csvPath = $targetPath.'/'.$csvFile;
$fp = fopen($csvPath, 'r');
while(!feof($fp) ){
$data[] = fgetcsv($fp, 1024);
}
fclose($fp);
$info = $data[$rowCount];
$totalProcessedRows = $rowCount;
$attributeOptionCheck = array();
$associatedSkuCheck = array();
$associatedSkuCheck[] = $info[5];
$errors = array();
for ($i = $totalProcessedRows + 1; $i <= sizeof($data); $i++) {
if(strtolower($data[$i][0]) != "configurable" && $data[$i][0] != "") {
$attributeOptionCheck[] = $data[$i][10];
$associatedSkuCheck[] = $data[$i][5];
$totalProcessedRows++;
} else {
if(count($attributeOptionCheck) != count(array_unique($attributeOptionCheck)))
$errors[] = Mage::helper('mpmassuploadaddons')->__('Skip import row, product with duplicate attribute combination');
elseif(count($associatedSkuCheck) != count(array_unique($associatedSkuCheck)))
$errors[] = Mage::helper('mpmassuploadaddons')->__('Skip import row,associated products with duplicate skus');
break;
}
}
if(empty($errors)) {
$wholedata = array(
'category' => $info[1],
'name' => $info[2],
'description' => $info[3],
'short_description' => $info[4],
'sku' => $info[5],
'price' => $info[6],
'tax_class_id' => $info[10],
'is_in_stock' => $info[11],
'_super_attribute_code' => $info[12],
'images' => $info[17]
);
// $wholedata = array(
// 'category' => $info[0],
// 'name' => $info[1],
// 'description' => $info[2],
// 'short_description' => $info[3],
// 'sku' => $info[4],
// 'price' => $info[5],
// 'tax_class_id' => $info[9],
// 'is_in_stock' => $info[10],
// 'stock' => $info[11],
// 'weight' => $info[12],
// 'images' => $info[13]
// );
if(isset($info[6])){
$specialdata=array(
'special_price' => $info[7],
'special_from_date' => $info[8],
'special_to_date' => $info[9]
);
$wholedata=array_merge($wholedata,$specialdata);
}
if(isset($info[20])){
$systemattribute=$data[0][20];
$othersystemattribute=array(
$systemattribute => $info[20]
);
$wholedata=array_merge($wholedata,$othersystemattribute);
}
list($wholedata, $errors) = $this->validatePost($wholedata);
if(empty($errors)) {
$customAttributeData = array();
$mediaTypeAttributedata = array();
if(isset($data[0][18])) {
$customAttributeCodes = explode('(', $data[0][18]);
if($customAttributeCodes[0] != "") {
list($customAttributeData, $errors) = $this->validateCustomAttributeValues($customAttributeCodes[0],$info[18]);
$mediaTypeAttributedata = $this->getMediaImageAttributesData($customAttributeCodes[0],$info[18]);
}
}
if(empty($errors)) {
$j = $rowCount;
for ($i = $j + 1; $i <= sizeof($data); $i++) {
if(strtolower($data[$i][0]) != "configurable" && $data[$i][0] != "") {
$associateWholedata = array(
'type_id' => $data[$i][0],
'name' => $data[$i][2],
'sku' => $data[$i][5],
'_super_attribute_code' => $data[$i][12],
'_super_attribute_option' => $data[$i][13],
'_super_attribute_price_corr' => $data[$i][14],
'_super_attribute_qty' => $data[$i][15],
'_super_attribute_weight' => $data[$i][16]
);
list($associateWholedata, $errors) = $this->validatePost($associateWholedata);
if(!empty($errors))
break;
} else {
break;
}
}
if(empty($errors)) {
$profile = Mage::getModel('mpmassuploadaddons/profilesession')->load($profileId);
$additionalInfo = array(
'type_id' => 'configurable',
'userid' => $profile->getSellerId(),
'wstoreids' => Mage::app()->getStore()->getStoreId(),
'attribute_set_id' => $profile->getAttributesetId()
);
$wholedata = array_merge($wholedata,$additionalInfo);
$proid = $this->saveConfigNewProduct($wholedata);
$objprod = Mage::getModel('catalog/product')->load($proid);
$websites = array();
foreach(Mage::app()->getWebsites(true) as $website) {
$websites[] = $website->getId();
}
$objprod->setWebsiteIds($websites)->save();
$marketplaceProduct = Mage::getModel('marketplace/product')->getCollection()
->addFieldToFilter("mageproductid",array("eq" => $proid))
->getFirstItem();
$marketplaceProduct->setUserid($profile->getSellerId())->save();
$totalProcessedRows = $rowCount;
$count = 1;
for ($i = $totalProcessedRows + 1; $i <= sizeof($data); $i++) {
if(strtolower($data[$i][0]) != "configurable" && $data[$i][0] != "") {
$associateWholedata = array(
'type_id' => 'simple',
'name' => $data[$i][2],
'sku' => $data[$i][5],
'stock' => $data[$i][15],
'weight' => $data[$i][16],
'status' => 1,
'visibility' => 1,
'mainid' => $proid
);
$configProduct = Mage::getModel("catalog/product")->load($proid);
$associatedPrice = $configProduct->getPrice();
$configattr = Mage::getModel('catalog/product_type_configurable')->getConfigurableAttributesAsArray($configProduct);
foreach (explode(',', $data[$i][12]) as $key => $attribute) {
$optionIds = explode(',', $data[$i][13]);
$optionId = $this->getAttributeOptionIdbyOptionText($attribute , $optionIds[$key]);
$optionPrice = explode(',', $data[$i][14]);
$associatedPrice = $associatedPrice + $optionPrice[$key];
foreach ($configattr as $value) {
if($value['attribute_code'] == $attribute) {
$optionString = $attribute."|price|".$value['id']."|".$optionId;
}
}
$associateWholedata[$attribute] = $optionId;
$associateWholedata[$optionString] = $optionPrice[$key];
$associateWholedata['price'] = $associatedPrice;
}
$this->quickcreate($associateWholedata);
$totalProcessedRows++;
$count++;
} else {
break;
}
}
if(isset($info[17]) && $info[17] != "") {
$images = array_reverse(explode(',',$info[17]));
foreach ($images as $image) {
$objprod = Mage::getModel('catalog/product')->load($proid);
$imgp = Mage::getBaseDir('media')."/marketplace/massuploaded/".$profileId."/".$imgDir."/";
$checkimg = glob($imgp . $image);
if(count($checkimg) != 0) {
$filepath = $imgp.$image;
$objprod->addImageToMediaGallery($filepath, array ('image','small_image','thumbnail'), true, false);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$objprod->save();
}
}
}
try {
Mage::dispatchEvent('mp_add_customattribute_mass', array('product_id' => $proid,'customattribute' => $customAttributeData));
if(Mage::getModel('customattribute/customattribute')) {
if(count($mediaTypeAttributedata)) {
foreach ($mediaTypeAttributedata as $imageType => $image) {
if($image != "") {
$objprod = Mage::getModel('catalog/product')->load($proid);
$imgp = Mage::getBaseDir('media')."/marketplace/massuploaded/".$profileId."/".$imgDir."/";
$checkimg = glob($imgp . $image);
if(count($checkimg) != 0) {
$filepath = $imgp.$image;
$objprod->addImageToMediaGallery($filepath, array ($imageType), true, false);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$objprod->save();
}
}
}
}
}
} catch(Exception $e) {
}
if(isset($info[19]) && $info[19] != "") {
$wholedata['id'] = $proid;
$data = json_decode($info[19],true);
$i = 0;
foreach($data as $k => $d) {
foreach ($d as $key => $value) {
if($key == 'values') {
$wholedata['selectoptions'][$i] = $d[$key];
} else {
$wholedata['options'][$i][$key] = $value;
$wholedata['options'][$i]['customoptindex'] = $i;
}
}
$i++;
}
Mage::dispatchEvent('mp_customoption_setdata', $wholedata);
}
$result['savedRows'] = $count;
$result['rowsCount'] = $totalProcessedRows;
$result['success'] = $helper->__("successfully saved.");
} else {
$result['savedRows'] = 0;
$result['rowsCount'] = $totalProcessedRows;
$result['errors'] = current($errors);
}
} else {
$result['savedRows'] = 0;
$result['rowsCount'] = $totalProcessedRows;
$result['errors'] = current($errors);
}
} else {
$result['savedRows'] = 0;
$result['rowsCount'] = $totalProcessedRows;
$result['errors'] = current($errors);
}
} else {
$result['savedRows'] = 0;
$result['rowsCount'] = $totalProcessedRows;
$result['errors'] = current($errors);
}
}
return $result;
}
one more related function for configurable products :
public function getConfigurableSuperAttributes() {
$allowedSets = explode(',',Mage::getStoreConfig('marketplace/marketplace_options/attributesetid'));
$attributeCodes = array();
foreach ($allowedSets as $attributeSetId) {
$attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);
$attributeCodes[$attributeSetId] = array();
$temp = array();
foreach($attributes as $attribute) {
$data = Mage::getModel('catalog/resource_eav_attribute')->load($attribute['attribute_id']);
if($data['frontend_input'] == 'select' && $data['is_user_defined'] == 1 && $data['is_configurable'] == 1&& $data['is_visible'] == 1 && $data['is_global'] == 1) {
array_push($temp, $data['attribute_code']);
}
}
$attributeCodes[$attributeSetId] = implode(",",$temp);
}
return json_encode($attributeCodes);
}
This is complete code of that file : http://pastebin.com/vZsf0kZG
The problem is that the simple products aren't linked to the configurable product. You need this attribute for that: simples_skus.
In that column you need the place the simple product SKU's, after each one you need an: ;
Hope that works!
I am trying to export rallygrid data in excel file, but getting only headers not values.
Below is my code which I wrote to generate grid and export button
From here [https://github.com/andreano/TaskDelta/blob/master/App.js], I stole the export code
prepareChart: function(iteration_data) {
this.converted_values = [];
this.accept_values = [];
this.commit_values = [];
parents = [];
rootParent = this.getContext().getProject().Name;
sortedArray = [];
var project_hash = {}; // project_by_name, with children
Ext.Array.each(iteration_data, function(iteration){
if ((iteration.ProjectName != rootParent && iteration.ChildCount > 0) || iteration.ParentName == rootParent) {
parents.push(iteration.ProjectName);
}
// make a place for me
if ( ! project_hash[iteration.ProjectName] ) { project_hash[iteration.ProjectName] = []; }
// make a place for my parent so it can know children
if ( iteration.ParentName ) {
if ( ! project_hash[iteration.ParentName]) { project_hash[iteration.ParentName] = []; }
project_hash[iteration.ParentName] = Ext.Array.merge( project_hash[iteration.ParentName], iteration.ProjectName);
}
}, this);
// build order this way:
//console.log("Current: ", this.getContext().getProject().Name );
// order the array by parents to children to grandchildren
sortedArray = this._getTreeArray( this.getContext().getProject().Name , project_hash);
parents = Ext.Array.unique(parents);
sortedData = [];
Ext.Array.each(sortedArray, function(name){
Ext.Array.each(iteration_data, function(ite){
if(ite.ProjectName == name) {
sortedData.push(ite);
};
});
});
Ext.Array.each(iteration_data, function(iteration){
if (iteration.ProjectName == rootParent) {
sortedData.push(iteration);
}
}, this);
iteration_data = sortedData;
sprints = [];
teams = [];
this.ratio = {};
for ( var i=0; i<iteration_data.length; i++ ) {
commit_accept_ratio = 0;
var data_point = iteration_data[i];
this.commit_values.push( data_point.Commit );
this.accept_values.push( data_point.Accept );
if ( data_point.Commit > data_point.Accept ) {
this.converted_values.push( data_point.Commit - data_point.Accept );
} else {
this.converted_values.push( 0 );
}
if (data_point.Commit != 0) {
commit_accept_ratio = (data_point.Accept / data_point.Commit ) * 100;
} else {
commit_accept_ratio = 0;
};
sprints.push(iteration_data[i].Name);
teams.push(iteration_data[i].ProjectName);
teams.push(rootParent);
this.ratio[data_point.ObjectID] = commit_accept_ratio;
}
this.sprints = Ext.Array.unique(sprints).sort();
this.teams = Ext.Array.unique(teams);
removable_teams = [];
for ( var i=0; i<this.teams.length; i++ ) {
team_name = null;
var count = 0;
Ext.Array.each(iteration_data, function(data) {
if (this.teams[i] == data.ProjectName && data.Commit == 0 || null || undefined && data.Accept == 0 || null || undefined) {
count += 1;
team_name = data.ProjectName;
}
}, this);
if (count == this.sprints.length) {
removable_teams.push(team_name);
}
}
removable_teams = Ext.Array.unique(removable_teams);
records = [];
recordHash = {};
summaryHash = {};
Ext.Array.each(iteration_data, function(iter) {
if (!recordHash[iter.ProjectName]) {
recordHash[iter.ProjectName] = {
Team: iter.ProjectName,
Name: '4 Sprint Summary',
Commit: [],
Accept: [],
Perc: [],
Summary: 0
};
}
if (!Ext.Array.contains(removable_teams, iter.ProjectName)) {
recordHash[iter.ProjectName]["Commit-" + iter.Name] = iter.Commit;
recordHash[iter.ProjectName]["Accept-" + iter.Name] = iter.Accept;
recordHash[iter.ProjectName]["Perc-" + iter.Name] = this.ratio[iter.ObjectID];
}
}, this);
var summaryArray = Ext.Array.slice( this.sprints, (this.sprints.length - 4))
var iterated_data = [];
Ext.Array.each(summaryArray, function(summ){
Ext.Array.each(iteration_data, function(team) {
if( summ == team.Name){
iterated_data.push(team);
}
});
});
Ext.Array.each(iteration_data, function(summ){
Ext.Array.each(iterated_data, function(team) {
if (!summaryHash[team.ProjectName]) {
summaryHash[team.ProjectName] = {
Commit: 0,
Accept: 0,
Total: 0
};
};
if (!Ext.Array.contains(removable_teams, team.ProjectName)) {
if( summ.ProjectName == team.ProjectName && summ.Name == team.Name) {
summaryHash[team.ProjectName]["Commit"] += summ.Commit;
summaryHash[team.ProjectName]["Accept"] += summ.Accept;
if (summaryHash[team.ProjectName]["Commit"] != 0) {
summaryHash[team.ProjectName]["Total"] = (summaryHash[team.ProjectName]["Accept"] / summaryHash[team.ProjectName]["Commit"] ) * 100;
} else {
summaryHash[team.ProjectName]["Total"] = 0;
};
};
}
});
}, this);
Ext.Object.each(recordHash, function(key, value) {
if (summaryHash[key]) {
value["Summary"] = summaryHash[key].Total;
records.push(value);
}
});
var cfgsValues = [];
cfgsValues.push({text: 'Team', style:"background-color: #D2EBC8", dataIndex: 'Team', width: 170, renderer: function(value, meta_data, record, row, col) {
if (Ext.Array.contains(parents, value)) {
meta_data.style = "background-color: #FFF09E";
return Ext.String.format("<div style='font-weight:bold;text-align:center'>{0}</div>", value);
} else if (rootParent == value){
meta_data.style = "background-color: #CC6699";
return Ext.String.format("<div style='font-weight:bold;text-align:center'>{0}</div>", value);
} else {
return value;
};
}});
cfgsValues.push({text: '4 Sprint Summary', style:"background-color: #D2EBC8", width: 70, dataIndex: 'Summary', renderer: function(value, meta_data, record) {
var color = null;
if (value >= 80 && value <= 120) {
color = "#00AF4F";
}
else if (value >= 60 && value <= 80) {
color = "#FBFE08";
}
else if (value <= 60) {
color = "#FC0002";
}
else if (value >= 120) {
color = "#98CCFB";
};
meta_data.style = "background-color: "+color+"";
return Ext.Number.toFixed(value, 0)+"%";
}});
Ext.Array.each(this.sprints, function(sprint) {
cfgsValues.push(
{text: sprint, style:'background-color:#D2EBC8;text-align:center;font-weight:bold', defaults: {enableColumnHide:false}, columns:[
{text: "Commit", dataIndex: 'Commit-' + sprint, width: 50, renderer: function(value, meta_data, record) {
if( value ) {
return value;
} else {
return "NA";
}
}},
{text: "Accept", dataIndex: 'Accept-' + sprint, width: 60, renderer: function(value, meta_data, record) {
if( value) {
return value;
} else {
return "NA";
}
}},
{text: "%", dataIndex: 'Perc-'+ sprint, width: 50, renderer: function(value, meta_data, record) {
var color = null;
if (value >= 80 && value <= 120) {
color = "#00AF4F";
}
else if (value >= 60 && value <= 80) {
color = "#FBFE08";
}
else if (value <= 60) {
color = "#FC0002";
}
else if (value >= 120) {
color = "#98CCFB";
}
meta_data.style = "background-color: "+color+"";
if (value) {
return Ext.Number.toFixed(value, 0)+"%";
} else {
return "NA";
};
}}
]}
);
});
var chart = Ext.getCmp('mychart');
if (chart) {
chart.destroy();
};
Ext.Array.each(this.sprints, function(sprint) {
Ext.Array.each(records, function(record) {
if (record["Accept-" + sprint] == undefined) {
record["Accept-" + sprint] = undefined;
}
if (record["Commit-" + sprint] == undefined) {
record["Commit-" + sprint] = undefined;
}
if (record["Perc-" + sprint] == undefined) {
record["Perc-" + sprint] = undefined;
}
});
});
this.add({
xtype: 'rallygrid',
id: 'mychart',
store: Ext.create('Rally.data.custom.Store', {
data: records,
pageSize: 100
}),
//viewConfig: {
//stripeRows: false
//},
columnCfgs: cfgsValues,
//columnLines: true
});
this.globalStore = Ext.getCmp('mychart');
console.log("this.globalStore", this.globalStore);
this.down('#grid_box').add(this.globalStore);
//this.setLoading(false);
},
_addPrintButton: function() {
var me = this;
this.down('#print_button_box').add( {
xtype: 'rallybutton',
itemId: 'print_button',
text: 'Export to Excel',
disabled: false,
margin: '20 10 10 0',
region: "right",
handler: function() {
me._onClickExport();
}
});
},
_onClickExport: function () { //using this function to export to csv
var that = this;
if (this.down('#grid_box')){
//Ext.getBody().mask('Exporting Tasks...');
//console.log('inside export');
setTimeout(function () {
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-' +
'microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head>' +
'<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>' +
'{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>' +
'</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}' +
'</table></body></html>';
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)));
};
var format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
var table = that.getComponent('grid_box');
//console.log("Exporting table ",table);
var excel_data = '<tr>';
Ext.Array.each(table.getEl().dom.outerHTML.match(/<span .*?x-column-header-text.*?>.*?<\/span>/gm), function (column_header_span) {
excel_data += (column_header_span.replace(/span/g, 'td'));
});
excel_data += '</tr>';
Ext.Array.each(table.getEl().dom.outerHTML.match(/<tr class="x-grid-row.*?<\/tr>/gm), function (line) {
excel_data += line.replace(/[^\011\012\015\040-\177]/g, '>>');
});
//console.log("Excel data ",excel_data);
var ctx = {worksheet: name || 'Worksheet', table: excel_data};
window.location.href = 'data:application/vnd.ms-excel;base64,' + base64(format(template, ctx));
Ext.getBody().unmask();
}, 500);
}else{
console.log("grid_box does not exist");
}
}
There is an example in new AppSDK2 documentation of exporting to CSV.
I also have an example of exporting to CSV in this github repo.