IIS Directory Services - c#

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%.

Related

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.

Published my ASP.Net 2013 Website to IIS 7 and receiving an error of Invalid attemp to read data when no data is present

I cannot seem to find out why my SQL data connections are not being recognized and the SQL Data Reader is not being able to read data when I publish my ASP.Net Site. It works when I just use the localhost and it is not published but once I publish it to IIS 7 it can no longer read data from SQL server. Please anyone if you can help that would great. I am very new to IIS 7 and cannot figure this out for the life of me. I have tried to check other blogs but I am coming up with nothing. The error that I am getting is:
Invalid attempt to read when no data is present.
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.InvalidOperationException: Invalid attempt to read when no data is present.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: Invalid attempt to read when no data is present.]
System.Data.SqlClient.SqlDataReader.CheckDataIsReady(Int32 columnIndex, Boolean allowPartiallyReadColumn, Boolean permitAsync, String methodName) +5327847
System.Data.SqlClient.SqlDataReader.TryReadColumn(Int32 i, Boolean setTimeout, Boolean allowPartiallyReadColumn) +47
System.Data.SqlClient.SqlDataReader.GetValueInternal(Int32 i) +31
System.Data.SqlClient.SqlDataReader.GetValue(Int32 i) +73
System.Data.SqlClient.SqlDataReader.get_Item(String name) +27
GLIncidentRequestForm._Default.Page_Load(Object sender, EventArgs e) +318
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
web.config connection string:
Page Code:
string connString = ConfigurationManager.ConnectionStrings["NPXL_REPORTINGConnectionString"].ConnectionString;
string strAccount = HttpContext.Current.User.Identity.Name.ToString();
string strUserName = strAccount.Split('\\').Last();
txtStrName.Text = strUserName;
string selectSQL = "SELECT sAMAccountName, mail FROM ActiveDirectories WHERE mail Is Not Null and sAMAccountName = '" + txtStrName.Text + "'";
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader = default(SqlDataReader);
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
txtADName.Text = reader["sAMAccountName"].ToString();
txtEmail.Text = reader["mail"].ToString();
}
finally
{
reader.Close();
con.Close();
}

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.

DirectoryEntry.Children.Remove throws "unspecified error"

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.

How can i get a list of the websites in IIS from within a ASPX page using c#?

I'm trying to use
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC/1/Root");
foreach (DirectoryEntry de in root.Children)
{
}
but I keep getting
[COMException (0x80005000): Unknown error (0x80005000)]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +557
System.DirectoryServices.DirectoryEntry.Bind() +44
System.DirectoryServices.DirectoryEntry.get_IsContainer() +42
System.DirectoryServices.ChildEnumerator..ctor(DirectoryEntry container) +36
System.DirectoryServices.DirectoryEntries.GetEnumerator() +36
IISVdir.List(String RootWeb) in c:\Development\Testing\App_Code\IISVdir.cs:116
_Default.Page_Load(Object sender, EventArgs e) in c:\Development\Testing\Default.aspx.cs:11
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
System.Web.UI.Control.OnLoad(EventArgs e) +132
System.Web.UI.Control.LoadRecursive() +66
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2428
In Windows 7/8 go Control Panel / Program And Features / Turn Windows features on or off, and check all items from: Web Managment Tools, (it's include: IIS Managment Service, II 6 Managment Compatibility).
And you can use the code:
public static void OpenWebsite(string name)
{
DirectoryEntry Services = new DirectoryEntry("IIS://localhost/W3SVC");
IEnumerator ie = Services.Children.GetEnumerator();
DirectoryEntry Server = null;
string nombre = "";
while (ie.MoveNext())
{
Server = (DirectoryEntry)ie.Current;
if (Server.SchemaClassName == IIsWebServer)
{
nombre = Server.Properties["ServerComment"][0].ToString();
if (nombre == name)
{
break;
}
}
}
Console.Write(nombre);
}
I'm not too sure what the error is but at a guess it might be installation issue or permissions.
For installation type issues:
http://blogs.msdn.com/b/jpsanders/archive/2009/05/13/iis-7-adsi-error-system-runtime-interopservices-comexception-0x80005000-unknown-error-0x80005000.aspx
For permissions type issues adding something to config like:
<identity impersonate="true" userName="AdminUserName" password="password" />
Or changing the user context that the application pool runs under to one that has local admin rights could work.
Also, the children of IIS://localhost/W3SVC/1/Root will be Virtual Directories or Folders. Websites would be IIS://localhost/W3SVC.

Categories