How to pass out argument of type BarTender.Messages - jacob

I try to integrate Java application with Bartender Seagull ActiveX interface using jacob 1.19 library. I have a problem with print method because I do not know how to call this method from jacob.
I tried following code:
public void print( String printJobName, Boolean waitForSpoolJobToComplete, Integer timeoutMs )
{
Variant args[] = new Variant[ 4 ];
args[ 0 ] = new Variant( printJobName );
args[ 1 ] = new Variant( waitForSpoolJobToComplete );
args[ 2 ] = new Variant( timeoutMs );
args[ 3 ] = new Variant();
args[ 3 ].putNoParam();
Variant ret = format.invoke( "Print", args );
}
where format is a .com.jacob.activeX.ActiveXComponent instance and I get exception:
A COM exception has been encountered: At Invoke of: Print Description:
80020005 / Type mismatch.
I think that Messages argument causes this exception. How to pass this argument?

Not 100% sure of the code as I didn't try the following code. If any Java errors happens, do correct me.
Did a few reading in Help Seagull:
1. Declare BarTender Variables
ActiveXComponent btApp = new ActiveXComponent( "BarTender.Application" );
2. Prepare Format.Print function
//Format.Print: Returns an object of btPrnRslt
public boolean print( String printJobName, Boolean waitForSpoolJobToComplete, Integer timeoutMs, Variant btMsgCol )
{
Variant args[] = new Variant[ 4 ];
args[ 0 ] = new Variant( printJobName );
args[ 1 ] = new Variant( waitForSpoolJobToComplete );
args[ 2 ] = new Variant( timeoutMs );
args[ 3 ] = new Variant( btMsgCol );
Variant result = format.invoke( "Print", args );
//if (btPrnRslt <> btPrnRsltSuccess)
// return false;
//else
// return true;
}
3. Test Run
if (myFormat.print(firstJob, true, timeOutMS, btMsgCol))
//Do something if success
else
//Do something not success

Related

Pagination on DevExtreme dxDataGrid with Skip / Take loadOptions

We have a table with a large amount of data and I do not want to load it at once for my dxDataGrid.
I want to implement paging with Skip / Take which is supplied from the dxDataGrid's DataSourceLoadOptions.
This is my controller:
[HttpGet]
public async Task<Object> GetSalesOrdersWithTotals(DataSourceLoadOptions loadOptions)
{
try
{
var results = await SalesOrderService.GetSalesOrdersWithTotals(loadOptions.Skip, loadOptions.Take, 40);
loadOptions.Skip = 0;
loadOptions.Take = 0;
return DataSourceLoader.Load(results, loadOptions);
}
catch (Exception ex)
{
return Json(new { code = "422", success = false, message = "Unable to fetch sales orders with totals - " + ex.ToString() });
}
}
This is the service that returns the data:
public async Task<IEnumerable<SalesOrderWithTotals>> GetSalesOrdersWithTotals(int skip, int take, int defaultPageSize)
{
if (take == 0)
{
//Fix for passing a 0 take
take = defaultPageSize;
}
var salesOrderWithTotals =
from o in _context.SalesOrder
select new SalesOrderWithTotals
{
SalesOrderId = o.SalesOrderId,
Net = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum(),
Tax = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage /100),
Gross = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() + _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage / 100),
Name = o.Customer.Name,
CustomerOrderNumber = o.CustomerOrderNumber,
Contact = o.Contact,
OrderDate = o.OrderDate
};
return await salesOrderWithTotals.Skip(skip).Take(take).ToListAsync();
}
Looking at SQL profiler, this takes the first 40 records but of course the dxDataGrid is not aware of the total count of records so pagination is not available.
What would be the best method to achieve what I want in this case?
Many thanks
You must do an extra query to get the count of your SalesOrder and keep it in for example salesOrderCount. Then keep the Load method return data as bellow.
LoadResult result = DataSourceLoader.Load(results, loadOptions);
LoadResult has a parameter called totalCount so set it with the real count of your data:
result.totalCount = salesOrderCount;
and then
return result;
Now the dxDataGrid is aware of the total count of records.

How to Add Custom Columns to RadExplorer

