Wednesday, June 11, 2008

How to display almost all properties for all IIS Virtual Web Servers

Thanks to blog.crowe.co.nz/archive/2006/06/01/644.aspx:

using System;
using System.DirectoryServices;
namespace IISSample
{
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
const string WebServerSchema = "IIsWebServer"; // Case Sensitive
string ServerName = "LocalHost";
DirectoryEntry W3SVC = new DirectoryEntry("IIS://" + ServerName + "/w3svc");
foreach (DirectoryEntry Site in W3SVC.Children)
{
if (Site.SchemaClassName == WebServerSchema)
{
Console.WriteLine("WebSite Instance ID : " +Site.Name);
foreach (string PropertyName in Site.Properties.PropertyNames)
{
Console.WriteLine(PropertyName);
PropertyValueCollection pvc = Site.Properties[PropertyName];
foreach(object Value in pvc)
Console.WriteLine(" " + Value.ToString());
}
}
Console.WriteLine("".PadRight(80, '-'));
}
}
}
}

Tuesday, June 10, 2008

Impersonating a user programmatically in C# code

The credit for this code goes to http://justgeeks.blogspot.com/2007/09/impersonating-user-programmatically-in_06.html
Here is how to call it....

public void SampleCallingMethod(Object s, EventArgs e)
{
if(ImpersonateUser("username", "domain", "password"))
{
//Insert your code that runs under the security context of a specific user here.
doSomethingHere();
UnImpersonation();
}
else
{
//Your impersonation failed. Therefore, include a fail-safe mechanism here.
}
}

Here is the source code....


using System;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;

namespace AuthenticationMapper
{
///
/// Use this class to run a section of code as a different user.
/// Most of this code was copied from: http://support.microsoft.com/kb/306158
/// Modifications by: Brent Vermilion 9/5/2007
///
public class Impersonation
{

WindowsImpersonationContext impersonationContext;

#region WIN32 definitions


public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

#endregion

public Impersonation()
{

}
#region SampleUsage
public void SampleCallingMethod(Object s, EventArgs e)
{
if(ImpersonateUser("username", "domain", "password"))
{
//Insert your code that runs under the security context of a specific user here.
UnImpersonation();
}
else
{
//Your impersonation failed. Therefore, include a fail-safe mechanism here.
}
}

#endregion

public bool ImpersonateUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if(RevertToSelf())
{
if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if(DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if(token!= IntPtr.Zero)
CloseHandle(token);
if(tokenDuplicate!=IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}

public void UnImpersonation()
{
impersonationContext.Undo();
}

}
}

Tuesday, June 3, 2008

Programmatically add an IP address to IIS Blocked IP List

Thanks to http://netcode.ru/dotnet/?lang=&katID=30&skatID=275&artID=7590.

using System;
using System.IO;
using System.Collections;
using System.DirectoryServices;
using System.Reflection;


namespace soccerwrek
{
class IISWMI
{

[STAThread]
static void Main(string[] args)
{
try
{
// retrieve the directory entry for the root of the IIS server

System.DirectoryServices.DirectoryEntry IIS =
new System.DirectoryServices.DirectoryEntry(
"IIS://localhost/w3svc/1/root");

// retrieve the list of currently denied IPs

Console.WriteLine(
"Retrieving the list of currently denied IPs.");

// get the IPSecurity property

Type typ = IIS.Properties["IPSecurity"][0].GetType();
object IPSecurity = IIS.Properties["IPSecurity"][0];

// retrieve the IPDeny list from the IPSecurity object
Array origIPDenyList = (Array) typ.InvokeMember("IPDeny",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty,
null, IPSecurity, null);

// display what was being denied
foreach(string s in origIPDenyList)
Console.WriteLine("Before: " + s);

// check GrantByDefault. This has to be set to true,
// or what we are doing will not work.
bool bGrantByDefault = (bool) typ.InvokeMember("GrantByDefault",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty,
null, IPSecurity, null);

Console.WriteLine("GrantByDefault = " + bGrantByDefault);
if(!bGrantByDefault)
{
typ.InvokeMember("GrantByDefault",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty,
null, IPSecurity, new object[] {true});
}

// update the list of denied IPs. This is a
// complete replace. If you want to maintain what
// was already being denied, you need to make sure
// those IPs are in here as well. This area
// will be where you will most likely modify to
// your needs as this is just an example.
Console.WriteLine("Updating the list of denied IPs.");
object[] newIPDenyList = new object[4];
newIPDenyList[0] = "192.168.1.1, 255.255.255.255";
newIPDenyList[1] = "192.168.1.2, 255.255.255.255";
newIPDenyList[2] = "192.168.1.3, 255.255.255.255";
newIPDenyList[3] = "192.168.1.4, 255.255.255.255";
Console.WriteLine("Calling SetProperty");

// add the updated list back to the IPSecurity object
typ.InvokeMember("IPDeny",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty,
null, IPSecurity, new object[] {newIPDenyList});

IIS.Properties["IPSecurity"][0] = IPSecurity;
Console.WriteLine("Commiting the changes.");

// commit the changes
IIS.CommitChanges();
IIS.RefreshCache();

// check to see if the update took
Console.WriteLine("Checking to see if the update took.");
IPSecurity = IIS.Properties["IPSecurity"][0];
Array y = (Array) typ.InvokeMember("IPDeny",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty,
null, IPSecurity, null);
foreach(string s in y)
Console.WriteLine("After: " + s);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.ToString());
}
}
}
}

ASP.NET - Disable the Submit Button on Form Submit Event

URL: http://www.codeproject.com/KB/aspnet/DisableSubmitButton.aspx

Button1.Attributes.Add("onclick","javascript:" +
Button1.ClientID + ".disabled=true;" +
this.GetPostBackEventReference(Button1));

Monday, June 2, 2008

Regular expression to evaluate text for SQL statements

http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_21946011.html

string sql = ReadTextFromFile("class.cs");

Match m = Regex.Match(sql,
@"([Ss][Ee][Ll][Ee][Cc][Tt].+[Ff][Rr][Oo][Mm] +.+ +([Ww][Hh][Ee][Rr][Ee])?.+;)|([Dd][Ee][Ll][Ee][Tt][Ee](.+[Ff][Rr][Oo][Mm])? +.+;)|([Ii][Nn][Ss][Ee][Rr][Tt](.+[Ii][Nn][Tt][Oo])? +.+;)|([Uu][Pp][Dd][Aa][Tt][Ee] +.+ +[Ww][Hh][Ee][Rr][Ee].+;)");