Search This Blog

Friday, August 29, 2014

QA For Master Page and Application Page

How many types of master pages in SharePoint 2010?There are total three types of master pages in SharePoint 2010:
  1. V4.master: This is default team site master page which provides ribbon bar and other editing features using UI.
  2. Default.Master : Sites which are upgraded from SharePoint 2007 to SharePoint 2010 uses this master page unless they are changed to use a v4 version.
  3. Minimal.master : These masterpages normally referred to as Starter Master pages in SharePoint 2010.
What are the things deployed as a sandbox solution in SharePoint 2010?Developers can deploy below things as a sandbox solution
  1.  WebParts.
  2.  Event Receivers.
  3. List Definitions.
  4. Workflows.
How many types of client object model extension available in SharePoint 2010, what is the criteria to use one or the other?There are three types of client object model extension has been introduced in the Microsoft.SharePoint.Client namespace. These three extensions are targeted for three different types of clients.
  1. .Net Managed Application : These are mostly used while developing console or windows application and also web applications which are not running into SharePoint context.
  2. Silverlight Applications
  3. ECMAScript : It is an extension using javascript or Jscript. These are mostly used for the applications which are hosted inside SharePoint.
How does user access ECMAScript object model API’s ?
The ECMAScript library is available in a number of JS file in the layouts folder. The main file among all the js files is SP.JS file. When a developer includes this file in the page all other JS files are loaded automatically. By linking SP.js to the page, the SP namespace is registered. SP is the SharePoint namespace that contains all objects. For debugging purposes, every js file also has a ‘debug’ equivalent in the same folder.
How many authentication methods are available for the client object model application ?
There are three authentication methods available while working with the client object model in SharePoint 2010:
  1. Anonymous
  2. Default
  3. FormsAuthentication
