Pullasync error new table - xamarin.android

I created a new table in my database using Visual Studio.
I created a data objects for my new table, added in my startup.mobileApp, in my controllers and in my model. Whatever i have error with my pullasync()...
"the resource you are looking for has been removed had its name changed or is temporarily unavailable xamarin"
my item mobile:
public class AlertMateriel
{
public string Id { get; set; }
[JsonProperty(PropertyName = "IdMateriel")]
public string IdMateriel { get; set; }
[JsonProperty(PropertyName = "IdDemandeur")]
public string IdDemandeur { get; set; }
[JsonProperty(PropertyName = "Demande")]
public string Demande{ get; set; }
[JsonProperty(PropertyName = "IdAssignMat")]
public string IdAssignMat { get; set; }
[JsonProperty(PropertyName = "IdReceveur")]
public string IdReceveur { get; set; }
[JsonProperty(PropertyName = "VU")]
public bool VU { get; set; }
[JsonProperty(PropertyName = "Deleted")]
public string Deleted { get; set; }
[Microsoft.WindowsAzure.MobileServices.Version]
public byte[] Version
{
get;
set;
}
}
Service:
public class AlertMateriel : EntityData
{
public string IdMateriel { get; set; }
public string IdDemandeur { get; set; }
public string Demande { get; set; }
public string IdAssignMat { get; set; }
public bool VU { get; set; }
public string IdReceveur { get; set; }
}
Controller:
public class AlertMaterielController : TableController<AlertMateriel>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
ChantierContext context = new ChantierContext();
DomainManager = new EntityDomainManager<AlertMateriel>(context, Request);
}
// GET tables/MaterielDB
public IQueryable<AlertMateriel> GetAllAlertMateriel()
{
return Query();
}
public SingleResult<AlertMateriel> GetAllMateriel(string id)
{
return Lookup(id);
}
public Task<AlertMateriel> PatchAlertMateriel(string id, Delta<AlertMateriel> patch)
{
return UpdateAsync(id, patch);
}
public async Task<IHttpActionResult> PostAlertMateriel(AlertMateriel item)
{
AlertMateriel current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
public Task DeleteAlertMateirel(string id)
{
return DeleteAsync(id);
}
}
Activity:
public class DefMatTable : Activity
{
private IMobileServiceSyncTable<AlertMateriel> AlertMat;
private IMobileServiceSyncTable<AssignMaterielDB> AssignMaterielTable;
private IMobileServiceSyncTable<Chantiers> ChantiersTable;
private IMobileServiceSyncTable<MaterielDB> MaterielTable;
private IMobileServiceSyncTable<Personnel> PersonnelTable;
private TableLayout _table;
private MobileServiceClient client;
private ArrayAdapter _adapter3;
private string idengin="";
private string idassign = "";
private string iddemandeur = "";
private string idreceveur = "";
/*
private TextView Engin;
private TextView Chantier;
private TextView Cdt;
private TextView datedu;
private TextView dateau;
private ArrayAdapter _adapter;*/
const string applicationURL = #"url";
const string applicationKey = #"key";
public List<string> assignmatod { get; private set; }
const string localDbFilename = "localstore.db";
private ProgressDialog progress;
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Layout_DemandeMat2);
this.Window.AddFlags(WindowManagerFlags.Fullscreen);
this.Window.ClearFlags(WindowManagerFlags.Fullscreen);
//this.Title += " " + ;
CurrentPlatform.Init();
client = new MobileServiceClient(applicationURL);
await InitLocalStoreAsync();
ChantiersTable = client.GetSyncTable<Chantiers>();
AssignMaterielTable = client.GetSyncTable<AssignMaterielDB>();
MaterielTable = client.GetSyncTable<MaterielDB>();
PersonnelTable = client.GetSyncTable<Personnel>();
AlertMat = client.GetSyncTable<AlertMateriel>();
// Create your application here
await SyncAsync(pullData: true);
string idass = Intent.GetStringExtra("IdAssignMat");
AssignMaterielDB assign = await AssignMaterielTable.LookupAsync(idass);
_table = FindViewById<TableLayout>(Resource.Id.table_main);
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
ViewGroup.LayoutParams.WrapContent,
ViewGroup.LayoutParams.WrapContent
);
List<string> assignmatod = new List<string>();
try
{
//string idass = Intent.GetStringExtra("IdAssignMat");
string IdUser = Intent.GetStringExtra("IdUser");
string Estcdt = Intent.GetStringExtra("iscdt");
if (Estcdt == "True")
{
var thelist = await AssignMaterielTable.Where(idmat => idmat.Id == idass).Take(1).ToListAsync();
//var thelist2 = await AssignPersonnelTable.Where(n => n.IdUser == IdUser).ToListAsync();
foreach (AssignMaterielDB item in thelist)
{
var chantier = await ChantiersTable.Where(idchat => idchat.Id == item.IdChantier).Take(1).ToListAsync();
var Matthelist = await MaterielTable.Where(Idmat => Idmat.Id == item.IdEngin).Take(1).ToListAsync();
foreach (MaterielDB mat in Matthelist)
{
foreach (Chantiers ch in chantier)
{
var listper = await PersonnelTable.Where(Idmat => Idmat.Id == ch.Cdt).ToListAsync();
foreach (Personnel pe in listper)
{
assignmatod.Add(item.Id);
TableRow tableR = new TableRow(this);
TextView text = new TextView(this);
text.SetText(ch.NomChantier.ToCharArray(), 0, ch.NomChantier.Length);
text.Gravity = GravityFlags.Center;
tableR.AddView(text,0);
TextView text2 = new TextView(this);
text2.Gravity = GravityFlags.Center;
string cdttr = pe.Pers_Prenom + " " + pe.Pers_Nom;
text2.SetText(cdttr.ToCharArray(), 0,cdttr.Length);
tableR.AddView(text2, 1);
TextView text3 = new TextView(this);
text3.Gravity = GravityFlags.Center;
text3.SetText(item.DateDebut.ToString("d").ToCharArray(), 0, item.DateDebut.ToString("d").Length);
tableR.AddView(text3, 2);
TextView text4 = new TextView(this);
text3.Gravity = GravityFlags.Center;
text4.SetText(item.DateFin.ToString("d").ToCharArray(), 0, item.DateFin.ToString("d").Length);
tableR.AddView(text4, 3);
tableR.Id =View.GenerateViewId();
tableR.Clickable = true;
idengin = item.IdEngin;
idassign = idass;
iddemandeur = IdUser;
idreceveur = ch.Cdt;
tableR.Click += HandleClick;
_table.AddView(tableR);
// _listView.ItemClick += _listView_ItemClick;
}
}
}
}
}
_adapter3 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, assignmatod);
}
catch (MobileServiceInvalidOperationException e)
{
Console.Error.WriteLine(#"ERROR {0}", e.Message);
// return null;
}
}
private void HandleClick(object sender, EventArgs e)
{
var clickedTableRow = sender as TableRow;
int s = clickedTableRow.Id;
var tag = clickedTableRow.Tag;
string ideng = idengin;
string idass = idassign;
string idrecev = idreceveur;
string iddeman = iddemandeur;
string arg = _adapter3.GetItem(s-1).ToString();
string message = "Envoyer une demande pour cette engin sur la période concernée?";
CreateAndShowDialogDemande(message, "DEMANDE ENGIN", ideng, iddeman, idass, idrecev);
Toast.MakeText(this, tag + " idassign "+ s+ "arg " + arg, ToastLength.Long).Show();
}
private async void CreateAndShowDialogDemande(string message, string title, string idmat, string IdDemande, string IdAssignMat, string Idreceveur )
{
Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
string IdDuChantier = Intent.GetStringExtra("IdDuChantier");
builder.SetMessage(message);
builder.SetTitle(title);
builder.Create();
builder.SetPositiveButton("Faire la demande ?", async (senderAlert, args) =>
{
var Demande = new AlertMateriel
{
IdMateriel = idmat,
IdDemandeur = IdDemande,
IdAssignMat = IdAssignMat,
IdReceveur = Idreceveur,
VU = false,
Deleted = "False",
};
try
{
progress = new Android.App.ProgressDialog(this);
progress.Indeterminate = true;
progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner);
progress.SetMessage("Envoie de la Demande ...");
progress.SetCancelable(false);
progress.Show();
await AlertMat.InsertAsync(Demande);
await SyncAsync(pullData: true);
progress.Cancel();
CreateAndShowDialog("Demande", "Votre demande a été envoyé...");
// Toast.MakeText(this, "Votre demande a été envoyé", ToastLength.Long).Show();
//await client.SyncContext.PushAsync();
}
catch (Exception e)
{
CreateAndShowDialog(e.ToString(), "Error");
}
});
builder.SetNegativeButton("Annuler", (senderAlert, args) =>
{
builder.Dispose();
});
builder.Show();
}
private void CreateAndShowDialog(String title, string message)
{
Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
builder.SetMessage(message);
builder.SetTitle(title);
builder.SetNegativeButton("Rester sur la page", (senderAlert, args) =>
{
builder.Dispose();
});
builder.Create().Show();
}
private async Task InitLocalStoreAsync()
{
// new code to initialize the SQLite store
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), localDbFilename);
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<AlertMateriel>();
store.DefineTable<Personnel>();
store.DefineTable<Chantiers>();
store.DefineTable<AssignMaterielDB>();
store.DefineTable<MaterielDB>();
// Uses the default conflict handler, which fails on conflict
// To use a different conflict handler, pass a parameter to InitializeAsync. For more details, see http://go.microsoft.com/fwlink/?LinkId=521416
await client.SyncContext.InitializeAsync(store);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
}
private async Task SyncAsync(bool pullData = false)
{
try
{
await client.SyncContext.PushAsync();
await ChantiersTable.PullAsync("allTodoItems", ChantiersTable.CreateQuery()); // query ID is used for incremental sync
await AssignMaterielTable.PullAsync("allMat", AssignMaterielTable.CreateQuery());
await MaterielTable.PullAsync("alltvx", MaterielTable.CreateQuery());
await PersonnelTable.PullAsync("allUsers", PersonnelTable.CreateQuery());
await AlertMat.PullAsync("AlertMateirel", AlertMat.CreateQuery());
}
catch (Java.Net.MalformedURLException)
{
CreateAndShowDialog("", "Error");
}
catch (Exception e)
{
CreateAndShowDialog( "Error", e.ToString());
}
}
}}
Exception:
MobileServiceInvalidOperationException
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
04-13 09:59:47.656 I/mono-stdout( 3806): Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient+<ThrowInvalidResponse>d__18.MoveNext () [0x0022f] in <7e121fd8cdc34770a425d1c0c9715a23>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.Comp
ilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
04-13 09:59:47.656 I/mono-stdout( 3806): at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient+<ThrowInvalidResponse>d__18.MoveNext () [0x0022f] in <7e121fd8cdc34770a425d1c0c9715a23>:0
04-13 09:59:47.656 I/mono-stdout( 3806): --- End of stack trace from previous location where exception was thrown ---
04-13 09:59:47.656 I/mono-stdout( 3806): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
04-13 09:59:47.656 I/mono-stdout( 3806): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
04-13 09:59:47.656 I/mono-stdout( 3806): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
04-13 09:59:47.656 I/mono-stdout( 3806): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
04-13 09:59:47.656 I/mono-stdout( 3806): at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:113
04-13 09:59:47.656 I/mono-stdout( 3806): at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient+<SendRequestAsync>d__1d.MoveNext () [0x0010d] in <7e121fd8cdc34770a425d1c0c9715a23>:0
04-13 09:59:47.656 I/mono-stdout( 3806): --- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/data/lanes/3511/501e63ce/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:113
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient+<SendRequestAsync>d__1d.MoveNext () [0x0010d] in <7e121fd8cdc34770a425d1c0c9715a23>:0
If something is missing or you need more details let me know.
Thank you by advance.

