How to create a new site based on a custom site template

Here is a method to create a sub site based on a custom site template.  You need to pass in your new site name and the name of the site template.  It will check the available site templates for the one you specified (so you must deploy the site template first).  If it’s not there an error gets displayed.  I put a label on my web part to display the error _lblErrMsg.  You will need that control (or you can remove it and handle errors whatever way you want.

private bool CreateSubSite(string newSiteName, string ProjectsiteTemplateName)
      {
          try
          {
              SPWeb webSite = SPContext.Current.Web;

              webSite.AllowUnsafeUpdates = true;

              //Get all the site templates
              SPWebTemplateCollection Templates = webSite.GetAvailableWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH));

              //Get the specific project template
              SPWebTemplate siteTemplate = null;

              //Verify the custom site template exists
              if (templateExists(Templates, ProjectsiteTemplateName))
              {
                  siteTemplate = Templates[ProjectsiteTemplateName];
              }
              else
              {
                  _lblErrMsg.Text = "Could not find the custom site template.";
              }

              if (siteTemplate != null)
              {

                  SPWeb newWeb; 
                  newWeb = SPContext.GetContext(HttpContext.Current).Web.Webs.Add(
                      newSiteName.Trim(),
                      newSiteName,
                              "Project Site",
                              LOCALE_ID_ENGLISH, siteTemplate,
                              true, false);

                  //Inherit navigation from parent site
                  newWeb.Navigation.UseShared = true;

                  newWeb.Update();

                  siteCreated = true;

                  webSite.AllowUnsafeUpdates = false;

              }

              webSite.Close();

          }
          catch (Exception ex)
          {
              this._lblErrMsg.Text = ex.Message.ToString();
          }

          return siteCreated;
      }
[tweetmeme only_single=”false”]
Advertisements

How to add a content editor web part to a SharePoint page

Here is some code to add a content editor web part to a page. So if you are creating a page in code (like during feature activation), then you put a content editor web part on the page.

Setting the InnerText (contentXMLElement.InnerText = “”;) will set the text in the content editor, incase you want something to be there by default.  User HTML.

using (SPWeb webSite = SPContext.Current.Site.OpenWeb(SiteToOpen))
{
using (SPLimitedWebPartManager mgr = webSite.GetFile(“default.aspx”).GetLimitedWebPartManager(PersonalizationScope.Shared))
{
if (mgr != null)
{
# region AddNewLink

ContentEditorWebPart cewp = new ContentEditorWebPart();
cewp.AllowClose = false;
cewp.AllowEdit = false;
cewp.AllowHide = false;
cewp.AllowMinimize = false;
cewp.ID = “ContentEditorWP”;
cewp.Title = “Content Editor Web Part”;
cewp.ChromeType = PartChromeType.None;

//Add content to the content editor web part
XmlDocument addNewXMLDoc = new XmlDocument();
XmlElement contentXMLElement = addNewXMLDoc.CreateElement(“Root”);
contentXMLElement.InnerText = “”;
cewp.Content = contentXMLElement;
cewp.Content.InnerText = contentXMLElement.InnerText;

// add the web part.
// first argument: web part object
// second argument: zone
// third argument: index (location within the zone)
mgr.AddWebPart(cewp,”left”, 0);

# endregion

}
}
}

Method to strip out special characters from a string.

Special characters can cause all kind of trouble.
So here is a method that you pass in a string and all the special characters will be removed.

 

