Codename One - Validator of PickerComponent - codenameone

In the following code, the Validator of the PickerComponent "date" is never executed on the Simulator with "GooglePixel2.skin", instead is executed with "iPhoneX.skin". Why?
In the log there isn't the string "Validator of date executed" after picking a date on Android (in the simulator), instead that string is continuosly logged on iPhone (in the simulator). Is my code incorrect?
I tried to follow this example: https://www.codenameone.com/javadoc/com/codename1/ui/layouts/TextModeLayout.html
public void show(Form backForm) {
TextModeLayout textModeLayout = new TextModeLayout(4, 1);
Container inputPersonData = new Container(textModeLayout);
TextComponent name = new TextComponent().label("Nome");
TextComponent surname = new TextComponent().label("Cognome");
PickerComponent gender = PickerComponent.createStrings("Maschio", "Femmina", "altro");
PickerComponent date = PickerComponent.createDate(new Date());
Validator val = new Validator();
val.addConstraint(name, new LengthConstraint(2));
val.addConstraint(surname, new LengthConstraint(2));
val.addConstraint(date, new Constraint() {
#Override
public boolean isValid(Object value) {
Log.p("Validator of date executed");
boolean res = false;
if (value instanceof Date) {
Calendar birthday = Calendar.getInstance();
birthday.setTime((Date) value);
Calendar nowLess13years = Calendar.getInstance();
nowLess13years.setTime(new Date());
nowLess13years.add(Calendar.YEAR, -13);
if (birthday.before(nowLess13years) || birthday.equals(nowLess13years)) {
res = true;
}
}
return res;
}
#Override
public String getDefaultFailMessage() {
return "You must be at least 13 years old";
}
});
inputPersonData.add(name);
inputPersonData.add(surname);
inputPersonData.add(gender);
inputPersonData.add(date);
add(inputPersonData);
super.show();
Log.p("Registry Form shown correctly");
}

That seems to be a bug in the validator code and picker component. It works for me only after I edit one of the fields regardless of the skin. I've fixed this to bind correctly everywhere.

Related

Codename One Picker text spinning after item is selected

I have a CN1 application that uses three pickers inside a container.
One of the pickers just contains small strings like "1x" , "2x" , etc.
Every time an item is selected on the running application, the selected text spins really fast, what looks kind of odd.
I have tried setting padding and margin to zero, and set SmoothScrolling to false.
picker.setSmoothScrolling(false);
All to no avail.
Is there ant solution to it? Many thanks in advance ..
Here is the relevant part of the code:
private final Picker pickerInterval = new Picker();
private final Picker pickerDayOrMonth = new Picker();
private final Picker pickerFinal = new Picker();
String stringPickerInterval = "repetir a cada ..";
pickerInterval.setType(Display.PICKER_TYPE_STRINGS);
pickerInterval.setUIID("DatePickerDialog");
pickerInterval.setStrings("1","2","3","4","5","6","6","8","9","10","11","12",stringPickerInterval);
pickerInterval.setSelectedString(stringPickerInterval);
pickerInterval.addActionListener((e) -> {
if (!pickerInterval.getSelectedString().equals(stringPickerInterval)) {
pickerInterval.setUIID("DatePickerDialogSelected");
} else {
pickerInterval.setUIID("DatePickerDialog");
}
});
String stringPickerDayOr = "dias ou semanas ou ...";
pickerDayOrMonth.setType(Display.PICKER_TYPE_STRINGS);
pickerDayOrMonth.setUIID("DatePickerDialog");
pickerDayOrMonth.setStrings("Dia(s)", "Semana(s)", "Mes(es)","Ano(s)" , stringPickerDayOr);
pickerDayOrMonth.setSelectedString(stringPickerDayOr);
pickerDayOrMonth.addActionListener((e) -> {
if (!pickerDayOrMonth.getSelectedString().equals(stringPickerDayOr)) {
pickerDayOrMonth.setUIID("DatePickerDialogSelected");
} else {
pickerDayOrMonth.setUIID("DatePickerDialog");
}
});
String stringPickerFinal = "freqüência das repetições ..";
pickerFinal.setType(Display.PICKER_TYPE_STRINGS);
pickerFinal.setUIID("DatePickerDialog");
pickerFinal.setStrings("1 x","2 x","3 x","4 x","5 x","6 x","6 x","8 x","9 x","10 x","11 x","12 x" , stringPickerFinal);
pickerFinal.setSelectedString(stringPickerFinal);
pickerFinal.addActionListener((e) -> {
if (!pickerFinal.getSelectedString().equals(stringPickerFinal)) {
pickerFinal.setUIID("DatePickerDialogSelected");
} else {
pickerFinal.setUIID("DatePickerDialog");
}
});
container = new Container(new GridLayout(1, 3));
container.setUIID("ContainerPicker");
container.add(pickerInterval).add(pickerDayOrMonth).add(pickerFinal);

