System.UnauthorizedAccessException was unhandled by user code, when deleting user alerts? - sharepoint

I am getting System.UnauthorizedAccessException was unhandled by user code when deleting user alerts by programming. It is working good in my QA farm. But not working in DEV farm.
I added application pool account to farm administation group and database users group as dbowner. Still getting same error.
protected void ChkBx41_CheckedChanged(object sender, EventArgs e)
{
SPUser user = SPContext.Current.Web.CurrentUser;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using(SPSite site=new SPSite(url.Text)){
using (SPWeb eweb = site.OpenWeb())
{
SPUser juser = null;
eweb.AllowUnsafeUpdates = true;
try
{
juser = eweb.AssociatedMemberGroup.Users[user.LoginName];
}
catch (Exception)
{
}
if (ChkBx41.Checked)
{
if (juser == null)
{
eweb.AssociatedMemberGroup.AddUser(eweb.EnsureUser(user.LoginName));
SPUtility.SendEmail(eweb, true, true, user.Email, "Welcome to " + eweb.Title, "Hello " + "<br><br>" + "Welcome to the " + eweb.Title + " ");
createalert(SPAlertFrequency.Daily, eweb, eweb.EnsureUser(user.LoginName),true);
}
RBList4.SelectedValue = "Daily";
RBList4.Enabled = true;
}
else
{
if (juser != null)
{
eweb.AssociatedMemberGroup.RemoveUser(juser);
removealert(eweb, juser);
RBList4.SelectedValue = null;
RBList4.Enabled = false;
}
}
eweb.AllowUnsafeUpdates = false;
}
}
});
}
public void removealert(SPWeb rweb, SPUser ruser)
{
bool oldCatchAccessDeniedException = rweb.Site.CatchAccessDeniedException;
try
{
SPUser cuser = rweb.EnsureUser(ruser.LoginName);
List<Guid> altid = new List<Guid>();
foreach (SPAlert alt in cuser.Alerts)
{
try
{
if (alt.AlertType == SPAlertType.List)
{
altid.Add(alt.ID);
}
}
catch (Exception) { }
}
rweb.Site.CatchAccessDeniedException = false;
foreach (Guid delid in altid)
{
cuser.Alerts.Delete(delid);
}
}
catch (UnauthorizedAccessException)
{
}
finally
{
rweb.Site.CatchAccessDeniedException = oldCatchAccessDeniedException;
}
}

Running from web part, try elevating?
public void removealert(SPWeb rweb, SPUser ruser) {
SPSecurity.RunWithElevatedPrivileges(delegate() {
using(SPSite csite = new SPSite(rweb.Site.Id)) {
using(SPWeb cweb = csite.OpenWeb(rweb.Id)) {
SPUser cuser = cweb.EnsureUser(ruser.LoginName);
List<Guid> altid = new List<Guid>();
foreach (SPAlert alt in cuser.Alerts) {
try {
if (alt.AlertType == SPAlertType.List) {
altid.Add(alt.ID);
}
} catch (Exception) {
}
}
foreach (Guid delid in altid) {
cuser.Alerts.Delete(delid);
}
}
}
});
}
I also would be interested to know where SPWeb rweb comes from. I hope not from SPContext, as you should not Dispose that.
I would recommend also having your SPWebs in a using block, in the same method block for easy reading.

Related

Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access denied

