Not able to get DirContext ctx using Spring Ldap - 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

Related

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

self hosted pushsharp - Events_OnNotificationSendFailure Failure: There were not enough free threads in the ThreadPool to complete the operation

i my PushSharp service is self hosted in windows service,
but after a short while it always throws:
Events_OnNotificationSendFailure
- the exception is "There were not enough free threads in the ThreadPool to complete the operation". what is the proper way to do that?
public partial class PushNotificationService : ServiceBase
{
private static bool flagNotification = true;
static PushService push;
protected override void OnStart(string[] args)
{
SetPushService();
//start console service worker
Thread t = new Thread(NotificationServiceWorker);
t.IsBackground = true;
t.Start();
}
private static void NotificationServiceWorker()
{
try
{
int sendNotificationTimeGap = Convert.ToInt32(ConfigurationManager.AppSettings["SendNotificationTimeGap"]);
while (flagNotification)
{
try
{
/// get IosPushNotificationService
IosPushNotificationService pns = new IosPushNotificationService();
/// Get The New Notification from db
List<NewPushNotifications> notificationToSend = pns.GetIosNotificationsToSend().Where(n => (n.CreatedDate ?? DateTime.Now) > DateTime.Now.AddMinutes(-5)).ToList();
if (notificationToSend != null && notificationToSend.Count > 0)
{
SendNotificationToIphone(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Iphone).ToList());
SendNotificationToAndroid(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Android).ToList());
}
Thread.Sleep(sendNotificationTimeGap);
}
catch (Exception ex)
{
CustomError.Error("error in flagNotification loop", ex);
}
}
}
catch (Exception ex)
{
CustomError.Error("error in NotificationServiceWorker", ex);
}
}
private static void SetPushService()
{
push = new PushService();
push.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
push.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
push.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
push.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
push.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
string androidSenderId = ConfigurationManager.AppSettings["AndroidSenderId"];
string androidSenderAuthToken = ConfigurationManager.AppSettings["AndroidSenderAuthToken"];
string androidPackage = ConfigurationManager.AppSettings["androidPackage"];
push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings(androidSenderId, androidSenderAuthToken, androidPackage), new PushSharp.Common.PushServiceSettings() { AutoScaleChannels = false });
string appleCertificates = ConfigurationManager.AppSettings["AppleCertificates"];
var appleCert = File.ReadAllBytes(appleCertificates);
var appleCertPassword = ConfigurationManager.AppSettings["AppleCertPassword"];
var appleIsProduction = ConfigurationManager.AppSettings["AppleIsProduction"].ToLower() == bool.TrueString;
push.StartApplePushService(new ApplePushChannelSettings(appleIsProduction, appleCert, appleCertPassword));
}
}
Don't use thread instead you can use timer like this
protected override void OnStart(string[] args)
{
NotificationServiceEventLog.WriteEntry("Service Started at"+DateTime.Now);
if (oNotificationComponent ==null)
oNotificationComponent = new NotificationComponent();
Heading
try
{
if (StartAppleNotificationService())
StartTimer();
}
catch (Exception ex)
{
NotificationServiceEventLog.WriteEntry(ex.Message);
}
base.OnStart(args);
}
private bool StartAppleNotificationService() {
bool IsStarted = false;
try
{
if (oPushService == null)
oPushService = new PushService();
NotificationServiceEventLog.WriteEntry("Apple Notification Service started successfully");
oPushService.Events.OnChannelCreated += new PushSharp.Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
oPushService.Events.OnChannelDestroyed += new PushSharp.Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);
oPushService.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
oPushService.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
oPushService.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
oPushService.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
oPushService.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
byte[] appleCert = File.ReadAllBytes("PushNSCert.p12");
var settings = new ApplePushChannelSettings(true, appleCert, "123456");
oPushService.StartApplePushService(settings);
IsStarted = true;
}
catch (Exception ex)
{
throw new Exception("Exception in starting Apple Service :" + ex.Message + Environment.NewLine + ex.StackTrace);
}
return IsStarted;
}
private bool StartTimer() {
try
{
Double Ms = Convert.ToDouble(ConfigurationManager.AppSettings["TickInterval"]);
NotificationServiceEventLog.WriteEntry("Time Interval" + Ms.ToString());
MyTimer = new Timer();
MyTimer.Interval += (1)*(60)*(1000);
MyTimer.Enabled = true;
MyTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
}
catch (Exception ex) {
throw ex;
}
return true;
}
private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
string SentNotificationIDz = "";
try
{
MyTimer.Enabled = false;
string szConnectionString = #"Server=.\SQL2K8;Database=PaychecksDB_Live;User Id=sa;Password=tdsadmin#321";
//ConfigurationManager.AppSettings["connString"];
lNotifictaion = oNotificationComponent.GetNotificationsList(szConnectionString);
foreach (NotificationModel oNotificationModel in lNotifictaion)
{
SendNotification(oNotificationModel.DeviceToken, oNotificationModel.NotificationMessage + " (" + oNotificationModel.NotificationTitle + ")");
if (SentNotificationIDz == null)
SentNotificationIDz += oNotificationModel.Oid;
else
SentNotificationIDz += "," + oNotificationModel.Oid;
}
oNotificationComponent.DeleteSentNotifications(SentNotificationIDz, szConnectionString);
MyTimer.Enabled = true;
}
catch (Exception ex) {
throw ex;
}
//
}
private void SendNotification(string p_szDeviceToken,string p_szAlert)
{
try
{
oPushService.QueueNotification(NotificationFactory.Apple()
.ForDeviceToken(p_szDeviceToken)
.WithAlert(p_szAlert)
.WithBadge(2)
.WithSound("default")
.WithExpiry(DateTime.Now.AddDays(1))
);
}
catch (Exception ex)
{
throw new Exception("Error in sending Push Notification:" + ex.Message + Environment.NewLine + ex.StackTrace);
}
}

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

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.

SharePoint List Service Recursive not working

I am using the following code to retrieve the documents in a list. Its working fine. However, it only returns documents and folders in root of the doc library. Is there any thing wrong I am doing here? I am looking for files in sub folders with recursive mode.
Service service = new Service();
service.setMaintainSession(true);
call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL("<host>/_vti_bin/lists.asmx") );
call.setOperationName(new QName("http://schemas.microsoft.com/sharepoint/soap/","GetListItems"));
call.setProperty(Call.SOAPACTION_USE_PROPERTY, new Boolean("true"));
call.setProperty(Call.SOAPACTION_URI_PROPERTY,"http://schemas.microsoft.com/sharepoint/soap/GetListItems");
call.addParameter(new javax.xml.namespace.QName("http://schemas.microsoft.com/sharepoint/soap/", "listName"),
new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"),
java.lang.String.class,
javax.xml.rpc.ParameterMode.IN);
MessageElement me =
new MessageElement(new QName("QueryOptions"));
me.addChildElement(new MessageElement(new QName(
"IncludeMandatoryColumns"))).addTextNode("true");
me.addChildElement(new MessageElement(new QName(
"ViewAttributes"))).addAttribute(javax.xml.soap.SOAPFactory.newInstance().createName("Scope"), "Recursive");
MessageElement[] me1 = {me};
String strMyString = ""
+ "<Query>"
+ "<OrderBy><FieldRef Name=\"ows_Modified\" Ascending=\"TRUE\" /></OrderBy>"
+ "</Query>";
MessageElement[] meArray = { getMeFromString(strMyString) };// Array
call.addParameter("query",org.apache.axis.Constants.XSD_SCHEMA,
javax.xml.rpc.ParameterMode.IN);
call.addParameter("queryOptions",org.apache.axis.Constants.XSD_SCHEMA,
javax.xml.rpc.ParameterMode.IN);
call.setReturnType(org.apache.axis.Constants.XSD_SCHEMA);
Schema ret = (Schema)call.invoke(new Object[] {"listGUID",meArray, me1 });
public org.apache.axis.message.MessageElement getMeFromString(final String strMyString) {
DocumentBuilder docBuilder = null;
try {
docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (final ParserConfigurationException e) {
e.printStackTrace();
} catch (final FactoryConfigurationError e) {
e.printStackTrace();
}
final StringReader reader = new StringReader(strMyString);
final InputSource inputsource = new InputSource(reader);
Document doc = null;
try {
doc = docBuilder.parse(inputsource);
} catch (final SAXException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
final Element ele = doc.getDocumentElement();
final MessageElement msg = new MessageElement(ele);
return msg;
}
query.ViewAttributes = "Scope='RecursiveAll'"

Resources