Session ID keeps changing when a call is made from angular - c#-4.0

Session ID changes when sendSmsRandomPass is called from angular side.
I tried solving according to this post and others but to no avail:
[https://stackoverflow.com/questions/2874078/asp-net-session-sessionid-changes-between-requests]
Does anyone have any ideas why it doesn't work
public void sendEmail()
{
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session["phoneSMSForSendPassword"] =
phoneSMSForSendPassword;
HttpContext.Current.Session["password"] = password;
}
sendSmsRandomPass();
sendoffice365();
}
public void sendSmsRandomPass() {
if (password == null && phoneSMSForSendPassword == null &&
HttpContext.Current.Session != null)
{
phoneSMSForSendPassword =
(string)HttpContext.Current.Session["phoneSMSForSendPassword"];
password = (string)HttpContext.Current.Session["password"];
}
SMS.sendSMS(phoneSMSForSendPassword, password );
}

Related

Enable Custom Field on Project Quote Screen

I am using Acumatica 2020 R1. I have a custom text field on the PMQuote DAC. This field is in a custom tab on the project quotes screen. I want that field to always be editable. I put the following in my RowSelected event:
protected virtual void PMQuote_RowSelected(PXCache cache, PXRowSelectedEventArgs e, PXRowSelected del)
{
del?.Invoke(cache, e);
PMQuote quote = e.Row as PMQuote;
cache.AllowUpdate = true;
PXUIFieldAttribute.SetEnabled(cache, e.Row, true);
PXUIFieldAttribute.SetEnabled<PMQuoteExt.usrMyCustomField>(cache, e.Row, true);
}
This didn't work, so I also looked in the automation steps. I didn't see any automation steps available to modify.
I then looked at Workflow. I didn't see any workflows to edit either. I tried creating a new one based on the status field. I added the user field for each status and made sure disabled was unchecked. This didn't work either.
Any ideas on how I can get that field to be enabled regardless of the document status?
Thanks for your help!
AllowUpdate is called only on the cache object, add it for the data view, example:
Base.Quote.AllowUpdate = true
Also, try to extend PXQuoteMaintExt graph extension:
public class PMQuoteMaintExtExtension : PXGraphExtension<PMQuoteMaintExt, PMQuoteMaint>
{
protected virtual void PMQuote_RowSelected(PXCache sender, PXRowSelectedEventArgs e, PXRowSelected sel)
{
sel?.Invoke(sender, e);
}
}
It manages visibility with RowSelected event:
namespace PX.Objects.PM
{
public class PMQuoteMaintExt : PXGraphExtension<PMDiscount, PMQuoteMaint>
{
protected virtual void PMQuote_RowSelected(PXCache sender, PXRowSelectedEventArgs e, PXRowSelected sel)
{
sel?.Invoke(sender, e);
var row = e.Row as PMQuote;
if (row == null) return;
VisibilityHandler(sender, row);
}
private void VisibilityHandler(PXCache sender, PMQuote row)
{
CR.Standalone.CROpportunityRevision revisionInDb = PXSelectReadonly<CR.Standalone.CROpportunityRevision,
Where<CR.Standalone.CROpportunityRevision.noteID, Equal<Required<CR.Standalone.CROpportunityRevision.noteID>>>>.Select(Base, row.QuoteID).FirstOrDefault();
CR.Standalone.CROpportunity opportunityInDb = (revisionInDb == null) ? null : PXSelectReadonly<CR.Standalone.CROpportunity,
Where<CR.Standalone.CROpportunity.opportunityID, Equal<Required<CR.Standalone.CROpportunity.opportunityID>>>>.Select(Base, revisionInDb.OpportunityID).FirstOrDefault();
CR.Standalone.CROpportunity opportunity = PXSelect<CR.Standalone.CROpportunity,
Where<CR.Standalone.CROpportunity.opportunityID, Equal<Required<CR.Standalone.CROpportunity.opportunityID>>>>.Select(Base, row.OpportunityID).FirstOrDefault();
var opportunityIsClosed = opportunity?.IsActive == false;
bool allowUpdate = row.IsDisabled != true && !opportunityIsClosed && row.Status != PMQuoteStatusAttribute.Closed;
if (opportunityInDb?.OpportunityID == opportunity?.OpportunityID)
Base.Caches[typeof(PMQuote)].AllowUpdate = allowUpdate;
else
{
var quoteCache = Base.Caches[typeof(PMQuote)];
foreach (var field in quoteCache.Fields)
{
if (!quoteCache.Keys.Contains(field) &&
field != quoteCache.GetField(typeof(PMQuote.opportunityID)) &&
field != quoteCache.GetField(typeof(PMQuote.isPrimary)))
PXUIFieldAttribute.SetEnabled(sender, row, field, allowUpdate);
}
}
PXUIFieldAttribute.SetEnabled<PMQuote.bAccountID>(sender, row, row.OpportunityID == null);
Base.Caches[typeof(PMQuote)].AllowDelete = !opportunityIsClosed;
foreach (var type in new[]
{
typeof(CR.CROpportunityDiscountDetail),
typeof(CR.CROpportunityProducts),
typeof(CR.CRTaxTran),
typeof(CR.CRAddress),
typeof(CR.CRContact),
typeof(CR.CRPMTimeActivity),
typeof(PM.PMQuoteTask)
})
{
Base.Caches[type].AllowInsert = Base.Caches[type].AllowUpdate = Base.Caches[type].AllowDelete = allowUpdate;
}
Base.Caches[typeof(CopyQuoteFilter)].AllowUpdate = true;
Base.Caches[typeof(RecalcDiscountsParamFilter)].AllowUpdate = true;
Base.Actions[nameof(Base.Approval.Submit)]
.SetVisible(row.Status == PMQuoteStatusAttribute.Draft);
Base.actionsFolder
.SetVisible(nameof(Base.Approval.Approve), Base.Actions[nameof(Base.Approval.Approve)].GetVisible());
Base.actionsFolder
.SetVisible(nameof(Base.Approval.Reject), Base.Actions[nameof(Base.Approval.Reject)].GetVisible());
Base.Actions[nameof(EditQuote)]
.SetVisible(row.Status != PMQuoteStatusAttribute.Draft);
Base.Actions[nameof(Base.Approval.Submit)]
.SetEnabled(row.Status == PMQuoteStatusAttribute.Draft && !opportunityIsClosed);
Base.Actions[nameof(Base.Approval.Approve)]
.SetEnabled(row.Status == PMQuoteStatusAttribute.PendingApproval);
Base.Actions[nameof(Base.Approval.Reject)]
.SetEnabled(row.Status == PMQuoteStatusAttribute.PendingApproval);
Base.Actions[nameof(EditQuote)]
.SetEnabled(row.Status != PMQuoteStatusAttribute.Draft && row.Status != PMQuoteStatusAttribute.Closed);
Base.Actions[nameof(Base.CopyQuote)]
.SetEnabled(Base.Caches[typeof(PMQuote)].AllowInsert);
Base.Actions[nameof(PMDiscount.GraphRecalculateDiscountsAction)]
.SetEnabled((row.Status == PMQuoteStatusAttribute.Draft));
Base.Actions[nameof(Base.PrimaryQuote)].SetEnabled(!String.IsNullOrEmpty(row.OpportunityID) && row.IsPrimary == false && row.Status != PMQuoteStatusAttribute.Closed);
Base.Actions[nameof(Base.SendQuote)].SetEnabled(row.Status.IsIn<string>(PMQuoteStatusAttribute.Approved, PMQuoteStatusAttribute.Sent, PMQuoteStatusAttribute.Closed));
Base.Actions[nameof(Base.PrintQuote)].SetEnabled(true);
Base.convertToProject.SetEnabled( (row.OpportunityID == null || row.IsPrimary == true) && row.QuoteProjectID == null && row.Status.IsIn<string>(PMQuoteStatusAttribute.Approved, PMQuoteStatusAttribute.Sent));
PXUIFieldAttribute.SetEnabled<PMQuote.subject>(sender, row, true);
PXUIFieldAttribute.SetEnabled<PMQuote.status>(sender, row, false);
}
}
}

