Archive for January, 2009

Backup and Restore Strategies in MOSS 2007

SharePoint is an incredible platform. It is all about a good return on investment for your clients. It lets you put together and deliver very compelling solutions with ease. It is thus not hard to imagine why a lot of clients get addicted to this good return on investment and misinterpret it as “Hey, it’s cheap!” and completely ignore long term planning of what they are addicted to.

They might ignore, but you shouldn’t, and lucky for you there are well defined mechanisms to perform backups and restore of your SharePoint environments. In this article, I will talk about the various standard mechanisms available to you as a SharePoint developer or administrator to perform reliable backups of your environment.

Backup using Central Administration

This is probably the simplest and most straightforward mechanism of performing backups and restores of your SharePoint installation. Under Central Administration à Operations, you would see an entire section for backup and restore as shown below:

Using this interface is quite straightforward, for instance, to perform a backup, click the top link titled “Perform a backup” and you are presented with a user interface similar to as shown below.

Over here, you would simply check-mark the portions of the farm that you intend to backup, and click on the “Continue to Backup Options” button. In step #2, you are presented with the following screen:

As you can see, this UI will let you specify a full or a differential backup, and all you need to do is supply a network location where the farm account has sufficient read/write writes, and your entire farm is easily backed up as a single file. You even get an estimate of what the backed up file size would be. This approach is dead simple, but the obvious problem here is that there is no straightforward way to automate this.

Backup using stsadm

I love GUIs. GUIs get me started on the basic tasks I need to accomplish to keep myself out of trouble. For instance, when I was learning SharePoint, I did realize that backup is an important aspect, and the dead straight UI made my learning curve a lot easier. But soon enough I got bored of performing all those clicks on a daily basis, so I wanted to script the backup process. As it turns out, stsadm.exe will allow me to backup individual sites and site collections very easily.

In order to backup a site collection, you can use the following command:

stsadm –o backup –url <site collection url> -filename <filename to store backup>

Similarly, to restore a backed up file to a site collection, you may use the following command:

stsadm –o restore –url <site collection url> -filename <filename that has backup>

Similarly, to backup a single site, you may use the following command:

stsadm –o export –url <site url> -filename <filename to store backup>

In order to restore a single site at any URl, you may use the following command:

stsadm –o import –url <site url> filename <filename that has backup>

Seems quite straightforward, but there is more to it than meets the eye. For starters, backing up individual sites, isn’t exactly backing up a site. It queries the site using the object model and stores everything the site had that was exposed using the front end UI, into the given file. By default, you might miss older versions of files in a document library that has versioning turned on. You can however specify command line parameters to these commands to influence further control on how older versions are backed up. Also, this approach is quite arduous for a farm with a number of sites. Most of all, stsadm can error out at times, and the error can show up on command line, or even worse, the command line may tell you that it worked, but an error may show up in a log file somewhere. So even though this approach is scriptable, making it 100% bullet proof is still somewhat of a problem.

Backup using database backups

This is probably the approach you will end up using most often. SharePoint stores all its data in SQL Server. Also, a site, or site collection, is nothing but data. Thus it is reasonable to assume that this data, can be easily backed up and restored using standard SQL Server mechanisms.

SharePoint stores its data in content databases. A single website can have a number of content databases, and a content database can contain one or more site collections. In other words, you cannot scope a content database to a single site or single list level.

You can view all the content databases associated with a given web application under central administration à Application Management à SharePoint Web Application Managementà Content Databases. This can be seen as below:

From this screen, you can add or remove content databases to a given web site. When you add a content database, you have the facility of specifying a database server and a content database name. If the database already exists on the server, it will be used as is. If in case the database does not exist on the server, it will be created for you by the farm account.

You can use this behavior to your advantage to backup restore web sites. In order to backup a web site, you simply backup all the content databases associated with the web application. In order to restore a website, you restore the content databases, and perform the extra step of specifying new site collection administrators in the new environment.

This is a fairly robust mechanism of backing up and restoring your SharePoint environment and I suspect that in any serious installation, this is what you will end up using the most anyway. This by far, however is not enough. Depending upon the specific needs of your SharePoint environment, also want to invest in the following:

  1. Backup the entire 12 hive (c:\program files\common files\microsoft shared\web server extensions\12). This is because, frequently you will deploy code to your SharePoint farm, and you will need to restore the supporting physical files for the site to work properly.
  2. You need to keep monitoring the size of your content databases. If you start hitting the 50GB mark, think of splitting them up, so the backups are done overnight before users start hitting the database in the morning.
  3. Backup the entire INETPUB directory.

4. Always maintain a path to restore the current state of the production environment as various releases are pushed into production. This can be achieved by following the below recommendations:

a. Always use a scripted deployment process with clear instructions for deploying code to production. Give special attention to ensuring releases capable of taking your SharePoint installation from one version to another. With various releases, your scripts and instructions should be capable of taking a fresh SharePoint installation to the current production state.