How to Add Custom Columns to RadExplorer I Added Two Columns Date And Owner To the RadExplorer. URL For Demo.
http://demos.telerik.com/aspnet-ajax/fileexplorer/examples/applicationscenarios/customgridcolumns/defaultcs.aspx
Previous I am Getting FileName And Size When I added Two coloumn Headings By
private void AddGridColumn(string name, string uniqueName, bool sortable)
{
RemoveGridColumn(uniqueName);
// Add a new column with the specified name
GridTemplateColumn gridTemplateColumn1 = new GridTemplateColumn();
gridTemplateColumn1.HeaderText = name;
if (sortable)
gridTemplateColumn1.SortExpression = uniqueName;
gridTemplateColumn1.UniqueName = uniqueName;
gridTemplateColumn1.DataField = uniqueName;
Aspx_RadFileExplorer.Grid.Columns.Add(gridTemplateColumn1);
}
Function For ResolveRootDirectoryAsTree
<pre>
public override DirectoryItem ResolveRootDirectoryAsTree ( string xszPath )
{
PathPermissions zPathPermission = FullPermissions;
if ( xszPath.Equals ( "Document/Private" ) )
zPathPermission = PathPermissions.Read;
else if ( xszPath.Equals ( "Document/Public" ) )
zPathPermission = PathPermissions.Read | PathPermissions.Upload;
return new DirectoryItem(GetName(xszPath), GetDirectoryPath(xszPath), xszPath, GetDate(xszPath), zPathPermission, GetChildFiles(xszPath), GetChildDirectories(xszPath));
}
</pre>
Function For ResolveDirectory
public override DirectoryItem ResolveDirectory(string xszPath )
{
PathPermissions zPathPermission = FullPermissions;
if ( xszPath.Equals ( "Document/Private" ) )
zPathPermission = PathPermissions.Read;
else if ( xszPath.Equals ( "Document/Public" ) )
zPathPermission = PathPermissions.Read | PathPermissions.Upload;
DirectoryItem[] zdlDirectories = GetChildDirectories ( xszPath );
return new DirectoryItem ( GetName ( xszPath ), EndWithSlash ( GetDirectoryPath ( xszPath ) ), string.Empty, string.Empty, zPathPermission, GetChildFiles ( xszPath ), zdlDirectories );
}
private string GetName ( string xszPath )
{
if ( xszPath == null )
{
return string.Empty;
}
return xszPath.Substring ( xszPath.LastIndexOf ( '/' ) + 1 );
}
In This Function I Will Get OwnerID And Date as strings LoadDocuments().How to Display Owner ID to Owner Custom Field,And Date To Date Field
private void SafeLoadDocument ( string xszUserID )
{
try
{
DataTable zdtReturn = new DataTable();
if ( ViewState["m_DocumentTable"] == null )
ViewState["m_DocumentTable"] = EMSBLCRM.LoadDocuments( xszUserID );
zdtReturn = (DataTable)ViewState["m_DocumentTable"];
foreach (DataRow dr in zdtReturn.Rows)
{
double zdbFileSize = Convert.ToDouble(dr["fld_document_latest_attachment_size"]);
string zsztest = String.Format("{0:#,##0}", zdbFileSize);
dr["fld_document_latest_attachment_size"] = zsztest;
Convert.ToDouble(dr["fld_document_created_on"]);
string date = dr["fld_document_created_on"].ToString();
string date2 = date.Substring(0, 10);
}
Session["sesDocumentTable"] = ViewState["m_DocumentTable"];
}
catch ( Exception e )
{
Utilities.SendCrashEMail ( ref e );
}
}
Here's a link to the documentation and following is the code.
// Add a new 'custom column for the file owner'
GridTemplateColumn gridTemplateColumn2 = new GridTemplateColumn();
gridTemplateColumn2.HeaderText = "Owner Name";
gridTemplateColumn2.SortExpression = "Owner";
gridTemplateColumn2.UniqueName = "Owner";
gridTemplateColumn2.DataField = "Owner";
RadFileExplorer1.Grid.Columns.Add(gridTemplateColumn2);// Add the second column
//And the code for adding value for the file entry for the custom column.
public override DirectoryItem ResolveDirectory(string path)
{
// Update all file items with the additional information (date, owner)
DirectoryItem oldItem = base.ResolveDirectory(path);
foreach (FileItem fileItem in oldItem.Files)
{
// Get the information from the physical file
FileInfo fInfo = new FileInfo(Context.Server.MapPath(VirtualPathUtility.AppendTrailingSlash(oldItem.Path) + fileItem.Name));
// Add the information to the attributes collection of the item. It will be automatically picked up by the FileExplorer
// If the name attribute matches the unique name of a grid column
fileItem.Attributes.Add("Date", fInfo.CreationTime.ToString());
// Type targetType = typeof(System.Security.Principal.NTAccount);
// string value = fInfo.GetAccessControl().GetOwner(targetType).Value.Replace("\\", "\\\\");
string ownerName = "Telerik";
fileItem.Attributes.Add("Owner", ownerName);
}
return oldItem;
}
Hope this will be helpful for you.

