DirectoryEntry.Children.Remove throws "unspecified error" - c#

I have a little code to delete a security group from Active Directory, but when run, I get a COMException with the message "Unspecified error".
Here is the code:
public void DeleteGroup(Model.Asset pADSecurityGroup)
{
using(DirectoryEntry ou = new DirectoryEntry(pADSecurityGroup.Organization.ActiveDirectoryMappings.Single().Identifier))
using(DirectoryEntry group = new DirectoryEntry("LDAP://" + pADSecurityGroup.ActiveDirectoryMappings.Single().Identifier))
{
ou.Children.Remove(group);
group.CommitChanges();
}
}
And here's the message in the Windows Event Console:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 8/23/2011 11:29:35 AM
Event time (UTC): 8/23/2011 5:29:35 PM
Event ID: 67e6356c9ff146c7a0d9024350cbb3a0
Event sequence: 79
Event occurrence: 1
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/1/ROOT-2-129585938920392018
Trust level: Full
Application Virtual Path: /
Application Path: C:\inetpub\wwwroot\vo\Web\Portal\
Machine name: TR-2K8-001 Process information:
Process ID: 8348
Process name: w3wp.exe
Account name: VO\treed Exception information:
Exception type: COMException
Exception message: Unspecified error
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_IsContainer()
at System.DirectoryServices.DirectoryEntries.Remove(DirectoryEntry entry)
at VirtualOffice.DirectoryServices.Impl.DirectoryService.DeleteGroup(ResourcePool pResourcePool) in C:\inetpub\wwwroot\vo\Common Libraries\VirtualOffice.DirectoryServices\Impl\DirectoryService.cs:line 249
at VirtualOffice.Controllers.ResourcePoolController.Delete(Int32 pServiceProviderId) in C:\inetpub\wwwroot\vo\Common Libraries\VirtualOffice.Controllers\ResourcePoolController.cs:line 171
at Organization_ResourcePools.rtbResourcePools_OnButtonClick(Object sender, RadToolBarEventArgs e) in c:\inetpub\wwwroot\vo\Web\Portal\Organization\ResourcePools.aspx.cs:line 85
at Telerik.Web.UI.RadToolBar.OnButtonClick(RadToolBarEventArgs e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Request information:
Request URL: https://localhost:443/Organization/ResourcePools.aspx
Request path: /Organization/ResourcePools.aspx
User host address: ::1
User: Portal Admin
Is authenticated: True
Authentication Type: Federation
Thread account name: VO\treed Thread information:
Thread ID: 5
Thread account name: VO\treed
Is impersonating: False
Stack trace:
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_IsContainer()
at System.DirectoryServices.DirectoryEntries.Remove(DirectoryEntry entry)
at VirtualOffice.DirectoryServices.Impl.DirectoryService.DeleteGroup(ResourcePool pResourcePool) in C:\inetpub\wwwroot\vo\Common Libraries\VirtualOffice.DirectoryServices\Impl\DirectoryService.cs:line 249
at VirtualOffice.Controllers.ResourcePoolController.Delete(Int32 pServiceProviderId) in C:\inetpub\wwwroot\vo\Common Libraries\VirtualOffice.Controllers\ResourcePoolController.cs:line 171
at Organization_ResourcePools.rtbResourcePools_OnButtonClick(Object sender, RadToolBarEventArgs e) in c:\inetpub\wwwroot\vo\Web\Portal\Organization\ResourcePools.aspx.cs:line 85
at Telerik.Web.UI.RadToolBar.OnButtonClick(RadToolBarEventArgs e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Custom event details:

Based on the questions/answer in the comments section I revise my answer.
I think you simply forgot the LDAP protocol identifier for the LDAP path of your organization unit. I think, unspecified error means invalid LDAP path.
Try the following code:
public void DeleteGroup(Model.Asset pAsset)
{
using(DirectoryEntry ou = new DirectoryEntry("LDAP://" + pResourcePool.Organization.ActiveDirectoryMappings.Single().Identifier))
{
using(DirectoryEntry group = new DirectoryEntry("LDAP://" + pResourcePool.ActiveDirectoryMappings.Single().Identifier), username, userpwd)
{
ou.Children.Remove(group);
group.CommitChanges();
}
}
}
By the same token, ensure that the LDAP protocol identifier is written using capital letters.
Hope, this helps.

Just guessing: Maybe the DirectoryEntry "ou" is not empty.
MSDN says:
If the entry to be removed is a container, the container must be empty. To delete a container and all its children, use the DeleteTree method.
You also may try to catch the ComException and gather more information so the problem can be analysed.

Related

IIS Directory Services

I am trying to get the website id from IIS on Windows Server 2012 R2. I want to fetch the Id, then add a website pointer for the website in IIS. I'm not sure where to grant the permissions for the code to work and at the same time, not leaving my web server vulnerable.
Here is my code for fetching Id
string result = "-1";
DirectoryEntry w3svc = new DirectoryEntry(string.Format("IIS://{0}/w3svc", "localhost"));
foreach (DirectoryEntry site in w3svc.Children)
{
if (site.Properties["ServerComment"] != null)
{
if (site.Properties["ServerComment"].Value != null)
{
if (string.Compare(site.Properties["ServerComment"].Value.ToString(),
"website.com", true) == 0)
{
result = site.Name;
break;
}
}
}
}
return result;
This is the error that is thrown:
Access is denied.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: Access
is denied.
Source Error:
Line 22: DirectoryEntry w3svc = new
DirectoryEntry(string.Format("IIS://{0}/w3svc", serverName));
Line 23:
Line 24: foreach (DirectoryEntry site in w3svc.Children)
Line 25: {
Line 26: if (site.Properties["ServerComment"] != null)
Source File: c:\inetpub\wwwroot\DNS_IIS\DNS.aspx.cs Line: 24
Stack Trace:
[COMException (0x80070005): Access is denied.
]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
+597561
System.DirectoryServices.DirectoryEntry.Bind() +44
System.DirectoryServices.DirectoryEntry.get_IsContainer() +42
System.DirectoryServices.DirectoryEntries.GetEnumerator() +49
DNS.GetWebSiteId(String serverName, String websiteName) in c:\inetpub
\wwwroot\DNS_IIS\DNS.aspx.cs:24
DNS.btnDNS_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot
\DNS_IIS\DNS.aspx.cs:85
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +155
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+3804
It was a simple thing to sort out.
So I just changed the Identity of the ApplicationPool to LocalSystem and it worked 100%.

Write a caught ASP.NET exception to EventLog without losing detail

This article explains in detail how to log an ASP.NET exception to the Windows EventLog and display a custom error page to the end-user.
However, the standard Event Logging mechanism for an ASP.NET web application automatically includes a lot of useful information not shown in this article. Implementing the code in the article results in a loss of detail/granularity in my error Event.
For example with automatic uncaught exception logging, you can see many attributes under the headings: Event Information, Application Information, Process Information, Request Information, Thread Information, Custom Event Details.
How can I implement logging of all of the same information that is logged in an uncaught exception and append my custom information into the section Custom Event Details? The best answer should preferably use some inbuilt method(s) of System.Diagnostics or System.Exception or similar i.e. writing as little code as possible to write the log entry with all sections mentioned above and simply append any custom details to the string.
If it is possible, I would also like to return the unique hashed Event ID (example b68b3934cbb0427e9497de40663c5225 from below) back to the application for display on my ErrorPage.aspx
Example of log format required:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 15/07/2016 15:44:01
Event time (UTC): 15/07/2016 14:44:01
Event ID: b68b3934cbb0427e9497de40663c5225
Event sequence: 131
Event occurrence: 2
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/3/ROOT-1-131130657267252632
Trust level: Full
Application Virtual Path: /
Application Path: C:\WWW\nobulus\nobulusPMM\Application\PMM\
Machine name: L-ADAM
Process information:
Process ID: 47216
Process name: iisexpress.exe
Account name: L-ADAM\Adam
Exception information:
Exception type: ApplicationException
Exception message: Error running stored procedure saveValidation: Procedure or function 'saveValidation' expects parameter '#ValidatedBy', which was not supplied.
at PMM.Models.PMM_DB.runStoredProcedure(String StoredProcedureName, List`1 SQLParameters) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Models\PMM_DB.cs:line 104
at PMM.Models.PMM_DB.saveValidation(String PTLUniqueID, String ValidatedBy, DateTime ValidationDateTime, Nullable`1 ValidationCategoryID, String ValidationCategory, String Comment, Nullable`1 ClockStartDate, Nullable`1 ClockStopDate, String StartRTTStatus, String StopRTTStatus, String LastRTTStatus, Boolean MergedPathway, String MergedPathwayID, String ExtinctPathwayID, DataTable ChecklistResponses) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Models\PMM_DB.cs:line 265
at PMM.Validate.lnkSaveButton_Click(Object sender, EventArgs e) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Validate.aspx.cs:line 323
at System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e)
at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Request information:
Request URL: http://localhost:6901/Validate?PTLUniqueID=RTT10487
Request path: /Validate
User host address: ::1
User: L-ADAM\Adam
Is authenticated: True
Authentication Type: Negotiate
Thread account name: L-ADAM\Adam
Thread information:
Thread ID: 19
Thread account name: L-ADAM\Adam
Is impersonating: False
Stack trace: at PMM.Models.PMM_DB.runStoredProcedure(String StoredProcedureName, List`1 SQLParameters) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Models\PMM_DB. cs:line 104
at PMM.Models.PMM_DB.saveValidation(String PTLUniqueID, String ValidatedBy, DateTime ValidationDateTime, Nullable`1 ValidationCategoryID, String ValidationCategory, String Comment, Nullable`1 ClockStartDate, Nullable`1 ClockStopDate, String StartRTTStatus, String StopRTTStatus, String LastRTTStatus, Boolean MergedPathway, String MergedPathwayID, String ExtinctPathwayID, DataTable ChecklistResponses) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Models\PMM_DB.cs:line 265
at PMM.Validate.lnkSaveButton_Click(Object sender, EventArgs e) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Validate.aspx.cs:line 323
at System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e)
at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Custom event details:
UPDATE
I actually found out using ILSpy and roaming in different framework classes that ASP.NET uses internally WebErrorEvent, which possess protected methods to achieve the same behavior.
Solution 1:
For that, just create a class which inherits WebErrorEvent, and then override its constructor:
public class CustomWebErrorEvent : WebErrorEvent
{
public CustomWebErrorEvent(string message, EventSource source, int eventCode, Exception ex) : base(message, source, eventCode, ex)
{
}
}
Then using it inside the Error management method from Global.asax:
protected void Application_Error(Object sender, EventArgs e)
{
// Log error to the Event Log
Exception myError = null;
if (HttpContext.Current.Server.GetLastError() != null)
{
var r = new CustomWebErrorEvent("error", null, 120, HttpContext.Current.Server.GetLastError());
}
}
I am pretty sure it is posslbe also to overload ASPNET to only raise straight a custom WebErrorEvent, but I didn't find it yet.
I am still trying to figure out how to add custom info to the event as overriding the method FormatCustomEventDetails is not getting called for Web Managed error events.
Solution 2:
If not possible as missing adding custom fields for now, you can use a similar method that I wrote which does the same output:
// Log error to the Event Log
Exception myError = null;
if (HttpContext.Current.Server.GetLastError() != null)
{
var request = HttpContext.Current.Request;
myError = HttpContext.Current.Server.GetLastError();
var dateAsBytes = System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("G"));
var id = Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(dateAsBytes));
// Event info:
var eventMessage = myError.Message;
var currentTime = DateTime.Now.ToString("G");
var currentTimeUTC = DateTime.UtcNow.ToString("G");
// Application info:
var appDomainName = AppDomain.CurrentDomain.FriendlyName;
var appDomainTrustLevel = (AppDomain.CurrentDomain.IsFullyTrusted) ? "Full" : "Partial";
var appVirtualPath = VirtualPathUtility.GetDirectory(request.Path);
var appPath = request.PhysicalApplicationPath;
var machineName = Environment.MachineName;
// Process info:
var process = Process.GetCurrentProcess();
var processId = process.Id;
var processName = process.ProcessName;
var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
var accountName = user.Translate(typeof(System.Security.Principal.NTAccount));
// Exception info:
var exceptionType = myError.GetType().FullName;
var exceptionMessage = myError.Message;
var exceptionStack = myError.StackTrace;
// Request info:
var url = request.Url.AbsoluteUri;
var urlPath = request.Url.PathAndQuery;
var remoteAddress = request.UserHostAddress;
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var isAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;
var authenticationType = System.Security.Principal.WindowsIdentity.GetCurrent().AuthenticationType;
// Thread info:
var impersonationLevel = System.Security.Principal.WindowsIdentity.GetCurrent().ImpersonationLevel;
var exceptionStack2 = myError.StackTrace;
// TODO: aggregate all info as string before writting to EventLog.
}
I found using existing .NET Apis almost all required fields from your output, just needed know to be aggregated as a string before outputting it in EventLog.
You can see that some of the object I am using (such as AppDomain.CurrentDomain, HttpContext.Current.Request or Process.GetCurrentProcess() returns a lot of other info, which could also ne added to the output if needed.
This all can be wrapped up under a method for code brevity of course.

OData from .Net application ends with Unauthorized

I am trying to consume the new Dynamics AX OData endpoint from a .Net console applications, I can see that the authentication is going fine but whenever I try to get the results on my application it ends with an Unauthorized error.
Any idea on what could be the cause or hos to get a more detailed information (logs)?
This is the code that throws the error at line:
foreach (var legalEntity in context.Teams.AsEnumerable())
static void Main(string[] args)
{
Uri oDataUri = new Uri(ODataEntityPath, UriKind.Absolute);
var context = new Resources(oDataUri);
context.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>(delegate (object sender, SendingRequest2EventArgs e)
{
var authenticationHeader = OAuthHelper.GetAuthenticationHeader();
e.RequestMessage.SetHeader(OAuthHelper.OAuthHeader, authenticationHeader);
});
foreach (var legalEntity in context.Teams.AsEnumerable())
{
Console.WriteLine("Name: {0}", legalEntity.Name);
}
Console.ReadLine();
Exception
at Microsoft.OData.Client.QueryResult.ExecuteQuery()
at Microsoft.OData.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)
Unauthorized
at Microsoft.OData.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)
at Microsoft.OData.Client.DataServiceQuery`1.Execute()
at Microsoft.OData.Client.DataServiceQuery`1.GetEnumerator()
at ODataConsoleApplication.Program.Main(String[] args)
Auth logs
Activated Event Time Duration Thread
06/04/2016 9:55:13: 42dbc15a-e068-4f46-9e99-3e41b1820eb9 - AcquireTokenHandlerBase: === Token Acquisition finished successfully.
An access token was retuned:
Access Token Hash: UsxaQ/QZQ+opGz/PC55O5cWYBV8kh1uhvf/CG269WSc=
Refresh Token Hash: 8aKSzBXtBrxr+uVaqhnT/IEg1+gXOkDqq/WHp8SmaBk=
Expiration Time: 06/04/2016 10:55:12 +00:00
User Hash: f1MLHm5K8HDY7tRpkz4amU2+CVFL53JJq3Ybc5q53g0= 4.59s
Activated Event Time Duration Thread
Exception thrown: 'Microsoft.OData.Client.DataServiceQueryException' in Microsoft.OData.Client.dll
("An error occurred while processing this request.") 5.13s [18036] <No Name>
You must add your application in Dynamics in order for it to work.
See ​System administration > Setup > Azure Active Directory applications

How to find all comments on a particular linkedin article given articleId?

I published a LinkedIn article and I'm trying to retrieve the comments for this particular article. I obtained the articleId by right clicking on the comments button and copying the link address. I get aritcleId = 7434836657526032700. Should I use GET http://api.linkedin.com/v1/posts/{post-id}/comments where {post-id} is same as articleId?
Below is my code after successful AuthorizationLinkGet call.
string oauth_token = Request.QueryString["oauth_token"];
string oauth_verifier = Request.QueryString["oauth_verifier"];
if (oauth_token != null && oauth_verifier != null)
{
Application["oauth_token"] = oauth_token;
Application["oauth_verifier"] = oauth_verifier;
//get access token
_oauth.Token = oauth_token;
_oauth.TokenSecret = Application["reuqestTokenSecret"].ToString();
_oauth.Verifier = oauth_verifier;
_oauth.AccessTokenGet(oauth_token);
sLinkedInCommentsURL = "http://api.linkedin.com/v1/posts/7434836657526032700/comments";
string response = _oauth.APIWebRequest("GET", sLinkedInCommentsURL, null);
lblMessage.Text = response;
}
I receive following error:
Server Error in '/dreamplaybook' Application.
The remote server returned an error: (403) Forbidden.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The remote server returned an error: (403) Forbidden.
Source Error:
Line 433: finally
Line 434: {
Line 435: webRequest.GetResponse().GetResponseStream().Close();
Line 436: responseReader.Close();
Line 437: responseReader = null;
Source File: c:\inetpub\calendias\dreamplaybook\App_Code\oAuthLinkedIn.cs Line: 435
Stack Trace:
[WebException: The remote server returned an error: (403) Forbidden.]
System.Net.HttpWebRequest.GetResponse() +6538872
oAuthLinkedIn.WebResponseGet(HttpWebRequest webRequest) in c:\inetpub\calendias\dreamplaybook\App_Code\oAuthLinkedIn.cs:435
oAuthLinkedIn.APIWebRequest(String method, String url, String postData) in c:\inetpub\calendias\dreamplaybook\App_Code\oAuthLinkedIn.cs:357
adposter.Page_Load(Object sender, EventArgs e) in c:\inetpub\calendias\dreamplaybook\adposter.aspx.cs:282
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34237
Article ID is not the same field as post id, so that is why you are getting the error you see. The API does not allow you to get comments from publications.

Problems in aspnet membership provider

I am using asp.net memebership
I log out the applcation by writting this code for log out
if (Membership.GetUser(HttpContext.Current.User.Identity).IsOnline) ;
{
FormsAuthentication.SignOut();
Response.Redirect(FormsAuthentication.LoginUrl);
}
Response.Redirect("loginpage.aspx");
After then I started the application and gettig the error in code block of authetication .below I am writtng a code and error message
else if (User.Identity.IsAuthenticated == true && Membership.GetUser( Membership.FindUsersByName(User.Identity.Name)).IsOnline==true)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
MembershipUser currUser = null;
string gt = null;
if (HttpContext.Current.User != null)
{
currUser = Membership.GetUser(true);
gt = currUser.Email;
}
/// string temp = User.Identity.GetProfile().ID;
//string query = "Insert into user_tbl(MemberID)(" + temp + ")";
//Response.Redirect("UserPanel.aspx");
//return;
}
here Membership.FindUsersByName(User.Identity.Name)).IsOnline==true) I am getting this error
[ArgumentException: The provider user key supplied is invalid. It
must be of type System.Guid. Parameter name: providerUserKey]
I am unable to find what to do , I debug the application and found User.Identity.Name as a hash value
Stack Trace
Exception Details: System.ArgumentException: The provider user key supplied is invalid. It must be of type System.Guid.
Parameter name: providerUserKey
Source Error:
Line 86: }
Line 87:
Line 88: else if (User.Identity.IsAuthenticated == true && Membership.GetUser( Membership.FindUsersByName(User.Identity.Name)).IsOnline==true)
Line 89: {
Line 90:
Source File: d:\31 May 2012\Demo\LoginPage.aspx.cs Line: 88
Stack Trace:
[ArgumentException: The provider user key supplied is invalid. It must be of type System.Guid.
Parameter name: providerUserKey]
System.Web.Security.SqlMembershipProvider.GetUser(Object providerUserKey, Boolean userIsOnline) +2242996
System.Web.Security.Membership.GetUser(Object providerUserKey, Boolean userIsOnline) +40
System.Web.Security.Membership.GetUser(Object providerUserKey) +6
LoginPage.Page_Load(Object sender, EventArgs e) in d:\31 May 2012\Demo\LoginPage.aspx.cs:88
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +36
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
Or you could also use Request.IsAuthenticated which dosent get the whole user object and just checks authentication.
According to Visual Studio, Membership.FindUsersByName returns MembershipUserCollection. You pass that object to the Membership.GetUser method, which does accept a parameter of the object type, but that object is supposed to be a user's ID (a GUID in ASP.NET). So, the exception is quite expected: you're trying to pass a collection of users, while the method expects a single user ID.
If you need to check whether a user is currently logged in, you can simply do this:
if (Membership.GetUser() != null)
See this MSDN Library article for more information on the method.

Categories