C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




how can we set the iis setting through programatically


Posted Date: 30 Aug 2008      Total Responses: 2

Posted By: vaddesreenivasulu       Member Level: Gold     Points: 1


my requirement is iam having 2 .net frame works like 1.1 and 2.0 i want to set the 1.1 when clicking the default website properties under asp.net tab set the asp.net version=1.1.4233 and in derictory security unchecking the anonymous access checkbox

how can i do above requirement through .net




Responses

Author: Rajesh(March-2008 Winner)    30 Aug 2008Member Level: GoldRating:     Points: 6
hi,
try this ,
using System;

using System.Collections;

using System.Collections.Generic;

using System.Text;

using System.Xml;

using System.DirectoryServices;

using System.Diagnostics;

using System.IO;

using System.Reflection;

//using FSHelperLib;

namespace FSCSharpLib.IISMetadata

{

/// <summary>

//see also IISChameleon.INETMGRHelper

/// Helper methods to access IIS Virtual directories

/// </summary>

/// <remarks>Code samples used are from ASP.NET IIS Chameleon Tool(http://www.123aspx.com/redir.aspx?res=33760 and

/// Creating Virtuals and reading Installed Sites on IIS with .Net(http://west-wind.com/weblog/posts/399.aspx ) </remarks>

public class IISMetaDataHelper

{

//For debugginh it is convinient to use adsutil.vbs http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d3df4bc9-0954-459a-b5e6-7a8bc462960c.mspx

/*e.g commands

C:\Inetpub\AdminScripts\Cscript.exe adsutil.vbs ENUM W3SVC/1/root/vKnowledge/admin/Security/WinLogin.aspx

C:\Inetpub\AdminScripts\Cscript.exe adsutil.vbs CREATE W3SVC/1/root/vKnowledge/admin/Security/WinLogin.aspx

C:\Inetpub\AdminScripts\Cscript.exe adsutil.vbs SET W3SVC/1/root/vKnowledge/admin/Security/WinLogin.aspx/keyType IISWebFile

C:\Inetpub\AdminScripts\Cscript.exe adsutil.vbs delete W3SVC/1/root/vKnowledge/admin/Security/WinLogin.aspx

*/

/// <summary>

/// Concat parts of the path using Site Path in format @"/LM/W3SVC/1" passed by Web Setup to path accepted by DirectoryEntry

/// </summary>

/// <param name="SiteMetaPath">Format @"/LM/W3SVC/1"</param>

/// <param name="VDirRoot">e.g vKnowledge</param>

/// <param name="relPath">e.g @"admin/Security/WinLogin.aspx"</param>

/// <returns>e.g IIS://localhost/W3SVC/1/root/vKnowledge/admin/Security/WinLogin.aspx</returns>

public static void SetIntegratedSecurityOnly(string SiteMetaPath, String VDirRoot, String relPath)

{

string MetabasePath = IISMetaPath(SiteMetaPath, VDirRoot, relPath);

SetIntegratedSecurityOnly(MetabasePath);

}

/// <summary>

/// Concat parts of the path using Site Path in format @"/LM/W3SVC/1" passed by Web Setup to path accepted by DirectoryEntry

/// </summary>

/// <param name="SiteMetaPath">Format @"/LM/W3SVC/1"</param>

/// <param name="VDirRoot">e.g vKnowledge</param>

/// <param name="relPath">e.g @"admin/Security/WinLogin.aspx"</param>

/// <returns>e.g IIS://localhost/W3SVC/1/root/vKnowledge/admin/Security/WinLogin.aspx</returns>

public static string IISMetaPath(string SiteMetaPath, String VDirRoot, String relPath)

{

SiteMetaPath = SiteMetaPath.Replace(@"/LM/", "localhost/");

return @"IIS://" + SiteMetaPath + @"/root/" + VDirRoot + @"/" + relPath;

}



/// <summary>

/// SetIntegratedSecurityOnly

/// </summary>

/// <param name="MetabasePath">e.g IIS://localhost/W3SVC/1/root/vKnowledge/admin/Security/WinLogin.aspx</param>

public static void SetIntegratedSecurityOnly(string MetabasePath)

{

if (MetabasePath != string.Empty)

{

DirectoryEntry entry = null;

if (!DirectoryEntry.Exists(MetabasePath))

{ //Usually files are not explicitly added to the IIS metabase

//See http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic12899.aspx

string sFolderPath = StringHelper.LeftBeforeLast(MetabasePath, @"/");//metabasePath.Substring(0,metabasePath.LastIndexOf("/"));

string sEntryName = StringHelper.RightAfterLast(MetabasePath, @"/");// metabasePath.Substring(metabasePath.LastIndexOf("/") + 1);

DirectoryEntry folder = new DirectoryEntry(sFolderPath);

DebugHelper.PrintDirectoryEntryProperties(folder, sFolderPath);

//SchemaClassNames are listed in http://blog.crowe.co.nz/archive/2006/06/01.aspx

string SchemaClassName = "IIsObject";

//can't assign "IIsWebFile" directly, causes HRESULT: 0x8000500F exception. E_ADS_SCHEMA_VIOLATION - The attempted action violates the directory service schema rules".

// see http://groups.google.com.au/group/microsoft.public.adsi.general/browse_frm/thread/3b339d218e673aca/050974e5903530e3

entry = folder.Children.Add(sEntryName, SchemaClassName);

//Fortunately ADSUTIL shows the WARNING: The Object Type of this object was not specified or was specified as IIsObject.

//This means that you will not be able to set or get properties on the object until the KeyType property is set.

entry.Properties[MetabasePropertyNames.keyType].Value = "IIsWebFile";

folder.CommitChanges();

entry.CommitChanges();

}

//must be created as new, even if entry was just created using Children.Add

entry = new DirectoryEntry(MetabasePath);

DebugHelper.PrintDirectoryEntryProperties(entry, MetabasePath);

AuthFlags nAuthFlags = (AuthFlags)(entry.Properties[MetabasePropertyNames.AuthFlags][0]);

nAuthFlags = nAuthFlags & ~AuthFlags.AuthAnonymous; //clear anonymous

nAuthFlags = nAuthFlags | AuthFlags.AuthNTLM; //Add Integrated

entry.Properties[MetabasePropertyNames.AuthFlags][0] = nAuthFlags;

// Chameleon sets Properties["AuthNTLM"] and ["AuthAnonymous"] -does it work?

//virtualDirectory.Properties["AuthNTLM"][0] = parametros.AuthNTLM;

//virtualDirectory.Properties["AuthAnonymous"][0] = parametros.AuthAnonymous;

entry.CommitChanges();

}

}

}//class



public class MetabasePropertyNames

{// from http://technet2.microsoft.com/WindowsServer/en/Library/271ae19b-853f-4672-b743-5ba126e902db1033.mspx?mfr=true

//TODO add all Properties

public const string AuthFlags = "AuthFlags";

public const string keyType = "keyType";

}



[FlagsAttribute()]

public enum AuthFlags

{//from http://technet2.microsoft.com/WindowsServer/en/Library/271ae19b-853f-4672-b743-5ba126e902db1033.mspx?mfr=true

AuthAnonymous=1,

AuthBasic=2,

AuthNTLM = 4,

AuthMD5 = 16,

AuthPassport=64

}

//Possible exceptions from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adsi/adsi/generic_adsi_error_codes.asp

// 0x80005006 - The property does not exist, or it does not exist at the access location where you are attempting to set it.

//0x8000500C-The data type of the property is different than the data type to which you are attempting to set it.

//0x8000500F exception. E_ADS_SCHEMA_VIOLATION - The attempted action violates the directory service schema rules".



}



Author: Vidhya    30 Aug 2008Member Level: GoldRating:     Points: 6
hi,

Steps to Create and Then to Install SSL Certificates
To programmatically create and then to install SSL certificates for IIS server, follow these steps: 1. You must send a request to the certification authority to issue a server certificate. If you already have the certificate, and then you store it in the file on the IIS server, do not send the request.
2. Import the certificate to the appropriate certificate store.
3. Configure IIS to use the certificate that you obtained in step 1.

Configure IIS to Create and Then to Install SSL Certificates
Warning If you edit the metabase incorrectly, you can cause serious problems that may require you to reinstall any product that uses the metabase. Microsoft cannot guarantee that problems that result if you incorrectly edit the metabase can be solved. Edit the metabase at your own risk.

Note Always back up the metabase before you edit it. Follow these steps to configure IIS to create and then to install SSL certificates: 1. Use Microsoft Windows Crypto APIs to obtain the Thumbprint property of the certificate.
2. You must set the IIS metabase property, SSLCertHash, to the value of the Thumbprint.
3. You must set the IIS metabase property, SSLStoreName, to the store that you want to use.
See the following article sections for code samples to obtain a Thumbprint of the certificate, and then to obtain the SSLCertHash property:
C Code to Obtain the Thumbprint of a Server Authentication Certificate
C Code to Enter the SSLCertHash Property into the Metabase

Steps to Enable SSL on a Particular Web Site
After you perform the steps in the "Configure IIS to Create and Then to Install SSL Certificates" section, then you can enable SSL on a particular site or in a particular folder. To do so, you must enable SSL options in the folder that you want to use. The following steps correspond with each step that is outlined in the "Configure IIS to Create and Then to Install SSL Certificates" section: 1. When you call the CEnroll::createPKCS10() method, the certificate request is created. Set the usage to the following predefined value: szOID_PKIX_KP_SERVER_AUTH:#define szOID_PKIX_KP_SERVER_AUTH "1.3.6.1.5.5.7.3.1"

2. When you call the ICertRequest::Submit () method, a request for the certificate is submitted to the certification authority.
3. The certificate is retrieved from the certification authority, and then it is installed in the appropriate store. The IIS Server Certificate Wizard looks only for certificates that it can use for server authentication in the Local Computer certificate store.

Steps to Configure IIS
After you save the certificate to the store, you must configure IIS as follows: 1. Use the CertGetCertificateContextProperty()method to obtain the values of the Thumbprint property and the CERT_HASH_PROP_ID property. The CertGetCertificateContextProperty() function uses the CryptHashCertificate() method to compute the value for the CERT_HASH_PROP_ID property. If the HASH value does not exist, CertGetCertificateContextProperty() returns the SHA1 algorithm.
2. You must create a new binary metabase property, SSLCertHash, that corresponds to the Web site. Set SSLCertHash to the certificate Thumbprint that you obtained in step 1 of this section. When this problem occurs, the schema incorrectly specifies the SSLCertHash property as an expanded null terminated string, instead of as binary data, and then you cannot use IIS Admin Objects to import SSLCertHash. You can use only IIS Admin Base objects to import this value. To use SSLCertHash with IIS Admin Base objects, you must use the Decimal value, 5506.
3. You must create a new string metabase property, SSLStoreName, for the corresponding Web site. Set SSLStoreName to the string MY value. You can either set SSLStoreName through IIS Admin Objects (for example, in ADSI Script) or through IIS Admin Base objects. To use SSLStoreName with IIS Admin base objects, use the Decimal value, 5511.

C Code to Obtain the Thumbprint of a Server Authentication Certificate
The following sample Microsoft C code describes how to obtain the Thumbprint property of a Server Authentication certificate:

#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#define MY_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

//--------------------------------------------------------------------
// Define the name of the store where the needed certificate
// can be found.

#define CERT_STORE_NAME L"MY"

//--------------------------------------------------------------------
// Declare local functions.
// Local function definitions follow main.

void HandleError(char *s);

void main(void)
{
//--------------------------------------------------------------------
// Declare and initialize local variables.
// This includes initializing a pointer to the message.
// Usually, the message will exist somewhere and a pointer will
// be passed to the application.

//--------------------------------------------------------------------
// System store handle

HCERTSTORE hStoreHandle;

//--------------------------------------------------------------------
// Pointer to a certificate

PCCERT_CONTEXT pCert;
PCCERT_CONTEXT pPrevCert;

LPBYTE pEncodedBytes = NULL;
LPBYTE pHash;
DWORD cbData, i;

//--------------------------------------------------------------------
// Open a certificate store.

if ( !( hStoreHandle = CertOpenStore(
CERT_STORE_PROV_SYSTEM,
0,
NULL,
CERT_SYSTEM_STORE_LOCAL_MACHINE,
CERT_STORE_NAME)))
{
HandleError("The MY store could not be opened.");
}


pPrevCert = NULL;

for (; ((pCert = CertEnumCertificatesInStore(hStoreHandle, pPrevCert))
!= NULL);
pPrevCert = pCert)
{
CERT_ENHKEY_USAGE *pKeyUsage;
DWORD j, nLen;
BOOL bFound = FALSE;
char certName[1024];

nLen = sizeof(certName);
certName[0] = 0;
if (CertNameToStr(MY_TYPE, &(pCert->pCertInfo->Subject),
CERT_X500_NAME_STR,
certName,
sizeof(certName)))
{
printf("Checking %s certificate\n", certName);
}

cbData = 0;
if (!CertGetEnhancedKeyUsage(pCert,
0,
NULL,
&cbData) || cbData == 0)
{
if (GetLastError() == CRYPT_E_NOT_FOUND)
{
printf("%s certificate is for all key usages\n", certName);
break;
}
else
printf("CertGetEnhancedKeyUsage failed with error code : %08X\n",
GetLastError());
}
pKeyUsage = (CERT_ENHKEY_USAGE *)
HeapAlloc(GetProcessHeap(), 0, cbData);
if (pKeyUsage == NULL)
{
printf("HeapAlloc failed with error code : %08X\n",
GetLastError());
HandleError("Certificate not found.");
}
if (!CertGetEnhancedKeyUsage(pCert,
0,
pKeyUsage,
&cbData))
{
if (GetLastError() == CRYPT_E_NOT_FOUND)
{
printf("%s certificate is for all key usages\n", certName);
HeapFree(GetProcessHeap(), 0, pKeyUsage);
break;
}
else
{
printf("CertGetEnhancedKeyUsage failed with error code : %08X\n",
GetLastError());
HeapFree(GetProcessHeap(), 0, pKeyUsage);
continue;
}
}

if (pKeyUsage->cUsageIdentifier == 0)
{
printf("%s certificate is for all key usages\n", certName);
HeapFree(GetProcessHeap(), 0, pKeyUsage);
break;
}

bFound = FALSE;
for (j = 0; j < pKeyUsage->cUsageIdentifier; j++)
{
if (strcmpi(pKeyUsage->rgpszUsageIdentifier[j],
szOID_PKIX_KP_SERVER_AUTH) == 0)
{
printf("%s certificate is for Server Authentication\n",
certName);
bFound = TRUE;
break;
}
}

HeapFree(GetProcessHeap(), 0, pKeyUsage);
if (bFound)
break;
}

if (pCert == NULL)
HandleError("Certificate not found.");

if (pPrevCert)
{
CertFreeCertificateContext(pPrevCert);
pPrevCert = NULL;
}

/// CASE 2 Get the hash from the certificate
pHash = NULL;
cbData = 0;
CertGetCertificateContextProperty(pCert, CERT_HASH_PROP_ID, NULL, &cbData);
if (cbData == 0)
{
HandleError("CertGetCertificateContextProperty 1 failed");
}

pHash = (LPBYTE)HeapAlloc(GetProcessHeap(), 0, cbData);
if (pHash == NULL)
{
HandleError("HeapAlloc failed");
}
if (!CertGetCertificateContextProperty(pCert, CERT_HASH_PROP_ID, pHash,
&cbData))
{
HandleError("CertGetCertificateContextProperty 2 failed");
}

printf("CERT_HASH_PROP_ID Length is %d\n", cbData);
printf("CERT_HASH_PROP_ID BYTES [", cbData);

for (i = 0; i < cbData; i++)
{
printf("%02X", pHash[i]);
}
printf("]\n");

//--------------------------------------------------------------------
// Clean up and free memory.

if (pEncodedBytes)
HeapFree(GetProcessHeap(), 0, pEncodedBytes);

if (pHash)
HeapFree(GetProcessHeap(), 0, pHash);

if(pCert)
CertFreeCertificateContext(pCert);
if(CertCloseStore(
hStoreHandle,
CERT_CLOSE_STORE_CHECK_FLAG))
{
printf("The store closed and all certificates are freed. \n");
}
else
{
printf("Store closed -- \n"
"not all certificates, CRLs or CTLs were freed");
}
} // End of main

//--------------------------------------------------------------------
// This example uses the function HandleError, a simple error
// handling function, to print an error message to the standard error
// (stderr) file and exit the program.
// For most applications, replace this function with one
// that does more extensive error reporting.

void HandleError(char *s)
{
fprintf(stderr,"An error occurred in running the program. \n");
fprintf(stderr,"%s\n",s);
fprintf(stderr, "Error number %x.\n", GetLastError());
fprintf(stderr, "Program terminating. \n");
exit(1);
} // End of HandleError



Post Reply
You must Sign In to post a response.
Next : Send SMS
Previous : please solve this problem
Return to Discussion Forum
Post New Message
Category: ASP.NET

Related Messages



dotNet Slackers   BizTalk Adaptors    Web Design

silicone halloween masks

Contact Us    Privacy Policy    Terms Of Use