Showing posts with label list or library. Show all posts
Showing posts with label list or library. Show all posts

Monday, June 12, 2017

SharePoint List versioning using c#

We can also enable SharePoint List versioning using c#

using (SPSite spsite = new SPSite("http://win7/"))
{
SPWeb spweb = spsite.OpenWeb();
SPList list = spweb.Lists["CustomList"];
list.EnableVersioning = true;
list.Update();
}

Retrieve SPListItem versions using c#

using (SPSite spsite = new SPSite("http://win7/"))
{
SPWeb spweb = spsite.OpenWeb();
SPListItemCollection listitems = spweb.GetList("http://win7/Lists/CustomList").Items;

foreach (SPListItem listitem in listitems)
{
//listitem.Versions.RestoreByID(5);
foreach (SPListItemVersion versionItem in listitem.Versions)
{
Console.WriteLine("VersionId :" + versionItem.VersionId);
Console.WriteLine("VersionLabel :" + versionItem.VersionLabel);
Console.WriteLine("IsCurrentVersion :" + versionItem.IsCurrentVersion);
Console.WriteLine("ListItem.Title :" + versionItem.ListItem.Title);
Console.WriteLine("Created :" + versionItem.Created);
Console.WriteLine("CreatedBy :" + versionItem.CreatedBy);
Console.WriteLine("Level :" + versionItem.Level);
}
}
}

Retrieve SPListItem version changes using c#

using (SPSite spsite = new SPSite("http://win7/"))
{
SPWeb spweb = spsite.OpenWeb();
SPListItemCollection listitems = spweb.GetList("http://win7/Lists/CustomList").Items;

foreach (SPListItem listitem in listitems)
{
for (int i = 0; i < listitem.Versions.Count - 1; i++)
{
SPListItemVersion oldVersion = listitem.Versions[i];
SPListItemVersion latestVersion = listitem.Versions[i + 1];
foreach (SPField field in oldVersion.Fields)
{
if (field.ShowInVersionHistory == false)
{
continue;
}

if (latestVersion == null)
{
Console.WriteLine("  > {0} changed to \"{1}\"",
field.StaticName, oldVersion[field.StaticName]);
continue;
}

if (oldVersion[field.StaticName].Equals(latestVersion[field.StaticName]))
{
continue;
}

Console.WriteLine("  > {0} changed from \"{1}\" to \"{2}\"",
field.StaticName, latestVersion[field.StaticName], oldVersion[field.StaticName]);
}
}

}
}
Console.ReadLine();


Tuesday, May 16, 2017

DateTime control "Sorry, this site hasn't been shared with you"

We developed custom web part for SharePoint 2013 using Visual Studio 2012.
In web part we used SharePoint Date Time control. For some user after clicking calendar image its showing " "Sorry, this site hasn't been shared with you". For some users its working fine, all users having same permission.
DatePickerFrameUrl="<%$SPUrl:~sitecollection/_layouts/15/iframe.aspx %>"

<SharePoint:DateTimeControl ID="dtStartdate" runat="server"
DateOnly="true" DatePickerFrameUrl="<%
$SPUrl:~sitecollection/_layouts/15/iframe.aspx %>" />

SharePoint 2013 : How to Change Site Logo Programmatically using PowerShell?

Changing the logo is a basic  when it comes to branding SharePoint 2013 sites.

If you have more site collection in SharePoint ,hundred of site collection with subsites , go with sharepoint Powershell script

Get-SPWebApplication "http://sharepoint.crescent.com" | Get-SPSite -Limit "All" | Get-SPWeb -Limit "All" |  foreach { $_.SiteLogoUrl=""; $_.update(); Write-host "Changing Logo for:"$_.Url;  }

How to change a logo across all sites/sub-sites and pages?

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue 