public static string StripSpecialCharacters(string stringToConvert)
        {
            stringToConvert = stringToConvert.Replace("~", string.Empty);
            stringToConvert = stringToConvert.Replace("#", string.Empty);
            stringToConvert = stringToConvert.Replace("%", string.Empty);
            stringToConvert = stringToConvert.Replace("&", string.Empty);
            stringToConvert = stringToConvert.Replace("*", string.Empty);
            stringToConvert = stringToConvert.Replace("{", string.Empty);
            stringToConvert = stringToConvert.Replace("}", string.Empty);
            stringToConvert = stringToConvert.Replace("\\", string.Empty);
            stringToConvert = stringToConvert.Replace(":", string.Empty);
            stringToConvert = stringToConvert.Replace("<", string.Empty);
            stringToConvert = stringToConvert.Replace(">", string.Empty);
            stringToConvert = stringToConvert.Replace("?", string.Empty);
            stringToConvert = stringToConvert.Replace("/", string.Empty);
            stringToConvert = stringToConvert.Replace("|", string.Empty);
            stringToConvert = stringToConvert.Replace("\"", string.Empty);
            return stringToConvert;
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

How to create sub sites in SharePoint 2007

Here is some code to create a subsite in SharePoint.
The important part to remember is to set AllUnsafeUpdates (and unset), otherwise it won’t work.

try
{
    SPWeb webSite = SPContext.Current.Web;

    webSite.AllowUnsafeUpdates = true;

        //Add subsite site
        webSite.Webs.Add(<WEBURL>, <TITLE>, <DESCRIPTION>, LOCALE_ID_ENGLISH, <SITE TEMPLATE>, true, false);

    webSite.AllowUnsafeUpdates = false;
}
catch (Exception ex)
{
    throw ex;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Detect who the current user in a SharePoint web part

It’s easy to detect who the current authenticated in ASP.HET (HttpContext.Current.User), but that doesn’t work in a web part.
So in a web part, you need to open a web and then you access the current user.

Below is an example (you just have to specify the “SiteToOpen”).

 

using (SPWeb webSite = SPContext.Current.Site.OpenWeb(SiteToOpen))
{
     //Determine who the current user is
        String currentUser = webSite.CurrentUser.Name;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Programmatically set url field on list

I had to find a way to programmatically add items to list that has a url field.
Here is an example of how to do it.
When you set the field that is an URL you have specify a url a coma (and a space) and the value to display.

 

using (SPWeb webSite = SPContext.Current.Site.OpenWeb(SiteToOpen))
{
       SPListCollection lists = webSite.Lists;
       SPList theLlist = webSite.Lists["listName"];
       string documentUrl = String.Empty;
       foreach (DocumentItems d in documents)
       {
            SPListItem listItem = theLlist.Items.Add();
             listItem["Title"] = "ItemTitle";
             listItem["Link"] = "URL" + ", " + "Display Value";
 
             listItem.Update();
        }
 }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

How to add a required field validator to a SharePoint web part.

You just have to set the ID property of the control, then set the control to validate to the ID of the control.

Below is an example

//Declare Controls
private TextBox _txtFirstName = new TextBox();
RequiredFieldValidator _rfvFirstName = new RequiredFieldValidator();

//Add text box
this._txtFirstName.ID = “txtFirstName”;
this.Controls.Add(_txtFirstName);

//Required field validator
_rfvFirstName.Text = “* First Name is required!”;
_rfvFirstName.Display = ValidatorDisplay.Dynamic;
_rfvFirstName.ControlToValidate = _txtFirstName.ID;
_rfvFirstName.ForeColor = Color.Red;
_rfvFirstName.ValidationGroup = “adduser”;
this.Controls.Add(_rfvFirstName);

[tweetmeme only_single=”false”]

Clear Controls on screen

Here is a method that will clear all the controls on your screen (as long as it matches one of the controls in the method).  It recursively calls itself until all the controls are clear.

Here is an example of how you call it:
ClearControlsOnScreen(this.Page);

  public void ClearControlsOnScreen(Control parent)
        {
            try
            {
                foreach (Control _ChildControl in parent.Controls)
                {
                    if ((_ChildControl.Controls.Count > 0))
                    {
                        ClearControlsOnScreen(_ChildControl);
                    }
                    else
                    {

                        TextBox textbox = _ChildControl as TextBox;
                        if (textbox != null)
                        {
                            textbox.Text = string.Empty;
                        }

                        DropDownList dropdownlist = _ChildControl as DropDownList;
                        if (dropdownlist != null)
                        {
                            dropdownlist.ClearSelection();
                        }

                        CheckBox checkBox = _ChildControl as CheckBox;
                        if (checkBox != null)
                        {
                            checkBox.Checked = false;
                        }

                        CheckBoxList checkBoxList = _ChildControl as CheckBoxList;
                        if (checkBoxList != null)
                        {
                            checkBoxList.ClearSelection();
                        }

                        GridView gridView = _ChildControl as GridView;
                        if (gridView != null)
                        {
                            gridView.DataSource = null;
                            gridView.DataBind();
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                throw ;
            }
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Run app as a specific user

Running an application as a specific user is common practice, but sometimes it’s helps to debug your application if you can run it as a specific user.

This does not change security context which the application runs as.
This works if you have your own user/role tables that control application security.

So if you add a key to your config file (web.config for example) then anytime you need to get the current user just call this method.

If the strUsername key is set to “Default” it will run as the current user.
If you set it to some other username it will return that username.

public static string GetUsername()
        {
            try
            {
                if (System.Configuration.ConfigurationManager.AppSettings["strUsername"].ToString() == "Default")
                {
                    return HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.IndexOf('\\') + 1).ToLower();
                }
                else
                {
                    return System.Configuration.ConfigurationManager.AppSettings["strUsername"].ToString();
                }
             }
            catch (Exception ex)
            {
                throw ;
            }
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }