Archive for ‘Share Point’

October 27, 2016

Error: “execution of scripts is disabled on this system”

When you try to execute a SharePoint Online PowerShell command you may come across the above error. Its due to some privacy settings in your local computer.

These scripts could potentially harmful things that you will never expect. 🙂  By default the execution of the PowerShell scripts are disabled by Microsoft. As well as before executing a script you have to make sure that the script is from a reliable source.

To over come the above error you just need to change the Execution policy on your computer using a simple Powershell command as below:

Set-ExecutionPolicy RemoteSigned

when you are done with the above you can execute the script without any issue. Once its done its safe to make the settings to the default as below:

Set-ExecutionPolicy Restricted

You can change the RemoteSigned portion of the command to any of the options as below:

Restricted – No scripts can be run. Windows PowerShell can be used only in interactive mode (This is the default).
AllSigned – Only scripts signed by a trusted publisher can be run.
RemoteSigned – Downloaded scripts must be signed by a trusted publisher before they can be run.
Unrestricted – No restrictions; all Windows PowerShell scripts can be run.

March 3, 2015

The Datasheet view of this list cannot be displayed.

When you get the below error while viewing a list view data :

The Datasheet view of this list cannot be displayed. Please wait while the page is redirected to Standard view. If your list does not appear in a few moments, open the list in Standard view.

err

Install the 2007 Office System Driver: Data Connectivity Components from the link.

October 30, 2014

Alternate languages are not supported on sites with customized CSS files

I had a site with variation for English and Arabic. I had no problem changing the language from Arabic to English and vice versa in our staging environment. For En and Ar subsite even was able to change the language without any issue.

But in production environment the case was so strange. I can be able to change the language in subsites (ex: for en and ar subsites) but not for the root site. When i try to do so was getting the error “Alternate languages are not supported on sites with customized CSS files.” Tried on searching in log files and couldn’t find any clue to sort out this issue.

One of the solution that i come across when searching was to delete the “_style” folder under root. I removed the folder and the situatoin was the same. I thought it was the problem with the Arabic Language pack. I tried repairing the Arabic Lanuage pack. Though it didnt work.

