Windows Form in a Revit Addin - revit-api
I have written quite a few different add-ins now but I keep struggling to get a windows form working on Revit. The program builds fine and I have the dll set up for Revit to access.
Here are the different sections of my code. The program is more extensive than what is seen but I believe that the problem is a reference issue or a problem with my ADDIN file. Maybe there is a different way I need to set up my ADDIN file since I have a windows form in it?? Let me know.
Here is a Dropbox folder with the screenshots in it.
Let me know if there is anything else you need to see. The error in Revit says it has to do with the FullName but I believe I put it in the ADDIN file correctly, and I did it the same as I had for other ADDINs.
Thank you for your help!
[TransactionAttribute(TransactionMode.Manual)]
[RegenerationAttribute(RegenerationOption.Manual)]
public class CicuitChecker : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
//set document variable
Document document = commandData.Application.ActiveUIDocument.Document;
using (Transaction trans = new Transaction(document))
{
trans.Start("Circuit Checker");
UIApplication uiApp = commandData.Application;
Document doc = uiApp.ActiveUIDocument.Document;
//run through looped form in case of user not selecting needed fields, and store what family the user wants the program to check
Boolean messedUp = false;
Boolean All = false, lightF = false, recep = false, elecEquip = false, equipCon = false, junc = false, panels = false;
FilteredElementCollector collector = new FilteredElementCollector(doc), collector2 = new FilteredElementCollector(doc);
while (messedUp)
{
CircuitChecker.CircuitCheckerForm form = new CircuitChecker.CircuitCheckerForm();
form.ShowDialog();
//Get application and document objects
foreach (String item in form.getSelectionElementsLB())
{
if (item.Equals("All"))
{
All = true;
break;
}
else if (item.Equals("Lighting Fixtures"))
{
lightF = true;
}
else if (item.Equals("Recepticales"))
{
recep = true;
}
else if (item.Equals("Electrical Equipment (including Panels)"))
{
elecEquip = true;
}
else if (item.Equals("Junctions"))
{
junc = true;
}
else
{
messedUp = true;
TaskDialog.Show("Error", "At least one element must be selected.");
}
}
if (form.getSelectionPlaceLB().Equals("Entire Project"))
{
collector
= new FilteredElementCollector(doc)
.WhereElementIsNotElementType();
collector2
= new FilteredElementCollector(doc)
.WhereElementIsNotElementType();
}
else if (form.getSelectionPlaceLB().Equals("Elements in Current View"))
{
collector
= new FilteredElementCollector(doc, document.ActiveView.Id)
.WhereElementIsNotElementType();
collector2
= new FilteredElementCollector(doc, document.ActiveView.Id)
.WhereElementIsNotElementType();
}
else
{
messedUp = true;
TaskDialog.Show("Error", "A place must be selected.");
}
}
Color color = new Color(138, 43, 226); // RGB
OverrideGraphicSettings ogs = new OverrideGraphicSettings();
OverrideGraphicSettings ogsOriginal = new OverrideGraphicSettings();
ogs.SetProjectionLineColor(color);
int notCircuited = 0;
//ElementId symbolId = family
ElementCategoryFilter lightFilter = new ElementCategoryFilter(BuiltInCategory.OST_LightingFixtures);
ElementCategoryFilter recepFilter = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalFixtures);
ElementCategoryFilter elecEquipFilter = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalEquipment);
//ElementClassFilter filter = new ElementClassFilter(typeof("Junction Boxes - Load"));
//FamilyInstanceFilter juncFilter1 = new FamilyInstanceFilter(doc, );
LogicalOrFilter first = new LogicalOrFilter(lightFilter, recepFilter);
if (All)
{
collector.WherePasses(first);
IList<Element> allArr = collector.ToElements();
foreach (Element e in allArr)
{
int cirNum = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER).AsInteger();
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM).AsString();
if (!(IsNumeric(cirNum)) || (panel.Equals("")) || (panel.Equals("<unnamed>")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
collector2.WherePasses(elecEquipFilter);
IList<Element> elecEquipArr = collector.ToElements();
foreach (Element e in elecEquipArr)
{
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_PANEL_SUPPLY_FROM_PARAM).AsString();
if ((panel.Equals("")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
TaskDialog.Show("Circuit Checker", notCircuited + " lighting fixtures are not circuited in this view.");
trans.Commit();
}
if (!trans.HasEnded())
{
if (lightF)
{
collector.WherePasses(lightFilter);
IList<Element> lightArr = collector.ToElements();
foreach (Element e in lightArr)
{
int cirNum = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER).AsInteger();
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM).AsString();
if (!(IsNumeric(cirNum)) || (panel.Equals("")) || (panel.Equals("<unnamed>")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
}
if (recep)
{
collector.WherePasses(recepFilter);
IList<Element> recepArr = collector.ToElements();
foreach (Element e in recepArr)
{
int cirNum = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER).AsInteger();
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM).AsString();
if (!(IsNumeric(cirNum)) || (panel.Equals("")) || (panel.Equals("<unnamed>")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
}
if (elecEquip)
{
collector.WherePasses(elecEquipFilter);
IList<Element> elecEquipArr = collector.ToElements();
foreach (Element e in elecEquipArr)
{
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_PANEL_SUPPLY_FROM_PARAM).AsString();
if ((panel.Equals("")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
}
if (junc)
{
collector.WherePasses(recepFilter);
IList<Element> juncArr = collector.ToElements();
foreach (Element e in juncArr)
{
int cirNum = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER).AsInteger();
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM).AsString();
if (!(IsNumeric(cirNum)) || (panel.Equals("")) || (panel.Equals("<unnamed>")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
}
TaskDialog.Show("Circuit Checker", notCircuited + " lighting fixtures are not circuited in this view.");
trans.Commit();
}
}
return Result.Succeeded;
}
public static Boolean IsNumeric(Object Expression)
{
if (Expression == null || Expression is DateTime)
return false;
if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if (Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
}
catch { } // just dismiss errors but return false
return false;
}
}
This code is having the functionality in the 'main class.' I have since moved the functionality to the form class as konrad suggested but am still receiving the FullClassName error in Revit. Please Help!
The schedule data add-in provides a full Visual Studio solution demonstrating how to display a Windows form in a Revit add-in, including the generation of the Windows form on the fly:
http://thebuildingcoder.typepad.com/blog/2012/05/the-schedule-api-and-access-to-schedule-data.html
Here's how I usually set up my Windows Forms based External Commands. Remember that you have to create an External Command, and your addin manifest must point at this class. Then from this class you can launch the Form like so:
[Transaction(TransactionMode.Manual)]
public class SomeCommand : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
// Get application and document objects
UIApplication uiApp = commandData.Application;
Document doc = uiApp.ActiveUIDocument.Document;
UIDocument uidoc = uiApp.ActiveUIDocument;
try
{
SomeNamespace.SomeForm form = new SomeNamespace.SomeForm(doc);
form.ShowDialog();
return Result.Succeeded;
}
// Catch any exceptions and display them
catch (Autodesk.Revit.Exceptions.OperationCanceledException)
{
return Result.Cancelled;
}
catch (Exception ex)
{
message = ex.Message;
return Result.Failed;
}
}
}
So I have a Form class that I instantiate from my ExternalCommand and pass Document to its constructor. That way I have access to document when I am interacting with the form later. I wire up all functionality in code behind of the Form.
Agree, the OP's question is why doesn't the addin work...
From looking at the images, it seems like the issue is that Revit is not properly finding the full class name of the command.
It's a little unusual that you don't have your command class wrapped in a namespace (your form class is, for example).
I would recommend wrapping it in a namespace like "circuitchecker" - like your form class.
Then the "full name" in the addin file would become "circuitchecker.circuitchecker"
(the namespace.classname) - this helps Revit distinguish different classes that might have the same name.
side note: I don't believe that putting a URL into the Image/LargeImage fields in the addin will work - but not positive.
Related
Apache POI - remove external Book reference
We receive excel files in our system and upon downloading them, i need to remove any reference to external workbook for security reasons. i wrote the following function to remove external links as well as removing content from the cell referencing the book. public static byte[] cleanFile(byte[] excelByteArrayworkbook) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (InputStream targetStream = new ByteArrayInputStream(excelByteArrayworkbook)){ try (XSSFWorkbook workbook = new XSSFWorkbook(targetStream)) { XSSFEvaluationWorkbook evalWorkbook = XSSFEvaluationWorkbook.create((XSSFWorkbook) workbook); Iterator<Sheet> sheetIterator = workbook.iterator(); int i = 0; while (sheetIterator.hasNext()) { Sheet sheet = sheetIterator.next(); EvaluationSheet evalSheet = evalWorkbook.getSheet(i); i++; for (Row row : sheet) { for (Cell cell : row) { if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { EvaluationCell evaluationCell = evalSheet.getCell(cell.getRowIndex(), cell.getColumnIndex()); try { Ptg[] formulaTokens = evalWorkbook.getFormulaTokens(evaluationCell); for (Ptg formulaToken : formulaTokens) { int externalSheetIndex = -1; if (formulaToken instanceof Ref3DPtg) { Ref3DPtg refToken = (Ref3DPtg) formulaToken; externalSheetIndex = refToken.getExternSheetIndex(); } else if (formulaToken instanceof Area3DPtg) { Area3DPtg refToken = (Area3DPtg) formulaToken; externalSheetIndex = refToken.getExternSheetIndex(); } else if (formulaToken instanceof Ref3DPxg) { Ref3DPxg refToken = (Ref3DPxg) formulaToken; externalSheetIndex = refToken.getExternalWorkbookNumber(); } else if (formulaToken instanceof Area3DPxg) { Area3DPxg refToken = (Area3DPxg) formulaToken; externalSheetIndex = refToken.getExternalWorkbookNumber(); } if (externalSheetIndex >= 0) { cell.setCellFormula(null); } else if (cell.getCellFormula().contains("[")) { cell.setCellFormula(null); } } } catch (Exception e) { cell.setCellFormula(null); } } } } } List<ExternalLinksTable> links = workbook.getExternalLinksTable(); links.forEach(link -> { if(link.getCTExternalLink().isSetDdeLink()) link.getCTExternalLink().unsetDdeLink(); if(link.getCTExternalLink().isSetExtLst()) link.getCTExternalLink().unsetExtLst(); if(link.getCTExternalLink().isSetOleLink()) link.getCTExternalLink().unsetOleLink(); if(link.getCTExternalLink().isSetExternalBook()) link.getCTExternalLink().unsetExternalBook(); link.getCTExternalLink().setNil(); }); try { workbook.write(bos); } finally { bos.close(); } } } try { bos.close(); } catch (IOException e) { } return bos.toByteArray(); } However, the file i am getting is not valid. Excel prompt me with an error message saying Excel error message The version of Apache POI i am using is 3.13 . I can't find an example where i can remove external links
I found the answer. The code was not removing references in the Name Manager area. I have added the following in my function List<XSSFName> nameUsingExternalBook = new ArrayList<XSSFName>(); for (int j = 0; j < workbook.getNumberOfNames(); j++) { XSSFName name= workbook.getNameAt(j); if(name.getRefersToFormula() != null && name.getRefersToFormula().contains("[")) { nameUsingExternalBook.add(name); } } nameUsingExternalBook.forEach(name->{ workbook.removeName(name.getNameName()); }); So the new excel file is wellformed
I want to send free form native query output to excel using a WebGrid
First I need to explain my problem, I have a native query application where someone types in "Select .... this and that" and the output is currently displayed in a grid that is paginated and I have been asked to add a button that will export the data to excel directly from an untyped datastream. my current code that I've found uses a grid and still doesn't prompt me to download a .xls file for some reason. [Authorize(Roles = "Portal administrator")] public void ExportExcel(NativeQueryVM model, int? page, string sort) { List<Dictionary<string, object>> result = null; String vartimedate = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"); try { var user = Membership.GetUser(); var grid = new System.Web.UI.WebControls.GridView(); if (page == null && sort == null) { if (model.QueryText.ToUpper().StartsWith("SELECT")) { UserQueryInput queryinput = new UserQueryInput(); queryinput.DatabaseId = model.selectedDatabase; queryinput.QueryText = model.QueryText; result = lookupProvider.GetSetNativeQuery((Guid)user.ProviderUserKey, user.UserName, queryinput, "Set"); model.QueryResultData = result; ViewBag.SubmitType = "Select"; CreateDynamicResult(model.QueryResultData); if (model == null || model.QueryResultData.Count == 0) { ViewBag.ResultMessage = "No Results Found"; } else { WebGrid wd = new WebGrid(source: ViewBag.DynamicResult, canPage: false, canSort: false ); string griddata = wd.GetHtml().ToString(); string attachment = "attachment; filename=NativeQuery" + vartimedate + ".xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); Response.Write(griddata); Response.End(); } } } else { //This part should come when page or sort is not null for Select. Should not be executed other than SELECT result = lookupProvider.GetSetNativeQuery((Guid)user.ProviderUserKey, user.UserName, null, "Get"); model.QueryResultData = result; ViewBag.SubmitType = "Select"; CreateDynamicResult(model.QueryResultData); if (model == null || model.QueryResultData.Count == 0) { ViewBag.ResultMessage = "No Results Found"; } else { } } } catch (Exception ex) { logger.Log(new LogMessage() .ForMethod("SubmitQuery") .WithContext(Environment.MachineName) .WithException(ex) .WithDescription("An error occurred while submiting query to get result")); } }
Hi all that answered this problem, and I've found the answer and issues reside outside of the code that I've entered into the question. Jquery was intercepting the output of my file stream and on the other hand, if the button was created with runat=server the model is out of scope and the main part of the solution involved saving the model to a session and pulling it back in. Thanks for your assistance all...
How are you calling this void function? The return paths include setting a ViewBag property with an error message along with modifying the response. It smells of bad design. I'd create a hyperlink that links to a #Url.Action for something like this. Note that you'd need to return a FileContentResult with the data UTF8-encoded rather than modifying the Response directly: public async Task<ActionResult> Test() { WebGrid wd = new WebGrid(source: ViewBag.DynamicResult, canPage: false, canSort: false ); string griddata = wd.GetHtml().ToString(); string attachment = "attachment; filename=NativeQuery" + vartimedate + ".xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/excel"; byte[] buffer = System.Text.UTF8Encoding.UTF8.GetBytes(griddata); return File(buffer, "application/octet-stream"); }
Telerik RadComboBox Items not getting checked
I have a search page where i select some parameters and hit submit I store sessions and get results in radgrid.And on the double click of the row i go to the edit page.. I am capturing radcombobox.text into a session..example Session["Status]=active,inactive,old I am retrieving the session on !postback to keep the values back from edit page.. Sample code... I tried the below code to get the items in combobox get chked when they return from edit page... Not sure why its not checking the items in RadCombobox.Please advise if (Session["Status"] != null) { ddlStatus.Text = Session["Status"].ToString(); string status = Session["Status"].ToString(); string[] words = status.Split(','); foreach (RadComboBoxItem item in ddlStatus.Items) { string strtext = item.Text.ToString(); if (strtext.Length > 0) { if(ddlStatus.Items.Any(x => words.Equals(x))) { item.Checked = true; } else { item.Checked = false; } } }
I just tried your code all you have to do just modify the foreach to be : foreach (RadComboBoxItem item in ddlStatus.Items.ToList()) { // if(ddlStatus.Items.Any(x => words.Equals(x))) if(words.Contains(item.Text)) { item.Checked = true; } else { item.Checked = false; } } and it would work.
Blackberry - How if addElement() doesn't work?
I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector. public class XmlParser extends MainScreen { Database d; private HttpConnection hcon = null; private Vector binN; public Vector getBinN() { return binN; } public void setBinN(Vector bin) { this.binN = bin; } LabelField from; LabelField ttl; LabelField desc; LabelField date; public XmlParser() { LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH); setTitle(title); try { URI myURI = URI.create("file:///SDCard/Database/WebFeed.db"); d = DatabaseFactory.open(myURI); Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed"); st.prepare(); Cursor c = st.getCursor(); while (c.next()) { Row r = c.getRow(); hcon = (HttpConnection)Connector.open(r.getString(0)); hcon.setRequestMethod(HttpConnection.GET); hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0"); hcon.setRequestProperty("Content-Length", "0"); hcon.setRequestProperty("Connection", "close"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.isValidating(); Document document = builder.parse(hcon.openInputStream()); Element rootElement = document.getDocumentElement(); rootElement.normalize(); NodeList list = document.getElementsByTagName("item"); int i=0; while (i<10){ Node item = list.item(i); if(item.getNodeType() != Node.TEXT_NODE) { NodeList itemChilds = item.getChildNodes(); int j=0; while (j<10){ Node detailNode = itemChilds.item(j); if(detailNode.getNodeType() != Node.TEXT_NODE) { if(detailNode.getNodeName().equalsIgnoreCase("title")) { ttl = new LabelField(getNodeValue(detailNode)) { public void paint(Graphics g) { g.setColor(Color.BLUE); super.paint(g); } }; from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH); ttl.setFont(Font.getDefault().derive(Font.BOLD)); from.setFont(Font.getDefault().derive(Font.BOLD)); add (from); add (ttl); } else if(detailNode.getNodeName().equalsIgnoreCase("description")) { desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH); add(desc); } else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) { date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) { public void paint(Graphics g) { g.setColor(Color.ORANGE); super.paint(g); } }; add(date); add(new SeparatorField()); } else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) { date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) { public void paint(Graphics g) { g.setColor(Color.ORANGE); super.paint(g); } }; add(date); add(new SeparatorField()); } else { System.out.println("not the node"); } } else { System.out.println("not text node"); } j++; } } i++; BinNews bin = new BinNews(); bin.setProv(from.getText()); bin.setTitle(ttl.getText()); bin.setDesc(desc.getText()); bin.setDate(date.getText()); binN.addElement(bin); } setBinN(binN); } //setBinN(binN); st.close(); d.close(); } catch (Exception e) { add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH)); System.out.println(e.toString()); } } public String getNodeValue(Node node) { NodeList nodeList = node.getChildNodes(); Node childNode = nodeList.item(0); return childNode.getNodeValue(); } } I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work. Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null. However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything. What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.
J2ME Login and Search Record Store
I'm new to J2ME and I'm taking a class where we use it. I created a simple travel reservation MIDlet using choice groups text fields etc. I then added a Record Store to capture this information. I now have a user login that only requires a user name, but i don't know how to verify that the user name is in the Record Store, so instead I accept any one as long as the Textfield for the user name is not empty. My first question is how would I verify that the user exist, I already can create an account. The second question is how can I search a record store not by id but say using a string within a certain range for each row of the Record store. Here is my code so far: $import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.util.Date; import javax.microedition.lcdui.*; import javax.microedition.midlet.MIDlet; import javax.microedition.rms.*; /** * #author XayBlu */ public class tripMe extends MIDlet implements CommandListener { Form startForm, airForm, trainForm, cruiseForm, autoForm, Ext, Pass,home,login, create; Command Exit, Trip, Cinfo, AutC,AiC,CrC, info,Tme,trainC, logC,signC, createC, prev, newTrip, Home; ChoiceGroup trans,hCAP, passCNT,airT,airC,AuC,AuT,CrL,CcabT,Tseat,TOP; Display Xdisplay; TextField Eneed, uName, uName2; Alert Final, FinalT, Sucess, nope; DateField dDate, rDate; Date d,r; Image [] image; String details =" ",tt="", Trav, Rdate, Ddate, extraA, Pcount,specialA, TT,AIR2, AIR,AUTO,AUTO2,CRUISE,CRUISE2,TRAIN,TRAIN2, USERS="USERS"; String op[] = {"Air","Auto","Cruise","Train"}; //Array Items for Choice Groups String ep[] = {"Wheel Chair","Baby Seat","Extended Seatbelt","Extra Pillows","Oxygen Tank","GPS"}; String count[] = {"1","2","3","4","5","6","7","8"}; String AL []= {"American Airlines","Delta","US Airways","South West Airlines","United Airlines"}; String Rental [] = {"Alamo","Avis","Budget","Enteprise","Dollar","Hertz"}; String CL [] = {"Carnival","Norwegian","Royal Caribbean","Celebrity X","MSC"}; String CT [] = {"Compact","Standard","Full","SUV","Luxury","Sports"}; String Cabin [] = {"Suite","Ocean Balcony","Standard","Economy"}; String tCAB[] = {"Standard Seat","Sleeper Cart"}; String Toptions[] ={"Extra Luggage room","Salad Buffet","Wifi Access","Extra Blanket"}; RecordStore usr,itt; RecordEnumeration recEnum = null; RecordFilter filter = null; int Umax=5; int tran1 =6; String last; Byte [] data = new Byte[Umax]; /* NEW COMMANDS FOR FLEXIBLE USER INPUT TO RECORD STORES */ public void writeRecord(String str){ // User to insert user input to record stores byte[] rec = str.getBytes(); try{ usr.addRecord(rec, 0, rec.length); }catch (Exception e){} } public void writeInfo(String str){ // User to insert user input to record stores byte[] rec = str.getBytes(); try{ usr.addRecord(rec, tran1, rec.length); }catch (Exception e){} } public void updateRecord(String str){ try{ usr.setRecord(1, str.getBytes(), 0, str.length()); }catch (Exception e){} } public void deleteRecord(){ try{ usr.deleteRecord(1); }catch (Exception e){} } public void closeRecord(){ try{ usr.closeRecordStore(); }catch (Exception e){} } public void deleteRecStore(){ if (RecordStore.listRecordStores() != null){ try{ RecordStore.deleteRecordStore(USERS); }catch (Exception e){} } } public void openRecStore() { try { // The second parameter indicates that the record store // should be created if it does not exist usr = RecordStore.openRecordStore(USERS, true ); } catch (Exception e) { System.out.print("Could not open record store"); } } public void readRecords() { try { // Intentionally make this too small to test code below byte[] recData = new byte[5]; int len; for (int i = 1; i <= usr.getNumRecords(); i++) { if (usr.getRecordSize(i) > recData.length) recData = new byte[usr.getRecordSize(i)]; len = usr.getRecord(i, recData, 0); home.append(new String(recData,0,len)); // System.out.println("Record #" + i + ": " + new String(recData, 0, len)); // System.out.println("------------------------------"); } } catch (Exception e) { nope = new Alert("Sorry no match!",null,null,AlertType.INFO); nope.setTimeout(Alert.FOREVER); //Append string for FinalT Alert Xdisplay.setCurrent(nope, login); } } } class Filter implements RecordFilter { private String search = null; private ByteArrayInputStream inputstream = null; private DataInputStream datainputstream = null; public Filter(String search) { this.search = search.toLowerCase(); } public void filterClose() { try { if (inputstream != null) { inputstream.close(); } if (datainputstream != null) { datainputstream.close(); } } catch (Exception error) { } } } public tripMe (){ try{ //Initializing individual images for Choice Group Icons Image car = Image.createImage("/car2.png"); Image plane = Image.createImage("/plane2.png"); Image train = Image.createImage("/train2.png"); Image cruise = Image.createImage("/cruise2.png"); image = new Image[] {plane,car,cruise,train}; //Initializing Image array for ChoiceGroup } catch (java.io.IOException err) {System.out.print("Could not load pics"); } //Throws exception if pic cannot be found startForm = new Form("Get Away Today"); //Initialization of forms Pass = new Form ("Passenger Information"); airForm = new Form("Low Prices!"); autoForm = new Form("Find the best car for you"); Ext = new Form("Itinerary Details"); Ext.setTicker(new Ticker("Enjoy Your Vacation")); cruiseForm = new Form("Sail Away Today"); trainForm = new Form("Chuuu- Chuuu"); login = new Form("Sign up Today"); home = new Form("Welcome Back"); create = new Form("Create an account"); trans = new ChoiceGroup("Select travel type",ChoiceGroup.EXCLUSIVE,op,image); //Transport tation choice group initialized with corresponding string and image array Exit = new Command("Exit", Command.EXIT,1);//Adding necessary commands Trip = new Command("Go", Command.SCREEN,2);//Adding go command which allows you to select travel type signC = new Command("Sign up",Command.SCREEN,2); logC = new Command("Log in",Command.SCREEN,2); createC = new Command("OK",Command.SCREEN,2); prev = new Command("History",Command.SCREEN,2); newTrip = new Command("Reservations",Command.SCREEN,2); Home = new Command("Log out",Command.SCREEN,1); hCAP = new ChoiceGroup("Extra Assistance", ChoiceGroup.MULTIPLE,ep,null);//Passenger Info items passCNT = new ChoiceGroup("Number of Passengers:",ChoiceGroup.POPUP,count,null); rDate = new DateField("Return Date",DateField.DATE_TIME);//Could not get the DateField to return string date value dDate = new DateField("Departure Date",DateField.DATE_TIME); Eneed = new TextField("Special Needs","",50,TextField.ANY); uName = new TextField("User Name","",5,TextField.ANY); uName2 = new TextField("User Name","",5,TextField.ANY); info = new Command("Next",Command.SCREEN,2); AiC = new Command("Complete",Command.SCREEN,2);//Air travel option items airT = new ChoiceGroup("Choose Airline", ChoiceGroup.POPUP,AL,null);//Airline selection airC = new ChoiceGroup("Select Class",ChoiceGroup.EXCLUSIVE);//Economy or first cass? airC.append("First Class", null);//Adding elements to Choice Group airC.append("Economy", null); AuC = new ChoiceGroup("Choose rental company", ChoiceGroup.POPUP,Rental,null);//Auto travel option items AuT = new ChoiceGroup("Select Vehicle Type", ChoiceGroup.EXCLUSIVE, CT,null);//Choicegroup for Vehicle type AutC = new Command("Drive away", Command.SCREEN,2);//Adding drive away command to form CrL = new ChoiceGroup("Select Cruise Line Comp.", ChoiceGroup.POPUP,CL,null);//Cruise option Items, Cruise line choicegroup CcabT = new ChoiceGroup("Select Cabin Type", ChoiceGroup.EXCLUSIVE,Cabin,null);//Cabin type choice group CrC = new Command("Cruise", Command.SCREEN,2);//Cruise form command being added trainC = new Command("Track!", Command.SCREEN,2);//Train option items, Train form command Tseat = new ChoiceGroup("Seat Type", ChoiceGroup.EXCLUSIVE,tCAB,null);//Choicegroup for train seat type TOP = new ChoiceGroup("Extra Options", ChoiceGroup.POPUP,Toptions,null);//Train extra options choice group /* Appending Items to necessary Forms*/ create.append(uName2); create.addCommand(createC); create.setCommandListener(this); home.addCommand(prev); home.addCommand(newTrip); home.setCommandListener(this); login.append(uName); login.addCommand(logC); login.addCommand(signC); login.setCommandListener(this); startForm.append(trans); startForm.addCommand(Exit); startForm.addCommand(Trip); startForm.setCommandListener(this); Pass.append(dDate); Pass.append(rDate); Pass.append(hCAP); Pass.append(passCNT); Pass.append(Eneed); Pass.addCommand(info); Pass.setCommandListener(this); airForm.append(airT); airForm.append(airC); airForm.addCommand(AiC); airForm.setCommandListener(this); autoForm.addCommand(AutC); autoForm.append(AuC); autoForm.append(AuT); autoForm.setCommandListener(this); cruiseForm.addCommand(CrC); cruiseForm.append(CrL); cruiseForm.append(CcabT); cruiseForm.setCommandListener(this); trainForm.addCommand(trainC); trainForm.append(Tseat); trainForm.append(TOP); trainForm.setCommandListener(this); Ext.addCommand(Exit); Ext.addCommand(Home); Ext.setCommandListener(this); } public void startApp() { Xdisplay= Display.getDisplay(this); Xdisplay.setCurrent(login); } public void pauseApp() { } public void destroyApp(boolean unconditional) { notifyDestroyed(); } public void commandAction(Command c, Displayable displayable){ try { usr = RecordStore.openRecordStore(USERS, false); } catch (Exception e) { Sucess = new Alert("Error","Could not open Record Strore",null,AlertType.INFO); Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert Xdisplay.setCurrent(Sucess, login); } if(c==signC) { Xdisplay.setCurrent(create); } else if(c == newTrip) { Xdisplay.setCurrent(startForm); } else if(c == prev) { try { String record = ""; for (int i = 1; i < usr.getNextRecordID(); i++) { record = new String(usr.getRecord(i)); } home.append(record); } catch (Exception e) { home.append("Could not retrieve data"); try { usr.closeRecordStore(); RecordStore.deleteRecordStore(USERS); } catch (Exception x) { } } try { usr.closeRecordStore(); } catch (Exception e) { } } else if(c==createC) { try { usr = RecordStore.openRecordStore(USERS, true); } catch (RecordStoreException ex) { ex.printStackTrace(); } if(!"".equals(uName2.getString())) { writeRecord(uName2.getString()); } Sucess = new Alert("Welcome to the mile high club","Hello:"+uName2.getString(),null,AlertType.INFO); Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert Xdisplay.setCurrent(Sucess, login); } else if (c == logC) { if(!"".equals(uName.getString())) { String name = uName.getString(); byte[] data = name.getBytes(); Xdisplay.setCurrent(home); } else { Sucess = new Alert("Please enter user name!","Invalid user name",null,AlertType.INFO); Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert Xdisplay.setCurrent(Sucess, login); } } else if(c==Trip) { tt +="Travel Mode: "+ trans.getString(trans.getSelectedIndex())+"\n"; if(trans.isSelected(0)) { TT="A"; //Sets the type of travel based on choicegroup user selection Xdisplay.setCurrent(Pass); } else if(trans.isSelected(1)) { TT="B"; Xdisplay.setCurrent(Pass); } else if(trans.isSelected(2)) { TT="C"; Xdisplay.setCurrent(Pass); } else if(trans.isSelected(3)) { TT="D"; Xdisplay.setCurrent(Pass); } } else if (c == info) { for(int i = 0; i < hCAP.size(); i++) //Checks to see what items are selected in a ChoiceGrou { if(hCAP.isSelected(i)) { details += hCAP.getString(i)+","; //If item is selected then it is appended to the string details } } Rdate = rDate.getDate().toString(); Ddate = dDate.getDate().toString(); tt+= "Departure Date: "+ Ddate.substring(0, 10)+"\n"; tt+= "Return Date: "+ Rdate.substring(0, 10)+"\n"; Pcount = passCNT.getString(passCNT.getSelectedIndex()); //Gets passenger count from choicegroup of integers specialA = Eneed.getString(); Final = new Alert("Your travel details: \n","Requested Devices:"+details+"\nPassenger Count: "+Pcount+ "\nSpecific Request: "+specialA,null,AlertType.INFO); //Appends string for alert Final.setTimeout(Alert.FOREVER); if("A".equals(TT)){ //Directs user to form based on travel type choice Xdisplay.setCurrent(Final,airForm); } else if("B".equals(TT)){//Directs user to form based on travel type choice Xdisplay.setCurrent(Final, autoForm); } else if ("C".equals(TT)){//Directs user to form based on travel type choice Xdisplay.setCurrent(Final, cruiseForm); } else if ("D".equals(TT)){//Directs user to form based on travel type choice Xdisplay.setCurrent(Final, trainForm); } } else if(c==AiC) { AIR = airT.getString(airT.getSelectedIndex());//Retrieves selected item from choicegroup tt+="Company: "+AIR+"\n"; AIR2 = airC.getString(airC.getSelectedIndex());//Retrieves selected item from choicegroup FinalT = new Alert("Flight Details: \n","Airline Company:"+AIR+"\nSeat Class: "+AIR2,null,AlertType.INFO); FinalT.setTimeout(Alert.FOREVER); //Append string for FinalT Alert Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+ "\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate; Ext.append(Trav); extraA ="Carrier Details\n"+"Airline Carrier: "+AIR+"\nSeat Type: "+AIR2; //Append string for final display of info to user Ext.append(extraA); try { usr = RecordStore.openRecordStore(USERS, true); } catch (RecordStoreException ex) { } writeRecord("\n"+tt); Xdisplay.setCurrent(FinalT,Ext); } else if (c == AutC) { AUTO = AuC.getString(AuC.getSelectedIndex());//Retrieves selected item from choicegroup tt += "Company: "+AUTO+"\n"; AUTO2 = AuT.getString(AuT.getSelectedIndex());//Retrieves selected item from choicegroup FinalT = new Alert("Auto Details: \n","Car Rental Company:"+AUTO+"\nVehicle Class: "+AUTO2,null,AlertType.INFO); FinalT.setTimeout(Alert.FOREVER); Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+ "\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate; Ext.append(Trav); extraA ="Carrier Details\n"+"Rental Company: "+AUTO+"\nVehicle Class: "+AUTO2; //Append string for final display of info to user Ext.append(extraA); try { usr = RecordStore.openRecordStore(USERS, true); } catch (RecordStoreException ex) { } writeRecord("\n"+tt); Xdisplay.setCurrent(FinalT, Ext); } else if (c == CrC) { CRUISE = CrL.getString(CrL.getSelectedIndex()); tt += "Company: "+CRUISE+"\n"; CRUISE2 = CcabT.getString(CcabT.getSelectedIndex()); FinalT = new Alert("Cruise Details: \n","Cruise Line Company:"+CRUISE+"\nCabin Type:"+CRUISE2,null,AlertType.INFO); FinalT.setTimeout(Alert.FOREVER); Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+ "\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate; Ext.append(Trav); extraA ="Carrier Details\n"+"Cruise Line Company: "+CRUISE+"\nCabin Type: "+CRUISE2; //Append string for final display of info to user Ext.append(extraA); try { usr = RecordStore.openRecordStore(USERS, true); } catch (RecordStoreException ex) { } writeRecord("\n"+tt); Xdisplay.setCurrent(FinalT, Ext); } else if (c == trainC) { TRAIN = Tseat.getString(Tseat.getSelectedIndex()); TRAIN2 = TOP.getString(TOP.getSelectedIndex()); FinalT = new Alert("Train Details: \n","Train Seat Type:"+TRAIN+"\nExtra Amenities:"+TRAIN2,null,AlertType.INFO); FinalT.setTimeout(Alert.FOREVER); Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+ "\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate; Ext.append(Trav); extraA ="Carrier Details\n"+"Train Seat Type: "+TRAIN+"\nExtra Amenities: "+TRAIN2; //Append string for final display of info to user Ext.append(extraA); try { usr = RecordStore.openRecordStore(USERS, true); } catch (RecordStoreException ex) { } writeRecord("\n"+tt); Xdisplay.setCurrent(FinalT, Ext); } else if(c == Home) { home.deleteAll(); Xdisplay.setCurrent(login); } else if(c==Exit) { destroyApp(false); notifyDestroyed(); } } }