Compare two different SOQL queries

I am new to salesforce and I am stuck with a situation here.
I have a class which is scheduled every hour. I hit an account with the below code and an email is sent out to MAROPOST (Marketing automation tool). When this happen I want to track the Account and create a case or a log which says Welcome Email is sent so that I don't hit the same Account again.
Please help. Below is the working class. Please help
public class PD_WelcomeMaroPost {
public static string sendEmailThroughMaro(string myInpEmail) {
string successContacts = '';
string failureContacts = '';
// SQL to fetch FBO who Joined Today
list<Account> conts = new list<Account> ([SELECT name, Email_FLP_com__c,
(SELECT Id
FROM Stripe_Subscriptons__r
WHERE Start_Date__c= TODAY
AND Status__c='active'
AND Welcome_Email__C = false
LIMIT 1)
from account
where ID IN (
select Distributor__c
from Stripe_Subscripton__c
where Start_Date__c= TODAY
AND Status__c='active'
AND Welcome_Email__C = false)
AND Email_FLP_com__c != NULL
LIMIT 100]);
system.debug('>>>>>>>>>>' + conts);
overallEmail myEmail = new overallEmail();
List<Stripe_Subscripton__c> subsToUpdate = new List<Stripe_Subscripton__c>();
for(Account c : conts){
myEmail.email.campaign_id = 172;
myEmail.email.contact.Email = c.Email_FLP_com__c;
myEmail.email.contact.first_name = c.name;
/**MAp<String, String> tags = new Map<String, String>();
tags.put('firstName', c.name);
myEmail.email.tags = tags;**/
system.debug('#### Input JSON: ' + JSON.serialize(myEmail));
try{
String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setbody(JSON.serialize(myEmail));
Http http = new Http();
system.debug('Sending email');
HTTPResponse response = http.send(req);
system.debug('sent email');
string resultBodyGet = '';
resultBodyGet = response.getBody();
system.debug('Output response:' + resultBodyGet);
maroResponse myMaroResponse = new maroResponse();
myMaroResponse = (maroResponse) JSON.deserialize(resultBodyGet, maroResponse.class);
system.debug('#### myMaroResponse: ' + myMaroResponse);
if(myMaroResponse.message == 'Email was sent successfully')
successContacts = successContacts + ';' + c.Email_FLP_com__c;
else
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
}
catch (exception e) {
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
system.debug('#### Exception caught: ' + e.getMessage());
}
c.Stripe_Subscriptons__r[0].Welcome_Email__c = true;
subsToUpdate.add(c.Stripe_Subscriptons__r[0]);
}
Update subsToUpdate;
return 'successContacts=' + successContacts + '---' + 'failureContacts=' + failureContacts;
}
public class maroResponse {
public string message {get;set;}
}
public class overallEmail {
public emailJson email = new emailJson();
}
public class emailJson {
public Integer campaign_id;
public contactJson contact = new contactJson();
// Public Map<String, String> tags;
}
public class contactJson {
public string email;
public string first_name;
}
}
You're making a callout in a loop, there's governor limit of max 100 callouts. See Limits class to obtain current & max numbers programatically rather than hardcoding it.
Other than that it should be pretty simple change. First add your filter to the query and add a "subquery" (something like a JOIN) that pulls the related list of subscriptions
list<Account> conts = new list<Account> ([SELECT name, Email_FLP_com__c,
(SELECT Id
FROM Stripe_Subscriptions__r
WHERE Start_Date__c= TODAY
AND Status__c='active'
AND Welcome_Email__C = false
LIMIT 1)
from account
where ID IN (
select Distributor__c
from Stripe_Subscripton__c
where Start_Date__c= TODAY
AND Status__c='active'
AND Welcome_Email__C = false)
AND Email_FLP_com__c != NULL
LIMIT 100]);
Then it's just few lines more
List<Stripe_Subscription__c> subsToUpdate = new List<Stripe_Subscription__c>();
for(Account a : conts){
// do your maropost code here
a.Stripe_Subscriptions__r[0].Welcome_Email__c = true;
subsToUpdate.add(a.Stripe_Subscriptions__r[0]);
}
update subsToUpdate;
Of course you might want to set that checkbox to true only if callout went OK ;)
After reading your code, I don't see where you tried to accomplish this. If you post your attempt I'd be glad to help fix it.
Instead I'll give you different logic for what you are trying to do.
1.) create new checkbox field
2.) in batch query where box is not checked
3.) send email
4.) check checkbox
to answer your comment here is some sample code, you will need to fix it yourself, i am just making temp names
for(sobjectname gg:[your query]){
Send email;
gg.checkbox = checked;
update gg;
}
it'd be better to make it bulkified though
list<yourSObject> tobeupdated = new list<yourSObject>([Your query]);
for(yourSObject gg: tobeupdated){
send email;
gg.checkbox = true;
}
update tobeupdated;

