Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

Monday, January 28, 2013

Saving page in SharePoint Designer gives JavaScript error



When you try to save document in SharePoint designer - the JavaScript error started raising.


I found that it occurred after a cumulative update SharePoint 2010 - KB2597132.

The solution to fixed it was -

1.Copying files:

FORM.JS
INIT.JS
CORE.JS
BFORM.JS
OWS.JS

from an environment where it works to : "../LAYOUTS/1033".

2.Reset the IE settings


Saturday, January 12, 2013

Method not found: 'System.String System.ServiceModel.Activation.Iis7Helper.ExtendedProtectionDotlessSpnNotEnabledThrowHelper(System.Object)'.

After installing Microsoft patch MS13-04[KB 2756920](Security Update for Microsoft .NET Framework 3.5.1 on Windows 7 and Windows Server 2008 R2 - A security issue has been identified that could allow an unauthenticated remote attacker to compromise your system and gain control over it.), our SharePoint Portal was down with the error :
 WebHost failed to process a request. 
 Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/17653682 Exception: System.ServiceModel.ServiceActivationException: The service '/SecurityTokenServiceApplication/securitytoken.svc' cannot be activated due to an exception during compilation. The exception message is: Method not found: 'System.String System.ServiceModel.Activation.Iis7Helper.ExtendedProtectionDotlessSpnNotEnabledThrowHelper(System.Object)'.. ---> System.MissingMethodException: Method not found: 'System.String System.ServiceModel.Activation.Iis7Helper.ExtendedProtectionDotlessSpnNotEnabledThrowHelper(System.Object)'. at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.WebConfigurationManagerWrapper.BuildExtendedProtectionPolicy(ExtendedProtectionTokenChecking tokenChecking, ExtendedProtectionFlags flags, List`1 spnList) at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.WebConfigurationManagerWrapper.GetExtendedProtectionPolicy(ConfigurationElement element) at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.ProcessWindowsAuthentication(String siteName, String virtualPath, HostedServiceTransportSettings& transportSettings) at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.CreateTransportSettings(String relativeVirtualPath) at System.ServiceModel.Activation.MetabaseSettingsIis.GetTransportSettings(String virtualPath) at System.ServiceModel.Activation.MetabaseSettingsIis.GetAuthenticationSchemes(String virtualPath) at System.ServiceModel.Channels.HttpChannelListener.ApplyHostedContext(VirtualPathExtension virtualPathExtension, Boolean isMetadataListener) at System.ServiceModel.Channels.HttpTransportBindingElement.BuildChannelListener[TChannel](BindingContext context) at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]() at System.ServiceModel.Channels.MessageEncodingBindingElement.InternalBuildChannelListener[TChannel](BindingContext context) at System.ServiceModel.Channels.BinaryMessageEncodingBindingElement.BuildChannelListener[TChannel](BindingContext context) at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]() at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters) at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession) at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result) at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost) at System.ServiceModel.ServiceHostBase.InitializeRuntime() at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHost.InitializeRuntime() at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) --- End of inner exception stack trace --- at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath) Process Name: w3wp 

 RESOLUTION: Uninstall KB 2756920

Wednesday, January 2, 2013

Get SPUser Object from SPListItem

Sometimes, you need to get SPUser object(to retrieve email, name,...) , however you have only SPListItem with SPFieldCollection. When you try to retrieve it, for example:


var field = item["user"]


you just get  a string with User ID , like : "123;#"

We need to cast this object to SPFieldUserValue.

This C# code can help us:



public SPUser GetSPUserObject(SPListItem spListItem, String fieldName)
    {
        SPUser spUser = null;
        try
        {
            if (fieldName != string.Empty)
            {
                SPFieldUser field = spListItem.Fields[fieldName] as SPFieldUser;
                if (field != null && spListItem[fieldName] != null)
                {
                    SPFieldUserValue fieldValue = field.GetFieldValue(spListItem[fieldName].ToString()) as SPFieldUserValue;
                    if (fieldValue != null)
                    {
                        spUser = fieldValue.User;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return spUser;
    }


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

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);
                });
            }
        });


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;
}
}


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()

    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);

    }));
    }
    }



    }
    }
    }