I encountered an exception when I used c# code to create subdirectories in sharepoint's specified directory.
Exception message:
Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access denied. You do not have permission to perform this action or access this resource.
Anybody can help me? thanks!
The following is parameters:
file: D:\Repos\helpfilesync\ArtefactUploader\bin\Release\ArtefactUploader.exe
fileName: ArtefactUploader.exe
uploadPath: /sites/Platform/Shared Documents/dailybuild/helpfilesync/
subFolderPath: v0.1.0/
public void Upload()
{
using (ClientContext clientContext = new ClientContext("*****"))
{
SecureString pass = new SecureString();
foreach (char ch in password)
{
pass.AppendChar(ch);
}
clientContext.Credentials = new SharePointOnlineCredentials(user, pass);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
if (!string.IsNullOrWhiteSpace(this.subFolderPath))
{
CreateFolder(clientContext.Web, uploadPath, subFolderPath);
}
using (FileStream fs = new FileStream(file, FileMode.Open))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect
(clientContext, $"{this.uploadPath}{this.subFolderPath}/{fileName}", fs, true);
}
Console.WriteLine("Uploaded File Successfully");
}
}
public void CreateFolder(Web web, string relativePath, string fullFolderPath)
{
if (web == null)
{
throw new ArgumentNullException(nameof(web));
}
if (string.IsNullOrWhiteSpace(relativePath))
{
throw new ArgumentNullException(nameof(relativePath));
}
if (string.IsNullOrWhiteSpace(fullFolderPath))
{
throw new ArgumentNullException(fullFolderPath);
}
Folder relativeFolder = web.GetFolderByServerRelativeUrl(relativePath);
CreateFolderInternal(web, relativeFolder, fullFolderPath);
}
public static Folder CreateFolderInternal(Web web, Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
//web.Context.Load(curFolder);
try
{
web.Context.ExecuteQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access
denied. You do not have permission to perform this action or access
this resource. at
Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream
responseStream) at
Microsoft.SharePoint.Client.ClientRequest.ProcessResponse() at
Microsoft.SharePoint.Client.ClientContext.ExecuteQuery() at
ArtefactUploader.SharepointUploader.CreateFolderInternal(Web web,
Folder parentFolder, String fullFolderPath) in
D:\Repos\helpfilesync\ArtefactUploader\SharepointUploader.cs:line 96
Did test of your code, works fine. Make sure the user/password is correct.
class Program
{
const string user = "user#teanat.onmicrosoft.com";
const string password = "password";
public static void Upload()
{
using (ClientContext clientContext = new ClientContext("https://tenant.sharepoint.com/sites/lee"))
{
SecureString pass = new SecureString();
foreach (char ch in password)
{
pass.AppendChar(ch);
}
clientContext.Credentials = new SharePointOnlineCredentials(user, pass);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
if (!string.IsNullOrWhiteSpace("a"))
{
CreateFolder(clientContext.Web, "/sites/lee/mydoc2", "childA");
}
//using (FileStream fs = new FileStream(file, FileMode.Open))
//{
// Microsoft.SharePoint.Client.File.SaveBinaryDirect
// (clientContext, $"{this.uploadPath}{this.subFolderPath}/{fileName}", fs, true);
//}
Console.WriteLine("Uploaded File Successfully");
}
}
public static void CreateFolder(Web web, string relativePath, string fullFolderPath)
{
if (web == null)
{
throw new ArgumentNullException(nameof(web));
}
if (string.IsNullOrWhiteSpace(relativePath))
{
throw new ArgumentNullException(nameof(relativePath));
}
if (string.IsNullOrWhiteSpace(fullFolderPath))
{
throw new ArgumentNullException(fullFolderPath);
}
Folder relativeFolder = web.GetFolderByServerRelativeUrl(relativePath);
CreateFolderInternal(web, relativeFolder, fullFolderPath);
}
public static Folder CreateFolderInternal(Web web, Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
//web.Context.Load(curFolder);
try
{
web.Context.ExecuteQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
static void Main(string[] args)
{
Upload();
}
}

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();
}
}
}

Error while adding entity object to DBContext object called from Parallel.Foreach loop