Android SMS date function call

I am working on Android SMS app. Part of it has to fetch inbox data (address, date, body) and fill list view. This works fine through following code :
public void btnInboxOnClick {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body", "date" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, null);
// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { "body", "address", "date" }, new int[] {
R.id.lblMsg, R.id.lblNumber, R.id.lblDate });
lvMsg.setAdapter(adapter);
I want to insert function call to display meaningful date-time string instead of milliseconds number fetched from db. My function code:
public static String millisToDate(String TimeMillis) {
String finalDate;
long tm = Long.parseLong(TimeMillis);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(tm);
Date date = calendar.getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-dd-yyyy HH:mm");
finalDate = outputFormat.format(date);
return finalDate;
}
Any attempt to call function compile, but app crashes. How should I connect function?
This answer was helpful too:
Code looks like this:
public void btnInboxOnClick {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body", "date" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, null);
// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { "body", "address", "date" }, new int[] {
R.id.lblMsg, R.id.lblNumber, R.id.lblDate });
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {
if (aColumnIndex == aCursor.getColumnIndex("date")) {
String createDate = aCursor.getString(aColumnIndex);
TextView textView = (TextView) aView;
textView.setText(millisToDate(createDate));
return true;
}
return false;
}
});
lvMsg.setAdapter(adapter);
public static String millisToDate(String TimeMillis) {
String finalDate;
long tm = Long.parseLong(TimeMillis);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(tm);
Date date = calendar.getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-dd-yyyy HH:mm");
finalDate = outputFormat.format(date);
return finalDate;
}

The given key was not present in the dictionary solrnet

