Dynamics AX 4.0 Export Forms - export

I created a method to export AOT (application object tree) Objects.
It works, but when I export the Forms-Treenodes cant find it.
The method is a server method and it runs on a BatchServer.
My idea was to export the objects as xpo files every 2 hours.
By the backup I can track the Code changes.
void run(str Path)
{
List _ValueList = new List(Types::String);
Counter _ListCounter;
ListIterator _ListIterator;
str _RootFolder;
str _FileName;
str _FolderName;
TreeNode _TreeNode;
TreeNode _InnerTreeNode;
TreeNodeIterator _TreeNodeIt;
FileIoPermission _Perm;
#define.ExportMode("w")
;
_RootFolder = Path;
//Objektbaum definition
_ValueList.addEnd("Forms");
_ValueList.addEnd("Reports");
_ValueList.addEnd("Queries");
_ValueList.addEnd("Classes");
_ValueList.addEnd("Macros");
_ValueList.addEnd("Jobs");
_ValueList.addEnd(#"Data Dictionary\Tables");
_ValueList.addEnd(#"Data Dictionary\Maps");
_ValueList.addEnd(#"Data Dictionary\Views");
_ValueList.addEnd(#"Data Dictionary\Extended Data Types");
_ValueList.addEnd(#"Data Dictionary\Base Enums");
_ListIterator = new ListIterator(_ValueList);
info(strfmt("RootExportPath: %1",_RootFolder));
// durch die zuvor definierte Liste laufen
while(_ListIterator.more())
{
try
{
info(strfmt(#"\%1",_ListIterator.value()));
//Haupttreenode objekt laden
_TreeNode = TreeNode::findNode(strfmt(#"\%1",_ListIterator.value()));
if (_TreeNode != null)
{
//Splitten des HauptNodes
_TreeNodeIt = _TreeNode.AOTiterator();
_InnerTreeNode = _TreeNodeIt.next();
//Durchlaufen der SubNodes
info(strfmt("Object found in Node: %1 ",_TreeNode.AOTchildNodeCount()));
while(_InnerTreeNode)
{
//Pfad und Filename bereitstellen
_FolderName = strfmt(#"%1\%2",_RootFolder,strreplace(_ListIterator.value(),#" ","_"));
_FileName = strfmt(#"\%1.xpo",strreplace(_InnerTreeNode.AOTname(),#" ","_"));
//Fileperms setzen ("w") = Write (OverWrite)
_Perm = new FileIoPermission(_FolderName+_FileName , #ExportMode);
if (_Perm == null)
{
return;
}
_Perm.assert();
try
{
if(!WinApi::pathExists(_FolderName))
{
if(WinApi::createDirectory(_FolderName))
{
throw error(strfmt("Pfad konnte nicht erstellt werden %1\n",_FolderName));
}
if(!WinApi::pathExists(_FolderName))
{
throw error(strfmt("Fehler beim erstellen des Pfades %1\n",_FolderName));
}
}
//Export in definierten Filename
if(WinApi::fileLocked(_FolderName+_FileName))
{
throw error("File ist ReadOnly\n");
}
_InnerTreeNode.treeNodeExport(_Foldername+_FileName);
}
catch
{
error(strfmt(#"xpo File %1 konnte nicht geschrieben werden\n",_FolderName+_Filename));
throw error("Abbruch des Jobs\n");
}
CodeAccessPermission::revertAssert();
_InnerTreeNode = _TreeNodeIt.next();
}
// BP deviation documented.
_TreeNode.treeNodeExport(_FileName);
}
else
{
error(strfmt("TreeNode empty %1",_ListIterator.value()));
}
}
catch
{
throw error("Fehler in der Verarbeitungsroutine\n");
}
_ListIterator.next();
}
}

Does the Forms folder exist in your export location?
You are attempting to assert permissions on a folder BEFORE checking it exists and creating it.

Forms can no be exported by a batch-server because the form's ar not loadet.
This ist a litle bit strange but the batchserver calls only class layer in AOT... the Forms ar hirarchical top of it and so on not exportable.

Related

Excel corrupted generated with Apache POI returned fronm API REST spring boot

EDIT :
If I hit directly the endpoint from the browser, the file is dowloaded correctly.
So I guess the problem is in the front and the way to create and save the file with the data received.
I have a java/spring boot application where I want to build an API endpoint that creates and returns a downloadable excel file. Here is my controller endpoint:
#GetMapping(path = "/informe/{informeDTO}")
public ResponseEntity<InputStreamResource> generarInforme(#PathVariable(value = "informeDTO") String informeDTOString) throws JsonParseException, JsonMappingException, IOException {
final InformeDTO informeDTO =
new ObjectMapper().readValue(informeDTOString, InformeDTO.class);
List<InformeDTO> listDatosinformeDTO = utilsService.getDatosInformeDTO(informeDTO);
for (InformeDTO informeDTO2 : listDatosinformeDTO) {
logger.debug(informeDTO2);
}
ByteArrayInputStream in = createReport(listDatosinformeDTO);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=IOPreport.xlsx");
return ResponseEntity.ok().headers(headers)
.contentType(
MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(new InputStreamResource(in));
}
This is the angular controller :
function generarInformeIOP(){
InformesService.generarInformeIOP($scope.informeView.sociedad, $scope.informeView.area, $scope.informeView.epigrafe,
$scope.informeView.cuenta, $scope.informeView.status, $scope.informeView.organizationalUnit,
$scope.informeView.societyGL, $scope.informeView.calculationType, $scope.informeView.provincia, $scope.informeView.financialSegment,
$scope.informeView.loadDateFrom, $scope.informeView.loadDateTo, $scope.informeView.incomeDateFrom, $scope.informeView.incomeDateTo)
.then(
function(response)
{
var blob = new Blob([response.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "IOPreport.xlsx");
$scope.informeFunctionality.errorMessage = '';
},
function(errResponse)
{
console.log("ERROR: " + errResponse.data);
$scope.informeFunctionality.errorMessage = "Ha ocurrido un error inesperado: " + errResponse.data.error +
": " + errResponse.data.message;
}
)
}
And the service :
....
$http.get(urls.SERVICE_API + "informe/"+ angular.toJson(informeDTO)).then(
function(response) {
console.log("GenerarInformeIOP - success");
deferred.resolve(response);
}, function(errResponse) {
console.log("GenerarInformeIOP - error");
deferred.reject(errResponse);
});
...
The generation is successfull, the file is downloaded but I think it is corrupted because Excel can't open it.
Are there anything wrong?
EDIT (adding createReport) :
private ByteArrayInputStream createReport(List<InformeDTO> datosInforme) {
ByteArrayInputStream result =null;
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream();) {
Set<String> columns = new LinkedHashSet<String>();
// Coumnas fijas
columns.add("Cuenta");
columns.add("Epigrafe");
columns.add("Descripcion");
columns.add("Total_Importe");
// Columnas dinamicas
/*
* Tedremos que recorrer todas las filas puesto que no sabremos si una traera
* menos periodos que otra de esta manera obtendremos todos los periodos
*/
for (InformeDTO informeDTO : datosInforme) {
for (Map.Entry<String, Double> entry : informeDTO.getTotalByPeriodoContable().entrySet()) {
columns.add(entry.getKey());
}
}
/*
* CreationHelper helps us create instances for various things like DataFormat,
* Hyperlink, RichTextString etc in a format (HSSF, XSSF) independent way
*/
// CreationHelper createHelper = workbook.getCreationHelper();
// Create a Sheet
Sheet sheet = workbook.createSheet("IOPReport");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.RED.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
// Creating cells
int i = 0;
for (String value : columns) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(value);
cell.setCellStyle(headerCellStyle);
i++;
}
// Create Other rows and cells with employees data
int rowNum = 1;
int cellDynamicNum = 0;
for (InformeDTO informeDTO : datosInforme) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(informeDTO.getCuenta());
row.createCell(1).setCellValue(informeDTO.getEpigrafe());
row.createCell(2).setCellValue(informeDTO.getDescripcion_epigrafe());
row.createCell(3).setCellValue("No Data");
cellDynamicNum = 4;
for (Map.Entry<String, Double> entry : informeDTO.getTotalByPeriodoContable().entrySet()) {
row.createCell(cellDynamicNum).setCellValue(entry.getValue());
cellDynamicNum++;
}
}
// Resize all columns to fit the content size
for (i = 0; i < columns.size(); i++) {
sheet.autoSizeColumn(i);
}
// Write the output to a file
workbook.write(out);
result = new ByteArrayInputStream(out.toByteArray());
out.close();
workbook.close();
} catch (Exception e) {
logger.debug("Excepcion en la creacion del report " + e);
}
return result;
}
Regards
When building the output here:
result = new ByteArrayInputStream(out.toByteArray());
The workbook is not saved into out until it is closed. So you need to change the order to:
workbook.close()
result = new ByteArrayInputStream(out.toByteArray());
Closing a ByteArrayOutputStream is not necessary but it's fine if you leave it.
I'm not sure why ResponseEntity<InputStreamResource> is used. I've another working solution which use byte-array ResponseEntity<byte[]>. Some of the code snippet are attached below:
After creating the workbook, write it to outputstream:
private final MediaType mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
...
...
// at the end
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.write(stream);
return getDownload(stream.toByteArray(), filename, mediaType);
....
Download method:
public static ResponseEntity<byte[]> getDownload(byte[] content, String filename, MediaType mediaType) {
HttpHeaders headers = new HttpHeaders();
headers.setContentLength(content.length);
headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
headers.set(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
headers.setContentType(mediaType);
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
Let me know if this works.
I resolved it adding the reponse type in the front call:
var config = { responseType: 'blob' };
$http.get(urls.SERVICE_API + "informe/"+ angular.toJson(informeDTO), config).then(
....
)

Array Loop with FirebaseObservable

I'm Working on the following Component:
import {BudgetItem} from "../models/budget.model";
import {Injectable} from "#angular/core";
import {FirebaseListObservable, AngularFire, FirebaseObjectObservable} from "angularfire2";
#Injectable()
export class BudgetService{
public ausgaben:number;
public einnahmen:number;
public budgetArray = [];
private budget:FirebaseListObservable<any>;
private budgetItemToUpdate;
constructor(private af:AngularFire){
this.budget = af.database.list('/Budget');
this.ausgaben = this.getAusgaben();
this.einnahmen = this.getEinnahmen();
this.budget.subscribe(items => {
// items is an array
items.forEach(item => {
this.budgetArray.push(new BudgetItem(item.zweck,item.betrag,item.ausgabe));
});
});
}
//Nimmt ein BugetItem als Parameter und fügt dieses der Datenbank als neuen Datensatz bei
addToBuget(item:BudgetItem){
this.budget.push({zweck:item.zweck,betrag:item.betrag,ausgabe:item.ausgabe});
}
//Nimmt den Key eines Objekts und löscht das jewelige Objekt aus der Datenbank
removeFromInventar(key:string){
this.budget.remove(key);
}
//Synchronisiert ein bestehendes Objekt mit der Datenbank
updateBudgetItem(item){
this.budgetItemToUpdate = this.af.database.object("Budget/" + item.$key)
this.budgetItemToUpdate.update({zweck:item.zweck,betrag:item.betrag,ausgabe:item.ausgabe});
}
//berechnet die totalen Einnahmen. Als Anfangswert wird 2500(Budget) gesetzt.
getEinnahmen(){
this.einnahmen = 2500;
console.log(this.budgetArray);
for(let item of this.budgetArray){
if(item.ausgabe === "Einnahme"){
this.einnahmen = this.einnahmen + item.betrag;
}
}
console.log(this.einnahmen);
return this.einnahmen;
}
//berechnet die totalen Ausgaben. Als Anfangswert wird 0 gesetzt.
getAusgaben(){
this.ausgaben = 0;
console.log(this.budgetArray);
for(let item of (this.budgetArray)){
if(item.ausgabe === "Ausgabe"){
this.ausgaben = this.ausgaben + item.betrag;
}
}
console.log("Ausgaben: " + this.ausgaben)
return this.ausgaben;
}
}
I can suggestfully push my items in the array, but I want to add up the itempropertiy "Betrag" of the idividual Objects and display the sum of them.
Where is my Mistake or what kind of suggestions do you have to get the code working?
Here's the gist of it:
af.database.list('/Budget')
// Reduce all the items to a single value.
.map(items => items.reduce((acc, item) => acc + item.betrag, 0))
// Log the total
.do(total => console.log(total));
Hopefully you can adapt this code to your situation. Let me know if you need help.
getEinnahmen(){
this.einnahmen = 0
this.af.database.list("/Budget",{query:{
orderByChild:'ausgabe',
equalTo:'Einnahme'
}}).map(items => items.reduce((acc, item) => acc + item.betrag, 0))
// Log the total
.subscribe(total => {console.log(total);this.einnahmen = total;});
return this.einnahmen+2500;
}
I changed up the code with the reduce-method. Now I'm able to log the total to the console, but now i want to add it as the returnvalue of the method getEinnahmen.

CSS3 paged media mode: Any way to prevent #top_right pdfreactor logo being inserted?

With any attempt to use paged media mode, with for example a style sheet containing :
<html><header>...<style type="text/css"> ...
body { counter-reset: chapter 1;
counter-reset: section 1;
counter-reset: page 1;
margin-left: +2%;
margin-right: -2%;
font-size: 10pt;
}
#page { size : a4 ;
margin: 8%;
#top-left { content: "abbrv"; ; font-size: 8pt;}
#top-center { content: "Chapter " counter(chapter) " : " counter(section); font-size: 8pt;}
#top-right { content: "$date : $initials"; ; font-size: 8pt; }
#bottom-center { content: "Page " counter(page) " / " counter(pages); font-size: 8pt; }
}
div.chapter {
break-before : always;
counter-increment: chapter;
counter-reset: section;
}
section.section {
counter-increment: section;
}
</style></header><body>
<div id="chap1" class="chapter"><h1>Chapter 1</h1></div>
...</body></html>
Note the above does not contain ANY reference to embedded images, but when run through PDFreactor the resulting PDF
contains a small round radio-active graphic with the word "PDF" overlaid on top , in the #top-right content, after my
"$date : $initials" content.
I think this is "pdfreactor.svg" ?
So is it not possible to remove the logo ?
Moving all files named pdfreactor.svg under the PDFreactor/
installation directory to other locations did not help.
I am using the free-for-personal-non-commercial license which
I obtained by email from Real Objects ,NOT the evaluation license .
Are personal non-commercial users not allowed to
disable the inclusion of this logo in the page header block ?
Has anyone succeeded in disabling the inclusion of the logo image - if so, how ?
Also, does anyone know why the chapter & section counters are always displayed as 0 in the page header of the above document?
The Java I am using is:
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.realobjects.pdfreactor.Configuration;
import com.realobjects.pdfreactor.PDFreactor;
import com.realobjects.pdfreactor.Result;
import com.realobjects.pdfreactor.Log;
import com.realobjects.pdfreactor.Record;
import com.realobjects.pdfreactor.events.DefaultHandler;
class PDFReactor
{
public static void main( String args[] )
{ File html_in = null , pdf_outf=null;
String html_in_url = null;
FileOutputStream pdf_out=null;
boolean expect_in=false , expect_out=false;
Logger logger = null;
try {
logger = Logger.getAnonymousLogger();
logger.setUseParentHandlers(false);
logger.setLevel(Level.INFO);
logger.addHandler(new DefaultHandler());
}catch(Exception e)
{ System.err.println("Failed to get logger: " + e.toString());
}
for ( String arg : args )
{ switch(arg)
{ case "-f" :
expect_in=true;
break;
case "-o" :
expect_out=true;
break;
default:
if(expect_in)
{ expect_in = false;
try {
html_in = new File( arg );
html_in_url = html_in.toURI().toURL().toString();
} catch (Exception e)
{ System.err.println("new File ( " + html_in + ") failed : "+e.toString());
}
}else
if(expect_out)
{ expect_out = false;
try {
pdf_outf = new File( arg );
pdf_out = new FileOutputStream( pdf_outf );
} catch (Exception e)
{ System.err.println("new File ( " + pdf_out + ") failed : "+e.toString());
}
}
}
}
if( (html_in != null) && (pdf_out != null) && (logger != null))
{
try
{ PDFreactor r = new PDFreactor();
if( r != null )
{ Configuration configuration = new Configuration();
configuration.setLicenseKey(
my_license_key_xml
);
configuration.setDocument(html_in_url);
configuration.setLogger(logger);
List<Configuration.ViewerPreferences> prefls = configuration.getViewerPreferences();
int n=prefls.size() + 1, i=0;
Configuration.ViewerPreferences[] prefs = new Configuration.ViewerPreferences[ n ];
for( Configuration.ViewerPreferences p : prefls )
{ prefs[i] = p;
i+=1;
}
prefs[i]= Configuration.ViewerPreferences.PAGE_MODE_USE_OUTLINES;
configuration.setViewerPreferences( prefs );
configuration.setAddLinks(true);
configuration.setAddBookmarks(true);
Result result = r.convert(configuration, pdf_out);
pdf_out.close();
if( result != null )
{ Log l = result.getLog();
if( l != null)
{ for( Record rec : l.getRecords() )
System.err.println(rec.getMessage());
}else
{ System.out.println("No log records produced.");
}
}
}else
{ System.err.println("new PDFreactor failed.");
}
}catch( Exception e)
{ System.err.println("PDFreactor conversion failed: "+e.toString());
}
}else
{ System.err.println("Expected -f <html input file name> -o <pdf output file name> arguments.");
}
}
}
All PDFs created with PDFreactor using a "Free Personal License" contain this PDFreactor logo. This is intended and referred to as "notices that identify PDFreactor" in the PDFreactor software license agreement which you accepted when requesting a "Free Personal License" key and by using the software. According to the agreement these notices (such as the logo) must not be removed or tampered with in any way. Should you require PDFs without any notices you have to buy and use a commercial license of PDFreactor.
Regarding the counter issues: You are defining the counters in the wrong scope. To use them in page margin boxes, you have to initialize the counters in the "#page" rule and not in the "body" element like this:
#page:first {
counter-reset: chapter 0 section 0;
}
Also, multiple "counter-reset" properties override previous ones, so only use one "counter-reset" property for multiple counters as shown above.

linkedin Import Resume is not working ( keeps Loading )

I do have website of cakephp framwork & integrated with linkedin api. website do have import resume functionality and stores user details(imported from linkedin) in edit profile page.
I have indexController and its action is something like this:-
public function linkedinlogin()
{
if (isset($_GET['oauth_problem']))
{
if (isset($_SESSION['requestToken']))
{
unset($_SESSION['requestToken']);
}
if (isset($_SESSION['oauth_verifier']))
{
unset($_SESSION['oauth_verifier']);
}
if (isset($_SESSION['oauth_access_token']))
{
unset($_SESSION['oauth_access_token']);
}
$this->redirect("registration");
exit;
}
//$this->autoRender = false;
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
$this->set('PageHeading', __('Linkedin Login'));
$config['base_url'] = 'http://upitchnew.inheritxserver.net/index/registration';
if (isset($_SESSION['user_id']))
{
$config['callback_url'] = 'http://upitchnew.inheritxserver.net/index/linkedinlogin?tc_id=' . $_SESSION['user_id'] . '&tc_id1=' . $_SESSION['user_ids'];
}
else
{
$config['callback_url'] = 'http://upitchnew.inheritxserver.net/index/linkedinlogin?tc_id=' . $_REQUEST['tc_id'] . '&tc_id1=' . $_REQUEST['tc_id1'];
}
$config['linkedin_access'] = 'linkedin_access';//LinkdingAccess key
$config['linkedin_secret'] = 'linkedin_secret';//Linkdin Scret key
//=require('../Vendor/linkedin/OAuth.php');
require('../Vendor/linkedin/linkedin.php');
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url']);
if (isset($_REQUEST['oauth_verifier']))
{
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
if (isset($_SESSION['requestToken']))
{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
}
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
$this->redirect($config['callback_url']);
//header("Location: " . $config['callback_url']);
exit();
}
else
{
if (isset($_SESSION['requestToken']) && $_SESSION['requestToken'] != '')
{
if (isset($_SESSION['oauth_access_token']) && $_SESSION['oauth_access_token'] != '')
{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);
}
else
{
//$linkedin->debug = true;
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
$this->redirect($linkedin->generateAuthorizeUrl());
// echo '<script>window.location.href="'.$linkedin->generateAuthorizeUrl().'"</script>';
//header("Location: " . $linkedin->generateAuthorizeUrl());
exit();
}
}
else
{
//$linkedin->debug = true;
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
$this->redirect($linkedin->generateAuthorizeUrl());
//echo '<script>window.location.href="'.$linkedin->generateAuthorizeUrl().'"</script>';
//header("Location: " . $linkedin->generateAuthorizeUrl());
exit();
}
}
}
This action has called once you click on import resume button, Instead of loading login with linkedin page, a page keeps loading and do not redirect to (linkedin)login page.
generateAuthorizeUrl() has called meanwhile:-
$_SESSION['requestToken'] = serialize($linkedin->request_token);
$this->redirect($linkedin->generateAuthorizeUrl());
generateAuthorizeUrl function is something like this:-
function generateAuthorizeUrl()
{
if (isset($_SESSION['user_id']))
{
$this->user_id = $_SESSION['user_id'];
}
if (isset($_SESSION['user_ids']))
{
$this->user_ids = $_SESSION['user_ids'];
}
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key . "&tc_id=" . $this->user_id . "&tc_id1=" . $this->user_ids;
}
Any help would be appreciated.
Man!! sucks! It was firewall issue linkedin is using https://api.linkedin.com/uas/oauth/authorize?oauth_token=auth_token url while processing with importing user details! and that url was blocked via Sophos securities.
So it neither showing any error or anything else just keeps loading..
Issue Resolved.

file upload cakephp

when uploading an image to the server using cakephp
$this->Model->Behaviors->attach('ImageUpload', Configure::read('photo.files'));
photo uploaded successfully, and the database fields also
but shows following error instead of returning to index page.
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 104]
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 107]
Warning (2): Cannot modify header information - headers already sent by (output started at E:\umoorthy_105act10\projects\dev1base\core\cake\basics.php:111) [CORE\cake\libs\controller\controller.php, line 614]
wat to do?
Cake has already wrote where to look for a problem
Configure::read('photo.files')
do following to check if everything is ok
pr(Configure::read('photo.files'))
public function uploadFilesIphone($folder, $formdata, $replace , $itemId = null) {
// setup dir names absolute and relative echo "<pre>"; print_r($formdata); exit;
$folder_url = WWW_ROOT.$folder;
$rel_url = $folder; //echo
// create the folder if it does not exist
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
// if itemId is set create an item folder
if($itemId) {
// set new absolute folder
$folder_url = WWW_ROOT.$folder.'/'.$itemId;
// set new relative folder
$rel_url = $folder.'/'.$itemId;
// create directory
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
}
// list of permitted file types, this is only images but documents can be added
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png','application/octet-stream');
// loop through and deal with the files;
$key = array();
$value = array();
foreach($formdata as $key => $value)
{
if($key == is_array($value))
{
$filename = str_replace(".", $replace , $value['name']);
}
// replace spaces with underscores
// assume filetype is false
$typeOK = false;
// check filetype is ok
foreach($permitted as $type)
{
if($key == is_array($value))
{
if($type == $value['type'])
{
$typeOK = true;
break;
}
}
}
// if file type ok upload the file
if($typeOK) {
// switch based on error code
if($key == is_array($value))
{
switch($value['error'])
{
case 0:
// check filename already exists
if(!file_exists($folder_url.'/'.$filename))
{
// create full filename
$full_url = $folder_url.'/'.$filename;
$url = $rel_url.'/'.$filename;
// upload the file
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
else
{
// create unique filename and upload file
// ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$full_url = $folder_url.'/'.$now.$filename;
$url = $rel_url.'/'.$now.$filename;
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
// if upload was successful
if($success)
{
// save the url of the file
$result['urls'][] = $url;
}
else
{
$result['errors'][] = "Error uploaded $filename. Please try again.";
}
break;
case 3:
// an error occured
$result['errors'][] = "Error uploading $filename. Please try again.";
break;
default:
// an error occured
$result['errors'][] = "System error uploading $filename. Contact webmaster.";
break;
}
}
elseif($value['error'] == 4)
{
// no file was selected for upload
$result['nofiles'][] = "No file Selected";
}
else
{
// unacceptable file type
$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
}
}
}
return $result;
}

Resources