Saturday, December 29, 2012

SHAREPOINT 2013 – USING “JS LINK”


SharePoint 2013 has a lot new features and functionalities that it can do OOB.
One of these new functionalities is the "JS Link" web part property. With this property you are able to control the rendering of the web part.

This will mostly be used in combination with List/Data View Web Part. So, no more server side XSLT rendering (XSL Link), just client side JavaScript (JS Link).
There is the link to MSDN

Monday, December 17, 2012

Cross Site Content - it's coming in SharePoint 2013

As a lot of programmers who had a problem with cross-site content:how to show data from another site collection,another web application or another farm. All of us can search the internet and find solutions (3rd party, code implementation, etc...). In SharePoint 2013 this problem will be resolved by Cross-Site Publishing. On the official blog of the Microsoft SharePoint Product Group says that the new XSP aggregates a data by the search-based publishing model and a content can be shared across site collections, web apps, and farms. The new concept which introduced in SharePoint 2013 allows to publish lists, libraries, search catalog or variation data. More information is here.

Wednesday, December 12, 2012

Error occurred in deployment step ‘Recycle IIS Application Pool’: The communication object, System.ServiceModel.InstanceContext, cannot be used for communication because it has been Aborted.

The Problem :

"Error occurred in deployment step ‘Recycle IIS Application Pool: The communication object, System.ServiceModel.InstanceContext, cannot be used for communication because it has been Aborted."

The Solution:

Restart  Visual Studio 2010 and the problem should be resolved.

Wednesday, October 31, 2012

Adding a footer to SharePoint v4 MasterPage

I have a simple customized v4 Master Page.
I tried to use "footer" tag to make my footer at bottom of the page.
This is the solution:

This is Contoso Site - Copyright© 2012 Contoso - All Rights Reserved.

Sunday, September 23, 2012

Select custom ribbon tab - jQuery

    I created custom ribbon tab and a button on a page. When  a user press the button on the page, I needed to focus him to the custom ribbon tab. Of course, I used 
_ribbonStartInit("Ribbon.CustomTab", false, null);

but the problem is, after a user changes it to another tab, i.e. "Read" or "Browse" the second pressing doesn't work. Therefore, the solution was - adding SelectRibbonTab() function:

$('img.CustomTabButtonClass').bind('click', function() { 
    
  if (typeof(_ribbonStartInit) == "function")
   {
     try 
     {
       _ribbonStartInit("Ribbon.CustomTab", false, null);
     }
     catch(e)
       {
                  
        }
     SelectRibbonTab("Ribbon.CustomTab", true);
    }
    });

Tuesday, September 11, 2012

CSS: Cursor hand not working in chrome, firefox

The problem is  - cursor "hand" is not a supported style in browsers other than IE.
Instead of it need to use :
cursor: "pointer"

The vertical scrolling bar doesn't work in Chrome browser

Like most of us, I faced this problem when scroll bar doesn't work in Chrome.
After googling, the solution was a jQuery script which I inserted to the master page:



Sunday, August 12, 2012

Create List Definition for Picture Library - C#


If you want to do it in Visual Studio, you're unable to see this definition in the drop down list. However it is very easy to do it:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint; 

namespace Console
{
    class Program
    {
        string listName = "Picture Library";
        string description = "My  Picture Library "; 

        public static void Main(string[] args)
        {
            using (SPSite oSite = new SPSite("http://contoso.com"))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (oWeb.Lists.TryGetList(listName) != null)
                    {
                        // SPListTemplate class - Used to represent the list definition or a list template 
                        // oWeb.ListTemplates - Used to get the "Picture Library" list template
      
                        SPListTemplate oTemplate = oWeb.ListTemplates["PictureLibrary"];

                        //Creates a new list with Title, Descrription and List Template "Picture Library" type

                        oWeb.Lists.Add(listName, description, oTemplate);
                    }
                    else
                    {
                        System.Console.WriteLine(listName + " already exists in the " + oWeb.Title + " site");
                        System.Console.ReadLine();
                    }
                }
            }
        }
    }
}

Wednesday, August 8, 2012

Add Title to Social Comments - jQuery

To insert some title or another text to social comments on a page:
You can resolve it by jQuery code:


  $(document).ready(function () {

            var socomHolders = $('div [id*="_socomHolder_"]');
            if (socomHolders.length) {

                socomHolders.each(function () {

                    var phName = $(this).attr('id');
                    var index = phName.substring(phName.lastIndexOf('socomHolder') + 
                        12, phName.length);

                    var socomContent = $('div [id*="_socomContents_' + index +'"]');
                    var newRow = $("Example : "+ index +"");
                    $(".ms-socialCommentItem", socomContent).prepend(newRow);
                });
            }
        });


Tuesday, July 31, 2012

How to know if the Page is in Edit Mode - C#