Error :
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
Object reference not set to an instance of an object. at
System.Data.Objects.ObjectStateManager.DetectConflicts(IList1
entries) at System.Data.Objects.ObjectStateManager.DetectChanges()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean
force) at
System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action,
EntityState newState, Object entity, String methodName) at
System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity)
at System.Data.Entity.DbSet1.Add(TEntity entity) at
ESHealthCheckService.BusinessFacade.BusinessOperationsLayer.AddErrorToDbObject(Exception
ex, Server serverObj, Service windowsServiceObj)
the message resource is present but the message is not found in the string/message table
public void CheckForServerHealth()
{
businessLayerObj.SetStartTimeWindowsService();
List<ServerMonitor> serverMonitorList = new List<ServerMonitor>();
serverList = businessLayerObj.GetServerList();
Parallel.ForEach(
serverList,
() => new List<ServerMonitor>(),
(server, loop, localState) =>
{
localState.Add(serverStatus(server, new ServerMonitor()));
return localState;
},
localState =>
{
lock (serverMonitorList)
{
foreach (ServerMonitor serverMonitor in localState)
{
serverMonitorList.Add(serverMonitor);
}
}
});
businessLayerObj.SaveServerHealth(serverMonitorList);
}
public ServerMonitor serverStatus(Server serverObj, ServerMonitor serverMonitorObj)
{
if (new Ping().Send(serverObj.ServerName, 30).Status == IPStatus.Success)
{
serverMonitorObj.Status = true;
try
{
PerformanceCounter cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total", serverObj.ServerName);
serverMonitorObj.CPUUtlilization = (cpu.NextValue());
}
catch (Exception ex)
{
businessLayerObj.AddErrorObjectToStaticList(ex, serverObj);
}
serverMonitorObj.ServerID = serverObj.ServerID;
try
{
string[] diskArray = serverObj.DriveMonitor.ToString().Split(':');
if (diskArray != null && diskArray.Contains("NA"))
{
serverMonitorObj.DiskSpace = "NA";
}
else
{
serverMonitorObj.DiskSpace = ReadFreeSpaceOnNetworkDrives(serverObj.ServerName, diskArray);
}
}
catch (Exception ex)
{
businessLayerObj.AddErrorObjectToStaticList(ex, serverObj);
}
serverMonitorObj.CreatedDateTime = DateTime.Now;
}
else
{
serverMonitorObj.Status = false;
serverMonitorObj.ServerID = serverObj.ServerID;
//return serverMonitorObj;
}
return serverMonitorObj;
}
public void AddErrorObjectToStaticList(Exception ex, Server serverObj = null, Service windowsServiceObj = null)
{
EShelathLoging esLogger = new EShelathLoging();
esLogger.CreateDatetime = DateTime.Now;
if (ex.InnerException != null)
{
esLogger.Message = (windowsServiceObj == null ? ex.InnerException.Message : ("Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.InnerException.Message));
//esLogger.Message = "Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.InnerException.Message;
esLogger.StackTrace = (ex.InnerException.StackTrace == null ? "" : ex.InnerException.StackTrace);
}
else
{
esLogger.Message = (windowsServiceObj == null ? ex.Message : ("Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.Message));
//esLogger.Message = "Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.Message;
esLogger.StackTrace = ex.StackTrace;
}
if (serverObj != null)
{
esLogger.ServerName = serverObj.ServerName;
}
try
{
lock (lockObject)
{
esHealthCheckLoggingList.Add(esLogger);
}
}
catch (Exception exe)
{
string logEntry = "Application";
if (EventLog.SourceExists(logEntry) == false)
{
EventLog.CreateEventSource(logEntry, "Windows and IIS health check Log");
}
EventLog eventLog = new EventLog();
eventLog.Source = logEntry;
eventLog.WriteEntry(exe.Message + " " + exe.StackTrace, EventLogEntryType.Error);
}
}
And then the below function is called to add objects from static list to the db object.
public void AddErrorToDbObject()
{
try
{
foreach (EShelathLoging eslogObject in esHealthCheckLoggingList)
{
lock (lockObject)
{
dbObject.EShelathLogings.Add(eslogObject);
}
}
}
catch (DbEntityValidationException exp)
{
string logEntry = "Application";
if (EventLog.SourceExists(logEntry) == false)
{
EventLog.CreateEventSource(logEntry, "Windows and IIS health check Log");
}
EventLog eventLog = new EventLog();
eventLog.Source = logEntry;
eventLog.WriteEntry(exp.Message + " " + exp.StackTrace, EventLogEntryType.Error);
}
catch (Exception exe)
{
string logEntry = "Application";
if (EventLog.SourceExists(logEntry) == false)
{
EventLog.CreateEventSource(logEntry, "Windows and IIS health check Log");
}
EventLog eventLog = new EventLog();
eventLog.Source = logEntry;
eventLog.WriteEntry(exe.Message + " " + exe.StackTrace, EventLogEntryType.Error);
}`enter code here`
}
DbSet<T> is not thread-safe, so you can't use it from multiple threads at the same time. It seems you're trying to fix that by using a lock, but you're doing that incorrectly. For this to work, all threads have to share a single lock object. Having separate lock object for each thread, like you do now, won't do anything.
Please note that I received the same exception with the application I was working on, and determined that the best way to resolve the issue was to add an AsyncLock, because of what #svick mentioned about how DbSet is not threadsafe. Thank you, #svick!
I'm guessing that your DbContext is inside your businessLayerObj, so here is what I recommend, using Stephen Cleary's excellent Nito.AsyncEx (see https://www.nuget.org/packages/Nito.AsyncEx/):
using Nito.AsyncEx;
// ...
private readonly AsyncLock _dbContextMutex = new AsyncLock();
public void CheckForServerHealth()
{
using (await _dbContextMutex.LockAsync().ConfigureAwait(false))
{
await MyDbContextOperations(businessLayerObj).ConfigureAwait(false);
}
}
private async Task MyDbContextOperations(BusinessLayerClass businessLayerObj)
{
await Task.Run(() =>
{
// operations with businessLayerObj/dbcontext here...
});
}

J2ME fetching sim contacts

How to retrieve both SIM and phone book contact using PIM in J2ME.
I Tried
PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
but it's only displaying Phone book contact.
May be this method can help you
public static HashLongObject loadContactFromPhone() {
PIM iPim = PIM.getInstance();
String[] allContactLists = iPim.listPIMLists(PIM.CONTACT_LIST);
// Phone or SIM
HashLongObject iPhoneBookList = new HashLongObject();
int i;
for (i = 0; i < allContactLists.length; i++) {
try {
PIMList iPIMList = iPim.openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, allContactLists[i]);
Enumeration iPimListEnum = iPIMList.items();
String iContactName, iTelNumber;
String []arrName;
boolean isSupportFormettedName = iPIMList.isSupportedField(Contact.FORMATTED_NAME);
if(isSupportFormettedName) {
while (iPimListEnum.hasMoreElements()) {
try {
Contact iContact = (Contact) iPimListEnum.nextElement();
iContactName = iContact.getString(Contact.FORMATTED_NAME, 0);
iTelNumber = iContact.getString(Contact.TEL, 0);
} catch (Exception e) {
Logger.logStackTrace(e);
continue;
}
long corePhoneNumber = StringUtils.toCCPhoneNumber(iTelNumber);
// Check Duplicate
if (iPhoneBookList.containsKey(corePhoneNumber)) {
continue;
}
iPhoneBookList.put(corePhoneNumber, iContactName);
}
} else {
while (iPimListEnum.hasMoreElements()) {
try {
Contact iContact = (Contact) iPimListEnum.nextElement();
arrName = iContact.getStringArray(Contact.NAME, Contact.ATTR_NONE);
iContactName = "";
if(arrName[Contact.NAME_FAMILY] != null) {
iContactName += arrName[Contact.NAME_FAMILY];
}
if(arrName[Contact.NAME_GIVEN] != null) {
iContactName += arrName[Contact.NAME_GIVEN];
}
iTelNumber = iContact.getString(Contact.TEL, 0);
} catch (Exception e) {
Logger.logStackTrace(e);
continue;
}
long corePhoneNumber = StringUtils.toCCPhoneNumber(iTelNumber);
// Check Duplicate
if (iPhoneBookList.containsKey(corePhoneNumber)) {
continue;
}
iPhoneBookList.put(corePhoneNumber, iContactName);
}
}
} catch (PIMException ex) {
Logger.logStackTrace(ex);
} catch (Exception otherEx) {
Logger.logStackTrace(otherEx);
}
}
return iPhoneBookList;
}

Not able to get DirContext ctx using Spring Ldap

Hi i am using Spring ldap , after execution below program It display I am here only and after that nothing is happening, program is in continue execution mode.
public class SimpleLDAPClient {
public static void main(String[] args) {
Hashtable env = new Hashtable();
System.out.println("I am here");
String principal = "uid="+"a502455"+", ou=People, o=ao, dc=com";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "MYURL");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS,"PASSWORD");
DirContext ctx = null;
NamingEnumeration results = null;
try {
ctx = new InitialDirContext(env);
System.out.println(" Context" + ctx);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
results = ctx.search("", "(objectclass=aoPerson)", controls);
while (results.hasMore()) {
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
Attribute attr = attributes.get("cn");
String cn = (String) attr.get();
System.out.println(" Person Common Name = " + cn);
}
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
}
}
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
}
}
}
}
}
Try fixing the below lines, i removed "ao" and it works fine.
results = ctx.search("", "(objectclass=Person)", controls);
You need to give search base as well
env.put(Context.PROVIDER_URL, "ldap://xx:389/DC=test,DC=enterprise,DC=xx,DC=com");
Refer this link as well http://www.adamretter.org.uk/blog/entries/LDAPTest.java

Resources