User Tools

Site Tools


notes:sharepoint2010:sputility

SPUtility

The following examples contains code snippets that use methods and properties from:

  • Microsoft.SharePoint.Utilities.SPUtility
  • Microsoft.SharePoint.Utilities.SPUrlUtility

Combine URLs:

// Example #1 - item URL
string itemUrl = SPUrlUtility.CombineUrl(siteUrl, myList.DefaultViewUrl);
 
// Example #2 - item properties URL
string itemPropertiesUrl = SPUrlUtility.CombineUrl(siteUrl, myList.DefaultDisplayFormUrl) + 
    "?id=" + myListItem.ID.ToString();

Obtain a query string parameter:

SPHttpUtility.UrlKeyValueDecode(Request.QueryString["MyParam"])

Redirect to a 'newUrl':

SPUtility.Redirect(newUrl, SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);

Convert a DateTime value to ISO8601 DateTime format (yyyy-mm-ddThh:mm:ssZ):

string now = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);

Send an email:

private void SendMail(SPWeb web, string from, string to, string subject, 
    string body, bool isBodyHtml, string cc, string bcc)
{
    try
    {
        StringDictionary headers = new StringDictionary();
        headers.Add("from", from);
        headers.Add("to", to);
        headers.Add("subject", subject);
        if (!String.IsNullOrEmpty(cc)) headers.Add("cc", cc);
        if (!String.IsNullOrEmpty(bcc)) headers.Add("bcc", bcc);
        headers.Add("content-type", "text/html");
 
        SPUtility.SendEmail(web, headers, body);
    }
    catch (Exception exc)
    {
        // ... log the exception
    }
}

Send an email using SmtpClient instead of SPUtility.SendEmail:

public void SendMail1(SPWeb web, string from, string to, string subject, 
    string body, bool isBodyHtml, string cc, string bcc)
{
    try
    {
        SmtpClient client = new SmtpClient();
        client.Host = web.Site.WebApplication.OutboundMailServiceInstance.Server.Address;
        MailMessage message = new MailMessage(from, to, subject, body);
        if (!String.IsNullOrEmpty(cc))
        {
            MailAddress addressCC = new MailAddress(cc);
            message.CC.Add(addressCC);
        }
        if (!String.IsNullOrEmpty(bcc))
        {
            MailAddress addressBcc = new MailAddress(bcc);
            message.Bcc.Add(addressBcc);
        }
        message.IsBodyHtml = isBodyHtml;
        client.Send(message);
    }
    catch (Exception exc)
    {
        // ... log the exception
    }
}

Check if the protocol (http, https, etc.) is allowed:

if (SPUrlUtility.IsProtocolAllowed(url))
{
    // ...
}
notes/sharepoint2010/sputility.txt · Last modified: 2016/10/19 by admin