Saturday, August 20, 2011

ASP.NET without Visual Studio

Sometimes you just don't need a project. You're writing a report or something really low rent and you just need to get a page out there quickly. Well you're in luck, inline declarations can be used to obviate the need for a project, references, etc.

You can have these standalone in any IIS web directory or you can make them into an app by putting them in a folder, adding a web.config, declaring an app pool in IIS admin, etc.

You can mix HTML and ASP tags as needed, or generate elements in code (as I've done below).

Your first line needs to declare a page and language used:
<%@ Page Language="VB" Debug="true" %>

You can import libraries from the GAC by using Import
<%@ Import Namespace="System.Text" %>

You can import libraries from outside the GAC using Register Assembly and then Import
<%@ Register Assembly="System.DirectoryServices, Version=2.0.50727.3053, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Namespace="System.DirectoryServices" TagPrefix="SD" %>
<%@ Import Namespace="System.DirectoryServices" %>

VB.NET uses a Page_Init function to initialize your web app.
<script runat="server">

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs)
    ' POST takes the usr and pwd fields and authenticates
    If Request.Form.Count > 0 Then
      AuthEntry(Request.Form.Item("usr"), Request.Form.Item("pwd"))
    End If
    ' no parameters will generate a login form
    If Request.QueryString.Count = 0 And Request.Form.Count = 0 Then
    End If
End Sub

' you can generate form elements using code or do more traditional ASP layout below the script tag
Protected Sub GenerateForm()
  Dim Form1 As System.Web.UI.HtmlControls.HtmlForm
  Dim Label1 As System.Web.UI.WebControls.Label
  Dim usr As System.Web.UI.WebControls.TextBox
  Dim pwd As System.Web.UI.WebControls.TextBox
  Dim btn1 As System.Web.UI.WebControls.Button

  Form1 = New HtmlForm()
  Form1.ID = "myForm"

  usr = New TextBox()
  usr.ID = "usr"

  pwd = New TextBox()
  pwd.ID = "pwd"
  pwd.TextMode = TextBoxMode.Password

  btn1 = new Button()
  btn1.Text = "Login"


End Sub

' Here is a function that will validate a user against Active Directory
' You are essentially performing an authenticated search for your own account.
Protected Sub AuthEntry(usr as String, pwd as String)

  Dim path as String = "LDAP://,DC=your,DC=domain,DC=com"
  Dim entry as DirectoryEntry = new DirectoryEntry(path,usr,pwd,AuthenticationTypes.Secure)

    Dim obj as Object = entry.NativeObject
    Dim search as DirectorySearcher = new DirectorySearcher(entry)
    search.Filter = "(SAMAccountName=" + usr + ")"
    Dim result As SearchResultCollection = search.FindAll()
    If result.Count > 0 Then
      ' authenticated
      Exit Sub
    End If
  Catch ex As Exception
    Exit Sub
  End Try

End Sub