Finally the solution is to remove the entry from the table “AllWebs” for the “CustomizedCSS” field for the root site.

  1. Connect to SQL Server using SQL Server Management Studio
  2. Open the “AllWebs” Table
  3. You will find 3 entries in this particular table for Root, English and Arabic Sites.
    When you check the CustomizedCSS for all these 3 records you will find some value for the root site record (in my case it was showing the ;#corei5; value) and for the other two you will find NULL value.
  4. Set the value for NULL for that.
  5. Once its done you can be able to change the language to Arabic without any issue.
October 30, 2014

Adding dynamic CSS link to Sharepoint MasterPage

In a situation where you have to load CSS files based on the current culture, in this situation you have to use the ~language variable in SharePoint. This will retrieve the proper language ID(example for English-US: en-US, Arabic-SA: ar-SA).

<link rel="stylesheet" href="<%$SPUrl:~sitecollection/_catalogs/masterpage/en-us/css/mystyle.css %>" />

In your master page HTML layout you can add the snippet as below:

<!--SPM:<asp:Literal runat="server" Text="<link rel='stylesheet' href='"/>-->
        <!--SPM:<asp:Literal runat="server" Text="<% $SPUrl:~sitecollection/_catalogs/masterpage/~language/css/mystyle.css %>"/>-->
        <!--SPM:<asp:Literal runat="server" Text="' type='stylesheet' />"/>-->

When using CSSRegistration can use the following snippet:

expected link URL :

<SharePoint:CssRegistration name=”<% $SPUrl:/_layouts/projectname/styles/~language/master.css %>” runat=”server”/>

Master page html page :

<!--SPM:<SharePoint:CssRegistration name="&lt;% $SPUrl:~site/_catalogs/masterpage/test/style.css %&gt;" runat="server" after="SharepointCssFile" />-->
<!--SPM:<SharePoint:CssRegistration name="&lt;% $SPUrl:~site/_catalogs/masterpage/test/style.css %&gt;" runat="server" after="SharepointCssFile" />-->
April 23, 2014

SharePoint Designer: The file is no longer checked out or has been deleted

While you were working with SharePoint designer 2013 you might face a situation where you will popup with an error “The file is no longer checked out or has been deleted” at a time when you try to check in any of the file from SharePoint designer. I tried restarting the SharePoint designer, resetting the IIS and restarting the machine even.

no longer checkout

Finally it seems that need to clear the cache in local app storage to resolve the above error.

Navigate to your local app settings cache folder located in the below location and delete the files corresponding to your site.

For ex: C:\Users\Ammar\AppData\Local\Microsoft\WebsiteCache (my local machine path)

March 13, 2014

Moving SharePoint 2013 Sites, Central Administration Console from one SQL Server to another SQL server

Please follow below steps in moving the SharePoint database from one server to another.

    1. Stop all the processes that might be accessing your SharePoint databasesFor ex:
      • SharePoint 2010 Administration
      • SharePoint 2010 Timer
      • SharePoint 2010 Tracing
      • SharePoint 2010 User Code Host
      • SharePoint 2010 VSS Writer
      • SharePoint Foundation Search V4
      • World Wide Web Publishing Service
      • SharePoint Server Search 14
      • Web Analytics Data Processing Service
      • Web Analytics Web Service


      runningservices

    2. Back up all your SharePoint databases on SQL Server A (this is in any case if anything
      went wrong).
    3. Deattach all your databases from SQL Server A.


deattache

    1. Move all the .mdf and .ldf file from SQL Server A to SQL Server B.
    2. Place them in the proper DATA folder on SQL Server B.
    3. Make sure the same structure of user accounts with proper privileges that was on
      SQL Server A to be created on SQL Server B.
    4. Then attach the databases on SQL Server B.


attach

    1. Modify the SQL alias on SharePoint that points SQL Server A to SQL Server B.


sqlclientutility

while i was detaching some of the databases was getting the error saying (Cannot detach the database ‘DEMO’ because it is currently in use.) that still some users are connected to the database. To get rid of that problem, executed the following SQL statements:

–Kick all users off of the database NOW
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE

–Kick all but after 60 seconds
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK AFTER 60 SECONDS

–restore connection to users
ALTER DATABASE YourDatabase SET MULTI_USER

January 7, 2014

Apps for SharePoint 2013

When I was setting up the SharePoint Apps environment in one of our client site, I have followed the below article to configure the same:

https://www.nothingbutsharepoint.com/

upong configuring the apps successfully the administrator of the SharePoint site can be able to navigate to SharePoint online store and can add the same to the site even. Even though when accessing the added SharePoint app it doesn’t display the app instead its getting crashed.

The redirection happens as below with the instance id of the SharePoint apps as below:

http://abcportal.efg.com.co/etc/_layouts/15/appredirect.aspx?instance_id=a72b7806%2Dca1a%2D41c7%2D974e%2D6f7145def00c

As the two applications (SharePoint site and the apps site) are not running under same domain, seems the IIS having problem with redirecting to the other application (SharePoint apps).

when i went through the logs was able to find the below related to the two apps added in the site:

Doing appredirect from appredirect.aspx: in site: 8308f31c-8e95-4bb2-ac5d-bfc6032efe2d with 302 redirect to: http://apps-a859967b8e5983.ETCApps.com/etc/ArtezioSPPhotoWallInstagram/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fcoeportal%2Eetc%2Eedu%2Fetc&SPLanguage=en%2DUS&SPClientTag=6&SPProductNumber=15%2E0%2E4551%2E1001&SPAppWebUrl=http%3A%2F%2Fapps%2Da859967b8e5983%2EETCApps%2Ecom%2Fetc%2FArtezioSPPhotoWallInstagram

Doing appredirect from appredirect.aspx: in site: 8be20238-f1a2-43c3-9d83-535554a7e4d0 with 302 redirect to: http://apps-a859967b8e5988.ETCApps.com/GoogleSearchApp/Pages/GoogleSearchWebpart.aspx?SPHostUrl=http%3A%2F%2Fcoeportal%2Eetc%2Eedu&SPLanguage=en%2DUS&SPClientTag=33&SPProductNumber=15%2E0%2E4551%2E1001&SPAppWebUrl=http%3A%2F%2Fapps%2Da859967b8e5988%2EETCApps%2Ecom%2FGoogleSearchApp

So finally there was a resolution to the above. the Resolution is to create a new SharePoint web application with the empty host header. Once its done the apps started to work without any further headache. 🙂

References:

http://social.technet.microsoft.com

http://absolute-sharepoint.com/

December 20, 2013

SharePoint 2013 My Newsfeed ‘Everyone’ Internal error code 55

I came across an error in Share Point News Feeds. When I clicked on ‘Everyone’ in the My newsfeed. The following error occurred:

sharepointfeed_error_1I had to give the service account that is running the User Profile Service application pool full control permissions for the User Profile Service Application.

Follow the below steps:

SharePoint Central Administration–> Application Management–> Manage service Applications

In Service applications Page, select User profile service application–> select permissions in the top ribbon

sharepoint_Feed_error_3

Assign full permissions for the account used to run User profile service application

sharepoint_Feed_error_2Upon following the steps above the feeds started to work as usual. 🙂

December 8, 2013

SQL Database State stuck in Restoring

Suddenly one of the production SharePoint site in one of our client site was down. When tried to browse the site was getting the error “Cannot connect to the configuration database. So i logged into the database server and was able to see the following: probsOne of the database was get stucked in the restoring mode. The rest of the databases was in the mode of restoring. I was waiting for more than one hour to let the restoring process get finish and unfortunately nothing happened. 😦

So the resolution is to:

Execute the following command in any case if your database get stucked at the time of restoring:

RESTORE DATABASE [DATABASENAME] WITH RECOVERY;

Once i execute the above i was getting the following error:

Msg 3104, Level 16, State 1, Line 1
RESTORE cannot operate on database ‘kiainternet01’ because it is configured for database mirroring. Use ALTER DATABASE to remove mirroring if you intend to restore the database.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.

i didn’t aware the above database is configured for mirroring. So i had to switch off the mirroring temporarily using the following command:

ALTER DATABASE [DATABASENAME] SET PARTNER OFF;

upon that executed the following command:

RESTORE DATABASE [DATABASENAME] WITH RECOVERY;

finally the databases were online :

final

November 3, 2013

Hide root node of the Sharepoint 2013 SiteMapPath

I had my sitemap path with following link in the master page.

Home > Portal Site > Departments >HR

Home link redirects me to the variationroot.aspx at the same time the “Portal site” also links with the default.aspx page. Anyhow the variationroot.aspx page will redirect the user to the same Default.aspx page. So needs to remove this redundant links and finally the site map path links should appear as below:

Portal Site > Departments >HR

Add the following CSS entry in any case if you wanted to hide the first node of the sitemappath in a variation enabled sharepoitn site.

<asp:SiteMapPath ID="contentNavigation" runat="server">
    <RootNodeTemplate>
    </RootNodeTemplate>
</asp:SiteMapPath>
#ctl00_contentNavigation span:nth-child(2),span:nth-child(3)
{
    display:none;
}
October 27, 2013

AppFabric installation failed because installed MSI returned with error code: 1603

I was getting the below error at the time of running the pre-requistes for a fresh installation of Sharepoint 2013 and SQL Server 2012. Rest of the prerequisites are getting installed without any problem but only the app fabric instllation getting failed. When i check the logs (AppServerSetup1_1_CustomActions(2013-10-27 11-09-45).log) located under path C:\Users\<username>\AppData\Local\Temp and was able to find the below:

27/10/2013 10:38:47 EXEPATH=powershell.exe PARAMS=-command “$content = Get-Content \”c:\Program Files\AppFabric 1.1 for Windows Server\\AppFabricServer.xml\”; $content = ForEach-Object -InputObject $content { $_ -replace \”INSTALLPATH\”, \”c:\Program Files\AppFabric 1.1 for Windows Server\\\” }; Set-Content -value $content -path \”c:\Program Files\AppFabric 1.1 for Windows Server\\AppFabricServer.xml\” ” LOGFILE=C:\Users\mssadmin\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2013-10-27 10-38-40).log
ExitCode=0
27/10/2013 10:38:48 EXEPATH=powershell.exe PARAMS=-command “$content = Get-Content \”c:\Program Files\AppFabric 1.1 for Windows Server\\Consolidator.xml\”; $content = ForEach-Object -InputObject $content { $_ -replace \”INSTALLPATH\”, \”c:\Program Files\AppFabric 1.1 for Windows Server\\\” }; Set-Content -value $content -path \”c:\Program Files\AppFabric 1.1 for Windows Server\\Consolidator.xml\” ” LOGFILE=C:\Users\mssadmin\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2013-10-27 10-38-40).log
ExitCode=0
Executing action : Microsoft.ApplicationServer.InstallHelper.SQMTaskInstallAction
SQMTaskInstall areguments –  /create /tn “\Microsoft\Windows\AppFabric\Customer Experience Improvement Program\Consolidator” /xml “c:\Program Files\AppFabric 1.1 for Windows Server\Consolidator.xml”
Output: SUCCESS: The scheduled task “\Microsoft\Windows\AppFabric\Customer Experience Improvement Program\Consolidator” has successfully been created.
27/10/2013 10:38:50 EXEPATH=c:\Windows\system32\\sc.exe PARAMS=privs AppFabricCachingService SeChangeNotifyPrivilege LOGFILE=C:\Users\mssadmin\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2013-10-27 10-38-40).log
Output: [SC] ChangeServiceConfig2 SUCCESS
ExitCode=0
27/10/2013 10:38:50 EXEPATH=c:\Windows\system32\\sc.exe PARAMS=sidtype AppFabricCachingService unrestricted LOGFILE=C:\Users\mssadmin\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2013-10-27 10-38-40).log
Output: [SC] ChangeServiceConfig2 SUCCESS
ExitCode=0
27/10/2013 10:38:50 EXEPATH=c:\Windows\system32\\netsh.exe PARAMS=advfirewall firewall add rule enable=no profile=any dir=in action=allow description=”@c:\Program Files\AppFabric 1.1 for Windows Server\ApplicationServerResources.dll,-203″ name=”@c:\Program Files\AppFabric 1.1 for Windows Server\ApplicationServerResources.dll,-202″ protocol=TCP program=”c:\Program Files\AppFabric 1.1 for Windows Server\DistributedCacheService.exe” LOGFILE=C:\Users\mssadmin\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2013-10-27 10-38-40).log
Output: Ok.
ExitCode=0
27/10/2013 10:38:51 EXEPATH=c:\Windows\system32\\netsh.exe PARAMS=advfirewall firewall add rule enable=no profile=any dir=out action=allow description=”@c:\Program Files\AppFabric 1.1 for Windows Server\ApplicationServerResources.dll,-207″ name=”@c:\Program Files\AppFabric 1.1 for Windows Server\ApplicationServerResources.dll,-206″ protocol=TCP program=”c:\Program Files\AppFabric 1.1 for Windows Server\DistributedCacheService.exe” LOGFILE=C:\Users\mssadmin\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2013-10-27 10-38-40).log
Output: Ok.
ExitCode=0
Executing action : Microsoft.ApplicationServer.InstallHelper.FirewallExceptionAction
27/10/2013 10:38:51 EXEPATH=powershell.exe PARAMS=-command “$str = [System.Environment]::GetEnvironmentVariable(\”PSModulePath\”, [System.EnvironmentVariableTarget]::Machine); $str = $str+\”;c:\Program Files\AppFabric 1.1 for Windows Server\PowershellModules\”; c:\Windows\system32\setx.exe /M PSModulePath \”$str\”” LOGFILE=C:\Users\mssadmin\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2013-10-27 10-38-40).log
Error: ERROR: Invalid syntax. Default option is not allowed more than ‘2’ time(s).
Error: Type “SETX /?” for usage.
ExitCode=1
27/10/2013 10:38:54 EXEPATH=c:\Windows\system32\\netsh.exe PARAMS=advfirewall firewall delete rule name=”@c:\Program Files\AppFabric 1.1 for Windows Server\ApplicationServerResources.dll,-206″ LOGFILE=C:\Users\mssadmin\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2013-10-27 10-38-40).log
Output: Deleted 1 rule(s).
Output: Ok.
ExitCode=0
27/10/2013 10:38:54 EXEPATH=c:\Windows\system32\\netsh.exe PARAMS=advfirewall firewall delete rule name=”@c:\Program Files\AppFabric 1.1 for Windows Server\ApplicationServerResources.dll,-202″ LOGFILE=C:\Users\mssadmin\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2013-10-27 10-38-40).log
Output: Deleted 1 rule(s).
Output: Ok.
ExitCode=0
Executing action : Microsoft.ApplicationServer.InstallHelper.SQMTaskUninstallAction
Output: SUCCESS: The scheduled task “\Microsoft\Windows\AppFabric\Customer Experience Improvement Program\Consolidator” was successfully deleted.