For a page we need to use:
if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Display)
  {
   //  display mode
  }
  else // Microsoft.SharePoint.SPContext.Current.FormContext.FormMode = SPControlMode.Edit
  {
   //  edit mode
  }



and for webpart pages:

   WebPartManager mgr = this.WebPartManager;
 if (mgr.DisplayMode == WebPartManager.EditDisplayMode)
     {
        // edit mode
     }
  else
     {
  //  display mode
     }

How to know if the Page is in Edit Mode - JavaScript ?

For a page we need to use:

var pageMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;

if (pageMode == 1)
{
// page is in edit mode
}
else
{
// page is in browse mode
}



and for wiki pages:



var pageMode = document.forms[MSOWebPartPageFormName]._wikiPageMode.value;

if (pageMode == "Edit")
{
// page is in edit mode
}
else
{
// page is in browse mode
}



This will refer to a value of the following html input control, which is rendering on the page when it is in edit mode:






Monday, July 30, 2012

Page Layout issue - Show/Hide fields in Display/Edit Mode

If you want to hide/display fields in edit/display mode on your page layout , you can do it by adding publishingwebcontrols:editmodepanel tag.




Put your fields here


or



Put your fields here

Thursday, July 12, 2012

The same client browser session has made '6' requests in the last '11' seconds.

After the configuration of ADFS v2 to SharePoint 2010 and
when I tried to login, I found at myself that after I authenticate to ADFS, get caught up in this endless loop where go back and forth between SharePoint and ADFS.
In Fiddler it turns out that I are authenticating successfully to ADFS, I am coming back to SharePoint and it is successfully issuing the FedAuth cookie,
it redirects you to /_layouts/authenticate.aspx on the SharePoint site which clears out the FedAuth cookie and redirects me back to the ADFS site.
I basically ping pong back and forth until ADFS stops it .

In Event Viewer of ADFS Server :



I saw the exception:



Exception details:
Microsoft.IdentityServer.Web.InvalidRequestException: MSIS7042: The same client browser session has made '6' requests in the last '11' seconds. Contact your administrator for details.
at Microsoft.IdentityServer.Web.FederationPassiveAuthentication.UpdateLoopDetectionCookie()
at Microsoft.IdentityServer.Web.FederationPassiveAuthentication.SendSignInResponse(MSISSignInResponse response)



That’s because the default LogonTokenCacheExpirationWindow for the SharePoint STS is 10 minutes. In this case when I created my relying party by default it sets the token lifetime in ADFS to be 2 minutes, so as soon as it authenticated it knew the cookie was good for less time than the LogonTokenCacheExpirationWindow value. Therefore it went back to ADFS to authenticate again. And so it went, back and forth. So I needed to change the LogonTokenCacheExpirationWindow to be less than the SAML TokenLifetime.

The solution is PowerShell Script:







$sts = Get-SPSecurityTokenServiceConfig
$sts.LogonTokenCacheExpirationWindow = (New-TimeSpan –minutes 1)
$sts.Update()
iisreset

Tuesday, July 10, 2012

The workbook cannot be opened



This is error I received on any excel file, which I tried to open in browser by Office Web Apps.

The solution was granting permissions to the service account for Excel Services.
The PowerShell script, which invokes the SPWebApplication.GrantAccessToProcessIdentity method helps to solve it:



Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0

$webApp = Get-SPWebApplication "http://contoso.com"

$webApp.GrantAccessToProcessIdentity("CONTOSO\spExcelServiceApp")

Monday, July 9, 2012

Create and Retrieve a Social Comment - C#

The SocialCommentManager object enables you to create a social comment for any specified URL. This topic demonstrates how to use the SocialCommentManager to create and retrieve social comments in a custom application.

Creating Social Comments using c#:


using (SPSite site = new SPSite("http://contoso"))
{
SPServiceContext context = SPServiceContext.GetContext(site);
SocialCommentManager mySocialCommentManager = new SocialCommentManager(context);
mySocialCommentManager.AddComment(new Uri("My URL"), “My Comment”);
}



Retrieving Social Comments using c#:


public class PageComments
{
public string Comment { get; set; }
public UserProfile CommentOwner { get; set; }
public DateTime CommentDate { get; set; }
}


public class GetCommentsClass
{

public PageComments GetCommentsByPage(SPListItem item,int prevDates)
{
PageComments pc = new PageComments();

SocialCommentManager mySocialCommentManager = new SocialCommentManager(context);
SocialComment[] comments = mySocialCommentManager.GetComments(new Uri(Site + "/" + item.File.Url));

foreach (SocialComment comment in comments)
{
if (comment.LastModifiedTime.ToLocalTime().CompareTo(DateTime.Now.AddDays(previousDates)) >= 0)
{
pc.Comment = comment.Comment;
pc.CommentDate = comment.LastModifiedTime;
pc.CommentOwner = comment.Owner;

}
}

return pc;
}
}


Thursday, June 28, 2012

Unable to authorize to SharePoint 2010 on Android phone

