Skip to main content

How to Create The Contact/feedback Web part in SharePoint 2010


Contact Feedback Webpart in Sharepoint 2010


This article will show, step-by-step, how to create simple visual web part that implements a contact feedback form. A contact feedback form is typically used on a public website to provide a way for customers, business partners, and others outside the company to submit questions or request information by filling out fields on a web page and clicking a Submit button. This web part will collect the user’s name, email address, and message, and send the information to an email address when the user clicks Submit.

The web part created in this article will use Sharepoint 2010. To create the web part, we will be using Visual Studio 2010 installed on Windows Server 2008.

Design the Webpart:

Add the following code in your webpart(Design Mode)

<style type="text/css">
    span.required
    {
        color: #FF0000;
        font-size: 12px;
        white-space: nowrap;
        padding-right: 3px;
    }
   
    .data
    {
        color: #000000;
        font-family: Arial,Helvetica,sans-serif;
        font-size: 12px;
        font-weight:bold;
        padding-left: 3px;
        line-height: 20px;
        vertical-align: top;
        text-align: left;
    }
    .error
    {
        color: #000000;
        font-family: Arial,Helvetica,sans-serif;
        font-size: 12px;
    }
    .test
    {
        color: #000000;
        font-family: Arial,Helvetica,sans-serif;
        font-size: 12px;
        padding-right: 10px;
    }
    table.ms-toolbar
    {
        background-color: #EBF3FF;
        background-repeat: repeat;
        border: 1px solid #BFBFBF;
    }
   
   
    .ms-formbody
    {
        background: none repeat scroll 0 0 #EBF3FF;
        border-top: 1px solid #D8D8D8;
        font-family: verdana;
        font-size: 0.7em;
        padding: 3px 6px 4px;
        vertical-align: top;
    }
   
    .ms-formbody
    {
        background: none repeat scroll 0 0 #EFEFEF;
    }
</style>
<div style="text-align: left;">
    <table cellpadding="2" cellspacing="0" border="0" width="100%">
        <tr align="right">
            <td colspan="2">
                <table class="ms-toolbar" align="center" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td>
                            <span class="required">* </span><span class="test">indicates a required field</span>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td   width="100%">
                <table align="center" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td class="data">
                            <%--<asp:Label ID="lblname" Text="Your Name" runat="server"></asp:Label>--%>
                            Your Name <span class="required">*</span>
                        </td>
                        <td class="ms-formbody">
                            <div style="width: 100%">
                                <asp:TextBox ID="txtName" runat="server" Width="450px"></asp:TextBox></div>
                            <asp:RequiredFieldValidator ID="rfvYourName" runat="server" ControlToValidate="txtName"
                                ErrorMessage="Please Enter Your Name." SetFocusOnError="True" ToolTip="Please Enter Your Name."
                                Display="Dynamic"></asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td class="data">
                            Your E-mail <span class="required">*</span>
                            <%--<asp:Label ID="Label1" Text="Your E-mail" runat="server"></asp:Label>--%>
                        </td>
                        <td class="ms-formbody">
                            <div style="width: 100%">
                                <asp:TextBox ID="txtEmail" runat="server" Width="450px"></asp:TextBox></div>
                            <asp:RequiredFieldValidator ID="rfvtxtEmail" runat="server" ControlToValidate="txtEmail"
                                ErrorMessage="Please Enter Your Email." SetFocusOnError="True" ToolTip="Please Enter Your Email."
                                Display="Dynamic"></asp:RequiredFieldValidator>
                            <asp:RegularExpressionValidator ID="revtxtEmail" runat="server" ErrorMessage="You must sepcify a valid email id"
                                ControlToValidate="txtEmail" Display="Dynamic" SetFocusOnError="True" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
                        </td>
                    </tr>
                    <tr>
                        <td class="data">
                            Subject
                        </td>
                        <td class="ms-formbody">
                            <div style="width: 100%">
                                <asp:TextBox ID="txtSubject" runat="server" Width="450px"></asp:TextBox></div>
                        </td>
                    </tr>
                    <tr>
                        <td class="data">
                            Message <span class="required">*</span>
                        </td>
                        <td class="ms-formbody">
                            <div style="width: 100%">
                                <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Height="100px" Rows="5"
                                    Width="450px"></asp:TextBox></div>
                            <asp:RequiredFieldValidator ID="rfvmessage" runat="server" ControlToValidate="txtMessage"
                                ErrorMessage="Please Enter The Message." SetFocusOnError="True" ToolTip="Please Enter The Message."
                                Display="Dynamic"></asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td class="data">
                            Attachments
                        </td>
                        <td class="ms-formbody">
                            <div style="width: 100%">
                                <asp:FileUpload ID="oFileUpload" runat="server" Width="450px" /></div>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="1">
                        </td>
                        <td align="right" style="padding-top: 20px; padding-bottom: 20px;">
                            <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" Style="margin-left: 0px"
                                Width="75px" />
                        </td>
                       
                    </tr>
                    <tr>
                        <td colspan="2">
                            <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>


Modify your styles and validation expressions according to your logic.

Development:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Net.Mail;
using System.IO;
using System.Net;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;


namespace ContactFeedback.Contact_Feedback_Form
{
    public partial class Contact_Feedback_FormUserControl : UserControl
    {
       // System.Collections.Specialized.StringDictionary oMessageHeader;

        Label oLabelValidMessage;
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        public string ReceipientsEmails
        {
            get;
            set;
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            oLabelValidMessage = new Label();
            //oLabelValidMessage.ID = "lbl_validmessage";
            this.Controls.Add(oLabelValidMessage);

            if (ReceipientsEmails !="")
            {
                string ValidateReceipEmailId = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
                System.Text.RegularExpressions.Regex oRegvReceipEMail = new System.Text.RegularExpressions.Regex(ValidateReceipEmailId);
                if (!oRegvReceipEMail.IsMatch(ReceipientsEmails))
                {
                    oLabelValidMessage.Visible = true;
                    oLabelValidMessage.Text = "You must specify a valid E-mail address in webpart properties";
                    return;
                }
                //if (txtName.Text == "" || txtEmail.Text == "" || txtMessage.Text == "")
                //{
                //    lblValidMessage.Visible = true;
                //    lblValidMessage.Text = "You must specify a value for required field";
                //    return;
                //}
                //string ValidateSenderEmailId = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
                //System.Text.RegularExpressions.Regex oRegvSenderEMail = new System.Text.RegularExpressions.Regex(ValidateSenderEmailId);
                //if (!oRegvSenderEMail.IsMatch(txtEmail.Text))
                //{
                //    lblValidMessage.Visible = true;
                //    lblValidMessage.Text = "You must sepcify a valid email id";
                //    return;
                //}
                try
                {
                    //oMessageHeader = new System.Collections.Specialized.StringDictionary();
                    //oMessageHeader.Add("To", ReceipientsEmail);
                    //oMessageHeader.Add("From", oTextEMail.Text);
                    //oMessageHeader.Add("Subject", oTextSubject.Text);
                    //oMessageHeader.Add("content-type", "text/plain");
                    //oMessageHeader.Add("FileUpload", oFileUpload.FileName);

                    //string oMessageBody = oTextMessage.Text.ToString();
                    //Microsoft.SharePoint.Utilities.SPUtility.SendEmail(SPContext.Current.Web, oMessageHeader, oMessageBody);

                    SmtpClient Client = LoadSmtpInformation();
                    Client.Send(BuildMailMessage(ReceipientsEmails, txtEmail.Text, txtSubject.Text, txtMessage.Text));

                    lblMessage.Visible = true;
                    lblMessage.Text = "Message Sent";
                }
                catch (Exception ex)
                {
                    lblMessage.Text = ex.ToString();
                }
            }
        }
        private SmtpClient LoadSmtpInformation()
        {

            string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
            string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;

            SmtpClient client = new SmtpClient(smtpServer);
            client.Credentials = CredentialCache.DefaultNetworkCredentials;
            return client;
        }
        private MailMessage BuildMailMessage(string strTo, string strFrom, string strSubject, string strContenttype)
        {
            MailMessage message = new MailMessage();
            message.From = new MailAddress(strFrom);
            message.To.Add(new MailAddress(strTo));
            message.IsBodyHtml = true;
            message.Body = strContenttype;
            message.Subject = strSubject;
            if (oFileUpload.FileContent.Length > 0)

            message.Attachments.Add(new Attachment(oFileUpload.FileContent, oFileUpload.FileName));
          
            return message;
        }
    }
}

Add the Webpart Properties(.cs file)

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace ContactFeedback.Contact_Feedback_Form
{
    [ToolboxItemAttribute(false)]
    public class Contact_Feedback_Form : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/ContactFeedback/Contact_Feedback_Form/Contact_Feedback_FormUserControl.ascx";
        private string _ReceipientsEmail = string.Empty;
        [WebBrowsable(true)]
        [Personalizable(PersonalizationScope.Shared)]
        [WebDescription("Send To EMail")]
        [Category("Receipents EMail")]
        [WebDisplayName("Email")]      
        public string ReceipientsEmail
        {
            get { return _ReceipientsEmail; }
            set { _ReceipientsEmail = value; }
        }
        protected override void CreateChildControls()
        {
           //ontrol control = Page.LoadControl(_ascxPath);
            Contact_Feedback_FormUserControl control = (Contact_Feedback_FormUserControl)Page.LoadControl("~/_CONTROLTEMPLATES/ContactFeedback/Contact_Feedback_Form/Contact_Feedback_FormUserControl.ascx");
            control.ReceipientsEmails = ReceipientsEmail;
            Controls.Add(control);
        }
    }
}


Deploying the Webpart:

Using Stsadm

C:\>stsadm -o addsolution -filename ContactFormWebPart.wsp

C:\>stsadm -o deploysolution -name ContactFormWebPart.wsp -immediate
           -allowgacdeployment –allcontenturls

Using powershell


Add-SPSolution C:\ContactFeedback.wsp

Install-SPSolution -Identity ContactFeedback.wsp -WebApplication http://devsps2010.abc.com/ –GACDeployment

Checking the Outgoing Email Settings:


Add your webpart on your page


Add the Webpart properties:


Done..







Comments

Post a Comment

Popular posts from this blog

Tab Control in Asp.Net

Scenerio: I need your help in designing tab control in   asp.net .My requirement is I need a tab control in   asp.net (C#) like  for example goto my computer ,right click c drive and select properties.we get tabs like general,security etc....... like that i need to design one tab control(no need of any rightclick) in my web page and the database table columns should come as tabs and inseide the tab data of that particular column should come.   Example:Employee master tab1:Employee name.........his name in the tab tab2:Age.............his age tab3:Address........his address   Solution:   You can do this using a simple div <style type="text/css"> .tabs         {             position: relative;             height: 20px;             margin: 0;   ...

AI and Microsoft: Revolutionizing Efficiency in Nonprofit Organizations

  How AI and Microsoft Enhance Efficiency in Nonprofit Organizations In today’s fast-paced world, nonprofit organizations face unique challenges—limited resources, increasing demands, and the constant need to do more with less. But what if technology could be the game-changer they need? In my latest research paper,  "How AI and Microsoft Enhance Efficiency in Nonprofit Organizations" , I explore how cutting-edge technologies like Artificial Intelligence (AI) and Microsoft’s innovative tools are revolutionizing the way nonprofits operate. From streamlining administrative tasks to enhancing donor engagement and optimizing resource allocation, AI and Microsoft’s solutions are empowering nonprofits to focus on what truly matters—their mission. This paper dives deep into real-world examples, practical applications, and the transformative potential of these technologies. Whether you’re a nonprofit professional, a tech enthusiast, or simply curious about the intersection of technolo...

Social tagging overview in Sharepoint 2010

A tag is a word or phrase that identifies an individual piece of information according to a set of attributes or criteria. Tags make it easy to find and share information about a specific subject or task. Social tagging helps users categorize information in ways that are meaningful to them. Social tagging can improve the quality of search results by filtering against specific tags, and it can also connect individuals who want to share information with other users who have like interests. This article describes the social tagging features in Microsoft SharePoint Server 2010. This article does not describe how to configure social tagging features. It also does not discuss how to implement social tagging features as part of an overall social media strategy for an enterprise. About using social tagging features Social tagging features help users to share information and to retrieve relevant, high-quality content more efficiently. Such sharing encourages collaboration and b...