Web Design, Programming, Tutorials
Programming
The Repository Pattern
Jan 26th
The repository pattern is a design pattern that creates repositories of data that talk to a data source. These repositories are used to segregate the code that talks to a data source from the rest of your program. For example, your code that communicates to a database connection is stored within a repository class. Communication between your program and the database is all funnelled through the repository class.
In Domain Driven Design, you create data objects that are logical representations of the data stored within a data source; such as a database. These data objects may not mimic the design of a database, but instead be a more logical grouping of properties and methods. The repository pattern can be used to create a repository class for each data object, where that object can then be created, read, updated, or deleted (CRUD) from the data source.
Using the repository pattern with Dependency Injection allows for the repository class to be mocked during testing, where a more controlled and faster repository can be created. Also, if the data source changes to a XML file or another database, the repository class can be replaced.
The Repository pattern is one of the design patterns that I use to build a more maintainable and flexible application.
Vector class for Lotus Script
Jan 25th
The following is a script library written in Lotus Script to allow programmers to use a vector in their Lotus Script code.
Option Declare Option Base 0 Public Class Vector 'Private data members Private vArray As Variant Private vCapacity As Integer Private vSize As Integer Public Sub New() 'Initialize variables Call SetCapacity(0) Call SetSize(0) Call Reserve(10) End Sub Public Sub Delete() Call EraseAll() 'Clear the array Set vArray = Nothing End Sub Private Sub SetCapacity(newCapacity As Integer) vCapacity = newCapacity End Sub Public Function Capacity() As Integer Capacity = vCapacity End Function Private Sub SetSize(newSize As Integer) vSize = newSize End Sub Public Function Size() As Integer Size = vSize End Function Public Function Empty() As Boolean 'Declare variables Dim valid As Boolean 'Get the size If (Size() = 0) Then valid = True Else valid = False End If 'Return if the vector is empty Empty = valid End Function Public Sub Reserve(minCapacity As Integer) 'Declare variables Dim openElements As Integer Dim newCapacity As Integer 'Initialize variables openElements = Capacity() - Size() newCapacity = Capacity() 'Check if there are any open slots remaining If (openElements = 0) Then newCapacity = (Capacity() * 1.5) End If 'Make sure that the minimum capacity is stored If (newCapacity < minCapacity) Then newCapacity = minCapacity End If 'Check if a change to the capacity is being made If (Not(Capacity() = newCapacity)) Then 'Check the size to determine if the array's contents need to be 'saved while redimensioning the array If (Size() = 0) Then 'Nothing stored yet, perform redim Redim vArray(newCapacity) Else 'Keep the array's contents while extending its boundaries Redim Preserve array(newCapacity) End If 'Update the capacity Call SetCapacity(newCapacity) End If End Sub Public Sub PushBack(newItem As Variant) 'Check if the passed item/items is actually an array or a list If ((Not(Isarray(newItem))) And (Not(Islist(newItem)))) Then 'Add the single item Call AddItem(newItem) Else 'Add multiple items Forall item In newItem Call AddItem(item) End Forall End If End Sub Private Sub AddItem(newItem As Variant) 'Declare variables Dim newSize As Integer 'Initialize variables newSize = Size() + 1 'Make sure there is enough capacity in the vector Call Reserve(newSize) 'Insert the item into the vector If (Isobject(newItem)) Then Set vArray(Size()) = newItem Else vArray(Size()) = newItem End If 'Increment the vector size Call SetSize(newSize) End Sub Public Function At(index As Integer) As Variant 'Check the vector's index boundaries If ((index < 0) Or (index => Size())) Then Error 2000, _ "[Vector Class]:(Function: At): Index out of bounds." 'Check if the item is an object If (Isobject(vArray(index))) Then Set At = vArray(index) Else At = vArray(index) End If End Function Public Sub Erase(index As Integer) 'Check if the index is out of bounds If ((index < 0) Or (index => Size())) Then Error 2000, _ "[Vector Class]:(Function: Erase): Index out of bounds." 'Declare variables Dim newArray As Variant Dim x As Integer Dim y As Integer 'Initialize variables y = 0 'Make a new array with the same capacity Redim newArray(Capacity()) 'Loop through each element of the vector For x = 0 To Size() - 1 'Check if the current index is the one to remove If ((x <> index) And (Not(y > Size()))) Then 'Check if the item is an object If (Isobject(vArray(x))) Then Set newArray(y) = vArray(x) Else newArray(y) = vArray(x) End If 'Increment the index counter y = y + 1 End If Next x 'Subtract one from the vector size Call SetSize(Size() - 1) 'Set the new array as the vector vArray = newArray End Sub Public Function BeginIndex() As Integer BeginIndex = 0 End Function Public Function EndIndex() As Integer EndIndex = Size() - 1 End Function Public Sub EraseAll() 'Declare variables Dim x As Integer 'Loop through each element of the array For x = BeginIndex() To EndIndex() 'Delete each element of the arra 'Check if the item is an object If (Isobject(vArray(x))) Then Set vArray(x) = Nothing End If Next 'Reset the size. Call SetSize(0) End Sub End Class
Copy the above code and paste into a script library for the database where you would like to use a vector. Then, you can use the example below to use the vector class.
Use "libVector" Dim vector As New Vector() dim obj As String obj = "hello" 'Load any object into the vector. Call vector.PushBack(obj) Call vector.PushBack(obj) 'Loop through the vector to retrieve objects. For i = vector.BeginIndex() To vector.EndIndex() Print "Item: " & i & " " & vector.At(i) Next
Clearing the Client Version from the Lotus Notes Directory
Jan 20th
With the latest version of Lotus Notes (8.5.1), you can now view the version of your clients by looking in the People -> by Client Version view. One problem with this, however, is that your users will show each client they have logged in as. Over the years, you may accumulate many versions for each user.
During an upgrade, you may wish to see what users are using the previous version of client against the ones who have the new version installed. But first, we’ll need to clean up the directory so we don’t see all this old version history.
To clean up these fields, you need to write an agent that will empty them for each selected person. This will allow you to run the clean up agent on only the users you wish to run it on.
Writing the agent
Open up the pubnames.ntf template file in your Notes Designer. You’ll need to go to Code and double-click on Agents to see the current agents for the template.
We’ll create a new agent and give it a name. Below is the code for the agent. Copy and paste it in the Designer.
Option Public
Option Declare
Sub Initialize()
'Declare.
Dim s As New NotesSession
Dim db As NotesDatabase
Dim dc As NotesDocumentCollection
Dim doc As NotesDocument
'Initialize.
Set db = s.Currentdatabase
Set dc = db.Unprocesseddocuments
Set doc = dc.Getfirstdocument()
While(Not(doc Is Nothing))
If (doc.Form(0) = "Person") Then
Call doc.Removeitem("ClntBld")
Call doc.Removeitem("ClntDate")
Call doc.Removeitem("ClntDgst")
Call doc.Removeitem("ClntMachine")
Call doc.Removeitem("ClntPltfrm")
Call doc.Save(False, False, False)
End If
Set doc = dc.Getnextdocument(doc)
Wend
End Sub
Now, after you refresh your names.nsf file, you can go to the Action menu and find your agent. Running the agent will only process those Person documents that you have selected.
Scheduling A Task In A Web Application On A Windows Server
Jan 19th
When writting web applications, there may be times when you would like to perform some task automatically at the same time or every X number of hours. Web applications only execute their code when a request is made from a client’s browser. Because of this, scheduled tasks within the web application will not work.
There are a few different options:
- Build a separate Windows Service application that can connect to the assemblies your web application uses to execute the scheduled task.
- Build a separate Windows application that communicates with a web service that your web application also uses to perform the scheduled task.
- Use the Windows Scheduler to call the URL of the action to perform the task.
The first option might sound good at first, but creating a separate program that talks to your web application’s library files is a bad idea. Maintenance will become a problem as you change your web application. Since the code is in two places, unit testing will not tell you that the class library you just changed has now broken your scheduled tasks in your windows service.
The second option is slightly better, but you still may have issues with changing your class library.
The third option is the one that I will show you how to configure. We will setup a VBS script that will perform a call to any web address we pass to it. Then, we’ll setup a batch file that calls the VBS script and passes in one or more URLs to execute. And finally, we’ll go through using the Windows Scheduler to create the scheduled task when the batch file should execute.
The primary advantage to this method is that you get to keep all of your code together in your web application. You simply setup an action that performs whatever task you wish to schedule and make sure that action is callable from an anonymous user.
WebRequest.vbs
You may copy the following code and paste into a text file. Then, rename the file to WebRequest.vbs. The script basically takes an argument that is passed into it as the URL. The HTTP object is setup and then the URL is called using a GET request. Then, the returned status is checked to see if the request was successful or not.
url = WScript.Arguments.Item(0)
'WScript.echo url
set WshShell = WScript.CreateObject("WScript.Shell")
set http = CreateObject("Microsoft.XmlHttp")
http.open "GET", url, FALSE
http.send ""
if (http.Status = 200) then
WScript.echo "Request successful."
else
WScript.echo "Error: " & http.Status
end if
set WshShell = nothing
set http = nothing
The Batch File
Calling the WebRequest.vbs file from a batch file is very easy. Simply create a new text file, calling it whatever you’d like, and paste in the following line of text. Rename the file to .BAT when finished.
cscript WebRequest.vbs "http://www.domain.com/controller/action"
Scheduling The Task
From your Windows server, open the Control Panel and then open the Scheduled Tasks item. Next, click on Add Scheduled Task. Choose any application to schedule. This will be changed later on. Configure how often you wish the schedule to run and enter a user name and password to run the schedule as. This users should have access to running the web browser from the server.
After your new scheduled task has been created, open it. In the Run text box, type in the full path to your batch file. Then, in the Start In text box, type in the full path without the batch file name. You can also adjust your scheduled time from within here. Click OK to save the changes and your scheduled task should be ready.
You can test the Windows Scheduler by setting the scheduled time to a minute or two in the future and then waiting for it to execute. If you just wish to test your action, or manually run it, you can simply run the batch file.
MVC and n-layer architecture
Jan 18th
When I write a program, no matter which tool I use, one problem I face is how to design the application. No matter if you use Java, PHP, or Visual Basic; if you design the application badly, you will have problems later when you try to fix bugs or enhance the product to the next version.
The MVC design pattern
MVC stands for Model, View, Controller. This is a very common design pattern used in programming today. When someone uses a MVC application, they make a request to a controller. The controller then talks to the model, which consists of business logic, to perform the action requested. The controller then processes the information from the model and sends it to the appropriate view.
By using the MVC design pattern, you will separate your business logic from your presentation HTML. This makes your application more easily maintainable because a bug can be fixed in the business logic without all that HTML display code getting in the way. Also, when multiple developers are working on a project, the developers who write HTML and CSS can work independently of the core programmers.
N-Layer Architecture
N-Layer, or multi-layer, applications are designed using layers that handle a single responsibility. Many applications use three layers; Presentation, Business Logic, and Data-Access. This is similar to the n-tier architecture, but the primary difference is tiers represent physical hardware, while layers represent software.
In the three-layer approach; the Presentation layer would consist of the user interface, the Business Logic would consist of objects that process Business Rules, and the Data-Access layer would talk directly to the data source. This design usually works well.
Putting them together
One of the things I found a little confusing about MVC at first was what exactly is the model? After much research and testing, I finally found something that makes sense to me.
The diagram above is the general layout that I use when developing a MVC application. Here is a brief description of the various components of the diagram:
- Model – In this diagram, the model would consist of the Services, Repositories, and DatabaseConnection layers along with Domain Objects.
- View - The view is the presentation or design elements of the application; such as HTML or CSS.
- Controller – The controller is the layer that drives the application. It processes requests from the user and sends them to the model and then returns the processed information to the view.
- Services – This layer handles requests from the controller. This is the layer that contains the business rules on how the application should function.
- Repositories - This layer performs CRUD (Create, Read, Update, and Delete) operations on the database.
- DatabaseConnection - This layer is further abstraction between the data source and the repository. It is not required, but I typically use it when I need to work with multiple databases. The DatabaseConnection layer was built to generalize between three different database drivers and use common methods to work with each.
- Data-Access layer- This layer would consist of the Repositories, DatabaseConnection, SQL Data Source and Other Data Sources.
- Other Data Sources – This could include a XML file, other database, or even a web service.
- Domain Objects – This is not necessarily a layer, just a collection of objects used to make it easier to work with the data from the data source. Notice that all of the other layers need to be able to work with these objects. An example of a Domain object might be an Employee class that stores information about an employee and is populated from a data source in the Repository. The Employee object can then be passed from each layer back to the view where it is displayed to the user.
This is just a brief overview of MVC with the n-layer approach.
Installing ASP.NET MVC
Jan 15th
Here are the steps to install into Visual Studio 2008:
- Download ASP.NET MVC 1.0 from Microsoft’s website. Make sure to download the MSI file and the source code if you would like to see how it works.
- Install the AspNetMVC1.msi file.
- Open Visual Studio 2008 and go to:
- File -> New -> Project
- Under Project Types, select Web under either Visual Basic or C#
- Under Templates, select ASP.NET MVC Web Application
- Give your application a name and change its location if you wish
That’s it! Upon creating a new web application, the default MVC application will open.
Note:
ASP.NET MVC should also work using the free development tool from Microsoft, Visual Web Designer 2008.
Why you should use ASP.NET MVC
Jan 14th
If you’re like me, you like to have control over how your websites look and the HTML returned to the browser. ASP.NET MVC gives you that control by letting you keep your HTML separate from the core application code. If you learn to use tools like CSS and JavaScript, you can use them in the exact same way you would if you were working with a static web page. There are no generated IDs or missing/custom HTML attributes. While it does give you some helpers to generate HTML, you do not have to use them if you don’t want to.
ASP.NET MVC is very extensible and flexible. Nearly any component of the framework can be swapped out for your own version, if you so choose to delve into the inner workings.
ASP.NET MVC was built with Unit Testing in mind. If you’re not using Unit Testing, you should definitely start researching how it can improve your code reliability.
So, why should you use ASP.NET MVC?
- Based on the MVC pattern.
- Allows you to use Standards such as XHTML and CSS.
- Separation of concerns allows for more maintainable code.
- Gives you help when you need it and gets out of your way when you want control.
- Unit Testing is built in and easy to do.
- Fully supported by Microsoft.
- You can download the code for the ASP.NET MVC Framework and see how it works.
If you know HTML, CSS, or JavaScript and you are familiar with ASP, then you should definitely look into ASP.NET MVC.
ASP.NET MVC Using Forms Authentication With LDAP
Oct 23rd
If you are using ASP.NET MVC and you want to authenticate your users against Active Directory using LDAP, you need to do a little work to get everything set up. It is pretty easy to authenticate users with Active Directory using the <Authorize()> attribute, but I ran into some problems when I wanted to authorize a user based on a Windows Group.
Here are the steps I took to be able to authenticate active directory users and authorize their use of actions based on being members to user groups.
Web.Config
Find the authentication tag and change it to the following:
<authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" /> </authentication>
The LoginUrl points to the Controller/Action where the login function is.
UserRepository
This is the class object that does the communication with Active Directory via LDAP. The project where this class resides should also add a reference to the System.DirectoryServices DLL.
Imports System.DirectoryServices
Public Class UserRepository
Private _server As String
Public Sub New(ByVal server As String)
_server = server
End Sub
Public Function GetUser(ByVal userName As String) As Data.User
Dim root As DirectoryEntry = New DirectoryEntry("LDAP://" + _server)
Dim search As DirectorySearcher = New DirectorySearcher(root)
search.SearchScope = SearchScope.Subtree
search.Filter = "(sAMAccountName=" + userName.Substring(userName.IndexOf("\") + 1) + ")"
Dim results As SearchResultCollection = search.FindAll()
Return _GetUser(results(0).Path)
End Function
Public Function GetUserByFullName(ByVal fullName As String) As Data.User
Dim root As DirectoryEntry = New DirectoryEntry("LDAP://" + _server)
Dim search As DirectorySearcher = New DirectorySearcher(root)
search.SearchScope = SearchScope.Subtree
search.Filter = "(displayName=" + fullName + ")"
Dim results As SearchResultCollection = search.FindAll()
Return _GetUser(results(0).Path)
End Function
Public Function GetMembers(ByVal groupPath As String) As IQueryable(Of Data.User)
Dim root As DirectoryEntry = New DirectoryEntry("LDAP://" + _server)
Dim search As DirectorySearcher = New DirectorySearcher(root)
Dim members As List(Of Data.User) = New List(Of Data.User)()
search.SearchScope = SearchScope.Subtree
search.Filter = "(memberOf=" + groupPath + ")"
Dim results As SearchResultCollection = search.FindAll()
For Each result As SearchResult In results
members.Add(_GetUser(result.Path))
Next
root.Close()
Return members.AsQueryable
End Function
Public Function Authenticate(ByVal userName As String, ByVal password As String) As Data.User
Dim root As DirectoryEntry = New DirectoryEntry("LDAP://" + _server, userName, password)
Dim search As DirectorySearcher = New DirectorySearcher(root)
Dim user As User = Nothing
search.SearchScope = SearchScope.Subtree
search.Filter = "(sAMAccountName=" + userName + ")"
Dim results As SearchResultCollection = search.FindAll()
If (Not (results Is Nothing)) Then
user = _GetUser(results(0).Path)
End If
Return user
End Function
Private Function _GetUser(ByVal userPath As String) As Data.User
Dim entry As DirectoryEntry = New DirectoryEntry(userPath)
Dim user As Data.User = New Data.User()
user.UserName = entry.Properties("sAMAccountName").Value
user.FirstName = entry.Properties("givenname").Value
user.LastName = entry.Properties("sn").Value
user.Email = entry.Properties("mail").Value
For Each group In entry.Properties("memberOf")
user.Groups.Add(_GetGroup(group))
Next
entry.Close()
Return user
End Function
Private Function _GetGroup(ByVal path As String) As String
Dim value As String = ""
Dim index1 As Integer = path.IndexOf("=", 1)
Dim index2 As Integer = path.IndexOf(",", 1)
If (Not (index1 = -1)) Then
value = path.Substring((index1 + 1), (index2 - index1) - 1)
End If
Return value
End Function
End Class
User
This class hold the user information that we want to work with from Active Directory. Here I am storing the username, first and last names, email address, and the list of groups the user is a member of.
This class is in my Data project and that is why you will see Data.User in the UserRepository. If you want everything to be in one project, you could create the Data namespace around the User class. I did run into problems with MVC getting confused between my User class and a built in one if I did not specify the namespace. You could also simply rename the User class to something else.
Public Class User
Private _userName As String
Private _firstName As String
Private _lastName As String
Private _email As String
Private _groups As List(Of String)
Public Property UserName() As String
Get
Return _userName
End Get
Set(ByVal value As String)
_userName = value
End Set
End Property
Public Property FirstName() As String
Get
Return _firstName
End Get
Set(ByVal value As String)
_firstName = value
End Set
End Property
Public Property LastName() As String
Get
Return _lastName
End Get
Set(ByVal value As String)
_lastName = value
End Set
End Property
Public Property Email() As String
Get
Return _email
End Get
Set(ByVal value As String)
_email = value
End Set
End Property
Public Property Groups() As List(Of String)
Get
Return _groups
End Get
Set(ByVal value As List(Of String))
_groups = value
End Set
End Property
Public Sub New()
Me.UserName = ""
Me.FirstName = ""
Me.LastName = ""
Me.Email = ""
Me.Groups = New List(Of String)()
End Sub
Public Function GetFullName() As String
Dim s As System.Text.StringBuilder = New System.Text.StringBuilder()
If (Not (Me.FirstName = "")) Then
s.Append(Me.FirstName)
s.Append(" ")
End If
s.Append(Me.LastName)
Return s.ToString()
End Function
Public Function SerializeGroups() As String
Dim text As String = ""
For Each item In Groups
If (text = "") Then
text = item
Else
text = text + "|" + item
End If
Next
Return text
End Function
End Class
AccountController
Next is the controller that handles signing in and out of the application. I’ve simplified this controller code for the sake of simplicity. Under normal circumstances, I would have the controller communicate to a service class that then interacts with the repository. The service class could do validation on the login form before attempting to authenticate empty user and password strings.
Imports System.Globalization
Imports System.Security.Principal
Imports S3.Data
<HandleError()> _
Public Class AccountController
Inherits System.Web.Mvc.Controller
'data members.
Private _userRepository as UserRepository
Private _formsAuthentication As IFormsAuthentication
Public Sub New()
_userRepository = New UserRepository(ConfigurationManager.AppSettings("LDAPServer")
_formsAuthentication = New FormsAuthentication()
End Sub
'GET: /Account/LogOn
Public Function LogOn() As ActionResult
Return View("LogOn")
End Function
'POST: /Account/LogOn
<AcceptVerbs(HttpVerbs.Post)> _
Public Function LogOn( _
ByVal userName As String, _
ByVal password As String, _
ByVal rememberMe As Boolean, _
ByVal returnUrl As String) As ActionResult
Dim result As ActionResult = View("LogOn")
Dim user As User = _userRepository.Authenticate(userName, password)
If (Not (user Is Nothing)) Then
_formsAuthentication.SignIn(user, rememberMe)
If (returnUrl Is Nothing) Then
result = RedirectToAction("Index", "Home")
Else
result = Redirect(returnUrl)
End If
End If
Return result
End Function
Public Function LogOff() As ActionResult
_formsAuthentication.SignOut()
Return RedirectToAction("Index", "Home")
End Function
End Class
FormsAuthentication
The next class is the FormsAuthentication class. The main reason that I made this code a class of its own is for the sake of unit testing my project. During unit testing, the commands that deal with writing and clearing the cookie would error out. To get around this, I created an empty FormsAuthenticationTest class that does nothing for the SignIn and SignOut methods. Note: The example code does not show the interfaces. Check out the repository pattern and factory pattern to see how to setup services and repositories for unit testing.
After a user has been authenticated by the UserRepository, the controller passes the returned user into the SignIn method of the FormsAuthentication. This method then stores the user’s full name and serialized groups in a cookie. The list of groups is serialized by creating a string with each group name separated by a “|” character. This serialization takes place in the User object.
Imports System.Web.Security
Public Class FormsAuthentication
Public Sub SignIn(ByVal user As Data.User, ByVal createPersistentCookie As Boolean)
Dim authTicket As System.Web.Security.FormsAuthenticationTicket = _
New System.Web.Security.FormsAuthenticationTicket( _
1, _
user.GetFullName(), _
Now, _
Now.AddMinutes(60), _
createPersistentCookie, _
user.SerializeGroups())
Dim encryptedTicket As String = System.Web.Security.FormsAuthentication.Encrypt(authTicket)
Dim authCookie As HttpCookie = New HttpCookie( _
System.Web.Security.FormsAuthentication.FormsCookieName, _
encryptedTicket)
If (createPersistentCookie) Then
authCookie.Expires = authTicket.Expiration
End If
HttpContext.Current.Response.Cookies.Add(authCookie)
End Sub
Public Sub SignOut()
System.Web.Security.FormsAuthentication.SignOut()
End Sub
End Class
Global.asax
With the previous code, you should be able to use Forms Authentication to log into your application and authenticate a user against the Active Directory via LDAP. The <Authorize()> attribute will allow you to secure your controller or actions. There’s just one problem. Now, if you want to use <Authorize(Roles:=”GroupName”), your user does not get authorization to the action or controller.
There’s just one change left that we need to make. ASP MVC makes the current logged in user available by accessing the Context.User. When you log into the application MVC is setting the user as authenticated, but no roles or groups have been added to that user. We need to modify the Global.asax file and use the AuthenticationRequest event.
The following code will fire each time an authentication request is triggered. The code will check if the authentication cookie exists and if it does, reads the user’s name and groups from it and stores them in the Context.User so MVC can access the groups.
Private Sub MvcApplication_AuthenticateRequest(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.AuthenticateRequest
Dim cookieName As String = System.Web.Security.FormsAuthentication.FormsCookieName
Dim authCookie As HttpCookie = Context.Request.Cookies(cookieName)
If (Not (authCookie Is Nothing)) Then
Dim authTicket As System.Web.Security.FormsAuthenticationTicket = Nothing
Try
authTicket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value)
If (Not (authTicket Is Nothing)) Then
Dim groups As String() = authTicket.UserData.Split(New Char() {"|"})
Dim id As System.Security.Principal.GenericIdentity = _
New System.Security.Principal.GenericIdentity(authTicket.Name, "LdapAuthentication")
Dim principal As System.Security.Principal.GenericPrincipal = _
New System.Security.Principal.GenericPrincipal(id, groups)
Context.User = principal
End If
Catch ex As Exception
'Do nothing.
End Try
End If
End Sub
And that should be all you need to use FormsAuthentication with LDAP and group authorization.
ASP.NET MVC Full URL From A Controller
Oct 16th
In working with ASP.NET MVC, I came across the need to send an email with the URL of a document that is to be approved. There are helper functions accessible from the View to build an ActionLink or get the URL of an action, but I had problems finding how to build this URL from within a controller. Here is the simple code that I finally pieced together to do what I wanted:
Dim link As String = HttpContext.Request.Url.Scheme + _
"://" + HttpContext.Request.Url.Authority + _
Url.Action("ActionName", "ControllerName", New With {.id = idOfDocument})
HttpContext.Request.Url.Scheme returns “http” or “https”, which ever one you’re using.
HttpContext.Request.Url.Authority returns the Base Url of your application.
And, the Url.Action method creates the Url to the Controller, Action, and ID of the document that is being sent out for approval.
SOLID Programming Principles
Sep 4th
The SOLID Principles of programming are a good set of rules to follow when you are designing and developing an object oriented application.
S
Single Responsiblity Principle – A class should do one thing and do it well. If you can think of more than one reason to change a class, then it has more than one responsibility.
O
Open / Closed Principle – A class should be open for extension but closed for modification. Classes should be designed so they can be inherited from without having to modify them.
L
Liskov Substitution Principle – Derived classes must be substitutable for their base class. When a class method accepts an object, the method should be able to accept children of that object without knowing anything about the children.
I
Interface Segregation Principle – Interfaces should be fine grained and only provide for your needs. When building your interfaces, you should not add more functionality than what you need at the time.
D
Dependency Inversion Principle – High level modules should not depend on low level modules, but instead both should depend on abstractions. Interfaces should be used as placeholders and factory classes should be used to instantiate objects. This causes loose coupling between classes.