Circular References in PHPExcel - infinite loop or wrong result

I am using PHPExcel 1.8.0
I have read the posts regarding circular references, such as this one, but I am still running into issues.
If a spreadsheet contains one circular ref. formula, PHPExcel's calculations do not match MS Excel.
If a spreadsheet contains more than one circular ref, then PHPExcel goes into an infinite loop.
Here are the details of what I've done so far.
Assume a spreadsheet where A1 = B1 and B1 = A1+1, and Excel is set to 100 iterations. Here is my code:
// create reader
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
// load workbook
$objPHPExcel = $objReader->load($this->_path);
// set iterative calculations max count
PHPExcel_Calculation::getInstance($objPHPExcel)->cyclicFormulaCount = 100;
// calculate
$objWorksheet = $objPHPExcel->getSheetByName('Testing');
$data = $objWorksheet->rangeToArray('A1:B1');
echo '<pre>';
print_r ($data);
echo '</pre>';
// release resources
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
MSExcel results in A1 = 99, B1 = 100. My code produces this:
Array
(
[0] => Array
(
[0] => #VALUE!
[1] => #VALUE!
)
)
Further to that, if I add A2 = B2 and B2 = A2+1, and attempt to calculate (A1:B2), it goes into an infinite loop and eventually crashes:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24 bytes) in C:\xampp\htdocs\cgc\bulldog\application\third_party\PHPExcel\Calculation.php on line 2837
Here is what I've done so far. In _calculateFormulaValue in Calculation.php:
Line 2383: $cellValue = ''; - this is the cause of the #Value! error. I changed that to $cellValue = 0;
Line 2400:
} elseif ($this->_cyclicFormulaCell == '') {
$this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
This is the cause of the infinite loop. $this->_cyclicFormulaCell does not get re-set to '' after the formula in row 1 is done, so this condition does not work for the formula in row 2.
I fixed this as follows, starting from Line 2389:
if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($wsTitle.'!'.$cellID))) {
if ($this->cyclicFormulaCount <= 0) {
return $this->_raiseFormulaError('Cyclic Reference in Formula');
} elseif (($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) &&
($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID)) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
} elseif ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID) {
++$this->_cyclicFormulaCount;
if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
}
} elseif ($this->_cyclicFormulaCell == '') {
$this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
}
}
After these fixes, if I run $data = $objWorksheet->rangeToArray('A1:B2');, I get the following result:
Array
(
[0] => Array
(
[0] => 100 // should be 99
[1] => 100
)
[1] => Array
(
[0] => 100 // should be 99
[1] => 100
)
)
As you can see, the results from PHPExcel are not consistent with MS Excel. Why is this happening and how can I get around this?
Ok, I managed to debug this. My spreadsheet was very complicated, lots of circular refs. The most challenging is a scenario where A depends on B, B depends on both A and C, and C depends on B.
I also added a maxChange parameter, so the thing works like Excel. Otherwise it takes too long on my spreadsheet.
Anyway, here is a usage example:
$objPHPExcel = PHPExcel_IOFactory::load($path);
$objCalc = PHPExcel_Calculation::getInstance($objPHPExcel);
$objCalc->cyclicFormulaCount = 100;
$objCalc->maxChange = 0.001;
The two files that were modified are: Calculation.php and CalcEngine/CyclicReferenceStack.php
Here is the code (sorry Mark, I can't afford more time to submit it to git properly).
Calculation.php
add these to class properties:
private $_precedentsStack = array();
public $maxChange = 0;
replace _calculateFormulaValue() function with this:
public function _calculateFormulaValue($formula, $cellID=null, PHPExcel_Cell $pCell = null) {
$this->_debugLog->writeDebugLog("BREAKPOINT: _calculateFormulaValue for $cellID");
// Basic validation that this is indeed a formula
// We simply return the cell value if not
$formula = trim($formula);
if ($formula{0} != '=') return self::_wrapResult($formula);
$formula = ltrim(substr($formula,1));
if (!isset($formula{0})) return self::_wrapResult($formula);
// initialize values
$pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
$wsTitle = ($pCellParent !== NULL) ? $pCellParent->getTitle() : "\x00Wrk";
$key = $wsTitle.'!'.$cellID;
$data = array(
'i' => 0, // incremented when the entire stack has been calculated
'j' => 0, // flags the formula as having been calculated; can only be 0 or 1
'cellValue' => $pCell->getOldCalculatedValue(), // default value to start with
'precedents' => array(),
'holdValue' => FALSE // set to TRUE when change in value is less then maxChange
);
// add this as precedent
$this->_precedentsStack[] = $key;
// if already been calculated, return cached value
if (($cellID !== NULL) && ( $this->getValueFromCache($wsTitle, $cellID, $cellValue))) {
return $cellValue;
}
$this->_cyclicReferenceStack->getValueByKey($key, $data);
extract($data);
$this->_debugLog->writeDebugLog("iteration # $i");
// if already calculated in this iteration, return the temp cached value
if ($i >= $this->cyclicFormulaCount || $j == 1) {
return $cellValue;
}
// on stack, but has not yet been calculated => return default value
if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($key))) {
if ($this->cyclicFormulaCount <= 0) {
return $this->_raiseFormulaError('Cyclic Reference in Formula');
}
return $cellValue;
}
// calculate value recursively
$this->_cyclicReferenceStack->push($key);
$cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell);
$this->_cyclicReferenceStack->pop();
// everything in precedent stack after the current cell is a precedent
// and every precedent's precedent is a precedent (aka a mouthfull)
while ( $this->_precedentsStack[ count($this->_precedentsStack) - 1 ] != $key ){
$data['precedents'][] = array_pop($this->_precedentsStack);
}
$data['precedents'] = array_unique($data['precedents']);
// check for max change
$oldValue = $this->_extractResult($data['cellValue']);
$newValue = $this->_extractResult($cellValue);
$data['cellValue'] = $cellValue;
$data['holdValue'] = (abs($oldValue - $newValue) < $this->maxChange);
// flag as calculated and save to temp storage
$data['j'] = 1;
$this->_cyclicReferenceStack->setValueByKey($key, $data);
// if this cell is a precedent, trigger a re-calculate
$tempCache = $this->_cyclicReferenceStack->showValues();
foreach ($tempCache as $tempKey => $tempData) {
if ( $tempData['holdValue'] == TRUE && ( in_array($key, $tempData['precedents'])) ) {
$tempData['holdValue'] = FALSE;
}
$this->_cyclicReferenceStack->setValueByKey($tempKey, $tempData);
}
// at the end of the stack, increment the counter and flag formulas for re-calculation
if (count($this->_cyclicReferenceStack->showStack()) == 0) {
$i++;
$this->_precedentsStack = array();
$tempCache = $this->_cyclicReferenceStack->showValues();
foreach ($tempCache as $tempKey => $tempData) {
$tempData['i'] = $i;
if ( ! $tempData['holdValue'] ) $tempData['j'] = 0;
$this->_cyclicReferenceStack->setValueByKey($tempKey, $tempData);
}
$this->_debugLog->writeDebugLog("iteration # $i-1 finished");
}
if ($i < $this->cyclicFormulaCount) {
$cellValue = $this->_calculateFormulaValue($pCell->getValue(), $cellID, $pCell);
} elseif ($cellID !== NULL) {
// all done: move value from temp storage to cache
$this->saveValueToCache($wsTitle, $cellID, $cellValue);
$this->_cyclicReferenceStack->removeValueByKey($key);
}
// Return the calculated value
return $cellValue;
} // function _calculateFormulaValue()
add this helper function:
private function _extractResult($result) {
if (is_array($result)) {
while (is_array($result)) {
$result = array_pop($result);
}
}
return $result;
}
CyclicReferenceStack.php
add a property:
private $_values = array();
add a bunch of functions:
public function setValueByKey($key, $value) {
$this->_values[$key] = $value;
}
public function getValueByKey($key, &$value) {
if (isset($this->_values[$key])) {
$value = $this->_values[$key];
return true;
}
return false;
}
public function removeValueByKey($key) {
if (isset($this->_values[$key])) {
unset($this->_values[$key]);
}
}
public function showValues() {
return $this->_values;
}

