Wednesday, 2 April 2014

Programmatically Create a New Task

The following code snippet can be used to programmatically create a new task.

 using (SPSite site = new SPSite("SiteUrl"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Tasks");
                    if (list != null)
                    {
                        // get the SharePoint group
                        SPUser user = web.EnsureUser(@"domain\administrator");

                        // Create a new task item
                        SPListItem task = list.Items.Add();
                        SPFieldUserValue assignToGroup = new SPFieldUserValue(web, user.ID, user.Name);
                        task["AssignedTo"] = assignToGroup;
                        task["Title"] = "Testing Tasks";
                        task["Description"] = "Testing Tasks";
                        task.ModerationInformation.Status = SPModerationStatusType.Approved;
                        task.Update();                    
                    }
                }
            }

Thursday, 27 March 2014

Find the assembly path in command line.


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")


SharePoint Rating Enable and Disable programmatically

The following code snippet can be used to SharePoint rating enable and disable programmatically.
 private static void EnableRatingSetting(SPList list)
        {
            SPFieldCollection allfields = list.Fields;
            SPFieldCollection availFields = list.ParentWeb.AvailableFields;
            if (!allfields.Contains(FieldId.AverageRatings))
            {
                SPField field = availFields[FieldId.AverageRatings];
                list.Fields.AddFieldAsXml(field.SchemaXmlWithResourceTokens, true, SPAddFieldOptions.AddFieldToDefaultView | SPAddFieldOptions.AddFieldInternalNameHint | SPAddFieldOptions.AddToAllContentTypes);
            }
            if (!allfields.Contains(FieldId.RatingsCount) && availFields.Contains(FieldId.RatingsCount))
            {
                SPField field2 = availFields[FieldId.RatingsCount];
                list.Fields.AddFieldAsXml(field2.SchemaXmlWithResourceTokens, false, SPAddFieldOptions.AddFieldInternalNameHint | SPAddFieldOptions.AddToAllContentTypes);
            }
            list.Update();
        }

   private static void DisableRatingSetting(SPList list)
        {
            SPField field1 = GetField(FieldId.AverageRatings, list.Fields);
            if (field1 != null)
            {
                list.Fields.Delete(field1.InternalName);
            }
            SPField field2 = GetField(FieldId.RatingsCount, list.Fields);
            if (field2 != null)
            {
                list.Fields.Delete(field2.InternalName);
            }
            list.Update();
        }
        private static SPField GetField(Guid id, SPFieldCollection fieldColl)
        {
            return fieldColl[id];
        }


Monday, 24 March 2014

Programmatically Column validations in SharePoint 2013

The following code snippet can be used to programmatically column validations.

using System;
using Microsoft.SharePoint;

namespace ValidationSettings
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            const string siteUrl = "SiteUrl";
            const string listName = "Custom List";
            FieldValidation(siteUrl, listName, "CID", "=AND([CID]<=50,[CID]>0)", "Please enter a value between 1-50.");
            FieldValidation(siteUrl, listName, "EmpId", "=EmpId=INT(EmpId)", "decimals are not allowed.");
            FieldValidation(siteUrl, listName, "EmpId", "=EmpId>10", "only EmpId greater than 10");
            FieldValidation(siteUrl, listName, "Phone", "=IF(LEN(Phone)>9,TRUE,FALSE)","length greater than 10 digits only");
            FieldValidation(siteUrl, listName, "CID", "=[CID]<> 00", "Restricts users not to give CID as 00");
            Console.ReadKey();
        }

        private static void FieldValidation(string siteUrl, string listName, string fieldName, string validationFormula,string validationMessage)
        {
            using (var spSite = new SPSite(siteUrl))
            {
                using (SPWeb spWeb = spSite.RootWeb)
                {
                    SPList customList = spWeb.Lists.TryGetList(listName);
                    if (customList != null)
                    {
                        var getListField = customList.Fields.GetField(fieldName) as SPFieldNumber;
                        if (getListField != null)
                        {
                            getListField.ValidationFormula = validationFormula;
                            getListField.ValidationMessage = validationMessage;
                            getListField.Update();
                            Console.WriteLine("Validation created in " + fieldName + "");

                        }
                        else
                        {
                            Console.WriteLine("Invalid Field Name");                          
                        }
                    }
                    else
                    {
                        Console.WriteLine("Invalid List Name");                    
                    }
                }
            }
        }
    }
}

Reference:
http://chakkaradeep.com/index.php/sharepoint-2010-list-improvements-column-validation-and-list-validation-settings/
http://adicodes.com/column-validations-and-list-validations-in-sharepoint-2010/

Saturday, 22 March 2014

Programmatically Backup and Restore in SiteCollection

The following code snippet can be used to programmatically backup the site collection.

     static void Main(string[] args)
        {
            var backupSiteUrl = "SiteUrl";
            var backupfilename = @"D:\\Backup\\SharePointSiteBackup_.bak";
            SiteBackup(backupSiteUrl, backupfilename);

        }
 public static void SiteBackup(string siteUrl, string fileName)
        {
            try
            {
                SPWebApplication webApplication = null;
                webApplication = SPWebApplication.Lookup(new Uri(siteUrl));
                SPSiteCollection sitecols = webApplication.Sites;
                string backupName = fileName;
                sitecols.Backup(siteUrl, backupName, true);             
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        } 



The following code snippet can be used to programmatically restore the site collection.

   static void Main(string[] args)
        {
            var restoreSiteUrl = "SiteUrl";
            var restoreBackupFile = "D:\\Backup\\SharePointSiteBackup_24-02-2014.bak";
            RestoreSite(restoreSiteUrl, restoreBackupFile);
        }

  private static void RestoreSite(string siteUrl, string fileName)
        {
            try
            {
                SPWebApplication webApplication = null;
                webApplication = SPWebApplication.Lookup(new Uri(siteUrl));
                SPSiteCollection sitecols = webApplication.Sites;
                sitecols.Restore("Teamsite", fileName, true);// overwrite sitecollection if already exists
                Console.WriteLine("Site collection restored successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

Enable Target Audience Field Programmatically

The following code snippet can be used to enable target audience field programmatically.

 using (SPSite site = new SPSite("SiteUrl"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Documents"];

                    XmlElement fldElement = new XmlDocument().CreateElement("Field");
                    fldElement.SetAttribute("ID", "61cbb965-1e04-4273-b658-eedaa662f48d");
                    fldElement.SetAttribute("Type", "TargetTo");
                    fldElement.SetAttribute("Name", "TargetTo");
                    fldElement.SetAttribute("DisplayName", "Target Audiences");
                    fldElement.SetAttribute("Required", "FALSE");

                    list.Fields.AddFieldAsXml(fldElement.OuterXml);
                    list.Update();
                }
            }

Friday, 21 March 2014

Retrieve ListItem data Using CAML in SharePoint 2013

The following code snippet can be used to programmatically retrieve list item data Using CAML

 SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists["Documents"];
            SPQuery query = new SPQuery();
            query.ViewFields = "<FieldRef Name='ID'/>" +"<FieldRef Name='Title'/>" + "<FieldRef Name='LastName'/>" +"<FieldRef Name='Age'/>";
            SPListItemCollection item = list.GetItems(query);
            GridView1.DataSource = item.GetDataTable();
            GridView1.DataBind();