Thursday, July 16, 2015

How to Get Outgoing E-Mail Settings Programatically

Sometimes it might be needed to get the Web Application outgoing emails settings programatically.
The below code snippet gives all the settings including Outbound SMTP server, From address, Reply-to address and Character set information.
using (SPSite site = new SPSite("http://siteurl"))
{
    SPWebApplication webApp = site.WebApplication;
    string outboundSMTPServer = webApp.OutboundMailServiceInstance.Parent.Name;
    string fromAddress = webApp.OutboundMailSenderAddress;
    string replyToAddress = webApp.OutboundMailReplyToAddress;
    int characterSet = webApp.OutboundMailCodePage;
}
Web application outgoing email settings can also be updated programatically as below.
using (SPSite site = new SPSite("http://siteurl"))
{
    string outboundSMTPServer = "Outbound SMTP server";
    string fromAddress = "From address";
    string replyToAddress = "Reply-to address";
    int characterSet = 65001; //Character set code

    SPWebApplication webApp = site.WebApplication;
    webApp.UpdateMailSettings(outboundSMTPServer,fromAddress,replyToAddress,characterSet);
}
Similarly we can get & set the Global outgoing email settings as below.
GET:
var globalAdmin = SPAdministrationWebApplication.Local;
var outboundSMTPServer = globalAdmin.OutboundMailServiceInstance.Parent.Name;
var fromAddress = globalAdmin.OutboundMailSenderAddress;
var replyToAddress = globalAdmin.OutboundMailReplyToAddress;
var characterSet = globalAdmin.OutboundMailCodePage;
SET:
string outboundSMTPServer = "Outbound SMTP server";
string fromAddress = "From address";
string replyToAddress = "Reply-to address";
int characterSet = 65001; //Character set code
var globalAdmin = SPAdministrationWebApplication.Local;
globalAdmin.UpdateMailSettings(outboundSMTPServer, fromAddress, replyToAddress, characterSet); 

Wednesday, July 15, 2015

SharePoint AutoComplete Lookup Field with JQuery

Created a Custom SharePoint Lookup field that offers new functionalities to default SharePoint lookup field by allowing Auto Complete or Type Ahead search functionality with Contains CAML query.
Below is a few of the features offered by AutoComplete Lookup field over standard SharePoint Lookup field:
  • Auto Complete or Type Ahead lookup search (queries after each typing)
  • OTB SharePoint Lookup Dropdown look and feel for the results 
  • Proper validations
  • Searches the lookup keyword with Contains CAML query
  • Configurable for No.of results to be displayed
  • Configurable for No.of characters to start the auto complete search
Limitations:
  • It cannot be multi-valuated
  • Only one AutoComplete Lookup field is allowed per list
  • The target lookup field is frozen and always the Title field
The project is packaged as a Windows installer using the SharePoint Solution installer; to install, simply run setup.exe. The software is available on CodePlex here.
AutoComplete Lookup - Create Column
AutoComplete Lookup - Configure Column
AutoComplete Lookup - Results Display

Please do let me know if you find any issues or bugs or useful enhancement that could be added.

Tuesday, July 14, 2015

Create Folder in SharePoint using REST

Here is the quick code snippet to create a folder in a Library or List using SharePoint REST.
var docLibraryName = "DocLibrary";
var folderName = "FolderTest";
var appWebUrl = "http://weburl";

var folderRelativePath = ''; //Populate with the path after folder creation to add files to folder
var folder = CreateFolder(appWebUrl, docLibraryName, folderName);
if (folder && folder.statusText && folder.statusText == 'Created') {
    if (folder.responseJSON && folder.responseJSON.d) {
        folderRelativePath = folder.responseJSON.d.ServerRelativeUrl;
    }
}

////Method to create a folder and returns folder object with metadata
CreateFolder = function (url, libraryname, foldername) {
    var folderRelPath = libraryname + '/' + foldername;
    var requestUri = url + "/_api/web/folders";
    var data = $.ajax({
        url: requestUri,
        type: "POST",
        async: false,
        data: JSON.stringify({ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': folderRelPath }),
        headers: {
            "accept": "application/json; odata=verbose",
            "content-type": "application/json; odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            alert('Folder created successfully.');
            return data;
        },
        error: function (error) {
            alert('Folder creation failed!');
            //alert(JSON.stringify(error));
            return data;
        }
    });
    return data;
}
Reference:
SharePoint REST Create Folder in Library
Creating Folder in Library using REST
REST Create Folder in SharePoint Library

Monday, July 13, 2015

SharePoint ListItem Update vs SystemUpdate vs UpdateOverwriteVersion

Here is a simple table format to explain the differences among Update vs SystemUpdate vs UpdateOverwriteVersion vs SystemUpdate(true). 

This information is pretty much useful to look at the differences between the following SPListItem methods when working with event receivers or workflows.


Update()
SystemUpdate()
SystemUpdate(true)
UpdateOverwriteVersion()
Updates the item in the database
ü  
ü  
ü  
ü  
Creates a new version
ü  
û   
ü  
û   
Updates the Modified and Modified By values
ü  
û   
û   
ü  

How to update Modified By field in a SharePoint list item programatically

While adding/updating a list item using SPSecurity.RunWithElevatedPrivileges with administrator privileges, Created By / Modified By fields are set to System Account as the piece of code is executed with Application Pool account context.

But in an ideal case Created By / Modified By fields should have the original user who actually did the modification. In order to achieve this Created By / Modified By fields needs to be updated at the time of inserting / updating list item.

The catchy point here is to get the Current User out of the SPSecurity.RunWithElevatedPrivileges scope because within the scope it is always System Account as mentioned.

The below code snippet works as as explained above:
////Get the current user out of the SPSecurity.RunWithElevatedPrivileges scope
SPUser currentUser = SPContext.Current.Web.CurrentUser;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite newSite = new SPSite("http://siteurl"))
    {
        using (SPWeb newWeb = newSite.OpenWeb())
        {
            SPList list = newWeb.Lists.TryGetList("List Title");
            if (null != list)
            {
                bool isNewItem = true; //Adding or Updating item
                SPListItem item = list.GetItemById(1);
                if (isNewItem)
                {
                    item["Author"] = currentUser;
                }
                item["Editor"] = currentUser;

                item.Update();
            }
        }
    }
});

Reference:
How to update Modified By field programatically
How to update Created By field programatically
SharePoint List Item update Modified By field programatically
SharePoint List Item update Created By field programatically