Deseralize Vector.<String> from ByteArray

I got this situation:
var vector:Vector.<String> = new Vector.<String>();
vector.push("uno");
vector.push("dos");
vector.push("tres");
var serializer:ByteArray = new ByteArray();
serializer.writeObject(vector);
serializer.position = 0;
var vector2:Vector.<String> = serializer.readObject();
trace(vector2[0]);
trace(vector2[1]);
trace(vector2[2]);
When the code reach the trace(vector2[0]); sentence i got this error:
TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>#16820d01 to __AS3__.vec.Vector.<String>.
Now, if i call registerClassAlias("com.some.alias", String) before declare the vector variable the code executes without problem.
Why the call to registerClassAlias() is needed in this case?
the writeObject() and readObject() methods respectively write(encode) and return a generic (untyped) Object typed objects.
so typing your vector2 as a Vector.< String > will cause the error you get while typing it as a Vector.< Object > or even not typing it at all should work ; in this case an Object will be returned:
var vector:Vector.<Object> = new Vector.<Object>();//Object
vector.push( 'abc' );
vector.push( 123 );
vector.push( { foo:"bar" } );
var serializer:ByteArray = new ByteArray();
serializer.writeObject(vector);
serializer.position = 0;
var vector2:Object = serializer.readObject();// NB: readObject returns an Object
trace( 'vector2 is a Object ?', vector2 is Object );//true
trace( 'vector2 is a Vector.<Object> ?', vector2 is Vector.<Object> );//true but see below
trace( vector2[0], 'is a String ?', vector2[0] is String );//abc is a String ? true
trace( vector2[1], 'is a Number ?', vector2[1] is Number );//123 is a Number ? true ( int and uints are Number )
trace( vector2[2] );//[object Object] untyped object
trace( 'vector2[2].foo => ', vector2[2].foo );// vector2[2].foo => bar
trace( 'vector2[2].bar => ', vector2[2].bar );// vector2[2].bar => undefined
the funny thing is that Vector.< Number > are also typed back correctly when read back while all other types fail are casted as Objects comment / uncomment the vector declarations below to see how it is typed after decoding.
//correctly typed
var vector:Vector.<Object> = new Vector.<Object>();
vector.push( 'abc', 123, { foo:"bar" } );
//var vector:Vector.<Number> = new Vector.<Number>();
//vector.push( 123, 456, 789 );
//generic Objects instead
//var vector:Vector.<String> = new Vector.<String>();
//vector.push( "a", "b", "c" );
//var vector:Vector.<Function> = new Vector.<Function>();
//vector.push( function a():*{}, function b():*{}, function c():*{} );
//var vector:Vector.<Boolean> = new Vector.<Boolean>();
//vector.push( true, false, true );
var serializer:ByteArray = new ByteArray();
serializer.writeObject(vector);
serializer.position = 0;
var vector2:* = serializer.readObject();
trace( 'vector2 is a Object ?', vector2 is Object );//true
trace( 'vector2 is a Vector.<Object> ?', vector2 is Vector.<Object> );
trace( 'vector2 is a Vector.<Number> ?', vector2 is Vector.<Number> );
trace( 'vector2 is a Vector.<String> ?', vector2 is Vector.<String> );
trace( 'vector2 is a Vector.<Function> ?', vector2 is Vector.<Function> );
trace( 'vector2 is a Vector.<Boolean> ?', vector2 is Vector.<Boolean> );
I don't know exactly why Numbers also make it, I don't know much about serialization though...

Multidimensional Vector in AS3

How can I initialise two-dimentional typed Vector is AS3?
Now I can get working only this:
private var _mainArray : Array = new Array( MyConst.DIMENTION );
public function MyArray()
{
for ( var i : int = 0; i < MyConst.DIMENTION; i++ ) {
_mainArray[ i ] = new Vector.<int>( MyConst.DIMENTION );
}
}
...
_mainArray[ i ][ j ] = 0;
What you have is an Array of Vector of int. What you want is a Vector of Vector of int.
So your "outer" Vector has to declare that contains elements of type Vector.<int>
Something like this (of course you can use a for loop):
var v:Vector.<Vector.<int>> = new Vector.<Vector.<int>>(2);
v[0] = new Vector.<int>(2);
v[1] = new Vector.<int>(2);
v[0][0] = 0;
v[0][1] = 1;
v[1][0] = 2;
v[1][1] = 3;
trace(v);
private var _labelsRefs:Vector.<Vector.<Object>> = new Vector.<Vector.<Object>>( );
private var _labelsFrRefs:Vector.<Object> = new Vector.<Object>( );
private var _labelsEnRefs:Vector.<Object> = new Vector.<Object>( );
_labelsRefs [ _labelsRefs.length ] = _labelsFrRefs;
_labelsRefs [ _labelsRefs.length ] = _labelsEnRefs;
You can add 10 additional items if you want
_labelsFrRefs [ _labelsFrRefs.length ] = [ _label.#key, _label.#xml ];
Then you can search in the _labelsRefs:Vector
public function searchKeyXml ( langue:String, key:String, val:int ):String
searchKeyXml ( "fr", "three", 1 ); medias/xmls/fr/homepage1.xml
searchKeyXml ( "en", "three", 1 ); medias/xmls/en/homepage1.xml

Resources