based on the above error log could notice that ” is getting amended to the PSModulePath path. So for this what you have to do is to remove that ” from the PSModulePath enviornmentabl variable.

envvvariable

references:

http://social.msdn.microsoft.com/Forums/vstudio/en-US/8cf55972-e441-4107-8c0d-1692ad03213d/error-with-installation-of-appfabric-11-on-psmodulepath?forum=velocity

http://social.msdn.microsoft.com/Forums/sharepoint/ja-JP/290ff740-d8f1-426c-b7f0-1152dc481779/appfabric-installation-failed-because-installer-msi-returned-with-error-code-1603?forum=sharepointgeneralprevious

http://social.msdn.microsoft.com/Forums/vstudio/en-US/8338a53e-6b4f-44a8-ac7b-a287f3b4b20e/installation-problem-msi-error-1603-win-7-x64-appfabric-11?forum=velocity

http://support.microsoft.com/kb/310519/en-us

October 9, 2013

Activating and Deactivating Features using PowerShell

Installing a feature:

Install-SPFeature FeatureFolderName

To activate a feature:

Enable-SPFeature FeatureFolderName -Url http://server/site/

To deactivate a feature:

Disable-SPFeature FeatureFolderName -Url http://server/site/

To uninstall a feature:

Uninstall-SPFeature FeatureFolderName
October 4, 2013