Developer needs to specify what authentication method in the code, if the developer didn’t mention the application will by default start using windows credentials ( i.e Default Credentials)
What is the main difference between Load() and LoadQuery() methods ?Load method basically used to populates client object directly from what it gets from the server i.e. a collection object like ListItemCollection etc. But Loadquery method returns totally new collection in IEnumerable format. The other difference is that the collections which Load method uses are eligible for garbage collection only when the client context variable goes out of scope whereas , in LoadQuery() method collection it goes out of scope at the end of IEnumerable<List>list.
What exactly the purpose of calling clientContext.ExecuteQuery() method?ExecuteQuery() method is used in the client object model, it basically used to avoid number of round trips to the server and all the components loaded into the clientcontext are executed in one go.
What is REST in SharePoint 2010 and how it is used ?
REST (Representation State Transfer).  It is basically a protocol which is powered by ADO.Net services which is used to get data out of the SharePoint via URL like webservices. It is also used to access data from the SharePoint even when the user is not in SharePoint context providing proper credentials.
What data type does REST return?It returns an XML output.
What is GAC ?GAC is a Global assembly cache folder on the server hosting SharePoint where user places their assemblies which needs to be used globally.
What is CAML ?
CAML is a Collaborative Application Markup Language and it is based on XML which is used in Microsoft Windows SharePoint services to define sites and lists. For example , fields, views, or forms, but CAML is also used to define tables in the Windows SharePoint services during site provisioning.
What is the benefit developer gets when they use LINQ over CAML for data retrieval?Unlike CAML, using LINQ to SharePoint provider, developers are mostly working with strongly types list item object. Suppose an item in the Announcement list is an object of type Announcement and an item on a Task list is an object of type task. Developer can then enumerate these objects and get the properties for their use. In addition, developer can take benefit of LINQ syntax and LINQ keywords which are much easier and sophisticated built in C# and VB for LINQ queries.
What are the main disadvantage of using LINQ in the code ?
Basically what LINQ does is it translates the LINQ queries in Collaborative Application Markup Language(CAML) queries which adds an extra step to retrieve the data
What exactly does RunWithElevatedPrivileges in Server Object model does ?Sometimes there are certain object model can call another model which requires site-administration privileges. To bypass the access-denied error we are using RunWithElevatedPrivileges. When a non-privileged  user initiates any request so at that time we can successfully make calls to the object model by using RunWithElevatedPrivileges method property provided by the SPSecurity class.
How to create a Content Type ?
Content type can be created in three ways,
1. SharePoint Foundation interface
2. SharePoint foundation object model
3. Deploying a feature that installs the content type based on an XML definition file.
How content type is deployed?
Content type can be associated with list or library and can be deployed using feature. Inside the Feature, it contains a feature.xml file which contains all the references to all the elements manifests within that Feature. Content type definitions are element manifests.
What exactly the scope of content type ?
Site
Is it possible to derived list definition from a custom content type ?Yes it is possible; It can be seen in the schema.XML of the list definition in the element.
While creating a list definition, how can a user create an instance of the list? 
User can create a new instance of a list by creating an instance.XML file
What is ghosted page in SharePoint 2010?
The page which is not stored in the content database instead it refers to a file which resides on the server’s file system.  These reference files are common for the site collections and Web applications within the SharePoint server.  If user modifies a reference file then that change will reflect in all the site collection within that SharePoint server automatically.
What is Un-ghosted page?All the pages which are stored in the content database are referred to as un-ghosted pages. All the un-ghosted pages are specific to that SharePoint web application only. i.e. changes done in an un-ghosted page will not reflect in other web applications within that SharePoint server.
How many types of pages available in SharePoint 2010?
Two types of pages are available in SharePoint 2010,
1.Application Page
2.Site Page
What are application pages in SharePoint 2010?
Application pages are stored on the file systems on the front end web servers in the layout directory. They allow in line code without restriction. Dynamic webparts or webpart zones cannot be created on application pages or they cannot modify on SharePoint Designer. Application pages are not stored in the content database. They never run in safe mode. As application pages reside on file system they cannot be used in sandbox solution.
In what scenarios we can use application pages?
1. Administrative pages
2. To capture data
3. Configuration pages
4. To restrict user to customize the page
5. with any site or site collection or web application on same server
6. When we want to add custom code or inline code to the page
What are the basic differences between site page and application page ?
S. NoApplication PagesSite Pages
1
Pages are stored in the file system.Pages are stored in the content database
2
Application pages cannot be used with Sandbox solutionsSite pages are used with Sandbox solution
3
Application pages cannot be edited in SharePoint DesignerSite pages can be edited in SharePoint Designer
4
An application page cannot be modified by end user for that developer is a must.Site pages can be edited by end user.
5
Inline code is used in Application pagesInline code cannot be used in Site Pages.
Is it possible to add web parts and web zones into an application page ?No, application pages does not support edit mode but static web parts can be added by editing them in visual studio.
How to edit an Application page?An application page can be edited in two way i.e Visual studio and notepad. However in both ways we need to deply application page again for further usage.
If a page with some code has to be deployed, which type of page should be selected?Application page should be selected.
What are the ways to create custom Master page ?
There are multiple ways to create custom master page files,
1.By SharePoint Designer
2.By editing minimal.master using any editor
3.By copying and editing existing master page

How to create and change the master page via SharePoint Designer


  1. Log in to your SharePoint site as an administrator and make sure that SharePoint Designer and Customizing Master Pages and Page Layouts are enabled at your site collection. To do this go to Site Actions - Site Settings and choose SharePoint Designer Settings under the Site Collection Administration header.
  2. See whether the Enable SharePoint Designer and Enable Customizing Master Pages and Page Layouts options are checked or check them if they are not. Then click OK.
  3. Open your site in the SharePoint Designer and choose Master Pages at the Navigation menu.
  4. Make a copy of the existing master page (SharePoint 2010 uses v4.master by default).
  5. Rename a copy of the master page (do not remove .master extension in the new name).
  6. Click on this new master page and click on Edit file .
  7. You can see your new master page in the editor tool. Make the changes you wish (you can apply styles, remove elements etc.).
  8. After all changes were made click on Save button in the SharePoint designer (you may also right click on the tab and then to choose Save).
  9. Right-click on your new master page in the Master pages folder and choose Set as Default Master Page.
  10. Now you can review your changes at your SharePoint site.
If you need further assistance, please do not hesitate to contact the PlexHosted support staff.

Keywords

SharePoint, Master Page, SharePoint Designer

Wednesday, August 27, 2014

Some Conept Of Master Page

Master Pages vs. Page Layouts in Sharepoint 2010

For those new to Sharepoint, specifically Sharepoint 2010, here is a primer on the difference between page layouts and master pages.

Master Pages
A master page is what I would normally call something like a template. It holds all of Sharepoint's necessary elements. It creates containers for your information to load into later. It sets the document structure. An analogy would be an empty bookcase. It's created a bunch of holding places for different elements. You'll use some of these elements, and Sharepoint will use the rest. So it's VERY important to not remove elements in this page unless you really know what you're doing. You might not need the item, but Sharepoint might need it to run the page correctly.

What Master Pages are used for:

Calling CSS files
Installing javascript & other scripts
Tracking codes (I put my Google Analytics code here)
Setting top navigation & sidebar functionality
Things that occur on EVERY page.
What Master Pages are not used for:

Controlling page-level design and structure
Webparts and Webpartzones (you can…but I wouldn't)
Anything that DOESN"T occur on EVERY page
Page Layouts
In a page layout, you are essentially telling Sharepoint what it should fill all those empty bookshelves with.You declare a control (a certain shelf), and then tell Sharpeoint what goes inside. You can't go beyond the reaches of the master pages. Whatever controls are on the master page are the controls you can use in a page layout.

What Page Layouts are used for:

Creating the layout of the pages (within the bounds of the master page)
Controlling page-level design elements.
Including page-level css files to override master page styles
Inserting Webparts and Webpartzones
Including custom codes (javascript, etc.)
Things that occur only on this page layout, not site-wide
What Page Layouts are not used for:

Content. This is not the place to write and display content. You'll create a page to do that. This is merely to provide the placeholders to do that.
Applying CSS styles that could be applied at a higher level. You want to keep the management of things like CSS as centralized and high as possible.
A few extra tips:

You should never need more than 1 master page (unless for some reason you decide you want a different "admin" and "front-end" master page.
Page layouts should be used sparingly. It can get a bit out of control, so consider what you need and make some generic templates using page layouts that will work for

Diff  user control VS MasterPage:
user control
1)it extension is .ascx.
2)it can be more than one on single web page.
3)it doesn't contain Contentplaceholder.
4)it doesn't work like a fixed template.it can be
display in diffrent manner in diffrent page.
MasterPage:
1) it extension is .Master.
2)it used like a template.
3)it contain ContentPlaceHolder.

Diff  MASTER PAGE VS  PAGE LAYOUT
Master page

Master pages form the basic structure of all pages in a site. A master page is the template into which the
other pages fit.
SharePoint uses a master page to define the basic structure and then a set of pages to provide the
page specific parts. SharePoint Server further uses page layouts to provide the template for the content to be displayed. From these page layouts, page instances are created.

Page Layout

Page Layout is part of SharePoint publishing features, which are the Web content management
features of SharePoint.

These templates allow content authors to focus on generating their content. SharePoint manages the merging of the user content and the template into a single, consistent page. Page layouts are templates into which
content will be added but these templates still fall inside of the scope of what the master page defines, but they further refine what is on the page by including specific Web Part zones, Web Parts, and field controls.
Page layouts are a SharePoint Server 2010 Web Content Management feature so they are not available in
SharePoint Foundation.
When users use the publishing features to create a new page, they are creating a new page instance. The
page layout is selected (the content type is inferred) and the user is presented with an opportunity to
enter the content. Under the covers, SharePoint merges the content and the template into a single output that is returned to users when they browse the site.


About Workflows

Workflows:
SharePoint Foundation 2010 workflows are made available to end-users at the list or document-library level. Workflows can be added to documents or list items. Workflow can also be added to content types.
Multiple workflows may be available for a given item. Multiple workflows can run simultaneously on the same item, but only one instance of a specific workflow can run on a specific item at any given time.
For example, you might have two workflows, called “SpecReview” and “LegalReview”, available for a specific content type, Specification. Although both workflows can run simultaneously on a specific item of the Specification content type, you cannot have two instances of the “LegalReview” workflow running on the same item at the same time.
Workflow forms:


Three types of forms are used in SharePoint Foundation workflows:
Association and Initialization Forms: Association and initialization forms are displayed for users to fill out before any workflow is actually started. You can use these forms to enable users to set parameters and other information for the workflow before it starts.

Modification Forms:   Modifications are options you present to users to change the workflow as it's running on an item. You can then create modification forms that enable users to specify the parameters of the modification.

Task Forms:  You can also specify custom forms for the tasks in your workflow. Because tasks are SharePoint items that are assigned a content type, however, the content type actually determines the custom forms used with the task type.
For more information, see Workflow Task Forms (SharePoint Foundation).

Workflow life cycle:
SharePoint workflow cycle is very much unique to SharePoint environment. SharePoint workflows are always connected in context with SharePoint content like list or a document.
There are four stages in the SharePoint workflow cycle. They are 

Associate: Association forms address how the workflow applies to a specific list, library, or content type. In this stage, workflow is associated with a content type like list or a document.
Association forms are displayed to administrators when they first decide to add—or associate—a workflow with a particular list, document library, or content type.

Initiate: Initiation forms address how the workflow applies to a specific SharePoint item. In this stage, the workflow created is to be initiated. Workflow are noting but classes. So a workflow instance needs to be created to start the workflow in action.
Initiation forms are displayed to users when they start a workflow on a specific SharePoint item.

Modify: In third stage, the instance of the workflow is modified as per the workflow stages.

Complete: Finally the workflow object is terminated.
Workflows and types of workflows?
SharePoint 2010 workflows are based on Windows Workflow Foundation (WF). WF is part of .NET 3.5 Framework.

Sequential workflows?
  1. In sequential workflows, the activities are placed in a logical order with an explicit start and an explicit end.
  2. The activities are executed sequentially one after the other like a flow chart.
  3. There is no going back to the previous step in a sequential workflow. 
Workflow object model:
  • Associate workflows to the list, library and content type:
  • To associate a workflow to a list or document library, use the AddWorkflowAssociationmethod of the SPList object.
  • To associate a workflow with a content type, use the AddWorkflowAssociation method of the SPContentType object.
  • Both of these methods take an SPWorkflowAssociation object and add it to the specified list or content type, respectively.
  • Remove workflow association from the list, library and content type:
  • Use the RemoveWorkflowAssociation method to remove a workflow association from a list, and the RemoveWorkflowAssociation method to remove a workflow association from a site or list content type.
Managing workflows instances programmatically:
Use the SPWorkflowManager object to manage the running instances of workflows across a site collection. The SPWorkflowManager object has no equivalent in the user interface. Use the SPWorkflowManager object to:
Start, run, or cancel workflows.
Return all the workflows currently running on a specific item.
Perform other workflow administration operations.
To manually start a specific workflow for an item—that is, a workflow that is not configured to start automatically—use the StartWorkflow(SPListItem, SPWorkflowAssociation, String) or StartWorkflow(SPListItem, SPWorkflowAssociation, String, Boolean) method.

Difference between event receivers and workflows?
Unlike Workflows, Event Receivers cannot be triggered manually.
Event receivers will support both Before/After properties but workflows supports only after properties [Means u can’t able to perform “ing” operations].
SharePoint event handlers run for a short period of time (generally seconds), while SharePoint workflows may run for a much longer time period (days, months, or even years).
 
Difference between SharePoint designer workflows and custom workflows?
  1. Only sequential workflows can be created in SharePoint Designer; state machine workflows cannot be created in SharePoint Designer.
  2. Deployment and moving is easy in custom workflows when compared to SharePoint designer workflows.
  3. Visual Studio can have code-behind.
  4. Visual Studio generates a workflow template which can be easily be deployed, SharePoint Designer workflows are typically built against specific lists and sites.
  5. Visual Studio allows for debugging!!
Why custom workflows can’t be deploying using sandbox solution?
In Workflow activity we have an .ACTIONS file. The .ACTIONS file will be stored in Physical Directory. But in Sandbox, we can't move any file to Physical location.
Name
Available for sandboxed solutions
Sequential Workflow
No. Programmatic workflows are not available for sandboxed solutions.
State Machine Workflow
No. Programmatic workflows are not available for sandboxed solutions.
Import Reusable Workflow
No. Programmatic workflows are not available for sandboxed solutions.
Import SharePoint Solution Package
Yes, if the items that is imported from the package are supported.
Workflow Association Form
No. Association forms include .aspx files and are not available for sandboxed solutions.
Workflow Initiation Form
No. Initiation forms include .aspx files and are not available for sandboxed solutions.

What type of issues you faced while developing workflows?
This view cannot be displayed because the number of lookup and workflow status columns it contains exceeds the threshold enforced by the administrator.
 
We will not get the metadata of document library when you assigned workflow. Workflow will immediately trigger once you upload doc to the doc library. So that’s the reason you can’t get the metadata of document library. So, I called my custom workflow manually in ItemAdded event.

How to attach workflows to the content types?
 
//To attach it for specific content type
<AssociationCategories>
ContentType;0x010100a945f312c7bd4a589d1489ca8307f24d</AssociationCategories>
//To attach it for all content types
<AssociationCategories>ContentType</AssociationCategories>
//To attach it for specific content type
<MetaData>
<AssociationCategories>
ContentType;0x010100a945f312c7bd4a589d1489ca8307f24d
;#ContentType;0x0101009a30bd7a9c18447e9b806af9c0931b9c
</AssociationCategories>
</MetaData>

How to attach workflows to the list and library?
  <Workflow
     Name="WorkflowProject1 - Workflow1"
     Description="My SharePoint Workflow"
     Id="d011cd8b-a95d-4d3e-bd53-e88345bbf5c4"
     CodeBesideClass="WorkflowProject1.Workflow1.Workflow1"
     CodeBesideAssembly="$assemblyname$">
    <Categories/>
    <MetaData>
      <AssociationCategories>List</AssociationCategories>
      <StatusPageUrl>_layouts/WrkStat.aspx</StatusPageUrl>
    </MetaData>
  </Workflow>
</Elements>

Remember points:
Workflows run with “system account” by default.
InfoPath forms cannot be created with Visual Studio. Previous versions of Visual Studio provided that capability but it was removed from the current 2010 version.

Other debugging tips:
Failed on Start usually means an error is happening in SharePoint before your workflow code spins up, such as not being able to find the workflow dll.  Error Occurred usually means the workflow started and the error is somewhere in the code.

Check the SharePoint ULS logs! – Fatal workflow errors might happen outside of your workflow, so they aren’t always visible in the debugger.  Consult the logs to see if this is the case by opening the latest log and searching from the bottom up for “Workflow”.  The logs are awesome resources that often get overlooked.  Logs can be found in %Program Files%\Common Files\Microsoft Shared\web server extensions\12\LOGS.
This view cannot be displayed because the number of lookup and workflow status columns it contains exceeds the threshold enforced by the administrator.
Coded workflows cannot be deployed in a sandboxed solution.
Only a Reusable workflow—not a List workflow or a Site workflow—can be saved as a sandboxed solution in SharePoint Designer.
A workflow that is published as a Global Reusable workflow cannot be directly saved as a sandboxed solution in SharePoint Designer. However, you can copy it as a non-global workflow, which you can then save as a sandboxed solution. [ http://msdn.microsoft.com/en-us/library/gg615452.aspx ]

Difference between SpListItem.Update and SpListItem.SystemUpdate

To update a list item we have two ways. One of them is SPListitem.Update and its is most popular way. But this method is change version history and trigger all alerts. Some times, some reason you can want to avoid change version history or triggering allerts. Like this case, SpListitem.SystemUpdate medhod help us. Because that SystemUpdate() is not changing version history.
For Example; I have a list name Personel and I want to change secont record by a console application with SPitem.Update method. Before Run this code sample my list item history like this.
 using (SPSite site = new SPSite("http://testsite"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Personel"];
                    SPListItem item = list.Items[1];
                    item["Title"] = "Sample Update with Versions.";
                    item.Update();
                    list.Update();
                }
            }
After work this Consle Application secont item version history changin like this;

The outher mathod which SystemUpdate() don't add new version history.
using (SPSite site = new SPSite("http://testsite"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Personel"];
                    SPListItem item = list.Items[1];
                    item["Title"] = "Sample Update with out add Versions";
                    item.SystemUpdate();
                    list.Update();
                }
            }
Finnaly My item history changing but not a new version number.

Some of important OOB features are listed below:


CQWP:
  • The Content Query Web Part is a very handy tool in SharePoint Standard and SharePoint Enterprise only i.e. not available at SharePoint Foundation.
  • The CQWP is used to display the content by querying, filtering and sorting.
  • The CQWP can fetch the data based on content types.
  • By default, we can group and sort by only one field.
  • Minimum designer level permissions required.
  • CQWP is part of a bundle of features called “SharePoint Server Publishing Infrastructure”.
  • The Content Query Web part cannot fetch data across site collections. If you really need it, you can take a look at the Lightning Conductor Web Part.
  • Ref: http://sharepointlogics.com/2012/03/how-to-use-content-query-webpart-in.html
DVWP:

  • A Data View Web part is a great way to display data with filtering, grouping, and user desired formatting.
  • SharePoint Designer is required for developing DVWP.
  • DVWP can fetch data from data sources other than lists like xml files.
  • DVWP can fetch data from other site collection.
  • DVWP can merge data from more than one list.
CQWP:

  • The Content Editor Web Part (CEWP) allows you to add text, html, scripts or styles to a SharePoint page.
XSLT list Web part:

  • Introduced in SP2010.
  • In SharePoint 2010, all views in lists and libraries are XSLT list view web parts. This means that you can edit views from the browser or from SharePoint Designer 2010.
CSWP:

  • Introduced in SP 2013.
  • The Content Search Web Part (CSWP) is a Web Part that displays search results based on a search query.
Difference between user control and webpart?
Webparts are like user controls, user controls are added in code but webparts are added at runtime.
The advantage of Web User Control is that you can use Visual Web Developer to design the web user control and in normal web parts all controls are created in the code itself i.e. on “CreateChildControls” method only.

User Control
Web Part
User controls are based on Microsoft ASP.NET, and most developers are familiar with developing user controls. This improves productivity.
In general, developers are not familiar with creating child controls by writing the code from scratch.
User controls can be used with ASP.NET -based solutions. If you decide later to convert a project containing a user control to an ASP.NET -based solution, you should be able to use the control without making any changes.
Web Parts can be used in ASP.NET -based solutions only when the solution uses Web Parts pages.
The Visual Web Developer designer provides support for designing the UI by using drag-and-drop operations that gives the control a consistent look-and-feel, which results in faster development.
The controls in Web Parts must be added by using code.
User controls must be compiled before use, which adds to the time it takes to load the control.
Web Parts are precompiled and ready for use as soon as you need them.


Monday, August 25, 2014

Creating a Web Part Project(Using Webpart(Dynamic Creation))

The first step is to create a new web part project using Visual Studio 2008. To do this, open Visual Studio 2008, and choose New – Project from the file menu. Select Visual C# - SharePoint from the Project Type list, and select the Web Part template from the list on the right. Enter ContactFormWebPart as the name and the solution name, and choose a directory where you want the solution files to be saved. When you click OK, an empty web part project will be created and opened in Visual Studio.

The empty project has one web part, called WebPart1, but this isn’t what we want to call our web part, so the first step is to delete WebPart1 from the project by right clicking on the WebPart1 folder in the Solution Explorer in Visual Studio and choosing Delete.
Next, let's add a new web part to the project, called ContactForm. Right click on the ContactFormWebPart project in the Solution Explorer, and choose Add – New Item from the context menu. Select SharePoint from the categories list, and Web Part from the templates list. Enter ContactForm for the name, and click Add.
Adding a New Web Part
This gives you a new source file called ContactForm.cs that has an empty class inheriting from WebPart, with some TODO comments. In the next section, we are going to replace the CreateChildControls() function and add some additional code to this class.
After Adding the ContactForm Web Part

Adding Code to Create the Controls

Now, we are ready to begin writing code that will display the web part. Open ContactForm.cs, and you will see a function called CreateChildControls(). This function is where we will add labels, textboxes, and a button to allow the user to interact with our web part.
But first, let's create some class-level variables for the controls that we will create. Declaring them at the class level as opposed to within the CreateChildControls() function will allow us to reference these controls from the button event handler later on.
TextBox txtContactName;
TextBox txtEmailAddress;
TextBox txtPhone;
TextBox txtMessage;
Button btnSendMessage;
Label lblMessageSent;
Now, let's add the code to CreateChildControls to build the display. In order to keep it simple, an HTML table will be used to align the controls in a consistent manner. Each table row will have two cells: one for the field label, and the other for the text boxes. Controls are created one at a time and added to a table cell, which is then added to a table row.
protected override void CreateChildControls()
{
    base.CreateChildControls();

    Table t;
    TableRow tr;
    TableCell tc;
    
    // A table that is used to layout the controls
    t = new Table();

    // Label with instructions for the user
    tr = new TableRow();
    tc = new TableCell();
    tc.ColumnSpan = 2;
    tc.VerticalAlign = VerticalAlign.Top;
    Label lblInstructions = new Label();
    lblInstructions.Text = "Please enter your contact" + 
                           " information and message below.";
    tc.Controls.Add(lblInstructions);
    tr.Controls.Add(tc);

    t.Controls.Add(tr);

    // Contact Name label
    tr = new TableRow();
    tc = new TableCell();
    tc.Style["padding-top"] = "7px";
    tc.VerticalAlign = VerticalAlign.Top;
    Label lblContactName = new Label();
    lblContactName.Text = "Name:";
    tc.Controls.Add(lblContactName);
    tr.Controls.Add(tc);

    // Contact Name textbox
    tc = new TableCell();
    tc.VerticalAlign = VerticalAlign.Top;
    txtContactName = new TextBox();
    txtContactName.ID = "txtContactName";
    txtContactName.Width = Unit.Pixel(300);
    tc.Controls.Add(txtContactName);
    tr.Controls.Add(tc);

    t.Controls.Add(tr);

    // Email Address label
    tr = new TableRow();
    tc = new TableCell();
    tc.Style["padding-top"] = "7px";
    tc.VerticalAlign = VerticalAlign.Top;
    Label lblEmailAddress = new Label();
    lblEmailAddress.Text = "Email Address:";
    tc.Controls.Add(lblEmailAddress);
    tr.Controls.Add(tc);

    // Email Address textbox
    tc = new TableCell();
    tc.VerticalAlign = VerticalAlign.Top;
    txtEmailAddress = new TextBox();
    txtEmailAddress.ID = "txtEmailAddress";
    txtEmailAddress.Width = Unit.Pixel(300);
    tc.Controls.Add(txtEmailAddress);
    tr.Controls.Add(tc);

    t.Controls.Add(tr);
    
    // Phone Number label
    tr = new TableRow();
    tc = new TableCell();
    tc.Style["padding-top"] = "7px";
    tc.VerticalAlign = VerticalAlign.Top;
    Label lblPhone = new Label();
    lblPhone.Text = "Phone Number:";
    tc.Controls.Add(lblPhone);
    tr.Controls.Add(tc);

    // Phone Number textbox
    tc = new TableCell();
    tc.VerticalAlign = VerticalAlign.Top;
    txtPhone = new TextBox();
    txtPhone.ID = "txtPhone";
    txtPhone.Width = Unit.Pixel(300);
    tc.Controls.Add(txtPhone);
    tr.Controls.Add(tc);

    t.Controls.Add(tr);
    
    // Message label
    tr = new TableRow();
    tc = new TableCell();
    tc.Style["padding-top"] = "7px";
    tc.VerticalAlign = VerticalAlign.Top;
    Label lblMessage = new Label();
    lblMessage.Text = "Message:";
    tc.Controls.Add(lblMessage);
    tr.Controls.Add(tc);

    // Message textbox
    tc = new TableCell();
    tc.VerticalAlign = VerticalAlign.Top;
    txtMessage = new TextBox();
    txtMessage.ID = "txtMessage";
    txtMessage.Height = Unit.Pixel(100);
    txtMessage.Width = Unit.Pixel(400);
    txtMessage.TextMode = TextBoxMode.MultiLine;
    txtMessage.Wrap = true;
    tc.Controls.Add(txtMessage);
    tr.Controls.Add(tc);

    t.Controls.Add(tr);
    
    // Empty table cell
    tr = new TableRow();
    tc = new TableCell();
    tr.Controls.Add(tc);    

    // Label for telling the user the message was sent
    tc = new TableCell();
    tc.VerticalAlign = VerticalAlign.Top;
    lblMessageSent = new Label();
    lblMessageSent.Text = "Your message has been sent. Thank you.";
    lblMessageSent.Font.Bold = true;
    lblMessageSent.Visible = false;
    tc.Controls.Add(lblMessageSent);
    tr.Controls.Add(tc);

    t.Controls.Add(tr);

    // Empty table cell
    tr = new TableRow();
    tc = new TableCell();
    tr.Controls.Add(tc);

    // Send Message button
    tc = new TableCell();
    btnSendMessage = new Button();
    btnSendMessage.Text = "Send Message";
    btnSendMessage.Click += new EventHandler(btnSendMessage_Click);
    tc.Controls.Add(btnSendMessage);
    tr.Controls.Add(tc);

    t.Controls.Add(tr);

    this.Controls.Add(t);
}
Finally, we need to add an event handler to send the message as an email when the Send Message button is clicked by the user. In the code above, the event handler was already wired up with the linebtnSendMessage.Click += new EventHandler btnSendMessage_Click);, so now we just need to create the btnSendMessage_Click function. This function simply builds an email message using text that was entered into the text boxes, and sends the email using SharePoint's SPUtility.SendEmail() function.
You will need to change the "to" and "from" fields in the message header for your specific situation. The "to" field specifies where the email will be sent, and the "from" field is the email address that the email should appear to be from. The "from" field isn't too important, but some mail servers may require this to be a valid email address.
protected void btnSendMessage_Click(object sender, EventArgs e)
{
    // Build the email subject string
    System.Text.StringBuilder subject = new System.Text.StringBuilder();
    subject.Append("Contact Form Message from ");
    subject.Append(txtContactName.Text);

    // Build the email message string
    System.Text.StringBuilder message = new System.Text.StringBuilder();
    message.Append("Contact Name: ");
    message.AppendLine(txtContactName.Text);
    message.Append("Email Address: ");
    message.AppendLine(txtEmailAddress.Text);
    message.Append("Phone: ");
    message.AppendLine(txtPhone.Text);
    message.AppendLine();
    message.AppendLine("Message:");
    message.AppendLine(txtMessage.Text);

    // Construct the message header
    System.Collections.Specialized.StringDictionary messageHeader = 
    new System.Collections.Specialized.StringDictionary();
    // TODO: Where to send the email
    messageHeader.Add("to", "CustomerService@example.com");
    // TODO: Who the email should be "from"
    messageHeader.Add("from", "ContactForm@example.com");
    messageHeader.Add("subject", subject.ToString());
    messageHeader.Add("content-type", "text/plain");

    // Send the email
    Microsoft.SharePoint.Utilities.SPUtility.SendEmail(
    SPContext.Current.Web, messageHeader, message.ToString());

    // Let the user know the message was sent
    lblMessageSent.Visible = true;

    // Clear out the input fields
    txtContactName.Text = "";
    txtEmailAddress.Text = "";
    txtPhone.Text = "";
    txtMessage.Text = "";
}