The default browser of Android Devices blocks the Authentication popup window of SharePoint 2010. Therefore when you try to get in the your site, you receive "401 Unauthorized error".

The easy way to resolve it : download Firefox browser on your phone, which officially supported by Microsoft for SharePoint 2010. Firefox supports SharePoint’s login popup and allows you to login to your site!

You can download it by Play Store of Android or by QR Code :


QRCode

Sunday, June 24, 2012

New CAML Designer is released !

All of us know U2U CAML Builder and all of us encountered on bugs of it.
So, Karine Bosch noticed on release of new version of CAML Designer.

I hope it will help us - SharePoint Developers




Monday, June 18, 2012

SharePoint 2010 - Creating a Anonymous Web Applications By PowerShell

I found a blog, there are scripts for creating Farm, Web Application, Site Collection: http://blog.brianbeach.com (all credits to Brian). I want to write it here, like a reminder for myself. In addition, I think that the sharing knowledge is a best way to help to each other.

AnonymousState determines if anonymous users have access to the site collection as follows:

  • A "0" disables anonymous access. In other words, anonymous users have no access to a Web site.
  • A "1" allows default anonymous access. This specifies that anonymous users can access lists and libraries if the lists and libraries allow anonymous access.
  • A "2" specifies that anonymous users can access the entire Web site.
AnonymousPermMask allows you to control granular permissions. The values of the mask (taken directly from the source code) are:

  • ViewListItems = View items in lists, documents in document libraries, and view Web discussion
  • AddListItems = items to lists, add documents to document libraries, and add Web discussion
  • EditListItems = Edit items in lists, edit documents in document libraries, edit Web discussion comments in documents, and customize Web Part Pages in document libraries.
  • DeleteListItems = Delete items from a list, documents from a document library, and Web discussion comments in documents.
  • ApproveItems = Approve a minor version of a list item or document.
  • OpenItems = View the source of documents with server-side file handlers.
  • ViewVersions = View past versions of a list item or document.
  • DeleteVersions = Delete past versions of a list item or document.
  • CancelCheckout = Discard or check in a document which is checked out to another user.
  • ManagePersonalViews = Create, change, and delete personal views of lists.
  • ManageLists = Create and delete lists, add or remove columns in a list, and add or remove public views of a list.
  • ViewFormPages = View forms, views, and application pages, and enumerate lists.
  • Open = Allow users to open a Web site, list, or folder to access items inside that container.
  • ViewPages = View pages in a Web site.
  • AddAndCustomizePages = Add, change, or delete HTML pages or Web Part Pages, and edit the Web site using a Windows SharePoint Services–compatible editor.
  • ApplyThemeAndBorder = Apply a theme or borders to the entire Web site.
  • ApplyStyleSheets = Apply a style sheet (.css file) to the Web site.
  • ViewUsageData = View reports on Web site usage.
  • CreateSSCSite = Create a Web site using Self-Service Site Creation.
  • ManageSubwebs = Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.
  • CreateGroups = Create a group of users that can be used anywhere within the site collection.
  • ManagePermissions = Create and change permission levels on the Web site and assign permissions to users and groups.
  • BrowseDirectories = Enumerate files and folders in a Web site using Microsoft Office SharePoint Designer 2007 and WebDAV interfaces.
  • BrowseUserInfo = View information about users of the Web site.
  • AddDelPrivateWebParts = Add or remove personal Web Parts on a Web Part Page.
  • UpdatePersonalWebParts = Update Web Parts to display personalized information.
  • ManageWeb = Grant the ability to perform all administration tasks for the Web site as well as manage content. Activate, deactivate, or edit properties of Web site features through the object model or through the user interface (UI). When granted on the root Web site of a site collection, activate, deactivate or edit properties of site collection scoped Features through the object model. To browse to the Site Collection Features page and activate or deactivate site collection scoped Features through the UI, you must be a site collection administrator.
  • UseClientIntegration = Use features that launch client applications; otherwise, users must work
  • UseRemoteAPIs = Use SOAP, WebDAV, or Microsoft Office SharePoint Designer 2007 interfaces to access the Web site.
  • ManageAlerts = Manage alerts for all users of the Web site.
  • CreateAlerts = Create e-mail alerts.
  • EditMyUserInfo = Allows a user to change his or her user information, such as adding a picture.
  • EnumeratePermissions = Enumerate permissions on the Web site, list, folder, document, or list item.




$WebAppURL = "http://www.brianbeach.com"
$HostHeader = "www.brianbeach.com"
$WebAppName = "Anonymous Web Application"
$ContentDatabase = "Content_Anonymous_Default"
$AppPoolName = "Anonymous Content"
$AppPoolUserName = "DOMAIN\USER_NAME"

Write-Host "Creating the anonymous web application"
$AppPoolCred = Get-Credential $AppPoolUserName
$AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCred
$AuthProvider = New-SPAuthenticationProvider -AllowAnonymous
$WebApp = New-SPWebApplication -AllowAnonymousAccess -ApplicationPool $AppPoolName -ApplicationPoolAccount $AppPoolAccount -Name $WebAppName -URL $WebAppURL -HostHeader $HostHeader -Port 80 -AuthenticationProvider $AuthProvider -DatabaseName $ContentDatabase


$SiteName = "Anonymous Root Site"
$OwnerEmail = "USER_NAME@DOMAIN.com"
$OwnerAlias = "DOMAIN\USER_NAME"
$SiteURL = "http://www.brianbeach.com"

Write-Host "Creating a default site collection in the anonymous web application"
New-SPSite -Url $SiteURL -owneralias $OwnerAlias -ownerEmail $OwnerEmail -Template "STS#0"
$Web = Get-SPWeb $SiteURL
$Web.title = $SiteName
$Web.AnonymousState = 2;
$Web.AnonymousPermMask64 = "ViewListItems, ViewVersions, ViewFormPages, Open, ViewPages, UseClientIntegration, AddListItems"
$Web.update()

SharePoint 2010 - Creating a Site Collections By PowerShell

I found a blog, there are scripts for creating Farm, Web Application, Site Collection: http://blog.brianbeach.com (all credits to Brian). I want to write it here, like a reminder for myself. In addition, I think that the sharing knowledge is a best way to help to each other.

List of common templates:
  • STS#0 - Team Site
  • STS#1 - Blank Site
  • STS#2 - Document Workspace
  • MPS#0 - Basic Meeting Workspace
  • MPS#1 - Blank Meeting Workspace
  • MPS#2 - Decision Meeting Workspace
  • MPS#3 - Social Meeting Workspace
  • MPS#4 - Multipage Meeting Workspace
  • WIKI#0 - Wiki
  • BLOG#0 – Blog


  • $SiteName = "Human Resources Site"
    $OwnerEmail = "USER_NAME@DOMAIN.com"
    $OwnerAlias = "DOMAIN\USER_NAME"
    $SiteURL = "http://intranet.DOMAIN.com/sites/hr"
    $SiteTemplate = "STS#0"

    Write-Host "Creating a relative site collection in the intranet web application"
    New-SPSite -Url $SiteURL -owneralias $OwnerAlias -ownerEmail $OwnerEmail -Template $SiteTemplate
    $Web = Get-SPWeb $SiteURL
    $Web.title = $SiteName
    $Web.update()



    $WebAppURL = "http://intranet.DOMAIN.com"
    $ContentDatabase = "Content_Intranet_BLOG"

    Write-Host "Creating a new content database in the intranet web application"
    New-SPContentDatabase $ContentDatabase -WebApplication $WebAppURL

    $SiteName = "Intranet Blog"
    $OwnerEmail = "USER_NAME@DOMAIN.com"
    $OwnerAlias = "DOMAIN\USER_NAME"
    $SiteURL = "http://intranet.DOMAIN.com/sites/blog"
    $SiteTemplate = "BLOG#0"

    Write-Host "Creating a relative site collection in the intranet web application with a separate content database"
    New-SPSite -Url $SiteURL -owneralias $OwnerAlias -ownerEmail $OwnerEmail -ContentDatabase $ContentDatabase -Template $SiteTemplate
    $Web = Get-SPWeb $SiteURL
    $Web.title = $SiteName
    $Web.update()



    $SiteName = "Intranet WIKI"
    $OwnerEmail = "USER_NAME@DOMAIN.com"
    $OwnerAlias = "DOMAIN\USER_NAME"
    $WebAppURL = "http://intranet.DOMAIN.com"
    $SiteURL = "http://wiki.DOMAIN.com"
    $SiteTemplate = "WIKI#0"

    Write-Host "Creating a hostheader site collection in the intranet web application"
    $WebApp = Get-SPWebApplication $WebAppURL
    New-SPSite -url $SiteURL -HostHeaderWebApplication $WebApp -owneralias $OwnerAlias -ownerEmail $OwnerEmail -Template $SiteTemplate
    $Web = Get-SPWeb $SiteURL
    $Web.title = $SiteName
    $Web.update()

    $WebAppName = "Intranet Web Application"
    $HostHeader = "wiki.DOMAIN.com"

    Import-Module WebAdministration
    New-WebBinding -Name $WebAppName -Port 80 -Protocol "http" -HostHeader $HostHeader

    SharePoint 2010 - Creating a Web Application By PowerShell

    I found a blog, there are scripts for creating Farm, Web Application, Site Collection: http://blog.brianbeach.com (all credits to Brian). I want to write it here, like a reminder for myself. In addition, I think that the sharing knowledge is a best way to help to each other.

    $WebAppURL = "http://intranet.DOMAIN.com"
    $HostHeader = "intranet.DOMAIN.com"
    $ContentDatabase = "Content_Intranet_Default"
    $WebAppName = "Intranet Web Application"
    $AppPoolName = "Intranet Content"
    $AppPoolUserName = "DOMAIN\SERVICE_ACCOUNT"

    Write-Host "Creating the intranet web application"
    $AppPoolCred = Get-Credential $AppPoolUserName
    $AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCred
    $AuthProvider = New-SPAuthenticationProvider
    $WebApp = New-SPWebApplication -ApplicationPool $AppPoolName -ApplicationPoolAccount $AppPoolAccount -Name $WebAppName -URL $WebAppURL -HostHeader $HostHeader -Port 80 -AuthenticationProvider $AuthProvider -DatabaseName $ContentDatabase


    $SiteName = "Intranet Root Site"
    $OwnerEmail = "USER_NAME@DOMAIN.com"
    $OwnerAlias = "DOMAIN\USER_NAME"
    $SiteURL = "http://intranet.DOMAIN.com"
    $SiteTemplate = "STS#1"

    Write-Host "Creating a default site collection in the intranet web application"
    New-SPSite -Url $SiteURL -owneralias $OwnerAlias -ownerEmail $OwnerEmail -Template $SiteTemplate
    $Web = Get-SPWeb $SiteURL
    $Web.title = $SiteName
    $Web.update()

    SharePoint 2010 - Creating the Farm By PowerShell

    I found a blog, there are scripts for creating Farm, Web Application, Site Collection: http://blog.brianbeach.com (all credits to Brian). I want to write it here, like a reminder for myself. In addition, I think that the sharing knowledge is a best way to help to each other.




    Add-PSSnapin Microsoft.SharePoint.Powershell -EA 0
    Clear-Host

    $FarmAccountName = "DOMAIN\SERVICE_ACCOUNT"
    $Passphrase = "PASSWORD"
    $DatabaseServer = "DATABASE_SERVER_NAME"
    $ConfigDatabase = "Config"
    $ContentDatabase = "Content_Admin"

    Write-Host "Creating Configuration Database"
    $FarmAccount = Get-Credential $FarmAccountName
    $Passphrase = (ConvertTo-SecureString $Passphrase -AsPlainText -force)
    New-SPConfigurationDatabase -DatabaseServer $DatabaseServer -DatabaseName $ConfigDatabase -AdministrationContentDatabaseName $ContentDatabase -Passphrase $Passphrase -FarmCredentials $FarmAccount

    Write-Host "Configuring Farm"
    Initialize-SPResourceSecurity
    Install-SPService
    Install-SPFeature -AllExistingFeatures

    Write-Host "Configuring Central Administration"
    New-SPCentralAdministration -Port 8080 -WindowsAuthProvider NTLM
    Install-SPHelpCollection -All
    Install-SPApplicationContent



    How to delete the deployed Event Receiver in Sharepoint server 2010 By C#

    I took it from this article




    private void DeleteEventReceiverFromAList(string siteUrl)
    {
    using (SPSite site = new SPSite(siteUrl))
    {
    using(SPWeb web = site.OpenWeb())
    {
    try
    {
    SPList list = web.Lists["myList"];
    if (list != null)
    {
    string className = "EventReceiverClass";
    string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1111111111111111";
    web.AllowUnsafeUpdates = true;
    int receivers = list.EventReceivers.Count;
    bool isAddedReceiverExist = false;
    bool isUpdatedReceiverExist = false;
    for (int i = 0; i < receivers; i++)
    {
    SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
    if (eventReceiver.Class == className && eventReceiver.Type == SPEventReceiverType.ItemAdded)
    {
    eventReceiver.Delete();
    break;
    }
    }
    }
    }
    catch { }
    finally
    {
    web.AllowUnsafeUpdates = false;
    }
    }
    }
    }

    How to delete the deployed Event Receiver in Sharepoint server 2010 - PowerShell

    I took it from this article

    $spWeb = Get-SPWeb -Identity http://contoso.com

    $spList = $spWeb.Lists["My List Name"]
    $eventsCount = $spList.EventReceivers.Count
    $assembly = "Project.Name.Class, Version=1.0.0.0, Culture=neutral, PublicKeyToken=11111111111"
    $class = "Namespace.MyClass.ClassName"
    $type = 10002
    $name = "My Event Name"
    for ($i = 0; $i -lt $eventsCount; $i+=1)
    {
    if ($spList.EventReceivers[$i].Assembly -eq
    $assembly
    -and
    $spList.EventReceivers[$i].Class -eq $class
    -and
    $spList.EventReceivers[$i].Type -eq $type
    -and $spList.EventReceivers[$i].Name -eq
    $Name)
    {
    $spList.EventReceivers[$i].Delete()
    }
    }
    $spList.Update()

    Tuesday, June 12, 2012

    Read SPListItemVersion in SharePoint 2010

    SPListItemVersion Class return the collection of versions for a list item. If versioning is enabled on a list, each time you modify an item a version is created.

    Enable SharePoint List versioning using c#:


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



    Retrieve SPListItem versions using c#:


    public  class PageVersions
    {
    public string PageVersion { get; set; }
    public SPUser PageVersionOwner { get; set; }
    public DateTime PageVersionDate { get; set; }
    }

    public class GetVersionsClass
    {

    public PageVersions CalculateVersionPoints(SPListItem item,int prevDates)
    {
    PageVersions pv = new PageVersions();

    SPListItemVersionCollection oVersionInfo = item.Versions;

    foreach (SPListItemVersion oVersion in oVersionInfo)
    {
    if (oVersion.Level == SPFileLevel.Published)
    {



    if (oVersion.Created.ToLocalTime().CompareTo(DateTime.Now.AddDays(prevDates)) >= 0)
    {
    pv.PageVersion = oVersion.VersionId.ToString();
    pv.PageVersionDate = oVersion.Created;
    pv.PageVersionOwner = oVersion.CreatedBy.User;

    }

    }
    }

    return pv;
    }
    }


    Monday, June 11, 2012

    Custom Style and Slots in Content Query Web Part (CQWP)


    The CQWP allows us to modify or create new styles which help to show custom data.
    In addition by Slots we can use custom parameters and show custom fields.

    For example:










    1.Open CQWP in notepad or VS

    2.Find "CommonViewFields"

    3.Add custom columns:


    Role, Text
    Action, Text
    Responsibility, Text




    4.Open SharePoint Designer and CheckOut of:

    /Style Library/XSL Style Sheets/ItemStyle.xsl

    5.Insert our new template or modify old one:






















    _blank








    <tr style="background-color:#f7f3f7;color:#848284">
    <td style="font-size:12px;color:black" valign="top">Role</td>
    <td style="font-size:12px;color:black" valign="top">Action</td>
    <td style="font-size:12px;color:black" valign="top">Responsibility</td>
    </tr>























    Thursday, June 7, 2012

    New feature of .NET Framework 4.5 - Await

    Most of us , who uses Silverlight Client Object Model has encountered with the problems of asynchronous programming by the Microsoft blog : Async in 4.5: Worth the Await.
    I just took a piece of code from this blog, to show how it makes our lives easier :)

    Synchronous example:


    public static void CopyTo(Stream source, Stream destination)
    {
    byte[] buffer = new byte[0x1000];
    int numRead;
    while((numRead = source.Read(buffer, 0, buffer.Length)) > 0)
    {
    destination.Write(buffer, 0, numRead);
    }
    }


    Asynchronous Programming Model:


    public static IAsyncResult BeginCopyTo(Stream source, Stream destination)
    {
    var tcs = new TaskCompletionSource();

    byte[] buffer = new byte[0x1000];
    Action readWriteLoop = null;
    readWriteLoop = iar =>
    {
    try
    {
    for (bool isRead = iar == null; ; isRead = !isRead)
    {
    switch (isRead)
    {
    case true:
    iar = source.BeginRead(buffer, 0, buffer.Length, readResult =>
    {
    if (readResult.CompletedSynchronously) return;
    readWriteLoop(readResult);
    }, null);
    if (!iar.CompletedSynchronously) return;
    break;

    case false:
    int numRead = source.EndRead(iar);
    if (numRead == 0)
    {
    tcs.TrySetResult(true);
    return;
    }
    iar = destination.BeginWrite(buffer, 0, numRead, writeResult =>
    {
    try
    {
    if (writeResult.CompletedSynchronously) return;
    destination.EndWrite(writeResult);
    readWriteLoop(null);
    }
    catch(Exception e) { tcs.TrySetException(e); }
    }, null);
    if (!iar.CompletedSynchronously) return;
    destination.EndWrite(iar);
    break;
    }
    }
    }
    }
    catch(Exception e) { tcs.TrySetException(e); }
    };
    readWriteLoop(null);

    return tcs.Task;
    }

    public static void EndCopyTo(IAsyncResult asyncResult)
    {
    ((Task)asyncResult).Wait();
    }



    New C# language async support:


    public static async void CopyToAsync(Stream source, Stream destination)
    {
    byte[] buffer = new byte[0x1000];
    int numRead;
    while((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) > 0)
    {
    await destination.WriteAsync(buffer, 0, numRead);
    }
    }


    Tuesday, May 29, 2012

    OpenXML doesn't work with Office 365(at least now)

    When you work with OpenXmL and SharePoint 365, you have to work by Sandboxed Solution.
    And that what you receive :

    Error validating assembly 'DocumentFormat.OpenXml.dll'

    I found this post which didn't me happy.

    Monday, May 28, 2012

    jQuery - Extension to SPServices.SPCascadeDropdowns

    We use SPServices.SPCascadeDropdowns , after 20 items it looks like this:




    Instead of:









    but the problem is that it doesn't work with Wiki Pages.
    Therefore I wrote little extension which helps me to solve this problem.

    I changed two things:
    1.
    After : "var defaultViewUrl = $(this).attr("DefaultViewUrl");"
    insert code :

    if (listPath.indexOf('/PAGES/') > 0)
    { listPath = listPath + 'FORMS/'; }



    2.
    Instead of "$(columnSelect.Obj).closest("td").prepend(simpleSelect);"
    replace with :

    if ($(columnSelect.Obj).closest("td").length)
    { $(columnSelect.Obj).closest("td").prepend(simpleSelect); }
    else
    { $(columnSelect.Obj).closest("span").prepend(simpleSelect); }


    Tuesday, May 22, 2012

    Set user permissions to SPList

    Sometimes I need to set permissions for special SPUser to special SPList.
    Therefore , I developed winform solution, which helps me.

    First of all, I use BackgroundWorker just to execute the operation on a separated thread.
    Second, I aggregate fields from the form, which help me to bring a relevant data:
    SiteURL - www.contoso.com
    List - myList
    ItemField - SPField("Display Name") For example item["ModifiedBy"]
    ItemField Text - For example item["ModifiedBy"] = "Victor"
    User - I use SPWeb.EnsureUser






    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using Microsoft.SharePoint;

    namespace GivenPermissions
    {
    public partial class Form1 : Form
    {

    BackgroundWorker bg2 = new BackgroundWorker();

    public Form1()
    {
    InitializeComponent();
    }

    private void btnRun_Click(object sender, EventArgs e)
    {
    bg2.DoWork += new DoWorkEventHandler(bg2_DoWork);
    bg2.ProgressChanged += new ProgressChangedEventHandler(bg2_ProgressChanged);
    bg2.RunWorkerAsync();
    }

    private void bg2_ProgressChanged(object sender,
    ProgressChangedEventArgs e)
    {

    }




    void bg2_DoWork(object sender, DoWorkEventArgs e)
    {
    try
    {
    using (SPSite site = new SPSite(txtSiteUrl.Text))
    {
    using (SPWeb web = site.OpenWeb())
    {

    SPList list = web.Lists[txtList.Text];

    SPQuery query = new SPQuery();
    query.ViewAttributes = "Scope=\"Recursive\"";


    SPListItemCollection col = list.GetItems(query);

    foreach (SPListItem item in col)
    {
    if (item[txtItemField.Text] != null && string.Compare(item[txtItemField.Text].ToString(), txtItemFielText.Text) == 0)
    {


    SPUser user = web.EnsureUser(txtUser.Text);
    SPRoleType roleType = SPRoleType.Contributor;


    SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)user);
    SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);

    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
    item.RoleAssignments.Add(roleAssignment);

    item.Update();

    }
    }


    }
    }




    if (txtMessage.InvokeRequired)
    {
    txtMessage.Invoke(new MethodInvoker(delegate
    {


    txtMessage.AppendText("DONE ! ! !");



    }));
    }
    }
    catch (Exception ex)
    {
    if (txtMessage.InvokeRequired)
    {
    txtMessage.Invoke(new MethodInvoker(delegate
    {

    txtMessage.AppendText(ex.Message + "\n" + ex.StackTrace);

    }));
    }
    }



    }
    }
    }


    Monday, May 21, 2012

    The Web application at http://contoso.com could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

    This is the message you can receive, when you try to run your application(winform or console) on SharePoint Application.
    The reason is that a application runs on x86.
    Here are a few steps which will help you (I hope):
    1.Right-Click on the application -> Properties:


    2. Build -> Platform target :



    3. Change it on "Any CPU" and "Save":



    Thursday, May 10, 2012

    JavaScript - Get the URL without the filename.

    When I need to get  URL without  the file's name , for example:

    instead of

    http://contoso.com/pages/test.aspx

    I need

    http://contoso.com/pages/

    I use this script (with regex pattern  "/^(http.+\/)[^\/]+$/"):

    location.href.match( /^(http.+\/)[^\/]+$/ )[1]

    Wednesday, May 9, 2012

    JavaScript - Get file name from URL

    This function get file name from URL by javascript:

    function getFileName()
     {

          var url = document.location.href;

          url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));

          url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));

          url = url.substring(url.lastIndexOf("/") + 1, url.length);

         return url;
    }

    Thursday, May 3, 2012

    T-SQL Script - Reduce log file of database

    Sometimes I need to reduce log files of SQL Databases
    This is the script which helps me:


    USE DataBase_Name;
    GO
    -- Truncate the log by changing the database recovery model to SIMPLE.
    ALTER DATABASE DataBase_Name
    SET RECOVERY SIMPLE;
    GO
    -- Shrink the truncated log file to 1 MB.
    DBCC SHRINKFILE ( DataBase_Name _log, 1);
    GO
    -- Reset the database recovery model.
    ALTER DATABASE DataBase_Name
    SET RECOVERY FULL;
    GO

    Tuesday, April 24, 2012

    JQuery - TaxonomyFieldControl changed

    In some case I needed to catch a event if TaxonomyFieldControl was changed.
    The solution was here.
    So, I added a plugin to my .js file


    jQuery.fn.contentChange = function(callback){
     var elms = jQuery(this);
     elms.each(
       function(i){
    var elm = jQuery(this);
    elm.data("lastContents", elm.html());
            window.watchContentChange =                                                                            window.watchContentChange 
                   ? window.watchContentChange : [];
    window.watchContentChange.push({"element": elm, "callback": callback});
                    })
    return elms;
    }
    setInterval(function(){
       if(window.watchContentChange){
           for( i in window.watchContentChange){
         if(window.watchContentChange[i].element.data("lastContents")!=
             window.watchContentChange[i].element.html())
            {
              window.watchContentChange[i].callback.apply(window.watchContentChange[i].element);
     window.watchContentChange[i].element.data("lastContents",
     window.watchContentChange[i].element.html())
    };
      }
      }
    },500);

    ...and in the end I put this code to watch it.


    $('div#taxonomyName').contentChange(function(){

    //TO DO
    });



    Monday, March 26, 2012

    Delete all items from SPList - SharePoint 2010 PowerShell

    I found this script in the internet, but don't remember where. Therefore I just put it here as is(Of course with all respect points to the anonymous writer of the script) :



    [System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
    [System.Reflection.Assembly]::Load("Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
    [System.Reflection.Assembly]::Load("Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
    [System.Reflection.Assembly]::Load("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

    # "Enter the site URL here"
    $SITEURL = "http://contoso"

    $site = new-object Microsoft.SharePoint.SPSite ( $SITEURL )
    $web = $site.OpenWeb()
    "Web is : " + $web.Title

    # Enter name of the List below
    $oList = $web.Lists["MyList"];

    "List is :" + $oList.Title + " with item count " + $oList.ItemCount

    $collListItems = $oList.Items;
    $count = $collListItems.Count - 1

    for($intIndex = $count; $intIndex -gt -1; $intIndex--)
    {
    "Deleting : " + $intIndex
    $collListItems.Delete($intIndex);
    }

    Sunday, March 25, 2012

    Enable/Disable feature - SharePoint 2010 PowerShell

    Some times you need just enable /disable feature .
    So for me the good way is doing by PowerShell :

    1. Get all installed features to the text file:

    Get-SPFeature | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id > c:\AllInstalledFeatures.txt

    2. Go to the c:\AllInstalledFeatures.txt and find the relevant feature. Copy the guid.

    3. Enable Feature:

    Enable-SPFeature -identity "cdd0d039-d2d2-40c8-81fc-0d5657fc2962" -URL http://contoso.com

    4. Disable Feature:

    Disable-SPFeature -identity "cdd0d039-d2d2-40c8-81fc-0d5657fc2962" -URL http://contoso.com

    Thursday, March 22, 2012

    Restore Managed Metadata Term Stores - SharePoint 2010

    Few days ago I needed to restore a managed metadata term stores, which were destroyed.
    First of all I looked at metadataexport, but the problem is a lot of our data connected to the old managed metadata terms. Therefore when I exported it, it didn't work , due to guids which were changed.
    So I needed to restore the Managed Metadata Term Stores from the DB backup.

    1. I had to know what is the name of the relevant database:
    Open - Central Admin - Application Management - Manage service application






    2.In Service Applications - Managed Metadata Service - Properties:







    3. Look at Database Server and Database Name of the relevant database:









    4. After it I needed to restore (attach/detach of database ).I wrote it before

    Wednesday, March 21, 2012

    Backup - Restore Content Database to another farm SharePoint 2010 Power Shell

    We need few steps to do it:
    1. Backup data from source.
    For this we need check which database we use for this web application









    and backup the database:
    From the SQL Server that your SharePoint farm users and where the instance of DB resides, backup the database.





    2.Restore the database to the destination :
    Take the backup file to the target SharePoint Farm's SQL Server (where we want to restore it to) and restore the database









    Now we have a new content database, but we need to connect it to our SP.
    Therefore we open SP Powershell :
    3. Dismount old database:

    Dismount-SPContentDatabase "Contoso_PortalContent_Old"

    4. Mount new :
    Mount-SPContentDatabase " Contoso_PortalContent_New" -DatabaseServer "contoso_db" -WebApplication http://contoso.com

    Monday, March 19, 2012

    SharePoint Power Shell Commands for adding solutions

    Adding Solution:

    Add-SPSolution "C:\WebPart.wsp"

    Installing Solution:

    Install-SPSolution –Identity WebPart.wsp –WebApplication http://contoso.com -GACDeployment


    Update Solution if exists:

    Update-SPSolution –Identity WebPart .wsp –LiteralPath “C:\WebPart .wsp” –GACDeployment