Creating a simple “Contact Us” form

SharePoint is a powerful application for managing and sharing information and documents within companies. Nevertheless, many organisations are still using other platforms or content management systems side-by-side. This does not prevent you from using SharePoint as a central sharing point for any of these. Camelot .NET Connector enables quick integration with other systems, for example Joomla or Umbraco.

This article will show, step-by-step, how to create a simple contact form in ASP.NET. Contact forms are typically used on a public website to provide a way for customers, business partners and others to submit questions or request information. This is a great example of using SharePoint in a creative way to simplify common tasks in any organisation. This example can practically be implemented as is in Umbraco.

Requirements

This example requires that you have a WSS3.0 or MOSS 2007/2010 environment available and Visual Studio 2010 installed on your development computer. You also need to download and install Camelot .NET Connector from http://www.bendsoft.com together with a valid license key. Developer licenses are free for anyone. I assume that you already know how to create and edit lists in SharePoint and familiar with the Visual Studio 2010 IDE.

Preparing SharePoint

The first thing to do is to create a custom SharePoint list in WSS 3.0 or MOSS 2007/2010 for storing incoming contact requests. In this example, we choose to call our new list ContactForm. We will also create a set of new columns to hold the details.

The contact list is defined by the columns Title, Company, Email and Message where Title will be used to store the name of the contact person. Message is created as a multi-line text column and the other holds a single line of text. This is what the empty list default view will looks like.

Creating a user control

Now we will create an ASP.NET web user control, which can then be placed on any ASP.NET web page within out site. In Visual Studio 2010, add a new Web User Control (language C#) to your web site and call it contactcontrol.ascx. Ensure that “Place code in separate file” is checked.

contactcontrol.ascx

Replace the content of the markup file (contactcontrol.ascx) with the following lines. We have added four input fields for name, e-mail address, company and message. The message input allows multiple lines. We have also added required field validation to the name, e-mail and message, leaving company optional. Besides, the e-mail address must be in valid format. Finally, I have added a submit button in the bottom of the form and hooked up the Submit_Click method on the OnClick event.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="contactcontrol.ascx.cs" Inherits="contactcontrol" %>
<asp:Panel ID="controlpanel" runat="server">
    <h2>Contact Us</h2>
    <p>Please use the form below to contact us. We will get back to you as quick as possible!</p>
    <asp:ValidationSummary ID="errors" runat="server" DisplayMode="BulletList" />
    <table>
        <tr>
            <td>Name:</td>
            <td><asp:TextBox ID="name" runat="server"></asp:TextBox> *</td>
        </tr>
        <tr>
            <td>E-mail address:</td>
            <td><asp:TextBox ID="email" runat="server"></asp:TextBox> *</td>
        </tr>
        <tr>
            <td>Company:</td>
            <td><asp:TextBox ID="company" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Message:</td>
            <td><asp:TextBox ID="message" runat="server" TextMode="MultiLine" Rows="10"></asp:TextBox> *</td>
        </tr>
    </table>
    <asp:Button ID="Submit" runat="server" Text="Submit Request" OnClick="Submit_Click" />
    <asp:RequiredFieldValidator ID="name_validator" runat="server" ControlToValidate="name" ErrorMessage="Name is missing" Display="None"></asp:RequiredFieldValidator>
    <asp:RequiredFieldValidator ID="email_validator_1" runat="server" ControlToValidate="email" ErrorMessage="E-mail is missing" Display="None"></asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator ID="email_validator_2" runat="server" ControlToValidate="email" ErrorMessage="Invalid E-mail address" ValidationExpression="^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$" Display="None"></asp:RegularExpressionValidator>
    <asp:RequiredFieldValidator ID="message_validator" runat="server" ControlToValidate="message" ErrorMessage="Message cannot be left empty" Display="None"></asp:RequiredFieldValidator>
</asp:Panel>

contactcontrol.ascx.cs

Open up the associated code file (contactcontrol.ascx.cs) and replace the content with the following code. The CssClass property is a quick way to enable setting the css class of the control. The most important section is the Submit_Click method which handles our submit button’s click event. The method first checks that the page is valid and then prepares and executes an insert query into our SharePoint list. The connection string is stored in the web.config ad named sharepoint_sales. Name this whatever you like and add the corresponding option to your web.config. The following connection string template can be used in most cases. More connection string options are descibed in the connector documentation found on the bendsoft website.

<add name="sharepoint_sales" connectionString="Server=my.sharepointserver.com;Database=customers;User=myuser;Password=mypass;Authentication=Ntlm;TimeOut=60;" />

Using parameters ensures that the data is inserted safely without need for escaping special characters. After inserting the post, the page shows a confirmation message. Note: Exception handling needs to be added before used in production.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Camelot.SharePointConnector.Data;

public partial class contactcontrol : System.Web.UI.UserControl
{
    public string CssClass {get; set;}

    protected void Page_Load(object sender, EventArgs e)
    {
        controlpanel.CssClass = this.CssClass;
    }


    protected void Submit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            using (SharePointConnection connection = new SharePointConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["sharepoint_sales"].ConnectionString)) 
            {
                connection.Open();
                using (SharePointCommand command = new SharePointCommand("INSERT INTO `ContactForm` SET Title = @name, `Email` = @email, `Company` = @company, Message = @message", connection))
                {
                    command.Parameters.Add("@name", this.name.Text);
                    command.Parameters.Add("@email", this.email.Text);
                    command.Parameters.Add("@company", this.company.Text);
                    command.Parameters.Add("@message", this.message.Text);
                    command.ExecuteNonQuery();

                    this.message.Text = "";
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Success", "alert('Your question has been sent to our team. We will handle your enquiry as soon as possible');", true);
                }
            }
        }
    }
}

Creating a sample page

Add a new web page to your project called contactus.aspx and replaced the content with the following markup code. On the top of the page, we register our new contact control and later down we add an instance of this control to the page. We have also added some css styling to the page to improve the visual impression.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="contactus.aspx.cs" Inherits="contactus" %>
<%@ Register TagPrefix="cc" TagName="ContactControl" Src="contactcontrol.ascx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Contact Us</title>
    <style type="text/css">
        body 
        {
            font-family:Trebuchet MS;
            font-size:12px;
        }
        .contactcontrol td
        {
            vertical-align:top;
        }
        .contactcontrol input
        {
            font-family:Trebuchet MS;
            font-size:12px;
        }
        .contactcontrol input[type="text"]
        {
            width:200px;
            border:solid #cccccc 1px;
        }
        .contactcontrol textarea
        {
            width:300px;
            border:solid #cccccc 1px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <cc:ContactControl ID="contactcontrol" runat="server" CssClass="contactcontrol" />   
    </div>
    </form>
</body>
</html>

Testing our page

Now, start your web site and browse to the contactus.aspx page. If everything goes well, you should be seeing the contract form. Don’t forget to add the connection string to your web.config first!

Test your form by adding a new post. You will get a confirmation from the web site that the post has been added.

Return to your SharePoint environment where your should be seeing the new entry in your ContactForm list.

Final word

The Camelot .NET Connector simplifies SharePoint integration. In fact, in many cases, .NET developers do not need to have any previous experience of SharePoint development. By using your general .NET skills and basic understanding of the SQL syntax and other ADO.NET drivers, you will be able to achive quite alot on your own. This is why the connector gives you advantage over you competitors.

If you any questions regarding the connector and how it can help you, please feel free to contact us using our very own contact form, of course powered by SharePoint 2010, at http://www.bendsoft.com/contact-us/.

This entry was posted in SharePoint. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>