Hiding the ribbon – SharePoint 2013

Add the following code to hide the ribbon in Share Point 2013.

<SharePoint:SPSecurityTrimmedControl PermissionsString="FullMask" runat="server">
<div id="ms-designer-ribbon">
<!--SID:02 {Ribbon}-->
<!--PS: Start of READ-ONLY PREVIEW (do not modify) --><div class="DefaultContentBlock" style="background:rgb(0, 114, 198); color:white; width:100%; padding:8px; height:64px; overflow:hidden;">
In true previews of your site, the SharePoint ribbon will be
here.</div><!--PE: End of READ-ONLY PREVIEW -->
</div>
</SharePoint:SPSecurityTrimmedControl> 

Once you apply the above code snippet the vertical bar would be get hidden.  For you to get the ribbon back, you have to over ride the style attribute of the body, so for that add the attribute to the style=”overflow: scroll !important” to the BODY element of your master page. Once you apply the same you will get the vertical scroll bar back. The reason behind this is that the master pages have a link to corev15.css. This stylesheet sets overflow to hidden for the BODY element, which removes the scroll bar.

more about the SPSecurityTrimmedControl you can find it in the below link : http://msdn.microsoft.com/en-us/library/jj822366.aspx

July 14, 2013

The dilemma of Double-Hop Dogma

Was wondering about the subject of the post which i am going to write. okay fine and its Double Hop Dogma. This is related to Exchange Web Services API. you can download the API from this link. Let me explain what happened. There was a requirement raised due to the fact that we cant view OWA websites (Outlook Webmail) inside an IFRAME. When we used the OWAInputWebPart the owa site used to display within the ifram of the OWAInputWebPart. Hence there was an exception saying that it cannot be displayed within IFRAME. So as a solution we had to develop our own custom web part to view the inbox emails.

Initially i was playing around with a single mail box and was able to fetch the mails without any problem. I refered this MSDN article for my reference.

binding.Credentials = new NetworkCredential("userid", "password", "domain");

So the above code works fine and was able to read the emails. As the next step the requirement was to read the emails based on the currently logged in user in Share Point. So started working on a new web part for this.

as per the link it says that…

If you want to connect to EWS from a computer that is logged on to the domain, using the credentials of the authenticated user, set the UseDefaultCredentials property on the ExchangeService object to true.

// Connect by using the default credentials of the authenticated user.
service.UseDefaultCredentials = true;

i kept trying the above code to work but unfortunately it didn’t work. I spent full whole day trying on this. I searched on the web and found the blog post about the double hop dogma. it says “The user who’s browsing the application from a client machine passes his credentials to the IIS server, i.e. the credentials of the user hop from the client to the IIS server. Subsequent to that, when the IIS application executes EWS calls, it is supposed to pass those same credentials to the Exchange server, to authenticate the logged on user. This works fine in the ideal scenario, and falters in alternative scenarios.”

They have mentioned following scenarios related to the above sentence as below:

Ideal scenario: Kerberos authentication method is being used within the organization
Frequent Scenarios: The non-ideal scenario is not being observed, i.e. NTLM might be the active authentication mechanism, or Kerberos could be failing and the application falls back on attempting authentication via NTLM which would eventually fail in a double-hop situation.”

In my case when i checked the active directory structure on the client site, i learnt that they are not using the Kebreros authentication instead they are using the NTLM authentication on AD.

So i came across the blog post : Need a way to authenticate to Exchange Web Services and based on the fact which explains that: “Create a service account that has either impersonation rights or delegate access over the employee mailboxes. Then log in as the service account.” I advised the network administrator to create a service account for me. Uplon creating the account i resumed my work as usual.

// Setup connection string
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new NetworkCredential("superadmin", "password", "domain");

Impersonating the service using a difference user id.

// Impersonation
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "useremail1@domain.com");

In this place i was able to get the currently logged in user by executing the following code

HttpContext.Current.User.Identity.Name.ToString()

Finally was able to retrieve mail details as below:

SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));

var inbox = new FolderId(WellKnownFolderName.Inbox);
var iv = new ItemView(9999);

FindItemsResults<Item> findResults = service.FindItems(inbox, searchFilter, iv);

if (findResults.Items.Count > 0)
{
foreach (Item item in findResults.Items)
{
mailboxDetails a = new mailboxDetails();
a.Subject = item.Subject;
}
}

Refer example post here by Jens Willmer.

Please refer the following articles to understand about Exchange Impersonation:

Delegate Access with Exchange Web Services

Exchange Impersonation vs. Delegate Access

The thread i posted on MSDN

Threads which was posted by others:

Exchange Web Services (EWS), GetItem() call produces AccessDenied error

ServiceRequestException Message : Request failed. The remote server returned an error: (401) Unauthorized

Exchange Web Services: UseDefaultCredentials property

please refer some samples related to the Exchange Web Services through this link.

Exchange Tutorial Part 1 – Impresonated Exchange Service Binding

June 17, 2013

A SharePoint server is not installed on this computer.

After installing Visual Studio 2012, I tried to create a new share point project using Visual Studio 2012.  So was getting the error “A SharePoint server is not installed on this computer. A SharePoint server must be installed to work with SharePoint projects“. Once you execute the following powershell command, it will set the registry values for the “HKLM:\Software\Microsoft\Shared Tools\web server extensions\14.0\”.

Set-ItemProperty -Path "HKLM:\Software\Microsoft\Shared Tools\web server extensions\14.0\" -Name "Location" -Value "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\"
Tags:
June 17, 2013

Remove “View All Site Content” link from quick launch – Sharepoint 2013

if you want to remove the “View All Site Content” link from the quick launch navigation, just comment out the following code from your master page.

<hr /><SharePoint:ClusteredSPLinkButton ID="idNavLinkViewAllV4" runat="server" Permissions="ViewFormPages" NavigateUrl="~site/{0}/viewlsts.aspx" Text="&lt;%$Resources:wss,quiklnch_allcontent_short%&gt;" accesskey="&lt;%$Resources:wss,quiklnch_allcontent_AK%&gt;" CssClass="ms-core-listMenu-item" />
April 3, 2013