Create user inside a transaction

When creating a user like so:
using var trans = Db.BeginTransaction();
AuthRepository.CreateUserAuth(newUser, request.Password);
AuthRepository.AssignRoles(created, new List<string> { request.role });
//.. do other stuff
throw new Exception("other code may throw this");
trans.Commit();
The Auth repo has it's own connection so it's not part of the transaction. This means, if my code bails out, I end up with an unwanted user.
Is there any way to use a transaction with AuthRepository or is only way to manually write to user and role tables? I couldn't find an example of creating the password hash in docs when manually saving, is there any example?
You can't use the existing Auth Repository APIs within a transaction because each uses its own DB connection.
If you want you can take the implementation of those OrmLite Auth Respository APIs in OrmLiteAuthRepository.cs and move them into your method so they're all using the same DB Connection + Transaction.
Also note that to use Transactions in OrmLite you should use OpenTransaction() instead, e.g:
using (var dbTrans = db.OpenTransaction())
{
}
Adding class I used here in case it helps anyone as needed a little refactoring:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using OutReachPete.ServiceModel.User;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.OrmLite;
namespace OutReachPete.ServiceInterface.User
{
public class UserHelper
{
public static bool ForceCaseInsensitiveUserNameSearch { get; set; } = true;
public static bool UseDistinctRoleTables { get; set; } = true;
public static UserAuthCustom CreateUserAuth(UserAuthCustom newUser, string password, IDbConnection db)
{
newUser.ValidateNewUser(password);
AssertNoExistingUser(db, newUser);
newUser.PopulatePasswordHashes(password);
newUser.CreatedDate = DateTime.UtcNow;
newUser.ModifiedDate = newUser.CreatedDate;
db.Save(newUser);
newUser = db.SingleById<UserAuthCustom>(newUser.Id);
return newUser;
}
public static void AssertNoExistingUser(IDbConnection db, IUserAuth newUser,
IUserAuth exceptForExistingUser = null)
{
if (newUser.UserName != null)
{
var existingUser = GetUserAuthByUserName(db, newUser.UserName);
if (existingUser != null
&& (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
throw new ArgumentException(string.Format(ErrorMessages.UserAlreadyExistsTemplate1,
newUser.UserName.SafeInput()));
}
if (newUser.Email != null)
{
var existingUser = GetUserAuthByUserName(db, newUser.Email);
if (existingUser != null
&& (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
throw new ArgumentException(string.Format(ErrorMessages.EmailAlreadyExistsTemplate1,
newUser.Email.SafeInput()));
}
}
public static UserAuthCustom GetUserAuthByUserName(IDbConnection db, string userNameOrEmail)
{
var isEmail = userNameOrEmail.Contains("#");
var lowerUserName = userNameOrEmail.ToLower();
UserAuthCustom userAuth = null;
// Usernames/Emails are saved in Lower Case so we can do an exact search using lowerUserName
if (HostContext.GetPlugin<AuthFeature>()?.SaveUserNamesInLowerCase == true)
{
return isEmail
? db.Select<UserAuthCustom>(q => q.Email == lowerUserName).FirstOrDefault()
: db.Select<UserAuthCustom>(q => q.UserName == lowerUserName).FirstOrDefault();
}
// Try an exact search using index first
userAuth = isEmail
? db.Select<UserAuthCustom>(q => q.Email == userNameOrEmail).FirstOrDefault()
: db.Select<UserAuthCustom>(q => q.UserName == userNameOrEmail).FirstOrDefault();
if (userAuth != null)
return userAuth;
// Fallback to a non-index search if no exact match is found
if (ForceCaseInsensitiveUserNameSearch)
{
userAuth = isEmail
? db.Select<UserAuthCustom>(q => q.Email.ToLower() == lowerUserName).FirstOrDefault()
: db.Select<UserAuthCustom>(q => q.UserName.ToLower() == lowerUserName).FirstOrDefault();
}
return userAuth;
}
public static void AssignRoles(IAuthRepository userAuthRepo, IUserAuth userAuth, IDbConnection db,
ICollection<string> roles = null, ICollection<string> permissions = null)
{
if (userAuthRepo is IManageRoles managesRoles)
{
AssignRoles(userAuth.Id.ToString(), db, roles, permissions);
}
else
{
AssignRolesInternal(userAuth, roles, permissions);
SaveUserAuth(userAuth, db);
}
}
public static IUserAuth GetUserAuth(string userAuthId, IDbConnection db)
{
if (string.IsNullOrEmpty(userAuthId))
throw new ArgumentNullException(nameof(userAuthId));
return db.SingleById<UserAuthCustom>(int.Parse(userAuthId));
}
public static void AssignRoles(string userAuthId, IDbConnection db, ICollection<string> roles = null, ICollection<string> permissions = null)
{
var userAuth = GetUserAuth(userAuthId, db);
if (!UseDistinctRoleTables)
{
if (!roles.IsEmpty())
{
foreach (var missingRole in roles.Where(x => userAuth.Roles == null || !userAuth.Roles.Contains(x)))
{
if (userAuth.Roles == null)
userAuth.Roles = new List<string>();
userAuth.Roles.Add(missingRole);
}
}
if (!permissions.IsEmpty())
{
foreach (var missingPermission in permissions.Where(x => userAuth.Permissions == null || !userAuth.Permissions.Contains(x)))
{
if (userAuth.Permissions == null)
userAuth.Permissions = new List<string>();
userAuth.Permissions.Add(missingPermission);
}
}
SaveUserAuth(userAuth, db);
}
else
{
var now = DateTime.UtcNow;
var userRoles = db.Select<UserAuthRole>(q => q.UserAuthId == userAuth.Id);
if (!roles.IsEmpty())
{
var roleSet = userRoles.Where(x => x.Role != null).Select(x => x.Role).ToHashSet();
foreach (var role in roles)
{
if (!roleSet.Contains(role))
{
db.Insert(new UserAuthRole
{
UserAuthId = userAuth.Id,
Role = role,
CreatedDate = now,
ModifiedDate = now,
});
}
}
}
if (!permissions.IsEmpty())
{
var permissionSet = userRoles.Where(x => x.Permission != null).Select(x => x.Permission).ToHashSet();
foreach (var permission in permissions)
{
if (!permissionSet.Contains(permission))
{
db.Insert(new UserAuthRole
{
UserAuthId = userAuth.Id,
Permission = permission,
CreatedDate = now,
ModifiedDate = now,
});
}
}
}
}
}
private static void AssignRolesInternal(IUserAuth userAuth, ICollection<string> roles, ICollection<string> permissions)
{
if (!roles.IsEmpty())
{
foreach (var missingRole in roles.Where(x => userAuth.Roles == null || !userAuth.Roles.Contains(x)))
{
if (userAuth.Roles == null)
userAuth.Roles = new List<string>();
userAuth.Roles.Add(missingRole);
}
}
if (!permissions.IsEmpty())
{
foreach (var missingPermission in permissions.Where(x =>
userAuth.Permissions == null || !userAuth.Permissions.Contains(x)))
{
if (userAuth.Permissions == null)
userAuth.Permissions = new List<string>();
userAuth.Permissions.Add(missingPermission);
}
}
}
public static void SaveUserAuth(IUserAuth userAuth, IDbConnection db)
{
if (userAuth == null)
throw new ArgumentNullException(nameof(userAuth));
userAuth.ModifiedDate = DateTime.UtcNow;
if (userAuth.CreatedDate == default(DateTime))
userAuth.CreatedDate = userAuth.ModifiedDate;
db.Save((UserAuthCustom)userAuth);
}
}
}
Then just call it like:
var created = UserHelper.CreateUserAuth(newUser, request.Password, Db);
UserHelper.AssignRoles(AuthRepository, created, Db, new List<string> { request.CreateUserType.ToString() });
It will only use the connection passed. Just change UserAuthCustom to whatever you user class is.

Sending notification to requester when PO is created in Acumatica

I need to be able to send an email to the original requester when a PO is created from a Requisition in Acumatica 6.1.
Per Acumatica, the Notification screen cannot handle this functionality, so I have this code to extend the POOrder Entry graph, which sends an email to the Customer's contact email from the Requisition when a PO is created (along with the RQRequisitionEntryExt trigger):
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
private bool sendEmailNotification = false;
public bool SendEmailNotification
{
get
{
return sendEmailNotification;
}
set
{
sendEmailNotification = value;
}
}
[PXOverride]
public void Persist(Action del)
{
using (var ts = new PXTransactionScope())
{
if (del != null)
{
del();
}
if (SendEmailNotification)
{
bool sent = false;
string sError = "Failed to send E-mail.";
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.name, Equal<Required<Notification.name>>>>
.Select(Base, "PurchaseOrderNotification");
if (rowNotification == null)
throw new PXException("Notification Template was not found.");
var order = Base.Document.Current;
var requisition = (RQRequisition)PXSelect<RQRequisition,
Where<RQRequisition.reqNbr, Equal<Current<POOrder.rQReqNbr>>>>
.SelectSingleBound(Base, new object[] { order });
if (requisition.CustomerID != null)
{
var customer = (BAccountR)PXSelectorAttribute.Select<RQRequisition.customerID>(
Base.Caches[typeof(RQRequisition)], requisition);
if (customer != null)
{
var defCustContact = (Contact)PXSelectorAttribute.Select<BAccountR.defContactID>(
Base.Caches[typeof(BAccountR)], customer);
if (String.IsNullOrEmpty(defCustContact.EMail))
throw new PXException("E-mail is not specified for Customer Contact.");
var sender = TemplateNotificationGenerator.Create(order,
rowNotification.NotificationID.Value);
sender.RefNoteID = order.NoteID;
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = defCustContact.EMail;
sent |= sender.Send().Any();
}
}
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(sError);
}
ts.Complete();
}
}
}
And this to modify RQRequisitionEntry:
public class RQRequisitionEntryExt : PXGraphExtension<RQRequisitionEntry>
{
public PXAction<RQRequisition> createPOOrder;
[PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)]
[PXUIField(DisplayName = Messages.CreateOrders)]
public IEnumerable CreatePOOrder(PXAdapter adapter)
{
PXGraph.InstanceCreated.AddHandler<POOrderEntry>((graph) =>
{
graph.GetExtension<POOrderEntryExt>().SendEmailNotification = true;
});
return Base.createPOOrder.Press(adapter);
}
}
In order to send an email to the Requester's (Employee) contact email from the Request, I modified the POOrderEntryExt to pull the information from the Request object and the Employee's Contact email (I left the RQRequisitionEntryExt the same and in place):
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
private bool sendEmailNotification = false;
public bool SendEmailNotification
{
get
{
return sendEmailNotification;
}
set
{
sendEmailNotification = value;
}
}
[PXOverride]
public void Persist(Action del)
{
using (var ts = new PXTransactionScope())
{
if (del != null)
{
del();
}
if (SendEmailNotification)
{
bool sent = false;
string sError = "Failed to send E-mail.";
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.name, Equal<Required<Notification.name>>>>
.Select(Base, "PurchaseOrderNotification");
if (rowNotification == null)
throw new PXException("Notification Template was not found.");
var order = Base.Document.Current;
var requisition = (RQRequisition)PXSelect<RQRequisition,
Where<RQRequisition.reqNbr, Equal<Current<POOrder.rQReqNbr>>>>
.SelectSingleBound(Base, new object[] { order });
var request = (RQRequest)PXSelectJoin<RQRequest,
InnerJoin<RQRequisitionContent,
On<RQRequisitionContent.orderNbr, Equal<RQRequest.orderNbr>>>,
Where<RQRequisitionContent.reqNbr, Equal<POOrder.rQReqNbr>>>
.SelectSingleBound(Base, new object[] { order });
if (request.EmployeeID != null)
{
var employee = (BAccountR)PXSelectorAttribute.Select<RQRequest.employeeID>(
Base.Caches[typeof(RQRequest)], request);
if (employee != null)
{
var defEmpContact = (Contact)PXSelectorAttribute.Select<BAccountR.defContactID>(
Base.Caches[typeof(BAccountR)], employee);
if (String.IsNullOrEmpty(defEmpContact.EMail))
throw new PXException("E-mail is not specified for Employee Contact.");
var sender = TemplateNotificationGenerator.Create(order,
rowNotification.NotificationID.Value);
sender.RefNoteID = order.NoteID;
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = defEmpContact.EMail;
sent |= sender.Send().Any();
}
else
throw new PXException("Customer not found.");
}
else
throw new PXException("Request not found.");
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(sError);
}
ts.Complete();
}
}
}
I can get the original code to send an email in my development environment, but my modified code only returns the outer "Failed to send E-mail" error.
Can anyone help point me in the right direction to get my modifications to work?
Because in Acumatica there is one-to-many relationship between RQRequisition and RQRequest, I believe the better approach is to loop through all requests linked to the current requisition and compose a list of requester's emails. After that we can go ahead and send emails to all requesters as part of the Create Orders operation:
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
private bool sendEmailNotification = false;
public bool SendEmailNotification
{
get
{
return sendEmailNotification;
}
set
{
sendEmailNotification = value;
}
}
[PXOverride]
public void Persist(Action del)
{
using (var ts = new PXTransactionScope())
{
if (del != null)
{
del();
}
if (SendEmailNotification)
{
bool sent = false;
string sError = "Failed to send E-mail.";
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.name, Equal<Required<Notification.name>>>>
.Select(Base, "PONotification");
if (rowNotification == null)
throw new PXException("Notification Template was not found.");
var order = Base.Document.Current;
var emails = new List<string>();
var requests = PXSelectJoinGroupBy<RQRequest,
InnerJoin<RQRequisitionContent,
On<RQRequest.orderNbr,
Equal<RQRequisitionContent.orderNbr>>>,
Where<RQRequisitionContent.reqNbr,
Equal<Required<RQRequisition.reqNbr>>>,
Aggregate<GroupBy<RQRequest.orderNbr>>>
.Select(Base, order.RQReqNbr);
foreach (RQRequest request in requests)
{
if (request.EmployeeID != null)
{
var requestCache = Base.Caches[typeof(RQRequest)];
requestCache.Current = request;
var emplOrCust = (BAccountR)PXSelectorAttribute
.Select<RQRequest.employeeID>(requestCache, request);
if (emplOrCust != null)
{
var defEmpContact = (Contact)PXSelectorAttribute
.Select<BAccountR.defContactID>(
Base.Caches[typeof(BAccountR)], emplOrCust);
if (!String.IsNullOrEmpty(defEmpContact.EMail) &&
!emails.Contains(defEmpContact.EMail))
{
emails.Add(defEmpContact.EMail);
}
}
}
}
foreach (string email in emails)
{
var sender = TemplateNotificationGenerator.Create(order,
rowNotification.NotificationID.Value);
sender.RefNoteID = order.NoteID;
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = email;
sent |= sender.Send().Any();
}
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(sError);
}
ts.Complete();
}
}
}

