Friday, 13 February 2015

Sharepoint Batch Add /Update List items using Object Model

Bulk Add/Update/ Delete Share point List Items

Bulk Adding :

#region [ Method : Batch Add List item details ]
        public void AddCanteenMenuDetails(string lstName, List<CanteenMenuDetails> objCanteenMenuDetails)
        {
            StringBuilder sbInsertCanteenMenu = new StringBuilder();
            sbInsertCanteenMenu.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList lstCanteenMenu = web.Lists.TryGetList(lstName);
                    bool allowUnsafeUpdates = web.AllowUnsafeUpdates;
                    web.AllowUnsafeUpdates = true;
                    web.Update();
                    foreach (CanteenMenuDetails item in objCanteenMenuDetails)
                    {
                        sbInsertCanteenMenu.AppendFormat("<Method ID=\"{0}\">" +
                                                "<SetList>{1}</SetList>" +
                                                "<SetVar Name=\"ID\">New</SetVar>" +
                                                "<SetVar Name=\"Cmd\">Save</SetVar>" +
                                                "<SetVar Name=\"{3}Title\">{2}</SetVar>" +
                                                "<SetVar Name=\"{3}Location\">{4}</SetVar>" +
                                                "<SetVar Name=\"{3}WeekDays\">{5}</SetVar>" +
                         "</Method>", item.Title, lstCanteenMenu.ID, item.Title, "urn:schemas-microsoft-com:office:office#", item.LocationID, item.WeekDays);
                    }
                    sbInsertCanteenMenu.Append("</Batch>");
                    web.ProcessBatchData(sbInsertCanteenMenu.ToString());
                    web.AllowUnsafeUpdates = allowUnsafeUpdates;
                    web.Update();
                }
            }
        }
        #endregion

Bulk Updating:

        #region [ Method : Batch Update List items details ]
        public void UpdateCanteenMenuDetails(string lstName, List<CanteenMenuDetails> objCanteenMenuDetails)
        {
            StringBuilder sbUpdateCanteenMenu = new StringBuilder();

            string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                  "<ows:Batch OnError=\"Return\">{0}</ows:Batch>";

            string methodFormat = "<Method ID=\"{0}\">" +
                         "<SetList>{1}</SetList>" +
                         "<SetVar Name=\"Cmd\">{2}</SetVar>" +
                         "<SetVar Name=\"ID\">{3}</SetVar>" +
                         "<SetVar Name=\"urn:schemas-microsoft-com:office:office#Breakfast\">{4}</SetVar>" +
                         "<SetVar Name=\"urn:schemas-microsoft-com:office:office#Lunch\">{5}</SetVar>" +
                         "<SetVar Name=\"urn:schemas-microsoft-com:office:office#Dinner\">{6}</SetVar>" +
                         "</Method>";

        
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    bool allowUnsafeUpdates = web.AllowUnsafeUpdates;
                    web.AllowUnsafeUpdates = true;
                    web.Update();
                    SPList lstCanteenMenu = web.Lists.TryGetList(lstName);
                    foreach (CanteenMenuDetails item in objCanteenMenuDetails)
                    {
                        sbUpdateCanteenMenu.AppendFormat(methodFormat, item.ID, lstCanteenMenu.ID.ToString(), "Save", item.ID, item.Breakfast,item.Lunch,item.Dinner);
                    }
                    //batch update script.   
                    string batchUpdateScript = string.Format(batchFormat, sbUpdateCanteenMenu.ToString());
                    web.ProcessBatchData(batchUpdateScript);
                    web.AllowUnsafeUpdates = allowUnsafeUpdates;
                    web.Update();
                }
            }

          
          
        }
        #endregion