SharePoint 2010 – Search Core Results XSLT Transformation

Suddenly your manger says to you, man, we just wanted to modify the core search results of the SharePoint 2010. So the first step is to add a Search core results web part to your search results page and open the same page in a browser. After that put the page in edit mode and choose edit web part from the Search Core Results Web Part menu.

In the Search Core Results Tool Pane open the Display Properties section and then uncheck “Use Location Visualization” and you can notice that the XSL Editor… button should become active.

image001

Click the “XSL Editor…” button to open the Text Editor dialog.

image002

Replace all the above XSL with the below (or just copy to the clipboard hence you will need the data in future):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<xmp><xsl:copy-of select="*"/></xmp>
</xsl:template>
</xsl:stylesheet>

The reason why I did substituted the existing XSLT is to know how the SharePoint renders the output of the search results.

So the core results search of the SharePoint will give you the results in a format as below:

<All_Results>
    <Result>
      <id>1</id>
      <workid></workid>
      <rank>1006</rank>
      <title>Your document title</title>
      <author>Mikael Svenson</author>
      <size>79872</size>
      <path>http://server/path/test.html</path>
      <description></description>
      <write>11/1/2010</write>
      <sitename>Procedures</sitename>
      <collapsingstatus></collapsingstatus>
      <hithighlightedsummary>This is a summary.</hithighlightedsummary>
      <hithighlightedproperties>
        <HHTitle>Your document title</HHTitle>
        <HHUrl>http://server/path/test.html</HHUrl>
      </hithighlightedproperties>
      <imageurl imageurldescription="Web Page">/_layouts/images/html16.png</imageurl>
      <contentclass></contentclass>
      <isdocument>True</isdocument>
      <picturethumbnailurl></picturethumbnailurl>
      <url>http://server/path/test.html</url>
      <serverredirectedurl></serverredirectedurl>
      <fileextension>ASPX</fileextension>
      <spsiteurl></spsiteurl>
      <docvector>[procedure overview, 1][links, 0.707107]</docvector>
      <fcocount>1</fcocount>
      <fcoid>336059505871761914</fcoid>
      <pictureheight></pictureheight>
      <picturewidth></picturewidth>
      <escbaseextension>xls</escbaseextension>
      <escprojname>00 - UNDEFINED</escprojname>
      <escdeptname>0000 - UNDEFINED</escdeptname>
      <escprocnumber></escprocnumber>
      <esccategoryname>COMPANY MANAGEMENT SYSTEM</esccategoryname>
      <escsubcategoryname>GOVERNING DOCUMENTS</escsubcategoryname>
      <eschistdocnum></eschistdocnum>
    </Result>
</All_Results>

When you wanted to modify the search results, then what you have to do is to modify the XSLT part that we copied in one of the steps above. I usually used to do is to copy all those XSLT in to Visual Studio and then modifying the same as needed.

image004

By default the search results would be as below with icons, etc.

image006

After modifying the XSLT the search results would like below:

image008

I was using the OOB search paging web part to get the paging for the search results.

image010

please refer the following links for more detail:

Enterprise Search Core Results XSLT Transformation
http://msdn.microsoft.com/en-us/library/ms584121%28v=office.12%29.aspx

How to: View Search Results XML Data
http://msdn.microsoft.com/en-us/library/ms546985.aspx

Take Control of Search XSL
http://www.ableblue.com/blog/archive/2011/09/30/take-control-of-search-xsl/

March 31, 2013

Publishing pages based on a SharePoint Article page layout programmatically

Glad I got some few minutes to update my blog after 2 months hence was in a busy schedule. J  Please refer the below code for you to create a Publishing page on Sharepoint 2010 based on a page layout which is available in your site.

PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
string pageName = “MyPageName.aspx”;
PageLayout[] pageLayouts = publishingWeb.GetAvailablePageLayouts();
PageLayout selectedLayout = null;
foreach (PageLayout pl in pageLayouts)
{
if (pl.Name == "MyPublishingPageLayout.aspx")
{
selectedLayout = pl;
break;
}
}
PageLayout currPageLayout = selectedLayout;
PublishingPageCollection pages = publishingWeb.GetPublishingPages();
PublishingPage newPage = pages.Add(pageName,currPageLayout);
newPage.ListItem[FieldId.PublishingPageContent] = “Content of the page”;
newPage.ListItem.Update();
newPage.Update();
newPage.CheckIn(“Comment for the checkin”);
newPage.ListItem.File.Publish("page published");
newPage.ListItem.File.Approve("page approved");

please refer the following links for more details:

http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/69b509cd-4865-4d9f-891f-5050d59e78b4/
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopmentprevious/thread/e6ca8a5f-b650-4759-8760-57086cb19765

January 10, 2013

Branding the Sharepoint 2010 Top Navigation

IF anyone interested in doing the branding the top navigation of the sharepoint site, just start it with this link.

before branding the Top Navigation:

beforebranding

After branding the Top Navigation:

afterbranding
The above mentioned SharePoint top navigation had to support variation with the Arabic fonts. So i had issues when the top navigation turns its direction to RTL. so the solution mentioned in the below link helped me out to find the problem which made the menu to behave naughty.

http://social.msdn.microsoft.com/Forums/da-DK/sharepointcustomizationprevious/thread/7f2b6811-1d19-4a9c-a5fa-29f5be4dbe5a

the problem which i was getting is from the following style in core4.css
.menu ul.dynamic {
position: absolute;
right: -999em;
}

Had to override the style which was mentioned in the core4.css with the below entry:

.menu ul.dynamic {
position: absolute!important;
top: -999em!important;
}

refer the following link to start up the branding:

Customizing SharePoint 2010 global navigation with Css and jQuery – Part 1

apart from the branding of the top navigation had to brand the search OOB webpart. You can find the style which i used in the below css style.

before branding the search OOB webpart:

searchbefore

after branding the search OOB webpart:

searchafterbranding
As well as if you need to hide the breadscrumb (sitemap path navigation) of the site please add the following entry in the master page or in a content editor web part on the page. (just check the ID of the control when browsing the page).

<style type=”text/css”>

#ctl00_PlaceHolderTitleBreadcrumb_ContentMap {display=none;}

