Developing A Form WebPart – Part 3 – Setup the Connection to the SQL Server with ADO.NET 2.0

In order to manage the connection to the database and perform relevant database operations, use ADO.NET functionality out of the System.Data.SqlClient namespace. For the Forms WebPart, ADO.NET provides the crux of the operations for database logic.

In order to open a connection to the SQL database, the Forms WebPart can harvest the connection information out of a configuration file by using WebConfigurationManager out of the System.Web.Configuration namespace. By exposing the AppSettings public property, you can return key-value pairs from the configuration file, allowing the exposure of the connection string information. By returning the connString argument from the Connection String data in the configuration file, you can then use the argument to pass into the SqlConnection object, which can then open a connection to the database by using the Open() method.

Here is the code for the SQL connection method:

[csharp]

public static void OpenSqlConnection(ref SqlConnection sqlConn, string webConfigConnectStringKey)
{
      NameValueCollection nvc =
      AppSettings as NameValueCollection;
      string connString = nvc[webConfigConnectStringKey];
      sqlConn = new SqlConnection(connString);
      sqlConn.Open();
}

[/csharp]

Once the OpenSqlConnection method has been declared, you can then call it in the OnInit method in order to intalize the connection to the database when the WebPart is firstly instantiated. In the OnInit method, there must be a call to base.OnInit(e) in order to raise the method’s associated events, which will directly impact inherent WebPart functionality such as WebPart menus provided that allow interaction with the WebPart such as closing, minimizing, modifying the WebPart properties, and managing WebPart connections . Also, in the OnInit is a good time to establish the site context and establish a reference to the SPWeb object using the OpenWeb() method as a best practice.

Here is the code for the OnInit method In the Form WebPart:

[csharp]

protected override void OnInit(EventArgs e)
{
       // must include for WebPart integrity
       // (menu registration items such as closing, minimizing, modifying
       // the WebPart properties, and managing WebPart connections)
       base.OnInit(e);
       // current site and web
       siteThis = SPControl.GetContextSite(Context);
       webThis = siteThis.OpenWeb();
       // reference the above connection method      
       OpenSqlConnection(ref sqlConn);

[/csharp]

Share

Developing A SharePoint Form WebPart – Part 2 – Declare Variables, Assign Controls, And Set up Exception Management

Once the class is setup for the Form WebPart, you need to declare relevant variables and instantiate the required controls by overriding the CreateChildControls() method. For the Forms WebPart, which only accepts an ID input, the only required controls are a TextBox control and a new button that is wired to a submission event.

[csharp]

        // Current Site
        SPSite siteThis = null;
        // Current Web
        SPWeb webThis = null;
        // Text Box Control
        private TextBox txtTextBox;
        // Button Control
        private Button save;
        // String Build In Order To Parse Relevant Errors
        private StringBuilder msgError = new StringBuilder();
        // SQL connection variable
        SqlConnection sqlConn = null;
        // Validator Control to Verify User Input
        private RequiredFieldValidator fieldVal;

[/csharp]

There are two best practices to consider when starting to script a piece of functionality such as the Forms WebPart. Firstly, it is advantageous to build a reference to the current site and web since this can be passed on the OnInit method in order to harvest the current site and web context by using SPControl.GetContextSite(Context). In terms of exception management, organizations typically vary in whether there are enterprise standards such as using the trapping logic out of the Microsoft Exception Handling Enterprise Library or a custom common exception library. If managing individual loose exceptions, use a class available StringBuilder() in order to append the string exception text by using (stringbuildervariable).Append within the relevant try/catch blocks.

Next, the controls have to be declared by overriding the CreateChildControls() method. The two controls that need to be instantiated are the TextBox control to accept the ID input from the user and the button control that is wired to an event handler to manage the data submission. This is accomplished by initializing each of the controls, and then call the add method out of the Controls property to add it to the WebPart output.

Wrapping this in a try/catch block, it is noticeable that the StringBuilder() being used to manage the exceptions is being called in the catch block if there is an error that occurs in the CreateChildControls().

[csharp]       

protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                // Call a new text box control
                txtTextBox = new TextBox();
                txtTextBox.ID = “txtTextBox”;
                Controls.Add(txtTextBox);
                // Call a new button control and bind it to an event
                save = new Button();
                save.Text = “Save”;
                save.Click += new EventHandler(save_Click);
                Controls.Add(save);
            }
            catch (Exception ex)
            {
                msgError.Append(“Error in CreateChildControls: ” + ex.Message);
            }
        }

[/csharp]

If more controls were required for data entry, such as using a ListBox control with relevant bound list items, the relevant variables need only be declared and the control added in the same fashion.

[csharp]      

private ListBox lbListBox
        // Under base.CreateChildControl() in the CreateChildControls Method
        lbListBox = new ListBox();
        lbListBox.Rows = 1;
        lbListBox.Items.Add(new ListItem(“my lbListBox Item”,” my lbListBox Item “));
        Controls.Add(lbListBox);

[/csharp]

Share

Developing A SharePoint Form WebPart – Part 1 – Set Up the WebPart Class

Before accomplishing any custom development, the necessary foundational code must be added to the WebPart in order to set it up for inclusion in the SharePoint environment. You must establish the following references (shown in the code listing) in the main WebPartclass file. Doing so allows WebPart class derivation out of the WebPart base class, procures SQL connectivity using ADO.NET 2.0, allows for definition of WebPart attributes, and tolerates the binding of the appropriate user interface controls for final output by an overridden RenderWebPart method.

[csharp]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Xml.Serialization;
using System.Xml;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using System.Collections;

[/csharp]

Supply the appropriate WebPart base class inheritance derivation for the parent class either through System.Web.UI.WebControls.WebParts or Microsoft.SharePoint.WebPartPages. For the Form WebPart, it is advisable to use the new ASP.NET 2.0 base class derivation, therefore set the inheritance to System.Web.UI.WebControls.WebParts.WebPart. Once the class has been defined, call the relevant XML decoration attributes in the XmlRoot element provided by the System.Xml.Serialization namespace by defining a default XML namespace in order to control the serialization of the WebPart properties.

Optionally, define the ToolBoxData attribute with the default Typename so that the control class is concretely defined when using it within an IDE. After modifications, your top level class definition should look like the following:

[csharp]

    [DefaultProperty(“Text”)]
    [ToolboxData(“<{0}: FormsWebPart runat=server></{0}: FormsWebPart >”)]
    [XmlRoot(Namespace = ” ProfessionalSharePoint2007.FormsWebPart “)]
    public class FormsWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
    }

[csharp]

Since you have now appropriately modified the class in order to assimilate into the WebPart framework and made the necessary references to draw on ADO.NET 2.0 functionality in order to submit user entered items to the backend SQL data store, the relevant child controls need to be instantiated in order to capture user input.

Share