Please note: I know for the question SolrNet - The given key was not present in the dictionary and I have initialized solr object just like Mauricio suggests.
I am using solr 4.6.0 and solrnet build #173, .net framework 4.0 and VS2012 for development. For some unknown reason I am receiving error 'The given key was not present in the dictionary'. I have a document with that id in solr, I've checked via browser. It's a document like any other document. Why is error popping up? My code (I've made a comment on the place where the error happens):
//establishes connection with solr
private void ConnectToSolr()
{
try
{
if (_solr != null) return;
Startup.Init<Register>(SolrAddress);
_solr = ServiceLocator.Current.GetInstance<ISolrOperations<Register>>();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//Returns snippets from solr as BindingSource
public BindingSource GetSnippets(string searchTerm, DateTime? startDate = null, DateTime? endDate = null)
{
ConnectToSolr();
string dateQuery = startDate == null
? ""
: endDate == null
? "savedate:\"" + convertDateToSolrFormat(startDate) + "\"" //only start date
: "savedate:[" + convertDateToSolrFormat(startDate) + " TO " +
convertDateToSolrFormat(endDate) + "]";//range between start and end date
string textQuery = string.IsNullOrEmpty(searchTerm) ? "text:*" : "text:*" + searchTerm + "*";
List<Register> list = new List<Register>();
SolrQueryResults<Register> results;
string currentId = "";
try
{
results = _solr.Query(textQuery,
new QueryOptions
{
Highlight = new HighlightingParameters
{
Fields = new[] { "*" },
},
ExtraParams = new Dictionary<string, string>
{
{"fq", dateQuery},
{"sort", "savedate desc"}
}
});
for (int i = 0; i < results.Highlights.Count; i++)
{
currentId = results[i].Id;
var h = results.Highlights[currentId];
if (h.Snippets.Count > 0)
{
list.Add(new Register//here the error "the given key was not present in the dictionary pops up
{
Id = currentId,
ContentLiteral = h.Snippets["content"].ToArray()[0].Trim(new[]{' ', '\n'}),
SaveDateLiteral = results[i].SaveDate.ToShortDateString()
});
}
}
BindingList<Register> bindingList = new BindingList<Register>(list);
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = bindingList;
return bindingSource;
}
catch(Exception e)
{
MessageBox.Show(string.Format("{0}\nId:{1}", e.Message, currentId), "Solr error");
return null;
}
}
I've found out what's causing the problem: saving empty documents into solr. If I make an empty query (with text:*) through solrnet (usually I do this if I want to see all saved documents) and empty document is one of saved docs, then 'The given key is not present in dictionary pops up'. If all of the documents have text in them, this error doesn't pop up.
If you document contains fields with types other than string and you index null value to a double or integer field you will get the same error.
solr query return the null field as:
<null name="fieldname"/>
should be
<double name="fieldname">0.0</double>
or
<double name="fieldname"/>

OptionSetValue does not contain constructor which takes one argument

I am creating a silverlight application as a web resource for CRM 2011. Now i am creating a ServiceAppointment record in DB and after creating it i want to change its Status to "reserved" instead of requested.
I googled about this and come across the examples like Close a Service Activity Through Code and Microsoft.Crm.Sdk.Messages.SetStateRequest
They all suggesting to use "SetStateRequest" and for using this i have to set the OptionSetValue like
request["State"] = new OptionSetValue(4);
But above line gives me error saying "OptionSetValue does not contain constructor which takes one argument"
BTW i am using SOAP end point of CRM 2011 service in silverlight application
Any ideas friends?
EDIT
Following is my code
var request = new OrganizationRequest { RequestName = "SetStateRequest" };
request["State"] = 3;
request["Status"] = 4;
request["EntityMoniker"] = new EntityReference() { Id = createdActivityId, LogicalName = "serviceappointment" };
crmService.BeginExecute(request,ChangeActivityStatusCallback,crmService);
And my callback function is
private void ChangeActivityStatusCallback(IAsyncResult result) {
OrganizationResponse response;
try
{
response = ((IOrganizationService)result.AsyncState).EndExecute(result);
}
catch (Exception ex)
{
_syncContext.Send(ShowError, ex);
return;
}
}
You must some how be referencing some other OptionSetValue class that is not the Microsoft.Xrm.Sdk one. Try appending the namespace to see if that resolves your issue:
request["State"] = new Microsoft.Xrm.Sdk.OptionSetValue(4);
Also, why are you using late bound on the SetStateRequest? Just use the SetStateRequest class:
public static Microsoft.Crm.Sdk.Messages.SetStateResponse SetState(this IOrganizationService service,
Entity entity, int state, int? status)
{
var setStateReq = new Microsoft.Crm.Sdk.Messages.SetStateRequest();
setStateReq.EntityMoniker = entity.ToEntityReference();
setStateReq.State = new OptionSetValue(state);
setStateReq.Status = new OptionSetValue(status ?? -1);
return (Microsoft.Crm.Sdk.Messages.SetStateResponse)service.Execute(setStateReq);
}
Thanks Daryl for you time and effort. I have solved my problem with the way u have suggested.
I am posting my code that worked for me.
var request = new OrganizationRequest { RequestName = "SetState" };
request["State"] = new OptionSetValue { Value = 3 };
request["Status"] = new OptionSetValue { Value = 4 };
request["EntityMoniker"] = new EntityReference() { Id = createdActivityId, LogicalName = "serviceappointment" };
crmService.BeginExecute(request,ChangeActivityStatusCallback,crmService);
private void ChangeActivityStatusCallback(IAsyncResult result) {
OrganizationResponse response;
try
{
response = ((IOrganizationService)result.AsyncState).EndExecute(result);
}
catch (Exception ex)
{
_syncContext.Send(ShowError, ex);
return;
}
}

Resources