$SiteURL = "http://Your-Site-Collection-URL" 
#Get the site collection
$Site = Get-SPSite $SiteURL #Iterate through each site in the site collection
 foreach($web in $Site.AllWebs)
 {
 #sharepoint change logo programmatically 
$web.SiteLogoUrl = "/relative-path-logo-file" 
$web.Update() 
}

This operation can be performed only on a computer that is joined to a server farm

 You need to update the web.config to show errors rather than giving the generic errors.  I typically use “RemoteOnly” I believe…
By the sounds of it, the user you used to install SharePoint doesn’t have the correct permissions on the database.
You should have a “farm” account and an “install” account.  
I typically have an “sp_admin” account which I use for general administration and installation.  Your farm account also has particular permissions.

Thursday, April 6, 2017

Listitem.Update vs ListItem.SystemUpdate


  • SPListItem.Update() is used to update all the values in SharePoint List Item including Modified Date, Modified By, Version fields

  • SPListItem.SystemUpdate() is used to update the values of the list item without modifying the Modified Date, Modified By and Version fields.

  • SPListItem.Update() . Event Receiver is fired in case if listitemupdated,listitemupdating  event is associated. 
  • SPListItem.SystemUpdate() Event Receiver won't be fired in case if list item updated, listitemupdating  event is associated

Wednesday, April 5, 2017

Fixed: Search Results not showing Document Titles

In this case  because the managed property ‘Title’ is mapped to crawled property ‘MetadataExtractorTitle’ by default at first priority .I have recreated the below issue my machine and I have provide the solution given below.


Go to Central Administration >Application Management> Manage service application and tried to modify the order of this crawled property and move it down.
Search Schema and search for managed property ‘Title.’ Now, inside the mappings of the managed property, you should be able to see the below attachment



Move the mapped crawled property ‘MetadataExtractorTitle’ down to the last position and save the managed property




Then reset the index,perform a full crawl against the content sources and refresh any cache associated with Site Collection.
Once the full crawl is complete, you should see the correct titles for documents in search results, as follows:



Hope It will works fine. 

Friday, March 31, 2017

How to determine the SharePoint version in PowerShell

# Add the snapin, in case it's not already installed
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$ver = (Get-PSSnapin microsoft.sharepoint.powershell).Version.Major
If ($ver -eq "15" )
    {
        Write-Output "SharePoint 2013 is installed"
        }
    elseif ($ver -eq "14")
    {
        Write-Output "SharePoint 2010 is installed"
        }
        else
        {
            Write-Output "Could not determine version of SharePoint"
            } 

Monday, March 27, 2017

Get Details of all fields associated with SharePoint List

$site = new-object Microsoft.SharePoint.SPSite("http://<Site URL>") #Change site URL#
    $web = $site.openweb()
    $list = $web.Lists["<List Name>"] #Get Field Details for specified list
   
    Write-Host "List Name: " $list.Title  ##Print List title
    Write-Host "------------------------------------------------------"
    Write-Host "Field Name | Field Title "
    Write-Host "------------------------------------------------------"        
   
    foreach ($field in $list.Fields) #Get all views in lists
    {
        Write-Host $field.Title " | " $field.Type -ForegroundColor Green #Write out each field (column)                        
       
    }  
    Write-Host "------------------------------------------------------"
    Write-Host " "

    $web.Dispose()
    $site.Dispose()

SharePoint: How to get Field details from list using PowerShell ?

In this article, we retrieved the particular list properties in SharePoint Site.

#Declare the variable for below functions
$SiteCollectionURL="https://sharepointonline.sharepoint.com/sites/mysite"
$listName="Project list"