Bulk Deleting :

 #region [Method : Batch Delete List item details ]
        public void DeleteCanteenMenu(string lstName, List<CanteenMenuDetails> objCanteenMenuDetails)
        {
            StringBuilder deletebuilder = new StringBuilder();
            deletebuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {

                    //SPSite site = SPContext.Current.Site;
                    //SPWeb web = site.OpenWeb();
                    bool allowUnsafeUpdates = web.AllowUnsafeUpdates;
                    web.AllowUnsafeUpdates = true;
                    web.Update();
                    SPList lstList = web.Lists.TryGetList(lstName);
                    if (lstList != null)
                    {

                        //  IEnumerable<SPListItem> lstItem = lstList.GetItems(query).OfType<SPListItem>();

                        string command = "<Method><SetList Scope=\"Request\">" + lstList.ID +
                            "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";
                        foreach (CanteenMenuDetails item in objCanteenMenuDetails)
                        {
                            deletebuilder.Append(string.Format(command, item.ID.ToString()));
                        }
                        deletebuilder.Append("</Batch>");
                        web.ProcessBatchData(deletebuilder.ToString());
                        web.Update();
                    }
                }
            }

        }
        #endregion

Tuesday, 20 January 2015

Adding Lists Programmatically in SharePoint

Developers often look for creating Custom Lists in SharePoint sites Programmatically.
Here is a sample code for creation of SharePoint Lists Programmatically
public void createSPList(string strListName)
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
    //Open your site
    SPSite site = new SPSite(Constants.strSiteURL);
    SPWeb web = site.OpenWeb();
    web.AllowUnsafeUpdates = true;
    SPListCollection lists = web.Lists;
    // create new Generic list
    lists.Add(strListName, "My Description", SPListTemplateType.GenericList);
    //Add Columns to SP List
    SPList newSPList = web.Lists[strListName];
    // create new column "User Name" and Field Type “Text”
    newSPList.Fields.Add("User Name", SPFieldType.Text, true);
    //creating lookup type column to this New List
    //Here I am getting information from the "Title" column from “Employee Roles” List
    SPList List2 = web.Lists["Employee Roles"];
    newSPList.Fields.AddLookup("Lookup Column", List2.ID, false);
    SPFieldLookup spLookup = (SPFieldLookup) newSPList.Fields["Lookup Column"];
    spLookup.LookupField = List2.Fields["Title"].InternalName;
    spLookup.Update();
    // Adding newly added column to default view
    SPView view = newSPList.DefaultView;
    view.ViewFields.Add("User Name");
    view.ViewFields.Add("Lookup Column");
    view.Update();
    newSPList.Update();
    web.AllowUnsafeUpdates = false;
    site.Dispose();
});
}



SharePoint List generation depends on the List Template type that we are specifying during list creation. one can create lists of type Custom Lists(Generic Lists), Document Library, Announcements, Picture Library, Tasks, Survey, Discussion Board, Contacts, Links, etc.

You can specify list template type in the below code highlighted

 lists.Add(strListName, "My Description", SPListTemplateType.GenericList);

Rating Scale in SharePoint Survey List Programmatically

In SharePoint Survey List, Rating scale is very easy to implement, set properties and use this in SharePoint. I found an easy way to implement this rating scale in SharePoint using coding in Feature activation.

When you are Creating a survey list programmatically, add this field to the SharePoint survey list.


Code:
//Adding Question to Survey List Programmatically with rating scale
strQuestionTitle = "Lecturer Skills";
StringCollection strQuestions = new StringCollection();
strQuestions.Add("Approachability");
strQuestions.Add("Availability");
strQuestions.Add("Share Knowledge");
strQuestions.Add("Motivate");
strQuestions.Add("Provide guidance");
objSurvey.Fields.Add(strQuestionTitle, SPFieldType.GridChoice, true, false, strQuestions);
//Updating Rating scale field properties
SPFieldRatingScale srs = objSurvey.Fields[strQuestionTitle] as SPFieldRatingScale;
srs.GridTextRangeLow = "Low";
srs.GridTextRangeHigh = "High";
srs.GridTextRangeAverage = "Avg";
srs.GridStartNumber = 1;
srs.GridEndNumber = 5;
srs.GridNAOptionText = "NA";
srs.Update();
//Updating survey list
objSurvey.Update();
 Hope this article is helpful and here ends your searching.

PowerShell Commands : Add, Install, Update, UnInstall, Delete WSP

Working with PowerShell Commands is very easy:

Copy your WSP file to an appropriate location e.g. C:\<foldername>

Launch PowerShell on the SharePoint server Start -> All Programs -> Microsoft SharePoint 2013 Products -> SharePoint 2013 Management Shell


Adding SharePoint WSP package using PowerShell command
To add a WSP package, you must use the following PowerShell command.

Add-SPSolution “<WSP package path>”
 

e.g.: Add-SPSolution “C:\testfile.wsp”
more info on : MSDN


Installing SharePoint WSP package using PowerShell command
To Install a WSP package, you must use the following PowerShell command.


Install-SPSolution -Identity “<wsp package name>” -WebApplication “<url of web application>” -GACDeployment
 

e.g.: Install-SPSolution -Identity “testfile.wsp” -WebApplication “http://localhost:11111” -GACDeployment
more info on : MSDN


Uninstalling SharePoint WSP package using PowerShell command
To uninstall a WSP package, you must use the following PowerShell command.

Uninstall-SPSolution -Identity “<wsp package name>” -WebApplication “<url of web application>”
 

e.g.: Uninstall-SPSolution -Identity “testfile.wsp” -WebApplication localhost:11111”
more info on : MSDN


Removing SharePoint WSP package using PowerShell command
To remove a WSP package, you must use the following PowerShell command.

Remove-SPSolution -Identity “<wsp package name>”
 
e.g.: Remove-SPSolution -Identity “testfile.wsp”

more info on : MSDN
 




Updating SharePoint WSP package using PowerShell command

To update a WSP package, you must use the following PowerShell command.

Update-SPSolution -Identity “<wsp package name>” -LiteralPath “<physical path of the wsp package>” -GacDeployment
 
e.g.: Update-SPSolution -Identity “testfile.wsp” -LiteralPath “C:\testfile.wsp” -GacDeployment

more info on : MSDN

Hope this article helped your search. Thank You.

Create User Friendly Time in SharePoint Programmatically using C#.NET.

        
/// <summary>
        /// Method used to Get the Datetime in User Friendly Date Format
        /// </summary>
        public static string GetUserFriendlyTime(DateTime dt, DateTime dtNowDate)
        {
            TimeSpan span = dtNowDate - dt;
            if (span.Days > 365)
            {
                int years = (span.Days / 365);
                if (span.Days % 365 != 0)
                    years += 1;
                return String.Format("about {0} {1} ago",
                years, years == 1 ? "year" : "years");
            }
            if (span.Days > 30)
            {
                int months = (span.Days / 30);
                if (span.Days % 31 != 0)
                    months += 1;
                return String.Format("about {0} {1} ago",
                months, months == 1 ? "month" : "months");
            }
            if (span.Days > 0)
                return String.Format("about {0} {1} ago",
                span.Days, span.Days == 1 ? "day" : "days");
            if (span.Hours > 0)
                return String.Format("about {0} {1} ago",
                span.Hours, span.Hours == 1 ? "hour" : "hours");
            if (span.Minutes > 0)
                return String.Format("about {0} {1} ago",
                span.Minutes, span.Minutes == 1 ? "minute" : "minutes");
            if (span.Seconds > 5)
                return String.Format("about {0} seconds ago", span.Seconds);
            if (span.Seconds <= 5)
                return "just now";
            return string.Empty;
        }

Wednesday, 19 November 2014

delete data from lists using power shell script in SharePoint

delete data from lists using power shell script

write-host "This will delete data, type YES to continue"
$retval = read-host
if ($retval -ne "YES")
{
    write-host "exiting - you did not type yes" -foregroundcolor green
    exit
}
write-host "continuing"

$web = get-spweb http://ggn-sp10:5555/
$list = $web.lists | where {$_.title -eq "ComplianceDetails"}
Write-host "List $($list.title) has $($list.items.count) entries"
$items = $list.items
foreach ($item in $items)
{
    Write-host "  Say Goodbye to $($item.id)" -foregroundcolor red
    $list.getitembyid($Item.id).Delete()
}

Sunday, 27 July 2014

Hiding SharePoint Ribbon Control from users

Hiding SharePoint Ribbon Control from users

Add this to the head section on master page.

<style type="text/css">
div#s4-ribbonrow {
display:none;
}
</style>

<Sharepoint:SPSecurityTrimmedControl runat="server"
Permissions="AddAndCustomizePages">
<style type="text/css">
div#s4-ribbonrow {
display:block;
}
</style>
</Sharepoint:SPSecurityTrimmedControl>



This should hide the ribbon control.