Related

Vaadin Combobox and LazyInitializationException

My question maybe simple simple but I don't understand why Vaadin combobox tries to get a colletion of nested entities set in a combobox if I do not call these items of collection.
See this:
#Entity
public class Estado extends AbstractEntity {
private String nome;
private String sigla;
#OneToMany(mappedBy = "estado")
private List<Municipio> municipios;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSigla() {
return sigla;
}
public void setSigla(String sigla) {
this.sigla = sigla;
}
public List<Municipio> getMunicipios() {
return municipios;
}
public void setMunicipios(List<Municipio> municipios) {
this.municipios = municipios;
}
private void initCbEstados() {
if (cbEstados.isEmpty()) {
List<Estado> estados = estadoService.findAllEager();
cbEstados.setItems(estados);
}
cbEstados.addValueChangeListener(e -> updateCbMunicipios());
cbEstados.setClearButtonVisible(true);
cbEstados.setItemLabelGenerator(Estado::getNome);
cbEstados.setWidth("50%");
}
private void updateViewToEdit(){
if (isEditMode) {
Estado estado = entity.getEndereco().getEstado();
***//this throws LazyInitializationException***
cbEstados.setValue(estado);
updateCbMunicipios();
}
I do not call at any time estado.getMunicipios. But apparently the behavior of the combobox tries to infer in the municipios released the exception.
Is this expected behavior?
I don't think it should be?
Sory, fisrt post on stack overflow and i was not familiar with the platform and ended not posting the entire code. The error occurred in
cbEstados.addValueChangeListener(e -> updateCbMunicipios());
that during the debug was not visible because it was occurring within the vaadin classes. The problem was solved by searching for the municpios in updateCbMunicpios(); So when FormBase calls beforeEnter(BeforeEnterEvent event) the readBean() set values on cbEstados that fires ValuechangeListener and load the LazeInicializaTionExceptions because Entity comes from the Request Scoope and not Fully filed to set the Value of Municipio in cbMunicipios. And cbMunicipios would be empty firing anhoter error from Vaadin.
public class FornecedorForm extends CadastroFormBaseGenerics<Fornecedor, FornecedorService> {
private static final long serialVersionUID = -5599427454458715210L;
EstadoService estadoService;
#PropertyId("ativo")
private Checkbox ckAtivo;
#PropertyId("razaoSocial")
private TextField txtRazaoSocial;
#PropertyId("nomeFantasia")
private TextField txtNomeFantasia;
#PropertyId("cnpj")
private TextField txtCnpj;
#PropertyId("contato")
private TextField txtContato;
#PropertyId("telefoneContato")
private TextField txtTelContato;
#PropertyId("telefone")
private TextField txtTelefone;
#PropertyId("observacao")
TextArea txtObservacao;
private ComboBox<Estado> cbEstados;
private ComboBox<Municipio> cbMunicipios;
private TextField txtCep;
private TextField txtLogradouro;
private TextField txtNumero;
private TextField txtComplemento;
#PropertyId("emailContato")
EmailField txtEmailContato;
private FormLayout layout;
HorizontalLayout layoutEstado;
public FornecedorForm(#Autowired EstadoService estadoService) {
super(Fornecedor.class, "Fornecedor");
this.estadoService = estadoService;
updateViewToEdit();
}
protected void configureAdditionalBinds() {
getBinder().bind(cbEstados, "endereco.estado");
getBinder().bind(cbMunicipios, "endereco.municipio");
getBinder().bind(txtCep, "endereco.cep");
getBinder().bind(txtLogradouro, "endereco.logradouro");
getBinder().bind(txtNumero, "endereco.numero");
getBinder().bind(txtComplemento, "endereco.complemento");
}
private void initCbEstados() {
cbEstados = new ComboBox<Estado>("Estado");
List<Estado> estados = estadoService.findAllEager();
cbEstados.setItems(estados);
cbEstados.addValueChangeListener(e -> updateCbMunicipios());
cbEstados.setClearButtonVisible(true);
cbEstados.setItemLabelGenerator(Estado::getNome);
cbEstados.setWidth("50%");
}
private void initCbMunicpios() {
cbMunicipios = new ComboBox<Municipio>("Município");
cbMunicipios.setItemLabelGenerator(Municipio::getNome);
cbMunicipios.setWidth("50%");
cbMunicipios.setReadOnly(true);
}
private void updateCbMunicipios() {
if (cbEstados.getValue() != null) {
cbMunicipios.clear();
cbMunicipios.setReadOnly(false);
Estado estado = estadoService.findMunicipios(cbEstados.getValue());
cbMunicipios.setItems(estado.getMunicipios());
} else {
cbMunicipios.clear();
cbMunicipios.setReadOnly(true);
}
}
#Override
protected void initViewComponents() {
layoutEstado = new HorizontalLayout();
layout = new FormLayout();
layoutEstado.setSizeFull();
initCbEstados();
initCbMunicpios();
ckAtivo = new Checkbox("Ativo ?", true);
txtRazaoSocial = new TextField("Razão Social");
txtNomeFantasia = new TextField("Nome Fantasia");
txtCnpj = new TextField("CNPJ");
txtCnpj.setWidth("25%");
// txtCnpj.setErrorMessage("CNPJ Incorreto.");
// txtCnpj.setPattern("^[0-9]{2}?[-s.]?[0-9]{3}[-s.]?[0-9]{3}[-s/]?[0-9]{4}[-s-]?[0-9]{2}$");
txtTelefone = new TextField("Telefone");
txtContato = new TextField("Nome Contato");
txtTelContato = new TextField("Telefone Contato");
txtEmailContato = new EmailField("Email Contato");
txtEmailContato.setClearButtonVisible(true);
txtEmailContato.setErrorMessage("Formato do E-mail incorreto");
txtEmailContato.setRequiredIndicatorVisible(false);
txtLogradouro = new TextField("Logradouro");
txtNumero = new TextField("Número");
txtNumero.setWidth("50px");
txtCep = new TextField("CEP");
txtCep.setPattern("^[0-9]{5}?[-s-]?[0-9]{3}$");
txtCep.setPlaceholder("00000-000");
txtCep.setRequired(true);
txtCep.setErrorMessage("Informe o CEP");
txtCep.setWidth("75px");
txtComplemento = new TextField("Complemento");
txtObservacao = new TextArea("Observações");
layout.add(ckAtivo, 2);
layout.add(txtCnpj, 2);
layout.add(txtRazaoSocial, txtNomeFantasia);
layout.add(layoutEstado, 2);
layout.add(txtLogradouro, txtNumero);
layout.add(txtComplemento, txtCep, txtTelefone);
HorizontalLayout layoutContato = new HorizontalLayout(txtContato, txtTelContato, txtEmailContato);
layoutContato.setSizeFull();
txtContato.setWidth("40%");
txtEmailContato.setWidth("40%");
txtTelContato.setWidth("20%");
layout.add(layoutContato, 2);
layout.add(txtObservacao, 2);
super.formLayout.add(layout);
layoutEstado.add(cbEstados, cbMunicipios);
configureAdditionalBinds();
}
protected void updateViewToEdit() {
if (isEditMode) {
Estado estado = entity.getEndereco().getEstado();
estado = estadoService.findMunicipios(estado);
cbEstados.setValue(estado);
}
}
#Override
protected void getNewEntityToPersist() {
entity = new Fornecedor();
entity.setEndereco(new Endereco());
ckAtivo.setValue(true);
}
}
public abstract class CadastroFormBaseGenerics<T, SERVICE extends ServiceInterface<T>> extends FormLayout
implements BeforeEnterObserver {
private static final long serialVersionUID = 7069232922824142288L;
protected T entity;
#Autowired
private SERVICE service;
private final Class<T> beanClass;
private Binder<T> binder;
private String nomeDoBean;
protected boolean isEditMode;
private Button btnSave = new Button("Salvar");
private Button btnDelete = new Button("Excluir");
private Button btnCancel = new Button("Cancelar");
protected VerticalLayout formLayout = new VerticalLayout();;
private HorizontalLayout buttonsLayout = new HorizontalLayout();
public CadastroFormBaseGenerics(Class<T> beanClass, String nomeDoBean) {
this.beanClass = beanClass;
this.nomeDoBean = nomeDoBean;
}
protected abstract void initViewComponents();
#PostConstruct
private void inicialize() {
checkEditMode();
initBinder();
initViewComponents();
addComponentAsFirst(formLayout);
configureFormLayout();
getEntityToEdit();
updateViewToEdit();
}
protected abstract void updateViewToEdit();
protected void initBinder() {
binder = new BeanValidationBinder<T>(beanClass);
}
protected void setPlaceHolders(String beanName) {
String primeiraLetra = "" + beanName.charAt(0);
primeiraLetra = primeiraLetra.toUpperCase();
char letraMaiuscula = primeiraLetra.charAt(0);
char[] cArray = beanName.toCharArray();
cArray[0] = letraMaiuscula;
beanName = new String(cArray);
for (int i = 0; i < formLayout.getComponentCount(); i++) {
Component c = formLayout.getComponentAt(i);
if (c.getClass().getName().equals("com.vaadin.flow.component.textfield.TextField")) {
TextField aux = (TextField) c;
aux.setPlaceholder(aux.getLabel() + " " + beanName + "...");
aux.setClearButtonVisible(true);
}
}
}
protected void configureFormLayout() {
formLayout.setSizeFull();
// formLayout.setMargin(true);
formLayout.setSpacing(true);
formLayout.setPadding(true);
formLayout.setAlignItems(Alignment.AUTO);
formLayout.setMargin(true);
// add(formLayout, 2);
configureButtonsLayout();
}
void configureButtonsLayout() {
btnDelete.setVisible(false);
btnSave.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
btnDelete.addThemeVariants(ButtonVariant.LUMO_ERROR);
buttonsLayout = new HorizontalLayout();
buttonsLayout.add(btnSave, btnDelete, btnCancel);
buttonsLayout.setMargin(true);
buttonsLayout.setPadding(true);
buttonsLayout.setSizeFull();
configureButtonEvents();
add(buttonsLayout, 2);
}
private void configureButtonEvents() {
btnSave.addClickListener(saveEvent -> save());
btnDelete.addClickListener(deleteEvent -> delete());
btnCancel.addClickListener(cancelEvent -> clearForm());
}
private void save() {
String msg = nomeDoBean + " Alterada(o) com sucesso.";
if (!isEditMode) {
msg = nomeDoBean + " Cadastrada(o) com sucesso.";
getNewEntityToPersist();
// getNewEntity();
}
try {
getBinder().writeBean(entity);
service.save(entity);
clearForm();
showSucess(msg);
} catch (DoisCsCrudException e) {
showWarnig(nomeDoBean + " já cadastrado. Verique.");
logException(e, "Metodo save()");
} catch (ValidationException e) {
showWarnig("Verique os campos obrigatórios.");
}
}
/**
* {#summary} Você deve implementar o {#code} entity = New POJO este método é
* chamado toda vez que {#code} save() para criar um novo BEAN a ser persistido.
*/
protected abstract void getNewEntityToPersist();
private void delete() {
try {
service.delete(entity);
clearForm();
showSucess(nomeDoBean + " removida(o) com sucesso.");
} catch (DoisCsCrudException e) {
showWarnig(nomeDoBean + " não pode ser removida(o), pois existem registros que dependem dele. %/n "
+ "Inative-o para que não seja mais exibido.");
}
}
#SuppressWarnings("unchecked")
private void getEntityToEdit() throws ClassCastException {
if (isEditMode) {
btnDelete.setVisible(true);
this.entity = (T) VaadinServletRequest.getCurrent().getAttribute("entityToEdit");
}
}
private boolean checkEditMode() {
if (VaadinServletRequest.getCurrent().getAttribute("entityToEdit") != null) {
isEditMode = true;
} else {
isEditMode = false;
}
return isEditMode;
}
/**
* Sempre deve ser chamado após um click no botão salvar, cancelar ou excluir
*/
protected void clearForm() {
// Desabilita o botão para excluir um Bean Cadastrado
btnDelete.setVisible(false);
// Seta editmode para falso, garantido que a proxima interação
// seja com um bean novo
isEditMode = false;
clearBinder();
}
protected void clearBinder() {
binder.readBean(null);
}
protected void showSucess(String message) {
createNotification(message, NotificationVariant.LUMO_SUCCESS, 3000);
}
protected void showError(String message) {
createNotification(message, NotificationVariant.LUMO_ERROR, 5000);
}
protected void showWarnig(String message) {
createNotification(message, NotificationVariant.LUMO_CONTRAST, 10000);
}
private void createNotification(String message, NotificationVariant variant, int duration) {
Notification n = new Notification(message);
n.setDuration(7000);
n.addThemeVariants(variant);
n.setPosition(Position.TOP_CENTER);
n.open();
}
protected void logException(Exception e, String logDesc) {
System.out.println("################ " + logDesc.toUpperCase() + " $$ " + getClass().getSimpleName()
+ " ################");
e.printStackTrace();
}
public Binder<T> getBinder() {
return binder;
}
#Override
public void beforeEnter(BeforeEnterEvent event) {
binder.bindInstanceFields(this);
if (entity != null) {
getBinder().readBean(entity);
}
}
}

Updating image control in Windows Phone 8

I have a HTML5 web app I can view through my mobile devices.
I have an img control that would download an image using an ashx asp.net handler.
I updated via a timer.
I am trying to port this over to a Windows Phone 8.1 app instead.
The image seems to take ages to update (if at all). This is my code:
long tick = DateTime.Now.Ticks;
BitmapImage bmp =new BitmapImage(new Uri("http://my url/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick));
imgFrame1.Source = bmp;
Is this the correct way?
this is the full code:
private async void LogIn()
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/UserManagement/Login.aspx/Test",
new { username = "", password = "", hubuserid = hubuserid });
var str = await resp.Content.ReadAsStringAsync();
var jsonObj = JsonConvert.DeserializeObject<UserLogIn>(str);
if (jsonObj.d.Success)
{
UpdateConnectionState("Logged In");
}
else
{
UpdateConnectionState("Not Logged In");
}
}
}
public class D
{
public string __type { get; set; }
public bool Success { get; set; }
}
public class UserLogIn
{
public D d { get; set; }
}
private string hubuserid = "";
public string Uptime { get; set; }
private byte ImageIsLoaded = 1;
private async void UpdateTime(int data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try
{
txtInfo.Text = data.ToString();
if (ImageIsLoaded == 1)
{
ImageIsLoaded = 0;
long tick = DateTime.Now.Ticks;
BitmapImage bi = new BitmapImage(new Uri("http://www.informedmotion.co.uk/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick, UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened; }
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
//throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
imgFrame1.Source = (BitmapImage)sender;
}
private void imgFrame1_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
}
private void imgFrame1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
ImageIsLoaded = 1;
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
imgFrame1.ImageFailed += imgFrame1_ImageFailed;
imgFrame1.ImageOpened += imgFrame1_ImageOpened;
ConnectToHub();
}
private void ConnectToHub()
{
proxy.On<int>("broadcastMessage", data =>
{
UpdateTime(data);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
ConnectToHub();
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
LogIn();
}
});
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
ConnectToHub();
};
connection.Reconnected += () =>
{
//LogIn();
UpdateConnectionState("The connection was re-established");
};
}
Windows.UI.Core.CoreDispatcher dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
async void UpdateConnectionState(string state)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try{
txtInfo.Text = state;
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
static HubConnection connection = new HubConnection("http://www.informedmotion.co.uk/");
IHubProxy proxy = connection.CreateHubProxy("ChatHub");
If you're going to download the image, then you probably want to hooked the
Image.DownloadProgress event
Image.ImageOpened event
ImageOpened will fire once the download is complete, so at that moment you can set the .Source to it.
While it is downloading (if it's a huge image) you can either show the previous image or a place holder image (with progress bar maybe?)
BitmapImage bi = new BitmapImage(new Uri("http://www.google.com/myimage.bmp", UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened;
hiddenImage.Source = bi; // we need to set it to an element in the visual tree so the
// events will fire, we're going to use the hiddenImage
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
<!-- myImage is your image that you use to show stuff -->
<!-- hiddenImage is the image we use to fire the event -->
<Image x:Name="myImage"></Image>
<Image x:Name="hiddenImage" Visibility="Collapsed"></Image>

How create a MultipartFormFormatter for ASP.NET 4.5 Web API

These links didn't help me:
Way 1
Way 2
Example:
//Model:
public class Group
{
public int Id { get; set; }
public File File { get; set; }
}
//Controller:
[HttpPost]
public void SaveGroup([FromBody]Group group) {}
//Formatter:
public class MultipartFormFormatter : MediaTypeFormatter
{
private const string StringMultipartMediaType = "multipart/form-data";
public MultipartFormFormatter()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(StringMultipartMediaType));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return false;
}
public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
//Implementation? What here should be?
}
}
What should the method ReadFromStreamAsync return?
How do I make it so that you can properly transmit parameter to the action?
public class MultipartFormFormatter : FormUrlEncodedMediaTypeFormatter
{
private const string StringMultipartMediaType = "multipart/form-data";
private const string StringApplicationMediaType = "application/octet-stream";
public MultipartFormFormatter()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(StringMultipartMediaType));
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(StringApplicationMediaType));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return false;
}
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var parts = await content.ReadAsMultipartAsync();
var obj = Activator.CreateInstance(type);
var propertiesFromObj = obj.GetType().GetRuntimeProperties().ToList();
foreach (var property in propertiesFromObj.Where(x => x.PropertyType == typeof(FileModel)))
{
var file = parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name.Contains(property.Name));
if (file == null || file.Headers.ContentLength <= 0) continue;
try
{
var fileModel = new FileModel(file.Headers.ContentDisposition.FileName, Convert.ToInt32(file.Headers.ContentLength), ReadFully(file.ReadAsStreamAsync().Result));
property.SetValue(obj, fileModel);
}
catch (Exception e)
{
}
}
foreach (var property in propertiesFromObj.Where(x => x.PropertyType != typeof(FileModel)))
{
var formData = parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name.Contains(property.Name));
if (formData == null) continue;
try
{
var strValue = formData.ReadAsStringAsync().Result;
var valueType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
var value = Convert.ChangeType(strValue, valueType);
property.SetValue(obj, value);
}
catch (Exception e)
{
}
}
return obj;
}
private byte[] ReadFully(Stream input)
{
var buffer = new byte[16 * 1024];
using (var ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
public class FileModel
{
public FileModel(string filename, int contentLength, byte[] content)
{
Filename = filename;
ContentLength = contentLength;
Content = content;
}
public string Filename { get; set; }
public int ContentLength { get; set; }
public byte[] Content { get; set; }
}
Please see below link for detail implementation:
https://github.com/iLexDev/ASP.NET-WebApi-MultipartDataMediaFormatter
Nuget:
https://www.nuget.org/packages/MultipartDataMediaFormatter/
I actually need to do "multipart/form-data" file upload and model binding today, I tried above lib from nuget and turns out it works as my expectation. Validation on model also works fine. Hopefully it helps to answer your question.

Parsing Jenkins xml result with XStream

I'm trying to parse lint-result.xml produced by Jenkins. I created stand-alone project that takes lint result file and parse it with XStream 1.4.1 (version that is currently used by Jenkins from what I seen in documentation) this works absolutely fine. However when I move code to Jenkins plugin (it is post-build plugin) I'm getting following error
com.thoughtworks.xstream.mapper.CannotResolveClassException: com.peter.android_lint.parser.LintIssues : com.peter.android_lint.parser.LintIssues
at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:68)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:71)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.ClassAliasingMapper.realClass(ClassAliasingMapper.java:86)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.ArrayMapper.realClass(ArrayMapper.java:96)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.CachingMapper.realClass(CachingMapper.java:56)
at com.thoughtworks.xstream.core.util.HierarchicalStreams.readClassType(HierarchicalStreams.java:29)
at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:136)
at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:33)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:926)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:912)
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:864)
at com.peter.android_lint.parser.LintParser.parse(LintParser.java:25)
at com.peter.ReportPublisher.findFiles(ReportPublisher.java:61)
at com.peter.ReportPublisher.perform(ReportPublisher.java:48)
at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:36)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:814)
at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:786)
at hudson.model.Build$BuildExecution.post2(Build.java:183)
at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:733)
at hudson.model.Run.execute(Run.java:1592)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
at hudson.model.ResourceController.execute(ResourceController.java:88)
at hudson.model.Executor.run(Executor.java:237)
Parser class
public class LintParser {
private File lintResult;
public void parse(String fileName) {
lintResult = new File(fileName);
XStream xstream = new XStream();
xstream.alias("issues", LintIssues.class);
xstream.alias("issue", LintIssue.class);
xstream.alias("location", Location.class);
//xstream.processAnnotations(new Class[]{LintIssues.class, LintIssue.class, Location.class});
LintIssues lintIssues = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(lintResult);
bis = new BufferedInputStream(fis);
lintIssues = (LintIssues) xstream.fromXML(bis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<LintIssue> issueList = lintIssues.getIssueList();
for (LintIssue issue : issueList) {
printIssue(issue);
}
if(bis != null){
try{
bis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void printIssue(LintIssue issue) {
System.out.println("ID= " + issue.getId() + " , severity= " + issue.getSeverity() + " , priority= " + issue.getPriority());
for (Location location : issue.getLocations()) {
printLocation(location);
}
}
private void printLocation(Location location) {
System.out.println("\t Location file=" + location.getFilename());
}
}
LintIssues class
//#XStreamAlias("issues")
public class LintIssues {
#XStreamImplicit(itemFieldName = "issue")
private List<LintIssue> issueList = new ArrayList<LintIssue>();
public LintIssues(List<LintIssue> issueList) {
this.issueList = issueList;
}
public List<LintIssue> getIssueList() {
return issueList;
}
}
LintIssue class
//#XStreamAlias("issue")
public class LintIssue {
#XStreamAlias("id")
#XStreamAsAttribute
private String id;
#XStreamAlias("severity")
#XStreamAsAttribute
private String severity;
#XStreamAlias("category")
#XStreamAsAttribute
private String category;
#XStreamAlias("priority")
#XStreamAsAttribute
private int priority;
#XStreamAlias("summary")
#XStreamAsAttribute
private String summary;
#XStreamAlias("explanation")
#XStreamAsAttribute
private String explanation;
#XStreamAlias("message")
#XStreamAsAttribute
private String message;
#XStreamAlias("errorLine1")
#XStreamAsAttribute
private String errorLine1;
#XStreamAlias("errorLine2")
#XStreamAsAttribute
private String errorLine2;
#XStreamImplicit(itemFieldName = "location")
private List<Location> locations = new ArrayList<Location>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getExplanation() {
return explanation;
}
public void setExplanation(String explanation) {
this.explanation = explanation;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getErrorLine1() {
return errorLine1;
}
public void setErrorLine1(String errorLine1) {
this.errorLine1 = errorLine1;
}
public String getErrorLine2() {
return errorLine2;
}
public void setErrorLine2(String errorLine2) {
this.errorLine2 = errorLine2;
}
public List<Location> getLocations() {
return locations == null ? new ArrayList<Location>() : locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
}
Location class
//#XStreamAlias("location")
public class Location implements Serializable {
private static final long serialVersionUID = 1128640353127613495L;
#XStreamAlias("file")
#XStreamAsAttribute
private String filename;
#XStreamAlias("line")
#XStreamAsAttribute
private int lineNumber;
#XStreamAlias("column")
#XStreamAsAttribute
private int column;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
}
You might have better luck getting a good answer to this question by participating in the jenkinsci-dev mailing list.

BlackBerry Alarm Integeration

Below is my application code. i want alarm to ring on my blackberry on every 6 of this month whether this apllication is running or not. please guide me in details i am a beginner.
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import net.rim.device.api.util.*;
import java.util.*;
import java.lang.String.*;
public class ListChk extends UiApplication
{
String getFirstName;
String getLastName;
String getEmail;
String getGender;
String getStatus;
String getCompany;
/*declaring text fields for user input*/
private AutoTextEditField firstName;
private AutoTextEditField lastName;
private AutoTextEditField company;
private EmailAddressEditField email;
/*declaring choice field for user input*/
private ObjectChoiceField gender;
/*declaring check box field for user input*/
private CheckboxField status;
//Declaring button fields
private ButtonField save;
private ButtonField close;
private ButtonField List;
private ButtonField search;
/*declaring vector*/
private static Vector _data;
/*declaring persistent object*/
private static PersistentObject store;
/*creating an entry point*/
public static void main(String[] args)
{
ListChk objListChk = new ListChk();
objListChk.enterEventDispatcher();
}//end of main of ListChk
public ListChk()
{
/*Creating an object of the main screen class to use its functionalities*/
MainScreen mainScreen = new MainScreen();
//setting title of the main screen
mainScreen.setTitle(new LabelField("Enter Your Data"));
//creating text fields for user input
firstName = new AutoTextEditField("First Name: ", "");
lastName= new AutoTextEditField("Last Name: ", "");
email= new EmailAddressEditField("Email:: ", "");
company = new AutoTextEditField("Company: ", "");
//creating choice field for user input
String [] items = {"Male","Female"};
gender= new ObjectChoiceField("Gender",items);
//creating Check box field
status = new CheckboxField("Active",true);
//creating Button fields and adding functionality using listeners
// A button that saves the the user data persistently when it is clicked
save = new ButtonField("Save",ButtonField.CONSUME_CLICK);
save.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
save();
}
});
// a button which closes the entire application when clicked
close = new ButtonField("Close",ButtonField.CONSUME_CLICK);
close.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
onClose();
}
});
// A button that shows the List of all Data being stored persistently
List = new ButtonField("List",ButtonField.CONSUME_CLICK);
List.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context){
// pushing the next screen
pushScreen(new ListScreen());
}
});
search = new ButtonField("Search",ButtonField.CONSUME_CLICK);
search.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
pushScreen(new SearchScreen());
}
});
//adding the input fields to the main screen
mainScreen.add(firstName);
mainScreen.add(lastName);
mainScreen.add(email);
mainScreen.add(company);
mainScreen.add(gender);
mainScreen.add(status);
// Addning horizontal field manager
HorizontalFieldManager horizontal = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
//adding buttons to the main screen in Horizontal field manager
horizontal.add(close);
horizontal.add(save);
horizontal.add(List);
horizontal.add(search);
//Adding the horizontal field manger to the screen
mainScreen.add(horizontal);
//adding menu items
mainScreen.addMenuItem(saveItem);
mainScreen.addMenuItem(getItem);
mainScreen.addMenuItem(Deleteall);
//pushing the main screen
pushScreen(mainScreen);
}
private MenuItem Deleteall = new MenuItem("Delete all",110,10)
{
public void run()
{
int response = Dialog.ask(Dialog.D_YES_NO,"Are u sure u want to delete entire Database");
if(Dialog.YES == response){
PersistentStore.destroyPersistentObject(0xdec6a67096f833cL);
Dialog.alert("Closing Application");
onClose();
}
else
Dialog.inform("Thank God");
}
};
//adding functionality to menu item "saveItem"
private MenuItem saveItem = new MenuItem("Save", 110, 10)
{
public void run()
{
//Calling save method
save();
}
};
//adding functionality to menu item "saveItem"
private MenuItem getItem = new MenuItem("Get", 110, 11)
{
//running thread for this menu item
public void run()
{
//synchronizing thread
synchronized (store)
{
//getting contents of the persistent object
_data = (Vector) store.getContents();
try{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
getFirstName = (info.getElement(StoreInfo.NAME));
getLastName = (info.getElement(StoreInfo.LastNAME));
getEmail = (info.getElement(StoreInfo.EMail));
getGender = (info.getElement(StoreInfo.GenDer));
getStatus = (info.getElement(StoreInfo.setStatus));
getCompany = (info.getElement(StoreInfo.setCompany));
//calling the show method
show();
}
}
}
catch(Exception e){}
}
}
};
public void save()
{
//creating an object of inner class StoreInfo
StoreInfo info = new StoreInfo();
//getting the test entered in the input fields
info.setElement(StoreInfo.NAME, firstName.getText());
info.setElement(StoreInfo.LastNAME,lastName.getText());
info.setElement(StoreInfo.EMail, email.getText());
info.setElement(StoreInfo.setCompany, company.getText());
info.setElement(StoreInfo.GenDer,gender.toString());
if(status.getChecked())
info.setElement(StoreInfo.setStatus, "Active");
else
info.setElement(StoreInfo.setStatus, "In Active");
//adding the object to the end of the vector
_data.addElement(info);
//synchronizing the thread
synchronized (store)
{
store.setContents(_data);
store.commit();
}
//resetting the input fields
Dialog.inform("Success!");
firstName.setText(null);
lastName.setText(null);
email.setText("");
company.setText(null);
gender.setSelectedIndex("Male");
status.setChecked(true);
}
//coding for persistent store
static {
store =
PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new Vector());
store.commit();
}
}
_data = new Vector();
_data = (Vector) store.getContents();
}
//new class store info implementing persistable
private static final class StoreInfo implements Persistable
{
//declaring variables
private Vector _elements;
public static final int NAME = 0;
public static final int LastNAME = 1;
public static final int EMail= 2;
public static final int GenDer = 3;
public static final int setStatus = 4;
public static final int setCompany = 5;
public StoreInfo()
{
_elements = new Vector(6);
for (int i = 0; i < _elements.capacity(); ++i)
{
_elements.addElement(new String(""));
}
}
public String getElement(int id)
{
return (String) _elements.elementAt(id);
}
public void setElement(int id, String value)
{
_elements.setElementAt(value, id);
}
}
//details for show method
public void show()
{
Dialog.alert("Name is "+getFirstName+" "+getLastName+"\nGender is "+getGender+"\nE-mail: "+getEmail+"\nStatus is "+getStatus);
}
public void list()
{
Dialog.alert("haha");
}
//creating save method
//overriding onClose method
public boolean onClose()
{
System.exit(0);
return true;
}
class ListScreen extends MainScreen
{
String getUserFirstName;
String getUserLastName;
String getUserEmail;
String getUserGender;
String getUserStatus;
String getUserCompany;
String[] setData ;
String getData = new String();
String collectData = "";
ObjectListField fldList;
int counter = 0;
private ButtonField btnBack;
public ListScreen()
{
setTitle(new LabelField("Showing Data",LabelField.NON_FOCUSABLE));
//getData = myList();
//Dialog.alert(getData);
// setData = split(getData,"$");
// for(int i = 0;i<setData.length;i++)
// {
// add(new RichTextField(setData[i]+"#####"));
// }
showList();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK|ButtonField.FIELD_HCENTER);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field,int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void showList()
{
HorizontalFieldManager hfManager = new HorizontalFieldManager(HorizontalFieldManager.HORIZONTAL_SCROLLBAR|HorizontalFieldManager.HORIZONTAL_SCROLL);
//SeparatorField spManager = new SeparatorField();
LabelField lblcheck = new LabelField("check",LabelField.NON_FOCUSABLE);
getData = myList();
setData = split(getData,"$");
fldList = new ObjectListField(ObjectListField.MULTI_SELECT);
fldList.set(setData);
//fldList.setEmptyString("heloo", 12);
//hfManager.add(lblcheck);
hfManager.add(fldList);
//hfManager.add(spManager);
add(hfManager);
addMenuItem(new MenuItem("Select", 100, 1) {
public void run() {
int selectedIndex = fldList.getSelectedIndex();
String item = (String)fldList.get(fldList, selectedIndex);
pushScreen(new ShowDataScreen(item));
}
});
}
public String[] split(String inString, String delimeter) {
String[] retAr;
try {
Vector vec = new Vector();
int indexA = 0;
int indexB = inString.indexOf(delimeter);
while (indexB != -1) {
vec.addElement(new String(inString.substring(indexA, indexB)));
indexA = indexB + delimeter.length();
indexB = inString.indexOf(delimeter, indexA);
}
vec.addElement(new String(inString.substring(indexA, inString
.length())));
retAr = new String[vec.size()];
for (int i = 0; i < vec.size(); i++) {
retAr[i] = vec.elementAt(i).toString();
}
} catch (Exception e) {
String[] ar = { e.toString() };
return ar;
}
return retAr;
}//end of Split Method
public String myList()
{
_data = (Vector) store.getContents();
try
{
for (int i = _data.size()-1; i >-1; i--,counter++)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
//StoreInfo info = (StoreInfo)_data.lastElement();
getUserFirstName = (info.getElement(StoreInfo.NAME));
getUserLastName = (info.getElement(StoreInfo.LastNAME));
//getUserEmail = (info.getElement(StoreInfo.EMail));
//getUserGender = (info.getElement(StoreInfo.GenDer));
//getUserStatus = (info.getElement(StoreInfo.setStatus));
getUserCompany = (info.getElement(StoreInfo.setCompany));
collectData = collectData + getUserFirstName+" "+getUserLastName+" "+getUserCompany+ "$";
}
}
}
catch(Exception e){}
return collectData;
}//end of myList method
public boolean onClose()
{
System.exit(0);
return true;
}
}//end of class ListScreen
class ShowDataScreen extends MainScreen
{
String getFirstName;
String getLastName;
String getCompany;
String getEmail;
String getGender;
String getStatus;
String[] getData;
public ShowDataScreen(String data)
{
getData = split(data," ");
getFirstName = getData[0];
getLastName = getData[1];
getCompany = getData[2];
_data = (Vector) store.getContents();
try
{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
if (!_data.isEmpty())
{
if((getFirstName.equalsIgnoreCase(info.getElement(StoreInfo.NAME))) && (getLastName.equalsIgnoreCase(info.getElement(StoreInfo.LastNAME))) && (getCompany.equalsIgnoreCase(info.getElement(StoreInfo.setCompany))))
{
getEmail = info.getElement(StoreInfo.EMail);
getGender = info.getElement(StoreInfo.GenDer);
getStatus = info.getElement(StoreInfo.setStatus);
HorizontalFieldManager hfManager = new HorizontalFieldManager(HorizontalFieldManager.NON_FOCUSABLE);
AutoTextEditField name = new AutoTextEditField("Name: ",getFirstName+" "+getLastName);
AutoTextEditField email = new AutoTextEditField("Email: ",getEmail);
AutoTextEditField company = new AutoTextEditField("Company: ",getCompany);
AutoTextEditField Gender = new AutoTextEditField("Gender: ",getGender);
AutoTextEditField status = new AutoTextEditField("Status: ",getStatus);
add(name);
add(email);
add(company);
add(Gender);
add(status);
}
}
}//end of for loop
}//end of try
catch(Exception e){}
//Dialog.alert("fname is "+getFirstName+"\nlastname = "+getLastName+" company is "+getCompany);
}
public String[] split(String inString, String delimeter) {
String[] retAr;
try {
Vector vec = new Vector();
int indexA = 0;
int indexB = inString.indexOf(delimeter);
while (indexB != -1) {
vec.addElement(new String(inString.substring(indexA, indexB)));
indexA = indexB + delimeter.length();
indexB = inString.indexOf(delimeter, indexA);
}
vec.addElement(new String(inString.substring(indexA, inString
.length())));
retAr = new String[vec.size()];
for (int i = 0; i < vec.size(); i++) {
retAr[i] = vec.elementAt(i).toString();
}
} catch (Exception e) {
String[] ar = { e.toString() };
return ar;
}
return retAr;
}//end of Split Method
}
class SearchScreen extends MainScreen
{
private ButtonField btnFirstName;
private ButtonField btnLastName;
private ButtonField btnSearch;
private ButtonField btnEmail;
private SeparatorField sp;
String userName;
HorizontalFieldManager hr = new HorizontalFieldManager();
public AutoTextEditField searchField;
public SearchScreen()
{
sp = new SeparatorField();
setTitle(new LabelField("your Search Options"));
add(new RichTextField("Search by : "));
btnFirstName = new ButtonField("First Name",ButtonField.CONSUME_CLICK);
hr.add(btnFirstName);
btnFirstName.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//HorizontalFieldManager hrs = new HorizontalFieldManager();
searchField = new AutoTextEditField("First Name: ","ali");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new FirstnameScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
//hrs.add(sp);
}
});
btnLastName = new ButtonField("Last Name",ButtonField.CONSUME_CLICK);
hr.add(btnLastName);
btnLastName.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int Context)
{
searchField = new AutoTextEditField("Last Name: ","");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new LastnameScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
}
});
btnEmail = new ButtonField("Email",ButtonField.CONSUME_CLICK);
hr.add(btnEmail);
btnEmail.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int Context)
{
searchField = new AutoTextEditField("Email: ","");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new EmailScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
}
});
add(hr);
}
void myShow()
{
Dialog.alert(searchField.getText());
}
}
class FirstnameScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public FirstnameScreen(String name)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+name));
userName = name;
searchFirstName();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void searchFirstName()
{
ButtonField btnDelete;
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
//mGrid.add(new ButtonField("Delete"));
//SeparatorField sps = new SeparatorField();
//mGrid.add(sps);
add(mGrid);
_data = (Vector) store.getContents();
try {
for (int i = _data.size() - 1; i > -1; i--) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
firstUserName = (info.getElement(StoreInfo.NAME));
if(firstUserName.equalsIgnoreCase(userName))
{
// if not empty
// create a new object of Store Info class
// stored information retrieved in strings
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
final int sn = i;
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
btnDelete.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
_data.removeElementAt(sn);
}
});
add(btnDelete);
// SeparatorField sps1 = new SeparatorField();
//mGrid.add(sps1);
}
}
}
} catch (Exception e) {
}
}
}
class LastnameScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public LastnameScreen(String name)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+name));
userName = name;
searchLastName();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void searchLastName()
{
ButtonField btnDelete;
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
//mGrid.add(new ButtonField("Delete"));
//SeparatorField sps = new SeparatorField();
//mGrid.add(sps);
add(mGrid);
_data = (Vector) store.getContents();
try {
for (int i = _data.size() - 1; i > -1; i--) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
lastUserName = (info.getElement(StoreInfo.LastNAME));
if(lastUserName.equalsIgnoreCase(userName))
{
// if not empty
// create a new object of Store Info class
// stored information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
final int sn = i;
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
btnDelete.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
_data.removeElementAt(sn);
}
});
add(btnDelete);
// SeparatorField sps1 = new SeparatorField();
//mGrid.add(sps1);
}
}
}
} catch (Exception e) {
}
}
}
class EmailScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public EmailScreen(String mail)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+mail));
userName = mail;
searchEmail();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBa
What are the benefits of integrating with the built-in alarm application? Would it be better for your application to place an event in the device's calendar and make the event show a reminder?
If you have to have a more prominent alarm, why not do it yourself? An alarm is an action the phone does (either make a sound and/or vibrate) that shows on the screen why it is taking that action and the action stops when someone responds to it.
Can you just make an app that starts in the background, checks the day, and makes a sound/vibrates on that day?
The default Alarm app on my phone only supports one time to ring. If I set it to wake me up at 4 a.m., but your app reschedules the alarm on my phone for 8 a.m., you would instantly lose a customer (after I wake up 4 hours too late).

Resources