function GetSPFieldDetailsForList($SiteCollectionURL, $listName)
{
    $site = new-object Microsoft.SharePoint.SPSite($SiteCollectionURL) #Change site URL#
    $web = $site.openweb()
    $list = $web.Lists[$listName] #Get Field Details for specified list
   
    foreach ($view in $list.Views) #Get all views in lists
    {
        $spView = $web.GetViewFromUrl($view.Url) #Grab views URL
        Write-Host "List Name: " $list.Title  ##Print List title
        Write-Host "------------------------------------------------------"
        Write-Host "Field Name | Field Title "
        Write-Host "------------------------------------------------------"
        foreach ($spField in $spView.ViewFields) #Loop through all view URLs and get Fields (columns)
        {
            foreach ($field in $list.Fields) #Get all fields in lists
            {
                if($spField -eq $field.Title) #if field in lists equals field in views
                {
                    Write-Host $spField " | " $field.Type -ForegroundColor Green #Write out each field (column)                      
                }
            }
        }
        Write-Host "------------------------------------------------------"
        Write-Host " "
    }  
    $web.Dispose()
    $site.Dispose()
}

GetSPFieldDetailsForAllLists

function GetSPFieldDetailsForAllLists($SiteCollectionURL)
{
    $site = new-object Microsoft.SharePoint.SPSite($SiteCollectionURL) #Change site URL#
    $web = $site.openweb()
   
    foreach ($list in $web.Lists) #Get all list in web
    {
        foreach ($view in $list.Views) #Get all views in lists
        {
            $spView = $web.GetViewFromUrl($view.Url) #Grab views URL
            Write-Host "List Name: " $list.Title  ##Print List title
            Write-Host "------------------------------------------------------"
            Write-Host "Field Name | Field Title " -ForegroundColor DarkGreen
            Write-Host "------------------------------------------------------"
            foreach ($spField in $spView.ViewFields) #Loop through all view URLs and get Fields (columns)
            {
                foreach ($field in $list.Fields) #Get all fields in lists
                {
                    if($spField -eq $field.Title) #if field in lists equals field in views
                        {
                            Write-Host $spField " | " $field.Type -ForegroundColor Green #Write out each field (column)                        
                        }
                }
            }
            Write-Host "------------------------------------------------------"
            Write-Host " "
        }
    }
    $web.Dispose()
    $site.Dispose()
}

Wednesday, August 10, 2016

jQuery SPServices get list guid

$().SPServices({
operation: "GetList",
listName: "GSMHelp",
async: false,
completefunc: function (xData, Status) {
alert($(xData.responseXML).find("List").attr("ID"));
}
});

Thursday, June 9, 2016

How can you move a document with its version history to a new library?

Tools:

 Lars Fastrup has created a tool that does just what you want: CopyMove for SharePoint
It also has a web service API.

2 document libraries
Both contain multiple documents
The documents have multiple versions
using objects like SPExport and SPImport

the copy, move actions of the content site and structure (sitemanagement.aspx) are performed using this API.

Current Limitations:

Document libraries should be in the same site.
Only default document library view is supported:
All views should have title.
All views should have summary toolbar.
All views should have the type and the name columns.
Only files with title can be moved.
You can’t drag folders or drop into folders.
Current Features:

Copy Operation has been added.
Folders are supported now.
Planned Features:

Delete Document by drag it to Recycle Bin.

Support Multiple Item Selection.

Document Library Vs Asset Library?



Asset Library is preconfigured to manage media content like images, audio and video files.
It has extra features over document library like Thumbnail view, Automatic metadata extraction for image files.
Document Library:

you can use it for sure to upload documents and use extra features that come with asset library.
Also you can add workflow and other features like versioning and everything that's possible in document library.
Only thing you need to do is to add new content types for Document and document set.

Wednesday, June 8, 2016

Unique Constraints Programmatically SharePoint

SPSite site = new SPSite("http://peakfinders");
SPWeb web = site.OpenWeb();

SPList custList = web.Lists["Employee"];
SPField vtid = custList.Fields["VoterID"];

vtid.Indexed = true;
vtid.EnforceUniqueValues = true;
custPhone.Update();

Enforcing Uniqueness in Column Values in SharePoint

Supported Column Types
Following is a list of column types that can be indexed and for which unique column constraints are supported:

  • Single line of text
  • Choice field (but not multichoice)
  • Number
  • Currency
  • Date/ Time
  • Lookup (but not multivalue)
  • Person or Group (but not multivalue)
  • Title (but not in a document library)


Unsupported Column Types

Following is a list of column types that cannot be indexed and for which unique column constraints are not supported:
  • Multiple lines of text
  • Hyperlink/Picture
  • Custom Field Types
  • Calculated Field
  • Boolean (yes/no)
  • Modified by
  • Modified time
  • UI version
  • Created time
  • Checked out to
  • Content type ID

How to check if a list template exists or not in SharePoint?

SPListTemplateCollection listColl = currentSite.GetCustomListTemplates(currentSite.RootWeb);

if (IsListTemplateExists(ListTemplateName, listColl )= true)
 {
 
     SPListTemplate listQuickLinksTemp = listColl [ListTemplateName];
     CreateList(currentWeb, ListName, "Description of the list", listQuickLinksTemp);
  }

Sub function:return true or false


public static bool IsListTemplateExists(string strListTemplateName, SPListTemplateCollection listTempColl)
  {
    bool isListTempExists = false;
    try {
      var temp = listTempColl.Cast().FirstOrDefault(x => x.Name.Equals(strListTemplateName));
      if (temp != null)
      isListTempExists = true;
     }
     catch (Exception ex)
     {
     
     }
   return isListTempExists;
  }

Delete a list programtically

Check for the specified list exists
AllowUnsafeUpdates 


urrentWeb.AllowUnsafeUpdates = true;
    if (IsListExists(strListName, currentWeb) == true)
    {
      SPList lst = currentWeb.Lists["Employee"];
      currentWeb.Lists.Delete(lst.ID);
    }
      currentWeb.AllowUnsafeUpdates = false;

Sharepoint LookUp field issue


Lookup fields one site to number of sites

list.ParentWeb.AllowUnsafeUpdates = true;
   if (list.Fields.ContainsField(fieldName))
   {                    
    SPFieldLookup field = (SPFieldLookup)list.Fields[fieldName];
    //check if the field link to the list is broken. 
    if (field.LookupList != targetList.ID.ToString())
    {
     //copy the schema from the field
     string newFieldXml = field.SchemaXml;
     string oldsourceid = field.LookupList;
     //put the ID of the current list as the source for the lookup
     field.SchemaXml = newFieldXml.Replace(oldsourceid, "{" + targetList.ID.ToString() + "}");
    }
   }
list.ParentWeb.AllowUnsafeUpdates = false;

Tuesday, June 7, 2016

Display attachments for each list item

$(document).ready(function() {
    $().SPServices({
        operation: "GetListItems",
        async: false,
        listName: "Repozytorium",
        /*CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",*/
        completefunc: function (xData, Status) {

            var output = "";
            $(xData.responseXML).SPFilterNode("z:row").each(function() {
                var id = $(this).attr("ows_ID");
                var title = $(this).attr("ows_Title");
                var liHtml = "<h5>"+title+"</h5>";
                $().SPServices({
                    async: false,
                    operation: "GetAttachmentCollection",
                    listName: "Repozytorium",
                    ID: id,
                    completefunc: function(xData, Status) {
                        liHtml += "<ul style='list-style: none;'>"; 
                        $(xData.responseXML).find("Attachments > Attachment").each(function(i, el) {
                            var $node = $(this),
                                    filePath = $node.text(),
                                    arrString = filePath.split("/"),
                                    fileName = arrString[arrString.length - 1];


                            liHtml += "<li><a href='"+ filePath +"' target='_blank'>" + fileName + "</a></li>";
                            //output += "<a href='" + filePath + "' target='_blank'>" + fileName + "</a><br />";

                        });
                        liHtml += "</ul>";


                    }
                });
                $("#drop-zone").append(liHtml);
            });

            //$("#drop-zone").html(output);
        }
    });
});