b. Always deploy custom code as solutions, not fragile xcopy scripts.

c. Backup source control databases, and establish a strong version control policy for all code that goes into production.

d. Document all customizations and administration done under central administration for every release.

e. Follow standard disaster recovery best practices, such as regular and verified backups, off-site storage etc.

f. Backup Shared Service providers and Central Administration using stsadm after every significant configuration change or production release.

Backing up shared service providers

You can backup and restore an SSP in a mechanism similar to restoring any other SharePoint website. You must however perform the additional step of associating the SSP with the appropriate web applications after such a restore has been performed. This may be achieved using the following steps.

  1. Under central administration, click on the “Shared Services Administration” on the left side of the page.
  2. Once on the “Manage this farms shared services” page, click on “Restore SSP”.
  3. Now assuming that you have already restored the SSP on a site, complete the required fields on the page shown. Just make sure that you specify the restored web application and database that the SSP site has already been restored to.

Backing up search

Search is probably the weirdest portion to backup on a SharePoint installation. First of all, given the additional complexity that backing up search requires, it might be a good idea to go with rebuilding the indexes for small or even medium sized farms. However, if your search database is huge, and your farm is quite big, and you need search to be online shortly after a disaster, you will need to look into an appropriate strategy for backing up search.

The reason backing up search is different than other portions of SharePoint, is because of how search works. Search data is stored in two locations, the search database, and the index files on the disk. You need both in order to be able to successfully serve search queries. Not only both, but you need both of them backed up concurrently for the restored versions to work together. In other words, if the search index was backed up 5 minutes after the search database, the index entries created in the additional 5 minutes will cause inconsistent results in the restored search.

In order to ensure this consistency, you should backup search using SharePoint 2007’s backup tool, or a third party product.


Backups are terribly important, do not ignore them. This article introduced you to various aspects of backing up your SharePoint farm. As you can see, you have a gamut of choices to pick from, and depending upon your environment you may want to pick the right combination of these choices that fits your needs the best.


No Comments

Check what port an application is using

There are a couple of applications that may fail to start and complaint because its port is being used by a different application. This is a quick and dirty way of knowing which application is responsible for tying up a port on a Windows box.

Open up a command prompt:

  1. Start | Run | type cmd | Enter
  2. Type netstat -aon | findstr “[port number]“
  3. Take note of the numbers on the last line. This is the PID or Process ID.
  4. Type tasklist | findstr “[PID]“ and this will return the application corresponding to that PID.
  5. Once PID is determined, you can now kill it in Task Manager or kill it typing tskill at the command prompt.


For example:

  1. I type netstat -aon | findstr “8080″ at command prompt (I’m on a proxy by the way)
  2. I see that the PID is 3624
  3. I type tasklist | findstr “3624″ to find what PID 3624 is and it points to msnmsgr.exe which is MSN/Live Messenger.
  4. I can now kill MSN Messenger from Task Manager or type tskill 3624

No Comments

a nice day

今日天氣好好啊 , 不過好凍… 8度only?

接堂妹放學琴 , 嚇親佢…

跟住去食盅頭飯, 2個點心, 0茶 , good~~~

慢慢行去海濵公園… 中間去左咭之島…

間esprit 都ok 大呀 , 不過D款差咁DD…

跟住海濱公園 , 影相 , 好靚~~

仲小睡片刻 , 雖然係一陣間 , 不過好舒服啊



Error Logging using ASP.NET 2.0

Error Logging using ASP.NET 2.0
This article has been republished with a few minor changes.
Errors and failures may occur during development and operation of a website. ASP.NET 2.0 provides tracing, instrumentation and error handling mechanisms to detect and fix issues in an application.
In this article, we will adopt a simple mechanism to log errors and exceptions in our website. We will be using a mechanism where the user will be redirected to a separate page whenever an error is encountered in the application. Simultaneously, the error will get logged in a text file on the server. The error file will be created on a daily basis, whenever the error is encountered. Having said that, let us now see some code.
Step 1: Start by creating an Error folder where all errors will be logged. Right click the website > New Folder. Rename the folder to “Error”. Also add a web.config file, if one does not already exist in your site. Right click the website > Add New Item > Web.config.
Step 2: Now we will create the error handler code. To do so, right click your website > Add New Item > select Class. Rename the class to ‘ErrHandler.cs’ and click on ‘Add’. When you do so, you will be prompted with a message to place the class in ‘App_Code’ folder. Accept the message to place the class in the ‘App_Code’ folder.
Step 3: Now let us add functionality to the ErrHandler class. This class will accept the error message and write the message in a text file. One text file will be created for each day. If the text file already exists, the message will be appended to the text file. If not, a new text file will be created based on today’s date and error message will be written in it.
The code will look similar to the following:
/// Handles error by accepting the error message
/// Displays the page on which the error occured
public static void WriteError(string errorMessage)
string path = “~/Error/” + DateTime.Today.ToString(“dd-mm-yy”) + “.txt”;
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
w.WriteLine(“\r\nLog Entry : “);
w.WriteLine(“{0}”, DateTime.Now.ToString(CultureInfo.InvariantCulture));
string err = “Error in: “ + System.Web.HttpContext.Current.Request.Url.ToString() +
“. Error Message:” + errorMessage;
catch (Exception ex)
”’ Handles error by accepting the error message
”’ Displays the page on which the error occured
Public Shared Sub WriteError(ByVal errorMessage As String)
Dim path As String = “~/Error/” & DateTime.Today.ToString(“dd-mm-yy”) & “.txt”
If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
End If
Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
w.WriteLine(Constants.vbCrLf & “Log Entry : “)
w.WriteLine(“{0}”, DateTime.Now.ToString(CultureInfo.InvariantCulture))
Dim err As String = “Error in: “ & System.Web.HttpContext.Current.Request.Url.ToString() & “. Error Message:” & errorMessage
End Using
Catch ex As Exception
End Try
End Sub
That was our ErrHandler class. We will now see how to use this Error Handler class and handle errors at the page level as well as at the application level.
Handling errors at Page Level
In the Default.aspx, drag and drop a button from the toolbox. Rename this button to btnError and set the Text as ‘Throw Handled Exception’. Here we will throw an exception. Since we have a catch block defined, the exception will be caught and the error will be logged in the Error folder. Since a text file with today’s date, does not exists, a new text file will be created by the code.
The button click handler will look similar to the following:
protected void btnHandled_Click(object sender, EventArgs e)
throw new Exception(“Sample Exception”);
catch (Exception ex)
// Log the error to a text file in the Error folder
Protected Sub btnHandled_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHandled.Click
Throw New Exception()
Catch ex As Exception
‘ Log the error to a text file in the Error folder
End Try
End Sub
Now with the code in place, run the application and click on the button. Since we have handled the error and logged the exception in our code, you will not notice anything when the button is clicked. However, close the application and refresh the Error folder. You will see a new text file created with today’s date. The exception has been logged successfully as shown below. The date and time will differ on your machine.
Log Entry :
01/11/2008 23:33:46
Error in: http://localhost:51087/ErrorHandling/Default.aspx. Error Message:Sample Exception
Redirecting users on unhandled errors
Let us see how to catch unhandled errors and redirect the user to a different page, whenever such an unhandled error occurs at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:
void Application_Error(object sender, EventArgs e)
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = “Error in: “ + Request.Url.ToString() +
“. Error Message:” + objErr.Message.ToString();
// Log the error
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
‘ Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = “Error in: “ & Request.Url.ToString() & “. Error Message:” & objErr.Message.ToString()
‘ Log the error
End Sub
We capture the error using the Server.GetLastError(). Now to redirect users to a different page whenever an unhandled error occurs, open your web.config file and locate the <customErrors> tag and uncomment it. After removing the comment, the tag will look similar to the following code:
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace. –>
<errorstatusCode=403redirect=NoAccess.htm />
<errorstatusCode=404redirect=FileNotFound.htm />
Now change:
defaultRedirect=GenericErrorPage.htm” to defaultRedirect=ErrorPage.aspx
The modified code will now look like this:
<errorstatusCode=403redirect=NoAccess.htm />
<errorstatusCode=404redirect=FileNotFound.htm />
This configuration will now redirect the user to an Error page when an error occurs. Let us create this error page and display some message to the user.
Right Click Project > Add New Item> Create a new ErrorPage.aspx page in the application and display a sample message on the page informing the user that an error has occurred.
To test our functionality, go back to Default.aspx, add another button and rename it to btnUnhandled and set its Text property to ‘Throw Unhandled Exception’. Here instead of throwing the exception as we did for ‘btn_Error’, we will introduce a ‘Divide By Zero’ exception and not handle it. Observe that there is no try catch block as shown below. So when the error occurs, the user will be redirected to the ‘ErrorPage.aspx’ as a result of the changes made in our web.config file.
protected void btnHandled_Click(object sender, EventArgs e)
throw new Exception(“Sample Exception”);
catch (Exception ex)
// Log the error to a text file in the Error folder
Protected Sub btnUnhandled_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUnhandled.Click
Dim i As Integer = 1
Dim j As Integer = 0
Response.Write(i \ j)
End Sub
Run the application and click on the ‘Throw Unhandled Exception’ button. You will observe that the user will be automatically redirected to the Error Page and the error will be logged in the Error folder. Well that’s it.
In this article, we saw how to implement a simple error logging system in our application. Logging errors can be very useful and helps us detect errors during development and operation of a website. ASP.NET also provides some advanced options titled under ‘Health Monitoring’ where the errors can be stored in Sql Server or even emailed to the administrator based on the criticality of it.

No Comments

70-536 Microsoft .Net Framework 2.0 Application Development Foundation Pro Developer


No Comments