(J2ME) login page to authenticate username and password and display retrieved data

can someone please help me, i am relatively new in J2ME coding.... i have an API link which contains username and password (e.g. http://sunday-tech.com/chunghua/api/login.php?username=yasir&password=yasir )
i am trying to authenticate the user inputs and access the API and read the data. I am using httpconnection but i am not sure if its the right one to use.
so far the codes do access and display the contents by reading each character but how do i EXCLUDE commas and brackets as well display the data in an organized manner in the phone. Also, when the username and password inputs are wrong, it should alert Invalid Login......
I would appreciate it so much if someone can enlighten about this by providing some code snippets. here is wht i have done so far.
public class Login extends MIDlet implements CommandListener {
TextField UserName = null;
TextField Password = null;
Form authForm, mainscreen;
TextBox t = null;
StringBuffer b = new StringBuffer();
private Display myDisplay = null;
private Command okCommand = new Command("OK", Command.OK, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 2);
private Command backCommand = new Command("Back", Command.BACK, 2);
private Alert alert = null;
public Login() {
myDisplay = Display.getDisplay(this);
UserName = new TextField("Username", "", 10, TextField.ANY);
Password = new TextField("Password", "", 10, TextField.ANY);
authForm = new Form("Identification");
mainscreen = new Form("Logging IN");
mainscreen.append("Logging in....");
mainscreen.addCommand(backCommand);
authForm.append(UserName);
authForm.append(Password);
authForm.addCommand(okCommand);
authForm.addCommand(exitCommand);
authForm.setCommandListener(this);
myDisplay.setCurrent(authForm);
}
public void startApp() throws MIDletStateChangeException {
}
public void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command c, Displayable d) {
if ((c == okCommand) && (d == authForm)) {
if (UserName.getString().equals("") || Password.getString().equals("")) {
alert = new Alert("Error", "You should enter Username and Password", null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
myDisplay.setCurrent(alert);
}
else {
//myDisplay.setCurrent(mainscreen);
login(UserName.getString(), Password.getString());
}
}
if ((c == backCommand) && (d == mainscreen)) {
myDisplay.setCurrent(authForm);
}
if ((c == exitCommand) && (d == authForm)) {
notifyDestroyed();
}
}
public void login(String UserName, String PassWord) {
HttpConnection connection = null;
DataInputStream in = null;
String base = "http://sunday-tech.com/chunghua/api/login.php";
String url = base + "?username=" + UserName + "&password=" + PassWord;
OutputStream out = null;
try {
connection = (HttpConnection) Connector.open(url);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("IF-Modified-Since", "2 Oct 2002 15:10:15 GMT");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.1 Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Length", "" + (UserName.length() + PassWord.length()));
connection.setRequestProperty("UserName", UserName);
connection.setRequestProperty("PassWord", PassWord);
out = connection.openDataOutputStream();
out.flush();
in = connection.openDataInputStream();
int ch;
while ((ch = in.read()) != -1) {
b.append((char) ch);
//System.out.println((char)ch);
}
//t = new TextBox("Reply",b.toString(),1024,0);
mainscreen.append(b.toString());
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (connection != null) {
connection.close();
}
} catch (IOException x) {
}
myDisplay.setCurrent(mainscreen);
}
}

Spring HibernateTemplate in multithread

I have a method in Struts action to deal with sending system-message,so I use Executors.newCachedThreadPool() to call a new thread run that, but when I operate sending again,the thread seemed be dead.Here is my code :
public String sendMessage(){
if(!validateSystemMessage(systemMessage)){
return ERROR;
}
systemMessage.setEnable(false);
systemMessage.setContent(systemMessage.getContent());
systemMessage.setTitle(systemMessage.getTitle());
systemMessage.setMessageTime(new Date());
systemMessageDao.saveOrUpdate(systemMessage);
**ExecutorService executor = Executors.newCachedThreadPool();
SendMessage sendMessage=new SendMessage(systemMessage.getSmId());
LOGGER.info("-- systemMessage---"+systemMessage.getSmId());
sendMessage.setSystemMessageDao(systemMessageDao);
sendMessage.setUserMessageDao(userMessageDao);
String[] ids = userIds.split(",");
LOGGER.info("-- ids.length---"+ids.length);
sendMessage.setUserIds(ids);
executor.submit(sendMessage);**
systemMessage=null;
message=SUCCESS;
return SUCCESS;
}
public class SendMessage implements Callable<Boolean>{
#Override
public Boolean call() throws Exception{
SystemMessage msg = null;
msg = this.systemMessageDao.findSystemMessageById(msgId);
List<Long> userIdsSended = this.userMessageDao.findUserIdsByMsgId(msgId);//thread seemed be dead here
List<Long> listUserIds = new ArrayList<Long>();
for (String userId : userIds) {
Long id=Long.valueOf(userId);
if (userIdsSended != null && userIdsSended.contains(id)) {
continue;
}
listUserIds.add(id);
}
if (listUserIds != null && !listUserIds.isEmpty()) {
this.userMessageDao.save(msgId, listUserIds);
}
msg.setEnable(true);
this.systemMessageDao.saveOrUpdate(msg);
return true;
}
}
public SystemMessage findSystemMessageById(Long smId) {
List<SystemMessage> list = this.getHibernateTemplate().find("from SystemMessage systemMessage where systemMessage.smId = ?", new Object[] { smId });
return list.size() != 0 ? list.get(0) : null;
}
if I send again after few minutes, it run normal, I think the difference is newCachedThreadPool run a new thread .But why in a thread it can't run again? is it the problem with hibernateTemplate or session ?

Resources