Import CSV-FILE to AX2012 - csv

I am trying to Import a csv-FILE in AX 2012
(Fields: FirstName, LastName, Birthdate, Jerseynumber)
class SYCImportData_Roster
{
}
public static void main(Args _args)
{
SYCImportData_Roster importData_Roster;
;
importData_Roster = new SYCImportData_Roster();
importData_Roster.run();
}
public void run()
{
AsciiIo rosterFile;
SYCu17roster u17RosterTable;
FilenameOpen filenameopen;
container records;
int totalRecords;
#FILE
;
filenameopen = this.dialog();
rosterFile = new AsciiIo(filenameopen, #IO_READ);
if ((!rosterFile) || (rosterFile.status() != IO_Status::Ok))
{
throw error("#SYC71");
}
rosterFile.inFieldDelimiter(#delimiterSemicolon);
try
{
ttsBegin;
while (rosterFile.status() == IO_Status::Ok)
{
records = rosterFile.read();
if (!records)
{
break;
}
totalRecords++;
this.doForEach(records);
}
ttsCommit;
}
catch (Exception::Error)
{
if (rosterFile)
{
rosterFile.finalize();
rosterFile = null;
}
throw error("#SYC70");
}
info(strFmt("#SYC52" + " = %1", totalRecords));
}
public FilenameOpen dialog()
{
Dialog dialog;
DialogField DF_dialogfield;
FilenameOpen filenameopen;
#FILE
;
dialog = new Dialog("Kaderliste importieren");
DF_dialogfield = dialog.addField(extendedTypeStr(filenameopen));
dialog.filenameLookupFilter(['csv' , '*' + #CSV, 'xlsx', '*' + #XLSX]);
if (!dialog.run())
{
throw error("#SYC70");
}
filenameopen = DF_dialogfield.value();
return filenameopen;
}
private void doForEach(container _records)
{
SYCu17roster u17rosterTable;
;
u17rosterTable.clear();
u17rosterTable.FirstName = conPeek(_records, 1);
u17rosterTable.LastName = conPeek(_records, 2);
u17rosterTable.BirthDate = conPeek(_records, 3);
u17rosterTable.jerseyNumber = conPeek(_records, 4);
u17rosterTable.insert();
}
The Error I get:
Error executing Code. Wrong type of Argument for conversion function.
Stack trace
(C)\Classes\SYCimportData_Roster\doForEach - line 10
(C)\Classes\SYCimportData_Roster\run- line 35
(C)\Classes\SYCimportData_Roster\main- line 8
I think it has to do something with the way the Birthdate field ist in my csv file.
Example:
Tom;Richards;28.02.1990;12

Related

JSP tag library to display MySQL rollup query with grouping and subtotals

I need to display several tables as HTML, using JSP, coming from MySQL GROUP BY a,b,c WITH ROLLUP queries. I'm looking for a good tag library to achieve this. I have found DisplayTag, but it'was last updated in 2008. And I would prefer using the subtotals calculated by MySQL, which seems to be tricky with DisplayTag.
MySQL does subtotals by adding extra rows to the resultset with the group field set to NULL.
Is there a better alternative? Printing the table is important, paging and sorting would be nice but I can live without them. No editing of any kind.
I wrote my own quick-and-dirty tag. Note that it expects the rollup data structure returned by MySQL, haven't tested it with anything else.
Usage example:
<xxx:rollupTable cssClass="data" data="${data}">
<xxx:rollupColumn title="Person" align="left" group="true" fieldName="personName" groupFieldName="personId" tooltipLink="person"/>
<xxx:rollupColumn title="City" align="left" group="true" fieldName="cityName" groupFieldName="cityId" tooltipLink="city"/>
<xxx:rollupColumn title="Price" align="right" format="#,##0.000" fieldName="price"/>
<xxx:rollupColumn title="Amount" align="right" format="#,##0" fieldName="amount"/>
</xxx:rollupTable>
The column tag does not much but adds the column definition to the table tag for later use.
package xxx.tags;
import...
public class RollupTableColumnTag extends SimpleTagSupport {
private String title;
private boolean group = false;
private boolean sum = false;
private String fieldName; // field name to output
private String groupFieldName; // field name to test for rollup level changes
private String align;
private String format;
private String tooltipLink;
private DecimalFormat formatter;
public void doTag() throws IOException, JspTagException {
RollupTableTag parent = (RollupTableTag)findAncestorWithClass(this, RollupTableTag.class);
if (parent == null) {
throw new JspTagException("Parent tag not found.");
}
parent.addColumnDefinition(this);
}
public void setFormat(String format) {
formatter = new DecimalFormat(format);
this.format = format;
}
public DecimalFormat getFormatter() {
return formatter;
}
// other getters and setters are standard, excluded
}
The table tag does the actual hard work:
package xxx.tags;
import ...
public class RollupTableTag extends BodyTagSupport {
protected String cssClass;
protected List<Map> data;
protected List<RollupTableColumnTag> columns;
protected List<Integer> groups;
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
public void setData(List data) {
this.data = (List<Map>)data;
}
public int doStartTag() throws JspException {
columns = new ArrayList<RollupTableColumnTag>();
groups = new ArrayList<Integer>();
return EVAL_BODY_BUFFERED;
}
public int doEndTag() throws JspException {
try {
JspWriter writer = pageContext.getOut();
if (data.size() == 0) {
writer.println("<P>No data.</P>");
return EVAL_PAGE;
}
int nLevels = groups.size();
int nNormalRowCount = 0;
boolean[] bStartGroup = new boolean[nLevels];
String[] sSummaryTitle = new String[nLevels];
for (int i=0;i<nLevels;i++) {
bStartGroup[i] = true;
}
writer.println("<TABLE class=\"" + cssClass + "\">");
writer.println("<THEAD><TR>");
for (RollupTableColumnTag column : columns) {
writer.print("<TH");
if (column.getAlign() != null) {
writer.print(" align=\"" + column.getAlign() + "\"");
}
writer.print(">" + column.getTitle() + "</TH>");
}
writer.println("</TR></THEAD>");
writer.println("<TBODY>");
for (Map dataRow : data) {
StringBuffer out = new StringBuffer();
out.append("<TR>");
// grouping columns always come first
String cellClass = null;
for (int i=0;i<nLevels-1;i++) {
if (bStartGroup[i]) {
Object dataField = dataRow.get(columns.get(groups.get(i)).getFieldName());
sSummaryTitle[i] = dataField == null ? "" : dataField.toString();
}
}
int nLevelChanges = 0;
for (int i=0;i<nLevels;i++) {
if (dataRow.get( columns.get(groups.get(i)).getGroupFieldName() ) == null) {
if (i>0) {
bStartGroup[i-1] = true;
}
nLevelChanges++;
}
}
int nTotalLevel = nLevels - nLevelChanges;
if (nLevelChanges == nLevels) { // grand total row
cellClass = "grandtotal";
addCell(out, "Grand Total:", null, cellClass, nLevelChanges);
} else if (nLevelChanges > 0) { // other total row
boolean isOneLiner = (nNormalRowCount == 1);
nNormalRowCount = 0;
if (isOneLiner) continue; // skip one-line sums
cellClass = "total"+nTotalLevel;
for (int i=0;i<nLevels-nLevelChanges-1;i++) {
addCell(out," ",null,cellClass, 1);
}
addCell(out, sSummaryTitle[nLevels-nLevelChanges-1] + " total:", null, cellClass, nLevelChanges+1);
} else { // normal row
for (int i=0;i<nLevels;i++) {
if (bStartGroup[i]) {
RollupTableColumnTag column = columns.get(groups.get(i));
Object cellData = dataRow.get(column.getFieldName());
String displayVal = cellData != null ? cellData.toString() : "[n/a]";
if (column.getTooltipLink() != null && !column.getTooltipLink().isEmpty() && cellData != null) {
String tooltip = column.getTooltipLink();
int dataid = Integer.parseInt(dataRow.get(column.getGroupFieldName()).toString());
displayVal = "<div ajaxtooltip=\"" + tooltip + "\" ajaxtooltipid=\"" + dataid + "\">" + displayVal + "</div>";
}
addCell(out, displayVal, column.getAlign(), null, 1);
} else {
addCell(out," ", null, null, 1);
}
}
for (int i=0;i<nLevels-1;i++) {
bStartGroup[i] = false;
}
nNormalRowCount++;
}
// other columns
for (RollupTableColumnTag column : columns) {
if (!column.isGroup()) {
Object content = dataRow.get(column.getFieldName());
String displayVal = "";
if (content != null) {
if (column.getFormat() != null) {
float val = Float.parseFloat(content.toString());
displayVal = column.getFormatter().format(val);
} else {
displayVal = content.toString();
}
}
addCell(out,displayVal,column.getAlign(),cellClass,1);
}
}
out.append("</TR>");
// empty row for better readability
if (groups.size() > 2 && nLevelChanges == groups.size() - 1) {
out.append("<TR><TD colspan=\"" + columns.size() + "\"> </TD>");
}
writer.println(out);
}
writer.println("</TBODY>");
writer.println("</TABLE>");
} catch (IOException e) {
e.printStackTrace();
}
return EVAL_PAGE;
}
public void addCell(StringBuffer out, String content, String align, String cssClass, int colSpan) {
out.append("<TD");
if (align != null) {
out.append(" align=\"" + align + "\"");
}
if (cssClass != null) {
out.append(" class=\"" + cssClass + "\"");
}
if (colSpan > 1) {
out.append(" colspan=\"" + colSpan + "\"");
}
out.append(">");
out.append(content);
out.append("</TD>");
}
public void addColumnDefinition(RollupTableColumnTag cd) {
columns.add(cd);
if (cd.isGroup()) groups.add(columns.size()-1);
}
}

Warning message not displaying

Take a look at the code below.
void viewStudent() throws ClassNotFoundException, SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
connect2 = DriverManager
.getConnection("jdbc:mysql://localhost:3306/project?"
+ "user=root&password=virus");
statement2 = connect2.createStatement();
preparedStatement2 = connect2
.prepareStatement("select regno from student where regno= "
+ ""+Integer.parseInt(txt1.getText())+"");
resultSet2 = preparedStatement2.executeQuery();
checkRegno(resultSet2);
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
close1();
}
}
void checkRegno(ResultSet resultSet2) throws SQLException {
while (resultSet2.next()) {
int trno = Integer.parseInt(resultSet2.getString("regno"));
int regno = Integer.parseInt(txt1.getText());
if (trno == regno) {
resultSet2 = statement2
.executeQuery("select * from student where regno= " + regno + "");
writeResultSet(resultSet2);
}
else {
final Text warning = new Text("Register Number Not Found...!");
warning.setFill(Color.RED);
warning.setStyle("-fx-font: 18 arial;");
Stage dialogStage = new Stage();
dialogStage.setTitle("Warning");
dialogStage.initStyle(StageStyle.UTILITY);
dialogStage.setScene(new Scene(VBoxBuilder.create().
children(warning).alignment(Pos.CENTER).
padding(new Insets(25, 25, 25, 25)).build()));
dialogStage.show();
}
}
}
I have a table named 'student' in database. When the "if (trno == regno)" is true, the "writeResultSet(resultSet2);" is working fine. When it is false, the else part is not working. How can I solve this issue ?
Most probably you are not calling your UI code on the FX thread. Try next:
Platform.runLater(new Runnable() {
#Override
public void run() {
final Text warning = new Text("Register Number Not Found...!");
warning.setFill(Color.RED);
warning.setStyle("-fx-font: 18 arial;");
Stage dialogStage = new Stage();
dialogStage.setTitle("Warning");
dialogStage.initStyle(StageStyle.UTILITY);
dialogStage.setScene(new Scene(VBoxBuilder.create().
children(warning).alignment(Pos.CENTER).
padding(new Insets(25, 25, 25, 25)).build()));
dialogStage.show();
}
});

SSIS custom destination component - Where do I Create ExternalMetaData Columns

I've created a custom SSIS destination component to write to an MQ. I'm changing the code as I go using a test SSIS package to confirm it works.
I've got it all working where it maps the Message to the input column. All good. However I'm creating the ExternalMetadataColumnCollection in ProvideComponentProperties. I only realised when I started a new test package that this is the wrong place to call it. Now when I try to add the new component to the package I get an error
Error at Data Flow Task [SSIS.Pipeline]: The property is read-only.
Error at Data Flow Task [IBM MQ Destination Jo [6]]: System.Runtime.InteropServices.COMException (0xC0204013): Exception from HRESULT: 0xC0204013
at Microsoft.SqlServer.Dts.Pipeline.Wrapper.IDTSExternalMetadataColumn100.set_ID(Int32 pID)
at IBMWebsphereMQ.DestinationAdapters.IbmMQDestinationAdapter.CreateInputAndMetaDataColumns (IDTSInput100 input)
at
IBMWebsphereMQ.DestinationAdapters.IbmMQDestinationAdapter.ProvideComponentProperties()
at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostProvideComponentProperties(IDTSManagedComponentWrapper100 wrapper)
Obviously ProvideComponentProperties is not the right place to create teh ExternalMetaData columns. Where should I be calling it?
Below is the code for the component
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Transactions;
using MyProject.IBMWebsphereMQ.ConnectionManagers;
using MyProject.IBMWebsphereMQ.Framework;
using MyProject.IBMWebsphereMQ.Interfaces;
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime;
using MyProject.IBMWebsphereMQ.MQ;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
namespace MyProject.IBMWebsphereMQ.DestinationAdapters
{
[DtsPipelineComponent(ComponentType = ComponentType.SourceAdapter,
DisplayName = "IBM MQ Destination Jo",
Description = "Writes messages to the defined queue",
IconResource = "Dts.Pipeline.SSISSourceAdapter.source.ico",
CurrentVersion = 1
)]
public class IbmMQDestinationAdapter : PipelineComponent, IEnlistmentNotification
{
private const string QueuePropertyName = "Queue";
private const string BatchWriteSize = "BatchWriteSize";
private const string ConnectionName = "IBM MQ connection";
private const string MessageInputName = "Message";
private const string ColumnName = "Message";
private const string InputDescription = "Input for IbmMQDestinationAdapter";
private IManagedConnection connection;
private IQueue queue;
private ArrayList columnInfos = new ArrayList();
private bool reRaise = true;
private IDTSInput100 messageInput;
#region ColumnInfo
private struct ColumnInfo
{
public int BufferColumnIndex;
public string ColumnName;
}
#endregion
private string QueueName
{
get { return GetProperty<string>(QueuePropertyName); }
}
private int BatchSize
{
get { return GetProperty<int>(BatchWriteSize); }
}
public override void ProvideComponentProperties()
{
TraceLogging.WriteTrace(this, "Executing ProvideComponentProperties");
//base.ProvideComponentProperties();
////Clear out base implementation
//ComponentMetaData.RuntimeConnectionCollection.RemoveAll();
//ComponentMetaData.InputCollection.RemoveAll();
//ComponentMetaData.OutputCollection.RemoveAll();
//Provide the inital components.
RemoveAllInputsOutputsAndCustomProperties();
ComponentMetaData.RuntimeConnectionCollection.RemoveAll();
ComponentMetaData.UsesDispositions = true;
SetComponentAttribute();
messageInput = ComponentMetaData.InputCollection.New();
messageInput.Name = MessageInputName;
messageInput.Description = InputDescription;
messageInput.HasSideEffects = true;
messageInput.ExternalMetadataColumnCollection.IsUsed = true;
TraceLogging.WriteTrace(this, "Creating InputColCollection");
IDTSInputColumn100 inCol = messageInput.InputColumnCollection.New();
TraceLogging.WriteTrace(this, "Setting incol.Name {0}" , ColumnName);
inCol.Name = ColumnName;
CreateInputAndMetaDataColumns(messageInput);
DtsExtensions.CreateCustomProperty(ComponentMetaData.CustomPropertyCollection.New(), QueuePropertyName, "The name of the queue to connect to", true, "QueueName");
//DtsExtensions.CreateCustomProperty(ComponentMetaData.CustomPropertyCollection.New(), BatchWriteSize, "Maximum number of messages to dequeue(0=all)", true, 5000);
//Reserve space for the connection manager
IDTSRuntimeConnection100 connectionSite = ComponentMetaData.RuntimeConnectionCollection.New();
connectionSite.Name = ConnectionName;
}
public override DTSValidationStatus Validate()
{
bool pbCancel = false;
if (ComponentMetaData.OutputCollection.Count != 0)
{
ComponentMetaData.FireError(0, ComponentMetaData.Name, "Unexpected Output found. Destination components do not support outputs",
"", 0, out pbCancel);
return DTSValidationStatus.VS_ISCORRUPT;
}
if (ComponentMetaData.AreInputColumnsValid == false)
{
ComponentMetaData.InputCollection["ComponentInput"].InputColumnCollection.RemoveAll();
return DTSValidationStatus.VS_NEEDSNEWMETADATA;
}
////What about if we have input columns but we have no ExternalMetaData
////columns? Maybe somebody removed them through code.
//IDTSInput100 input = ComponentMetaData.InputCollection[MessageInputName];
//if (DoesEachInputColumnHaveAMetaDataColumnAndDoDatatypesMatch(input.ID) ==false)
//{
// ComponentMetaData.FireError(0, "Validate", "input columns and metadata columns are out of sync. Making call to ReinitializeMetaData", "", 0, out pbCancel);
// return DTSValidationStatus.VS_NEEDSNEWMETADATA;
//}
return base.Validate();
}
private bool DoesEachInputColumnHaveAMetaDataColumnAndDoDatatypesMatch(int inputID)
{
IDTSInput100 input = ComponentMetaData.InputCollection.GetObjectByID(inputID);
IDTSExternalMetadataColumn100 mdc;
bool rtnVal = true;
foreach (IDTSInputColumn100 col in input.InputColumnCollection)
{
if (col.ExternalMetadataColumnID == 0)
{
rtnVal = false;
}
else
{
mdc =
input.ExternalMetadataColumnCollection[col.ExternalMetadataColumnID];
if (mdc.DataType != col.DataType || mdc.Length != col.Length ||
mdc.Precision != col.Precision || mdc.Scale != col.Scale || mdc.CodePage !=
col.CodePage)
{
rtnVal = false;
}
}
}
return rtnVal;
}
public override void OnInputPathAttached(int inputID)
{
IDTSInput100 input = ComponentMetaData.InputCollection.GetObjectByID(inputID);
IDTSVirtualInput100 vInput = input.GetVirtualInput();
foreach (IDTSVirtualInputColumn100 vCol in vInput.VirtualInputColumnCollection)
{
this.SetUsageType(inputID, vInput, vCol.LineageID, DTSUsageType.UT_READONLY);
}
}
public override void PreExecute()
{
TraceLogging.WriteTrace(this, "PreExecute");
IDTSInput100 input = ComponentMetaData.InputCollection[MessageInputName];
// CreateInputAndMetaDataColumns(input );
TraceLogging.WriteTrace(this, "PreExecute after getting Inputcollection");
ComponentMetaData.FireInformation(0, "PreExecute about to loop", "Start loop of columns", null, 0, ref reRaise);
TraceLogging.WriteTrace(this, "PreExecute Loop");
foreach (IDTSInputColumn100 inCol in input.InputColumnCollection)
{
ColumnInfo ci = new ColumnInfo();
ci.BufferColumnIndex = BufferManager.FindColumnByLineageID(input.Buffer, inCol.LineageID);
ci.ColumnName = inCol.Name;
TraceLogging.WriteTrace(this, " PreExecute columnInfo Name: {0}", inCol.Name);
columnInfos.Add(ci);
}
}
public override void ReinitializeMetaData()
{
IDTSInput100 _profinput = ComponentMetaData.InputCollection[MessageInputName];
if (_profinput.ExternalMetadataColumnCollection.Count > 0)
{
_profinput.ExternalMetadataColumnCollection.RemoveAll();
}
if (_profinput.InputColumnCollection.Count > 0)
{
_profinput.InputColumnCollection.RemoveAll();
}
CreateMetaDataColumns(_profinput);
}
private void CreateMetaDataColumns(IDTSInput100 input)
{
TraceLogging.WriteTrace(this, "CreateMetaDataColumns");
IDTSExternalMetadataColumnCollection100 extCols = input.ExternalMetadataColumnCollection;
TraceLogging.WriteTrace(this, "Got extCols");
//IDTSInputColumn100 inCol = messageInput.InputColumnCollection.New();
//inCol.Name = ColumnName;
foreach (IDTSInputColumn100 inCol in input.InputColumnCollection)
{
TraceLogging.WriteTrace(this, "For Each ColumnName = {0}", inCol.Name);
if (inCol.Name == ColumnName)
{
TraceLogging.WriteTrace(this, "Create new ExtCol");
IDTSExternalMetadataColumn100 extCol = extCols.New();
TraceLogging.WriteTrace(this, "Set them to input col");
extCol.Name = inCol.Name;
extCol.ID = inCol.ID;
extCol.DataType = inCol.DataType;
extCol.Length = inCol.Length;
extCol.Precision = inCol.Precision;
extCol.Scale = inCol.Scale;
extCol.CodePage = inCol.CodePage;
}
}
}
public override void AcquireConnections(object transaction)
{
if (transaction != null && connection.Configuration.AcknowledgementMode == Acknowledgement.Session)
{
ComponentMetaData.FireInformation(0, "AcquireConnections()", "Enlist in transaction", null, 0,
ref reRaise);
//If the connection mode is session and there is a valid transaction then enlist.
IntPtr pUnk = Marshal.GetIUnknownForObject(transaction);
var dtcTrans = (IDtcTransaction)Marshal.GetTypedObjectForIUnknown(pUnk, typeof(IDtcTransaction));
Transaction managedTrans = TransactionInterop.GetTransactionFromDtcTransaction(dtcTrans);
managedTrans.EnlistVolatile(this, EnlistmentOptions.EnlistDuringPrepareRequired);
}
IDTSRuntimeConnection100 conn = ComponentMetaData.RuntimeConnectionCollection[0];
connection = (IManagedConnection)conn.ConnectionManager.AcquireConnection(transaction);
if (connection is IbmMQConnection)
{
ComponentMetaData.FireInformation(0, "AcquireConnections()", "Connecting", null, 0, ref reRaise);
//Connect if not connected
if (!connection.IsConnected())
connection.Connect();
if (connection.IsConnected())
{
ComponentMetaData.FireInformation(0, "AcquireConnections()", "Connected.", null, 0, ref reRaise);
ComponentMetaData.FireInformation(0, "AcquireConnections()", "Connecting to queue", null, 0, ref reRaise);
queue = new IbmMQQueue(connection) { QueueName = QueueName };
queue.Open();
}
}
}
public override void ReleaseConnections()
{
if (queue != null)
queue.Close();
base.ReleaseConnections();
}
//public void CreateExternalMetaDataColumn(IDTSInput100 input, int inputColumnID)
//{
// IDTSInputColumn100 oColumn = input.InputColumnCollection.GetObjectByID(inputColumnID);
// IDTSExternalMetadataColumn100 eColumn = input.ExternalMetadataColumnCollection.New();
// eColumn.DataType = oColumn.DataType;
// eColumn.Precision = oColumn.Precision;
// eColumn.Scale = oColumn.Scale;
// eColumn.Length = oColumn.Length;
// eColumn.CodePage = oColumn.CodePage;
// oColumn.ExternalMetadataColumnID = eColumn.ID;
//}
public override void ProcessInput(int inputID, PipelineBuffer buffer)
{
ComponentMetaData.FireInformation(0, "ProcessInput Jo", "Beginning Process Input", null, 0, ref reRaise);
if (!buffer.EndOfRowset)
{
while (buffer.NextRow())
{
ComponentMetaData.FireInformation(0, "ProcessInput()", "Beginning loop of columnns", null, 0,
ref reRaise);
TraceLogging.WriteTrace(this, "Process Input columninfos,count = {0}", columnInfos.Count);
var message = new Message();
for (int i = 0; i < columnInfos.Count; i++)
{
ColumnInfo ci = (ColumnInfo) columnInfos[i];
object o = buffer[ci.BufferColumnIndex];
if (o == null)
{
TraceLogging.WriteTrace(this, "o is null");
TraceLogging.WriteTrace(this, "ColumnName: {0} ", ci.ColumnName);
}
else
{
TraceLogging.WriteTrace(this, "testing trace {0}: ", "Jo");
TraceLogging.WriteTrace(this, "ColumnName: {0}", ci.ColumnName);
TraceLogging.WriteTrace(this, "Column Value: {0}", buffer[ci.BufferColumnIndex].ToString());
if (ci.ColumnName == ColumnName)
{
TraceLogging.WriteTrace(this, "Setting MessageContents");
message.Contents = buffer[ci.BufferColumnIndex].ToString();
}
else
{
TraceLogging.WriteTrace(this, "Setting MessageId");
message.MessageId = buffer[ci.BufferColumnIndex].ToString();
}
}
}
queue.Write(message);
//string messageContents = buffer.GetString(m_BlobColumnIndex);
//TraceLogging.WriteTrace(this, "Message contents", messageContents);
//var message = new Message("1", messageContents);
//ComponentMetaData.FireInformation(0, "ProcessInput()", "Beginning queue write set contents", null, 0,
// ref reRaise);
//queue.Write(message);
ComponentMetaData.FireInformation(0, "ProcessInput()", "after queue write", null, 0, ref reRaise);
connection.Commit();
}
}
}
private void SetComponentAttribute()
{
var componentAttribute =
(DtsPipelineComponentAttribute)
Attribute.GetCustomAttribute(GetType(), typeof(DtsPipelineComponentAttribute), false);
int currentVersion = componentAttribute.CurrentVersion;
ComponentMetaData.Version = currentVersion;
ComponentMetaData.ContactInfo = ContactInfo;
}
private T GetProperty<T>(string propertyName)
{
foreach (IDTSCustomProperty100 possibleProperty in ComponentMetaData.CustomPropertyCollection)
{
if (possibleProperty.Name == propertyName)
{
return (T)possibleProperty.Value;
}
}
return default(T);
}
#region IEnlistmentNotification Members
public void Commit(Enlistment enlistment)
{
ComponentMetaData.FireInformation(0, "Commit(Enlistment enlistment)", "Beginning commit", null, 0, ref reRaise);
connection.Commit();
ComponentMetaData.FireProgress("Committed", 100, 0, 0, "IbmMQSourceAdapter", ref reRaise);
enlistment.Done();
}
public void InDoubt(Enlistment enlistment)
{
}
public void Prepare(PreparingEnlistment preparingEnlistment)
{
if (connection != null)
{
preparingEnlistment.Prepared();
// TraceLogging.WriteTrace(this, "Transaction Preparing");
}
}
public void Rollback(Enlistment enlistment)
{
connection.Rollback();
// TraceLogging.WriteTrace(this, "Rollback Executed");
ComponentMetaData.FireWarning(0, "Rollback(Enlistment enlistment)", "Rolling back transaction", null, 0);
enlistment.Done();
}
#endregion
}
}

IllegalStateException BlackBerry

public class show extends MainScreen {
private String date1;
private long date1l;
private long date2l;
private LabelField curDate = new LabelField();
private LabelField toDate = new LabelField();
private LabelField diffe = new LabelField();
// private LabelField info;
// private LabelField empty;
// private InvokeBrowserHyperlinkField hello;
ButtonField activate = null;
ButtonField disactivate = null;
Timer timer;
Timer timer2;
public String date1s[];
int d, m, y;
int x = 1;
String day, hour, minute;
Date date = new Date();
Calendar calendar = Calendar.getInstance();;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy HH mm");
public show() {
add(curDate);
add(toDate);
add(new SeparatorField());
add(diffe);
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTick(), 0, 1000);
}
private class TimerTick extends TimerTask {
public void run() {
if (x != 0) {
date1l = date.getTime();
try {
date1 = dateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.YEAR, 2012);
date2l = cal.getTime().getTime();
date1s = StringUtilities.stringToWords(date1);
d = Integer.parseInt(date1s[0]);
m = Integer.parseInt(date1s[1]);
y = Integer.parseInt(date1s[2]);
display();
} else {
timer.cancel();
}
}
}
public void display() {
String monw = convertToWords(m);
curDate.setText("Current Date = " + d + " " + monw + " " + y + " "
+ date1s[3] + ":" + date1s[4]);
toDate.setText("To Date = 1 February 2012 00:00");
long diffms = date2l - date1l;
long ds = diffms / 1000;
long dm = ds / 60;
long dh = dm / 60;
long dd = dh / 24;
long q = dd;
long h = (ds - (dd * 24 * 60 * 60)) / (60 * 60);
long m = (ds - (dh * 60 * 60)) / 60;
diffe.setText("Remaining Time : \n" + Long.toString(q) + " day(s) "
+ Long.toString(h) + " hour(s) " + Long.toString(m)
+ " minute(s)");
day = Long.toString(q);
hour = Long.toString(h);
minute = Long.toString(m);
showMessage();
}
/*
* private void link() { empty = new LabelField("\n\n"); add(empty); hello =
* new InvokeBrowserHyperlinkField("Click here",
* "http://indri.dedicated-it.com/wordpress/?page_id=17"); add(hello); info
* = new LabelField("\n\nPress menu then choose \"Get Link\" to access");
* add(info); }
*/
void showMessage() {
activate = new ButtonField("Activate", FIELD_HCENTER) {
protected boolean navigationClick(int action, int time) {
if (activate.isFocus()) {
Dialog.alert("Started!!");
Start();
}
return true;
}
};
add(activate);
disactivate = new ButtonField("Disactivate", FIELD_HCENTER) {
protected boolean navigationClick(int action, int time) {
if (disactivate.isFocus()) {
Dialog.alert("Stopped!!");
timer2.cancel();
}
return true;
}
};
add(disactivate);
/*
* UiEngine ui = Ui.getUiEngine(); Screen screen = new
* Dialog(Dialog.D_OK, data, Dialog.OK,
* Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
* Manager.VERTICAL_SCROLL); ui.queueStatus(screen, 1, true);
*/
}
public void Start() {
timer2 = new Timer();
timer2.scheduleAtFixedRate(new TimerTick2(), 0, 6000);
}
private class TimerTick2 extends TimerTask {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
Screen screen = new Dialog(Dialog.D_OK, "Hello!",
Dialog.OK,
Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
Manager.VERTICAL_SCROLL);
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
});
}
}
private String convertToWords(int m) {
String w = "";
switch (m) {
case 1:
w = "January";
break;
case 2:
w = "February";
break;
case 3:
w = "March";
break;
case 4:
w = "April";
break;
case 5:
w = "May";
break;
case 6:
w = "June";
break;
case 7:
w = "July";
break;
case 8:
w = "August";
break;
case 9:
w = "September";
break;
case 10:
w = "October";
break;
case 11:
w = "November";
break;
case 12:
w = "December";
break;
}
return w;
}
public boolean onClose() {
UiApplication.getUiApplication().requestBackground();
return true;
}
}
What actually is JVM 104 IllegalStateException? This program is a countdown program, which counts the remaining time from today until February 1st. Also, I implement a timer function that appears even if the application is closed. Can u please help me locate the problem? Thank you
As Richard said, you are trying to update LabelField from another thread. Try the following code snippet:
synchronized (UiApplication.getEventLock()) {
labelField.setText();
}
Try this below code and change according to your requirement;
public class FirstScreen extends MainScreen implements FieldChangeListener
{
LabelField label;
Timer timer;
TimerTask timerTask;
int secs=0;
long start,end;
String startDate="2012-01-28",endDate="2012-01-29";
ButtonField startCountDown;
public FirstScreen()
{
createGUI();
}
private void createGUI()
{
startCountDown=new ButtonField("Start");
startCountDown.setChangeListener(this);
add(startCountDown);
}
public void fieldChanged(Field field, int context)
{
if(field==startCountDown)
{
start=System.currentTimeMillis();
//this is the current time milliseconds; if you want to use two different dates
//except current date then put the comment for "start=System.currentTimeMillis();" and
//remove comments for the below two lines;
//Date date=new Date(HttpDateParser.parse(startDate));
//start=date.getTime();
Date date=new Date(HttpDateParser.parse(endDate));
end=date.getTime();
int difference=(int)(end-start);
difference=difference/1000;//Now converted to seconds;
secs=difference;
Status.show("Seconds: "+secs,100);
callTheTimer();
}
}
public void callTheTimer()
{
label=new LabelField();
add(label);
timer=new Timer();
timerTask=new TimerTask()
{
public void run()
{
synchronized (UiApplication.getEventLock())
{
if(secs!=0)
{
label.setText(""+(secs--)+" secs");
}
else
{
timer.cancel();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
label.setText("");
Dialog.alert("Times Up");
}
});
}
}
}
};
timer.schedule(timerTask, 0, 1000);
}
protected boolean onSavePrompt()
{
return true;
}
public boolean onMenu(int instance)
{
return true;
}
public boolean onClose()
{
UiApplication.getUiApplication().requestBackground();
return super.onClose();
}
}
In this code I am taking taking two different dates and start the countdown by taking their difference(in seconds); See the comments in the code;

Getting computer name in Adobe AIR

Hi all:
Can anyone tell me how to get local computer name using Adobe AIR.
Please reply me as soon as possible. Thanks in advance.
This might do the trick.
Last post on the page.
What I did in Air 2 to accomplish that is the following:
public function getHostName():void {
if(NativeProcess.isSupported) {
var OS:String = Capabilities.os.toLocaleLowerCase();
var file:File;
if (OS.indexOf('win') > -1) {
//Executable in windows
file = new File('C:\\Windows\\System32\\hostname.exe');
} else if (OS.indexOf('mac') > -1 ) {
//Executable in mac
} else if (OS.indexOf('linux')) {
//Executable in linux
}
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = file;
var process:NativeProcess = new NativeProcess();
process.addEventListener(NativeProcessExitEvent.EXIT, onExitError);
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutput);
process.start(nativeProcessStartupInfo);
process.closeInput();
}
}
import utls.StringHelper;
public function onOutput(event:ProgressEvent):void {
var strHelper:StringHelper = new StringHelper();
var output:String = event.target.standardOutput.readUTFBytes(event.target.standardOutput.bytesAvailable);
output = strHelper.trimBack(output, "\n");
output = strHelper.trimBack(output, "\r");
trace('"'+output+'"');
}
The package that I used is from the manual:
package utls
{
public class StringHelper
{
public function StringHelper()
{
}
public function replace(str:String, oldSubStr:String, newSubStr:String):String {
return str.split(oldSubStr).join(newSubStr);
}
public function trim(str:String, char:String):String {
return trimBack(trimFront(str, char), char);
}
public function trimFront(str:String, char:String):String {
char = stringToCharacter(char);
if (str.charAt(0) == char) {
str = trimFront(str.substring(1), char);
}
return str;
}
public function trimBack(str:String, char:String):String {
char = stringToCharacter(char);
if (str.charAt(str.length - 1) == char) {
str = trimBack(str.substring(0, str.length - 1), char);
}
return str;
}
public function stringToCharacter(str:String):String {
if (str.length == 1) {
return str;
}
return str.slice(0, 1);
}
}
}
import flash.filesystem.File;
var OS:String = Capabilities.os.toLocaleLowerCase();
function currentOSUser():String {
var userDir:String = File.userDirectory.nativePath;
var userName:String = userDir.substr(userDir.lastIndexOf(File.separator) + 1);
return userName;
}
trace( 'Os : ' + OS );
trace( 'Os Name: ' + currentOSUser() );