</style>

the complete style sheet:

/* Drop Down: Container Style */
.s4-tn ul.dynamic{
background-color:rgb(65, 64, 66)!important;
border:thin rgb(182, 164, 85) double !important;
border: thick #b6a455 double!important;

}
/* Drop Down: Item Padding Style */
.s4-tn li.dynamic > .menu-item{
/*padding:10px 20px 10px 20px;*/
}
/* Drop Down: Hyperlink Styles */
.s4-tn li.dynamic > a{
font-size: 9px!important;
font-weight:normal!important;
color:#b6a455!important;
border:thin rgb(182, 164, 85) double!important;
text-align:left;
}
/* Drop Down: Hyperlink Hover Style */
.s4-tn li.dynamic > a:hover{
background-color:rgb(182, 164, 85)!important;
color:rgb(65, 64, 66)!important;
border: thin rgb(65, 64, 66) double!important;
}

/*          top menu */
/* Drop Down: Hyperlink static style */
.s4-tn li.static > .menu-item {
font-size: 9px!important;
font-weight:normal!important;
color:#b6a455!important;
border:thin rgb(182, 164, 85) double !important;
background-color:rgb(65, 64, 66);
border: thick #b6a455 double!important;
}
/* Drop Down: Hyperlink static Hover Style */
.s4-tn li.static > a:hover{
background-color:rgb(182, 164, 85)!important;
color:rgb(65, 64, 66)!important;
border: thick rgb(65, 64, 66) double!important;
}
/* Drop Down: Hyperlink static Hover Style */
.s4-tn li.static > a.selected{
background-color:rgb(182, 164, 85)!important;
color:rgb(65, 64, 66)!important;
border: thick rgb(65, 64, 66) double!important;
}
/* top down menu */
.menu-horizontal a.dynamic-children span.additional-background, .menu-horizontal span.dynamic-children span.additional-background
{
background-image:none!important;
}
.menu-horizontal ul.dynamic a.dynamic-children span.additional-background, .menu-horizontal ul.dynamic span.dynamic-children span.additional-background
{
background-image:url(“/Style Library/Images/Arrow_English.gif”)!important;
}
.menu-vertical a.dynamic-children span.additional-background, .menu-vertical span.dynamic-children span.additional-background{
background-image:url(“/Style Library/Images/Arrow_English.gif”)!important;
}

/* Search Box */

.s4-search input.ms-sbplain {
width: 220px !important;
line-height: 20px !important;
height:17px!important;
background-color: #F5EFE0 !important;
border: 1px solid #D3AE81 !important;
}
.s4-search .ms-sbgo {
padding: 0;
margin: 0;
line-height: 20px;
text-align:center!important;
vertical-align:middle!important;
}
.s4-search .ms-sbgo a {
background-image: url(‘/Style Library/Images/Search_en.gif’);
background-repeat: no-repeat;
width: 120px;
height: 33px;
display: block;
text-align:center;
vertical-align:middle;
margin-left:10px;
margin-top:5px;
}
.s4-search .srch-gosearchimg {
display: none;
}
.ms-sbscopes {
display: none;
}
td.ms-sbcell{
background-color:rgb(182, 164, 85)!important;
border:0px;
text-align:center;
vertical-align:middle;
}
.ms-sbtable{
border-top-width:0px!important;
border-right-width:0px!important;
border-bottom-width:0px!important;
border-left-width:0px!important;
background-color:white!important;
border-top-style:none!important;
border-right-style:none!important;
border-bottom-style:none!important;
border-left-style:none!important;
border-bottom-color:rgb(182, 164, 85)!important;
border-top-color:rgb(182, 164, 85)!important;
border-right-color:rgb(182, 164, 85)!important;
border-left-color:rgb(182, 164, 85)!important;
}
.ms-sbLastcell{
display:none;
}
.search .ms-sbcell{
color:#4f4f4f!important;
}
.menu-horizontal li.static, .menu-horizontal a.static, .menu-horizontal span.static{
float:none!important;
display:inline-block!important;
}

November 29, 2012

Restore-SPSite : Your backup is from a different version

I was restoring a SharePoint backup which i took it from one of our staging servers to the virtual machine in my local machine. So was unable to restore the same and was getting the following error due to imcompatible versions in between the Servers (sharepoint foundation versions).

Restore-SPSite : Your backup is from a different version of Microsoft SharePoint Foundation and cannot be restored to a server running the current version. The backup file should be restored to a server with version ‘14.0.0.6106’ or later.
At line:1 char:15 + Restore-SPSite <<<<  http://smssps:3333/ -Path ?C:\AppDev-01 backups 28 Nov 2012\ShounAlQuran\ShounalQuranAppDev01.bak” -Force -DatabaseServer “smssps” -DatabaseName “WSS_Content_ShounAlQuran”
+ CategoryInfo          : InvalidData: (Microsoft.Share…dletRestoreSite:
SPCmdletRestoreSite) [Restore-SPSite], SPException + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletRestoreSite

use the powershell command : (get-spfarm).BuildVersion to find the version of the sharepoint foundation.


so if the versions differs please go through the following link and install the correct patches to make sure that the versions are same in both the source and the destination.

http://www.sharepointdesignerstepbystep.com

November 21, 2012

Website got hacked

Shortly, after publishing of the website which i was working on few days back, yesterday i noticed some unexpected number of records is being inserted into one of the Share Point List we do have in our system. The purpose of the said list was to get the user comments from the website visitors for the News, Articles, etc via a User Input Form. The said form was fully secured with the client side scripts for malicious data inputs. At first i panicked, because i was worried about the rest of the user input forms also been compromised. But, thankfully its not and the intrusion was limited only to the said form above. 🙂

When investigated the data that hacker tried to inject into the system seems an automated script which is being used for SQL Injection and as well as a sort of a DOS (Denial of Service) attack. As an urgent fix for this had to implement the Captcha (Completely Automated Public Turing test to tell Computers and Humans Apart) feature to make sure the data is being inputted by a human and not from an automated robotic program.

the scripts which was embedded..

November 14, 2012

Adding a single value and multiple values into a Lookup Column

There might be situations where you may have to add multiple values to a SharePoint list field.


SPFieldMultiChoiceValue multiChoiceFunction = new SPFieldMultiChoiceValue();

for (int i = 0; i &lt; CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
int lvId = Convert.ToInt32(CheckBoxList1.Items[i].Value);
string lvValue = CheckBoxList1.Items[i].Text.ToString().Trim();
SPFieldLookupValue lv = new SPFieldLookupValue(lvId, lvValue);
multiChoiceFunction.Add(lv.ToString());
}
}

item["Function"] = multiChoiceFunction;

below is the code snippet of the way to add a value to a SharePoint look up column field :

foreach (ListItem lst in RadioButtonList1.Items)
{
if (lst.Selected == true)
{
int lvId = Convert.ToInt32(lst.Value);
string lvValue = lst.Text.ToString().Trim();
SPFieldLookupValue lv = new SPFieldLookupValue(lvId, lvValue);
item["TypeOfTest"] = lv;
}
}
October 29, 2012

Google Map Visual Web Part

Finally was able to finish the share point 2010 visual web part which i was working on. Seems the webpart looks cool. Its nothing other than JQuery and Google MAP API v 3.o with customization.

refer the google map API documentation for the v 3.0 via this link.

the interesting part of the above web part is that the markers used to fly in to the locations based on the category. you can refer the following out of the box source code below with zero customization:

http://code.google.com/

October 29, 2012

Dynamically load CSS file on SharePoint 2010

I was in a situation where i had to load a share point page into SPDialog (SP.UI.ModalDialog.showModalDialog) after removing the unwanted tags like header, footer, the ribbon, etc. (just need to add the class=”s4-notdlg” for the tags you are expecting not to be included in the dialog).

So in that case you will be in a situation where you may need to remove the background of the dialog which automatically inherits from the parent, etc in other words you may have to load a new CSS when the dialog window opens. Please follow the steps as below to load a CSS file on the fly.

var isInIFrame = window.location != window.parent.location;
	if(isInIFrame)
	{
		 var fileref=document.createElement("link")
  		 fileref.setAttribute("rel", "stylesheet")
 		 fileref.setAttribute("type", "text/css")
 		 fileref.setAttribute("href", "/Style%20Library/ar-sa/css/My_Dialog.css")
 		 if (typeof fileref!="undefined")
		 document.getElementsByTagName("head")[0].appendChild(fileref)

refer the following link for more details to read about more on above.

http://www.javascriptkit.com/

if you want to change the dialog borer, the background of the dialog caption then add the following style into your CSS file

/* dialog border black and the title of the background */

.ms-dlgBorder, .ms-dlgContent {border:1px solid #333;}
.ms-dlgTitle {
border:none;
border-bottom:1px solid #fff;
background-color:black;
}

August 2, 2012

MSChart Controls in SharePoint / MOSS 2010

I had a chance to develop a Survey Webpart with MS Chart Control for SharePoint 2010.

Initially thought that getting the chart controls to work in SharePoint is similar to the way that we have to do in ASP.NET. But with SharePoint there are some stuffs we have to do it manually.

You can download the MS Chart from this link  and read more about the MS Chart controls from the link.


Once you open up a new fresh SharePoint 2010 project with a visual web part, then add a reference to the System.Web.DataVisualization.dll.

please add these entries in the web.conf file as below:

</pre>
<handlers>
 <add name="ChartImageHandler" preCondition="integratedMode"  verb="GET,HEAD,POST" path="ChartImg.axd"
 type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler,  System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
 </handlers>
[/sourcode]

</pre>
<appSettings>
 <add key="ChartImageHandler" value="storage=file;timeout=20;" />
 //<add key="ChartImageHandler" value="Storage=file;Timeout=20;Url=/_layouts/Images/MSChartImages/;" />
 //<add key="ChartImageHandler" value="Storage=memory;Timeout=20;" />
 </appSettings>

As well as please register the assembly in your user controls (.ascx file) as below.

</pre>
<%@ Register Assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
 Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

After that add the Chart control to your page as mentioned below:

<asp:Chart ID="Chart1" runat="server" Width="550px" Height="350px">
 <Series>
 <asp:Series Name="Request" XValueMember="Column1"
 YValueMembers="Column2"
 ChartType="Column" Palette="EarthTones"
 ChartArea="MainChartArea">
 </asp:Series>
 </Series>
 <ChartAreas>
 <asp:ChartArea Name="MainChartArea" Area3DStyle-
 Enable3D="true">
 <Area3DStyle Enable3D="true"></Area3DStyle>
 </asp:ChartArea>
 </ChartAreas>
 </asp:Chart>

From your code behind, retrieve the data what you need to be pushed into chart as a datatable and just set the datasource of the chart control as below.

</pre>
Chart1.DataSource = yourDataTable;
 Chart1.DataBind();

read more about the MS Chart control in below link:

http://www.dotnetspark.com/

July 10, 2012

System.Security.SecurityException: Request for the permission of type

System.Security.SecurityException: Request for the permission of type ‘System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ failed

I was getting the above error at the time when a Form (Sharepoint Webpart) submits some data to a sharepoint list. To overcome the above said error follow the below steps:

1. Navigate to the folder => “C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\CONFIG” and open the wss_minimaltrust.config file.

2. Under the XML section <namedpermissionsets> you can find the <permissionset>. After that add the below segement:

<ipermission>
class=”WebPermission”
version=”1″
Unrestricted=”true”>
</ipermission>

Error Details:

Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application’s trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type ‘System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ failed.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

June 12, 2012

SPContentDeploymentWizard and the deployment

Finally the projects that we were working was over (not 100%) and had to deploy the site that we were developing on client site. We did some test deployments in our virtual servers using the SharePoint Content Deployment Wizard and everything was working fine. When we started deploying the site on client site using the Share Point Content Deployment Wizard it didn’t allow us to deploy the site. When it starts to deploy its getting crashed or hanged. We tried many ways to get this thing work and finally it didn’t work at all.

When investigated finally we got to know it was due to the SharePoint version. In other words the exported site from our staging environment and the SharePoint version which was installed in live environment on client site was different.

Finally we had to deploy the site by moving the content database of the sharepont site from the staging to live enviornment. woowww!! without any issue it worked fine. 🙂

you can find more details about moving a content database from this link.

May 30, 2012

Populate drop down with user created sharepoint fields

Assume that there is a situation where you have to expose only the user defined fields from a sharepoint list by filling up a dropdown. Usually when you tried to get fields collection list from a sharepoint list or a document library you will get list of columns roughly which will include around 40+ columns.

Following code snippet explains you how to populate a drop down list only with the fields that you have created.

Populatet the dropdown using a sharepoint list :

   using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        SPList list = web.Lists["MainSpecificationList"];                        

                        SPList oSPList = web.Lists["MainSpecificationList"];
                        for (int i = 0; i < list.Fields.Count - 1; i++)
                        {
                            if (!list.Fields[i].Hidden && !list.Fields[i].ReadOnlyField &&
                            list.Fields[i].Type != SPFieldType.Attachments)
                            {
                                if (list.Fields[i].Title.ToString() != "Title" && list.Fields[i].Title.ToString() != "Content Type"
                                    && list.Fields[i].Title.ToString() != "SpecificationPDFURL" && list.Fields[i].Title.ToString() != "PDF View URL")
                                {
                                    ddlDropDown.Items.Add(list.Fields[i].Title.ToString());
                                }
                            }
                        }
}
}

Populate the dropdown using a sharepoint View:

   using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.RootWeb)
                    {
SPView view = list.Views["SearchView"];

                        SPListItemCollection itemCol = list.GetItems(view);                                                           

                        for (int Cnt = 0; Cnt <= list.Fields.Count - 1; Cnt++)
                        {
                            if (!list.Fields[Cnt].Hidden && !list.Fields[Cnt].ReadOnlyField &&
                            list.Fields[Cnt].Type != SPFieldType.Attachments)
                            {
                                if (list.Fields[Cnt].Title.ToString() != "Title" && list.Fields[Cnt].Title.ToString() != "Content Type"
                                    && list.Fields[Cnt].Title.ToString() != "SpecificationPDFURL" && list.Fields[Cnt].Title.ToString() != "PDF View URL")
                                {
                                    ddlDropDown.Items.Add(list.Fields[Cnt].Title.ToString());
                                }
                            }
                        }

                    }
                }
            
May 12, 2012

Shaerpoint Site Templates, Powershell commands to create subsites

The following list of template ids will be useful at the time when you are creating sub sites using powershell command lines.

GLOBAL#0 = Global template
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
CENTRALADMIN#0 = Central Admin Site
WIKI#0 = Wiki Site
BLOG#0 = Blog
BDR#0 = Document Center
OFFILE#0 = Records Center
OFFILE#1 = Records Center
OSRV#0 = Shared Services Administration Site
SPS#0 = SharePoint Portal Server Site
SPSPERS#0 = SharePoint Portal Server Personal Space
SPSMSITE#0 = Personalization Site
SPSTOC#0 = Contents area Template
SPSTOPIC#0 = Topic area template
SPSNEWS#0 = News Site
CMSPUBLISHING#0 = Publishing Site
BLANKINTERNET#0 = Publishing Site
BLANKINTERNET#1 = Press Releases Site
BLANKINTERNET#2 = Publishing Site with Workflow
SPSNHOME#0 = News Site SPSSITES#0 = Site Directory
SPSCOMMU#0 = Community area template
SPSREPORTCENTER#0 = Report Center
SPSPORTAL#0 = Collaboration Portal
SRCHCEN#0 = Search Center with Tabs
PROFILES#0 = Profiles
BLANKINTERNETCONTAINER#0 = Publishing Portal
SPSMSITEHOST#0 = My Site Host
SRCHCENTERLITE#0 = Search Center
SRCHCENTERLITE#1 = Search Center
SPSBWEB#0 = SharePoint Portal Server BucketWeb Template

you can use the following power shell script to create sub sites within a site collection.

please put the following scripts in a file and name it as you wish (for ex: MyScript.ps1). Please make sure to change the site URL and the subsite names.

Add-PsSnapin Microsoft.SharePoint.PowerShell

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

#Creating Sub Sites in top site collection.
Write-Output " "
Write-Output "Creating Sub Sites"

$SiteCollectionURL = "http://localhost/"

$SiteCollectionTemplate = "BLANKINTERNET#2"

$SiteCollectionLanguage = 1025

$SubSites = @("ContactUs", "Membership", "Codes", "Specification", "HR")

$Names = @("ContactUs", "Membership", "Codes", "Specification", "HR")

for($i=0 ; $i -lt $SubSites.count ; $i++)
{
$SiteUrl = ""
$SiteUrl = $SiteCollectionURL + "/"
$SiteUrl = $SiteUrl += $SubSites[$i]
Write-Output " "
#Write-Output "Creating Site for " += $SubSites[$i]
Write-Output " "
New-SPWeb $SiteUrl -Template $SiteCollectionTemplate -Name $Names[$i]  -UseParentTopNav -Language $SiteCollectionLanguage
Write-Output " "
#Write-Output "Site Created for " += $SubSites[$i]
Write-Output " "
}

Remove-PsSnapin Microsoft.SharePoint.PowerShell

To automatically execute the above poweshell script you can create a small bat file as below:

cd /d %~dp0
powershell -noexit -file ".\MyScript.ps1" "%CD%"
pause
April 6, 2012

Session state can only be used when enableSessionState is set to true

Today i was working with a sharepoint visual webpart and was trying to add some data in to session and was getting the error : {System.Web.HttpException: Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.
at System.Web.UI.Page.get_Session()
at inc_coe_forms.ContactUs.ContactUsUserControl.btnAddMoreFiles_Click(Object sender, EventArgs e)}

Or

Unexpected error occurred: System.Web.HttpException: Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.
Solution

Usually Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive.

configuration file

<pages enableSessionState="true" >
<httpModules>
 <add type="System.Web.SessionState.SessionStateModule" name="Session" />
 </httpModules>

Page directive

<%@ Page Language="C#" enableSessionState="true"%>

This happens when IIS is not configured properly after creating SharePoint application and there are web parts or features that use session you may get the above error.

You can enable the session state in IIS when you followed step as below: