Wednesday, June 17, 2026

Integrating AI API with SPFx Web Part

AI is becoming an important part of modern applications. One useful use case in SharePoint is connecting AI APIs inside an SPFx web part.

This post will explain at high level ,how we can connect an AI API with an SPFx web part and create a simple 'Document Summary' solution.


Solution Architecture


Process
  1. SPFx web part reads document content from SharePoint
  2. Document content is sent securely to AI API
  3. AI service generates summary of the document
  4. SPFx web part displays summary to the user
Technology Stack
  • SharePoint Framework (React + TypeScript)
  • Microsoft SharePoint Online
  • REST API or Microsoft Graph API
  • AI API such as OpenAI, Azure OpenAI, or custom AI service
  • Azure Function or Backend API for secure communication

Frontend – SPFx Web Part


Read Document Content

The SPFx web part can read document content using SharePoint APIs/ PnP / Graph APIs.

Example:

const apiUrl = `${webAbsoluteUrl}/_api/web/GetFileByServerRelativeUrl('${fileUrlEncoded}')/$value`;

const response = await context.spHttpClient.get( apiUrl, SPHttpClient.configurations.v1 );

const content = <get text content from response based on different file type>


Calling AI API

After reading the document content, send it to AI service.

Example:

let headers = {
    'Content-Type': 'application/json'
};

headers.Authorization = `Bearer ${openAiKey}`;

let requestBody = {
    messages: [
        { 
        role: 'system', 
        content: 'You are a helpful summarization assistant.' 
        },
        { 
        role: 'user', 
        content: `Summarize this document. Document text:\n${content}` 
        }
    ],
    max_tokens: <maxTokens>
};

requestBody.model = <model>;

const result = await fetch(apiUrl, {
    method: "POST",
    headers,
    body: JSON.stringify(requestBody)
});

const summary = await result.json();

The AI service will process the document and return the summary.


Security Consideration

Do not keep API keys directly inside frontend code.

Recommended approach:

  • SPFx sends request to Azure API or Azure Function
  • Backend stores API key securely
  • Backend calls AI provider
  • Response is returned back to SPFx web part

This helps in protecting API keys and keeps the solution secure.


Conclusion

Integrating AI APIs with SPFx web parts can make SharePoint applications smarter and more useful. The future of SharePoint development is AI-powered intelligent solutions.

Sunday, December 28, 2025

SharePoint Online + Acumatica Integration Architecture (Using SPFx & OAuth2)

Modern SPFx + OAuth2 + Acumatica ERP Integration

Integrating SharePoint Online with Acumatica ERP allows organizations to bring core ERP data—such as Stock Items, Customers, Vendors, Sales Orders, and Cases—directly into a modern SPFx web part. This post shows how authentication, tokens, and data flows work together in a secure enterprise-ready design.


🌐 High-Level Architecture

The following diagram shows the full end-to-end architecture:


Figure 1 — SharePoint–Acumatica Integration Architecture


1️⃣ Solution Overview

The SPFx web part enables users to:

  • Filter and browse Acumatica entities
  • Select entity items and display fields in real time
  • Optionally save entity fields into a SharePoint list
  • Work with either cached or live ERP data

2️⃣ Architecture Components

🔹 SharePoint Online

  • Hosts SPFx UI
  • Stores selected entity data in lists
  • Authenticates via Microsoft Entra ID (MSAL)

🔹 SPFx Web Part

  • React-based UI
  • Calls backend API using access token
  • Stores access + refresh tokens
  • Displays live or saved Acumatica data

🔹 Integration API (Azure Function / App Service)

  • Handles authentication to Acumatica
  • Stores and refreshes tokens
  • Executes REST calls securely

🔹 Acumatica ERP

  • Exposes REST API
  • Supports OAuth2 & Azure AD SSO
  • Returns requested entities

3️⃣ Authentication Flows

Three authentication models can be used depending on business and security needs.

🔵 Flow A: Service Account (Admin Credentials)

A backend service account authenticates to Acumatica and returns ERP data to SharePoint. This is easiest for read-only, system-level operations.

🟢 Flow B: User Credentials (OAuth 2.0 Authorization Code)

Users enter their Acumatica credentials. Access token is issued per user, respecting their permissions in Acumatica.

🟣 Flow C: Azure AD SSO (Recommended)

Provides seamless login between SharePoint and Acumatica using the same Entra ID identity.


4️⃣ Token Lifecycle

SPFx stores and uses the following:

  • Access Token
  • Refresh Token
  • Expiry Time

When the access token expires, the refresh token is used to obtain a new one automatically. No user interaction needed.


5️⃣ Data Delivery Modes

🔹 Local Mode (Cached Data)

  • Selected entity fields saved in SharePoint list
  • Fast page load
  • Best for stable master-data

🔹 Live Mode (Real-Time API Calls)

  • Data fetched from Acumatica on every page load
  • No duplication of ERP data in SharePoint
  • Ideal for dynamic data (orders, quantities, QC updates)

6️⃣ High-Level Data Flow

  1. User opens the SharePoint page
  2. SPFx authenticates using MSAL
  3. SPFx queries the Integration API
  4. API manages token lifecycle
  5. Acumatica returns requested entity data
  6. SPFx outputs or stores the data

7️⃣ Why This Architecture Works

  • Secure (OAuth2 + Azure AD)
  • No credentials stored client-side
  • Supports real-time and cached modes
  • Scalable using Azure Functions
  • Works with enterprise SSO


Part 1 - Acumatica Files -> SharePoint DMS Integration

Part 2 - SharePoint DMS -> Acumatica Files Integration

Displaying SharePoint Files Inside a Custom Acumatica Screen

Allow Users to Fetch Files From SharePoint Into Acumatica Entities

Many organizations use SharePoint Online as their primary document management system while relying on Acumatica as their ERP. A common requirement is enabling users to view SharePoint files inside Acumatica and selectively attach them to ERP entities such as:

  • Sales Orders
  • Purchase Orders
  • Vendor Profiles
  • Customer Accounts
  • Cases / Projects
  • Quality Documents (QC)
  • Any custom entity

This article describes an architecture where a custom Acumatica screen displays files from a SharePoint library. Users can select a document and import it into Acumatica as an attachment.


1. Overview

A custom screen is added to Acumatica that connects to a SharePoint document library. The integration supports:

  • Viewing SharePoint files within Acumatica
  • Filtering files based on metadata
  • Previewing files
  • Selecting one or multiple files
  • Attaching selected files into Acumatica entities

The integration works using either:

  • Azure AD SSO (user identity flows from Acumatica to SharePoint), or
  • Azure App Authentication (client credentials for system-to-system calls).

2. Authentication Options

Option 1 — SSO Authentication (Recommended)

  • Acumatica user logs in via Azure AD
  • The same identity is used to call SharePoint
  • No additional login required
  • Ensures user-based permissions on SharePoint
  • True single sign-on experience

Option 2 — Azure App (Client Credentials)

  • Background service or Acumatica server calls SharePoint
  • Uses App Registration (Client ID + Secret or Certificate)
  • Useful when document visibility does not depend on user rights
  • Consistent system identity for auditing

Both models allow Acumatica to securely communicate with SharePoint using the Microsoft Graph API.


3. What the Custom Screen Does

3.1 Fetch SharePoint Files

The custom screen retrieves the following information from SharePoint:

  • File names
  • Versions
  • Metadata
  • Approval status
  • Last modified date
  • Secure, time-bound download URL

Files are displayed inside Acumatica using a grid or panel.

3.2 Select and Import

  • User selects one or more files
  • Acumatica requests the file binary from SharePoint
  • File is securely returned via API
  • Document is attached to the selected entity (SO, PO, Vendor, etc.)

3.3 Metadata Mapping

Typical metadata synced from SharePoint:

  • Document Category
  • Entity ID (e.g., SO000234)
  • Entity Type (SalesOrder, PurchaseOrder, Customer, Vendor)
  • Uploaded By
  • Approval Workflow Status

4. Architecture

High-Level Flow

Acumatica Custom Screen → Integration API (optional) → Microsoft Graph → SharePoint Library

Steps in Detail

  1. User opens the custom screen in Acumatica
  2. Screen retrieves SharePoint library items
  3. Metadata and file information is displayed
  4. User selects files and clicks Import
  5. SharePoint returns the file binary
  6. Acumatica attaches the document to the target entity

If an Azure Function is used as middleware, it handles:

  • OAuth2 / SSO token management
  • Secure Graph API calls
  • Normalized JSON responses

5. Typical Use Cases

Finance

Attach invoice PDFs or bank receipts stored in SharePoint to AP/AR transactions.

Procurement

Link vendor quotes, contracts, and specifications to Purchase Orders.

Sales

Attach proposals, agreements, and customer documents.

Quality (QC)

Pull approved certificates and inspection reports into Acumatica.

Projects

Attach drawings, CAD files, and site documentation stored centrally.


6. Benefits

  • Centralized document management in SharePoint
  • No manual download and re-upload
  • Approval-driven governance before ERP usage
  • Consistent security using Azure AD
  • Improved user experience within Acumatica
  • Full audit trail using SharePoint and ERP metadata
  • Higher data quality through metadata mapping

7. Conclusion

This integration allows Acumatica to consume approved, metadata-rich documents directly from SharePoint, providing a seamless and secure way to attach files to ERP entities.

Result:

  • SharePoint for document storage
  • Approval workflows via SharePoint / Power Automate
  • Acumatica for business processing


Part 1 - Acumatica Files -> SharePoint DMS Integration

Part 3 - Acumatica Entity -> SharePoint List/Pages Integration

Thursday, December 25, 2025

Acumatica - SharePoint DMS Integration
SPFx Library Extension + Approval Workflow

SharePoint–Acumatica DMS Integration — SPFx Library Extension

SharePoint Online is a powerful DMS (versioning, metadata, workflows). Acumatica is the ERP system of record. This integration routes documents through SharePoint libraries, enforces approval and metadata, and only publishes validated documents into Acumatica.


Overview

A custom SPFx Library Extension adds two actions to document libraries:

  • Get From Acumatica — Fetch attachments from Acumatica into the current library.
  • Publish to Acumatica — Push approved SharePoint files into Acumatica as attachments.

All uploaded files are routed through the SharePoint library, reviewed via an approval workflow, and only published to Acumatica after approval—ensuring governance and auditability.


How It Works

Step 1 — Upload & Metadata

When a user uploads a file, default metadata is applied automatically:

  • Entity Type (Customer, Vendor, Order, Project, etc.)
  • Entity ID
  • Document Category
  • Status = Draft

Step 2 — Approval Workflow

A Power Automate approval flow handles reviewer assignment, notifications and status changes. Only when the file is Approved does the Publish to Acumatica action become available.

Step 3 — Publish to Acumatica

  1. SPFx extension invokes the Integration API (Azure Function / App Service)
  2. API authenticates with Acumatica (OAuth2 / SSO)
  3. File binary + metadata are posted to Acumatica and attached to the correct entity
  4. SharePoint status updated to Published and audit log saved

Reverse Sync — Get From Acumatica

The extension can also pull attachments from Acumatica to SharePoint. Workflow:

  • Select entity in the UI
  • Click Get From Acumatica
  • Attachments are downloaded to the current folder with mapped metadata

Architecture (High-level)

Key components:

  • SharePoint Online Library — storage, metadata, versioning
  • SPFx Library Extension — UI actions, client logic
  • Power Automate — approval workflows
  • Integration API (Azure) — token handling, Acumatica calls
  • Acumatica REST API — attachments & entity metadata
Figure — SharePoint to Acumatica DMS Integration (high-level)

SPFx Library Extension

The SPFx Library Extension is the core interaction layer embedded directly within the SharePoint document library. It provides contextual actions and communicates with Acumatica in real time.

  • Get From Acumatica – Fetch documents or metadata from Acumatica into SharePoint.
  • Publish to Acumatica – Publish approved files directly to Acumatica using REST APIs.

Authentication is handled using either:

  • Azure AD access token (recommended)
  • Stored Acumatica OAuth token (where required)

Power Automate

Power Automate is intentionally kept minimal and focused only on business approvals.

  • Used exclusively for approval workflows
  • No publishing or integration logic

Once the approval is completed:

  • File status is updated to Approved
  • The Publish to Acumatica action becomes available in the SPFx extension

Azure Function (Optional)

An Azure Function can be introduced if additional security or backend validation is required.

Typical use cases include:

  • IP-restricted Acumatica environments
  • Backend token handling
  • Additional validation or logging

If Acumatica allows direct client-to-API communication, this layer can be skipped.


End-to-End Flow

The overall document flow is simple, auditable, and approval-driven:

  1. User uploads a document to the SharePoint Library
  2. Approval workflow runs via Power Automate
  3. After approval, SPFx Extension enables publishing
  4. SPFx Extension calls Acumatica REST API (directly or via Azure Function)

User → SharePoint Library → SPFx Extension → (Optional Azure Function) → Acumatica REST API



Business Benefits

  • Governance: Only approved documents reach ERP.
  • Consistency: Metadata normalization for better search & reporting.
  • Auditability: Version history, approver details and workflow logs.
  • Process Control: Centralized ingestion point for all company uploads.
  • Compliance: Documents validated before ERP consumption.
  • Clear separation of concerns
  • Secure and governed document publishing
  • No unnecessary backend dependency
  • Better user experience within SharePoint

Common Use Cases

  • Invoice and Finance document validation before publish
  • Purchase / Sales attachments (POs, Delivery Notes)
  • QC Reports and Certificates—approved prior to upload
  • Vendor and Customer contract lifecycle management
  • Project documentation and technical drawings

Implementation Notes

  • Security: Keep credentials & tokens in a secure server-side store. Do not store refresh tokens in browser localStorage.
  • API: Integration API should handle retries, throttling and token refresh.
  • UX: Display publish status and last-synced timestamp on the file card.
  • Audit: Log every publish and retrieval action with user context for compliance.

Conclusion

Making SharePoint the document gateway for Acumatica provides strong governance, better collaboration, and a single controlled ingestion point. By using SPFx library extensions, Power Automate approval workflows, and a secure integration API, organizations ensure only validated, metadata-rich documents enter the ERP—reducing errors and improving compliance.


Part 2 - SharePoint DMS -> Acumatica Files Integration

Part 3 - Acumatica Entity -> SharePoint List/Pages Integration

Monday, December 28, 2020

Authenticate SharePoint Online SOAP Services

Connect To Office 365 SharePoint Online site through SOAP service, authenticate user and get the list of all SharePoint List .
1. Authenticate User Function , Get Authenticate cookie -

public static CookieContainer GetAuthCookies(Uri webUri, string userName, string password)
{
    var securePassword = new SecureString();
    foreach (char c in password) { securePassword.AppendChar(c); }
    var credentials = new SharePointOnlineCredentials(userName, securePassword);
    var authCookie = credentials.GetAuthenticationCookie(webUri);
    var cookieContainer = new CookieContainer();
    cookieContainer.SetCookies(webUri, authCookie);
    return cookieContainer;
}


2. Connect to SharePoint Online SOAP Service

var webUri = new Uri("https://MyTest.sharepoint.com/");
Lists list = new Lists();  //SharePoint Lists SOAP Service
list.CookieContainer = GetAuthCookies(webUri,"userName","password");
XmlNode result = list.GetListCollection();
var docResult = XDocument.Parse(result.OuterXml);
XNamespace s = "http://schemas.microsoft.com/sharepoint/soap/";
var listEntries = from e in docResult.Descendants(s + "List")
select new
{
      Title = e.Attribute("Title").Value
};



 

Also Applicable For -
Connect with SharePoint Online Web Services to access list
Authenticate
Office 365 SharePoint Online SOAP Services
Get All Lists from Office 365 SharePoint Online Site

Thursday, December 7, 2017

SharePoint Site Retention Solution

SharePoint sites can quickly grow , keeping outdated/inactive sites around takes up storage space, makes it difficult for people to find current information, and may also be undesirable for compliance reasons. 
Retention policies are particularly helpful for organizations that allow large groups of users to create their own sites. This policy is extremely important for organization, because transferring the content to another location significantly reduces the cost of its storage.

Default retention options has limited features and less user involvement in process. My custom solution,  provide all site user and record management team involvement in retention process.

 


Thursday, March 12, 2015

ListView Day Filter in SharePoint

There was a query at technet forum , "Requirement to show "Daily" stats on a custom list.  Criteria are to show items modified between 3pm yesterday to 3pm today. "

Solution -  

1- Create a Calculated column in list. The formula should be  -
  • Name - ModifiedHrs
  • Type - Calculated
  • Formula:     =HOUR(Modified)
  • Format -Number (1, 1.0, 100)
    Number of decimal places:  0
2- Create a Tabular View ( e.g. DayState.aspx) for List. (not Calendar View), through browser with filter ( Modified equal to [Today]).
3. Now Open the view page (DayState.aspx) in SharePoint Designer code view [Edit in Advance Mode]
4. Locate the CAML query associated with the filter (Modified = [Today]), you can find something like

<WebPartPages:WebPartZone ---
<WebPartPages:XsltListViewWebPart ----
-----
<XmlDefinition>
<View --->
<Query>
<OrderBy>--</OrderBy>
<Where>
<Eq>
<FieldRef Name="Modified"/>
<Value Type="DateTime"><Today/></Value>
</Eq>
</Where>
</Query>
<ViewFields---->
----
</View></XmlDefinition>
</XmlDefinition>




5. Replace the <Where>----</Where> Section with this one

<Where>
<Or><And><Eq><FieldRef Name="Modified"/>
<Value Type="DateTime"><Today OffsetDays="-1"/>
</Value></Eq><Gt><FieldRef Name="ModifiedHrs"/>
<Value Type="Number">14</Value></Gt></And>
<And><Eq><FieldRef Name="Modified"/>
<Value Type="DateTime"><Today/></Value></Eq><Lt>
<FieldRef Name="ModifiedHrs"/>
<Value Type="Number">16</Value></Lt></And></Or>
</Where>
 
6. Save the page , and test in browser

Microsoft.SharePoint.PostSetupConfiguration.PostSetupConfigurationTaskException was thrown


Problem :
In a sharepoint 2013 Installation or SP1/CU installation ,  after installation when start psconfig wizard, it throws error - " An exception of type Microsoft.SharePoint.PostSetupConfiguration.PostSetupConfigurationTaskException was thrown.  Additional exception information: Failed to upgrade SharePoint Products."

Solution:

  •  Restart your Timer service before you run config wizard."Run As Administrator" on the Products Configuration Wizard.
  • Make sure no other user, other than SharePoint managed accounts, have dbowner permissions for the SharePoint databases.
  • Reboot after CU installed and disable the User Account Control for you service accounts.
  •  Try using powershell -PSConfig.exe -cmd upgrade -inplace b2b -force -cmd applicationcontent -install -cmd installfeatures

Ref - https://social.technet.microsoft.com/Forums/en-US/bd6f406a-a75b-4958-88be-06d364a60451/microsoftsharepointpostsetupconfigurationpostsetupconfigurationtaskexception-was-thrown-while?forum=sharepointadmin

Sunday, December 28, 2014

hide empty list view webpart

<script language="javascript">
var show="0";

function GetParentByTagName(parentTagName, childElementObj)
{
var parent = childElementObj.parentNode;
while(parent.tagName.toLowerCase() != parentTagName.toLowerCase())
{
parent = parent.parentNode;
 if (parent == null) break;
 }
return parent;
}

 if (show == "0")
{
var tds = document.getElementsByTagName("TD");
//var txt = 'There are no items to show in this view of the "Diaspark Contacts" list. To create a new item, click "New" above.';

var listname = new Array("Diaspark Contacts","Conference Room Booking","OnTourRootList","Absence List");

var webpartTitle = new Array("Announcements","My Conference Room Bookings","I am on Tour","I am Out Of Office","Birthday Wishes To...","Anniversary Wishes To..");

 var txtArr = new Array();

for(var j=0 ; j= 0) 
 { 
var nod = tds[i]; 
while (nod) 
{ 
nod = GetParentByTagName("TD",nod); 
if (nod.id.indexOf('WebPartWPQ') >= 0) 
 break; 
} 
var tmp = nod.getElementsByTagName("span")[0].innerText; 
 if (webpartTitle.join().indexOf(tmp) >=0) 
nod.style.display= "none"; 
} 
 }
 } 
}
 } 
</script>

Wednesday, November 27, 2013

Forms Based Authentication (FBA) in SharePoint 2013

Setting Forms Based Authentication (FBA) in SharePoint 2013 is almost same as to SharePoint 2010 [ http://gj80blogtech.blogspot.in/2010/12/forms-based-authentication-in.html ]. Some differences are in .net framework version (4.0),  web.config entries ,  .Net 4.0 membership provider configuration not supported in IIS directly, No option for classic mode authentication now etc.

In this article, we will see how to configure SQL Server based authentication on SharePoint 2010 site. The Process involve following step of configuration …

  1.     Create SqlServer User membership database
  2.     Create or Extend SharePoint Web application
  3.     Modify Web.Config files for following we applications
  4.     Create Custom Login Form   

Step 1: Create SqlServer User membership database

  • Run aspnet_regsql.exe Located at "C:\Windows\Microsoft.NET\Framework64\v4.0.30319" Directory
  • ASP.NET SQL Server Setup Wizard Will appears, On welcome screen . Click Next 
  • Select “Configure SQL Server for application services”, and then click next
  • Enter the SQL Server, authentication information  and FBA Database name; E.g. Server = SP2013 ;  Windows Authentication;   Database = FBADB
  • Complete the Wizard and close;
  • Make sure the Application Pool accounts (your web application, Security Token Site, Central Administration web site) have access [dbowner role] to the FBA database.
  • Create some test user on this database ;You can use some Membership tools for this e.g. http://www.codeplex.com/CKS/Release/ProjectReleases.aspx?ReleaseId=7450.Or alternatively do it from any asp.net website in IIS. Create a dummy asp.net web site only for managing users. –
    • Open IIS - inetmgr. Right click on Sites and select “Add Web Site…”
    • Enter the field values, e.g. site name = TestASPFBAUser , physical Path = C:\ TestASPFBAUser VirtualDirectory , port =12345 and click OK.
    • Open “Application Pools”. Check framework for this new application pool “TestASPFBAUser”, it should be “2.0″.  Note: IIS does not support management of users and roles for .NET 4.0.
    • Set the identity of application pool “TestASPFBAUser”  to the account that has read/write permissions to the membership database [FBADB]. – Right Click application pool -> click Advanced Settings -> click Identity.
    • Add Connection String :
      • Select your new site “TestASPFBAUser”   and open the “Connection Strings” page.
      • On Connection Strings page, click “Add…”
      • On the Add Connection String dialog, Enter the field values , e.g. name = FBADBConnection , server = SP2013 , database = FBADB , Credentials - “Use Windows Integrated Security” and click OK.
    • Add Provider :
      • Select your new site “TestASPFBAUser”   and open the “Providers” Page.
      • On Providers page, select Feature = ‘.Net Users’. Click “Add…”
      • In Add dialog, choose type = “SQLMembershipProvider”. Enter a name, e.g. FBAASPMembershipProvider.
      • Set Profile Properties. Note: The options selected here must match with the options in SharePoint web.config provider settings. e.g. I chose: [EnablePasswordReset=True, RequiresUniqueEmail    = True , StorePasswordInSecureFormat=True and left others as default false]. 
      • Set ConnectionStringName = FBADBConnection (we just created) and ApplicationName = /
      • Click OK to close the dialog
    • Add User:
      • Select your new site “TestASPFBAUser”   and open the “.Net Users” page.
      • Set default membership provider. Click “Set Default Provider…” in the right side panel.  Choose the membership provider “FBAASPMembershipProvider” (we just created )and click OK.
      • Click “Add…” in the right side panel to add a user.
      • From the “Add .Net User” dialog, give the user a name, email and password. E.g. User -  FBAAdmin , password  - admin@1234, email – abc@test.com, left Question and Answer fields blank. Click OK to create the user and close the dialog.
  • Now we have one test user in FBADB , we will use this user as a admin for FBA. You can use this page to add and edit other users.

Create or Extend SharePoint Web application

You Can create a new site for testing and can use both windows authentication and FBA on same site. Or you can extend any existing site and use FBA for extended site & windows authentication for existing site.E.g. in my case i have extended port 80 site (http://server/) to port 90 (http://server:90)
  • Create a new web application
    • Open SharePoint Central Administration -> Application Management -> Manage Web Applications -> Click New
    • Select “Create a new IIS web site” and enter other fields – Name , Port , Path etc.
    • Check the Enable Forms Based Authentication(FBA) checkbox
    • Enter the ASP.Net Membership Provider Name and ASP.NET Role Provider Name that you are planning to configure in the web.config. e.g. FBAMembershipProvider and FBARoleProvider
    • Left “Enable Windows Authentication” checked, to use dual authentication, Click OK.
    • An Application Created dialog will appear. Click the “Create Site Collection” link to create the first site collection for this web application.
    • On Create Site Collection dialog, enter name,  URL , template, Primary Site Collection administrator [domain account], leave Secondary Site Collection Administrator blank for now. 
    • Click OK.
  • Extend existing web application
    • Open SharePoint Central Administration -> Application Management -> Manage Web Applications ->Select Existing Web Application
    • Click on Extend in ribbon menu
    • Select “Create a new IIS web site” and enter other fields – Name , Port , Path etc.
    • Uncheck Enable Windows Authentication
    • Check the Enable Forms Based Authentication(FBA) checkbox
    • Enter the ASP.Net Membership Provider Name and ASP.NET Role Provider Name that you are planning to configure in the web.config. e.g. FBAMembershipProvider and FBARoleProvider
    • Select Zone = Intranet , click Ok

Edit Web.Config Files

Modify Web.Config files for following web applications
  1. Central Administration
  2. Security Token Service (STS)
  3. Web application 
Modify Central Administration site’s web.config File

•  "ConnectionStrings" Entry 
<configSections>…</configSections>
<connectionStrings>
<clear />
<add name="FBADBConnection" connectionString="data source=SP2013; Integrated Security=SSPI; Initial Catalog=FBADB" providerName="System.Data.SqlClient" />
</connectionStrings>

•  "PeoplePickerWildcards" Entry
<PeoplePickerWildcards>
<clear />
<add key="FBAMembershipProvider" value="%" />
<add key="AspNetWindowsTokenRoleProvider" value="%"/> 
</PeoplePickerWildcards>

•  "RoleManager & Membership" Entries
<system.web>
.......
  <roleManager enabled="true"
cacheRolesInCookie="false"
cookieName=".ASPXROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All"
defaultProvider="AspNetWindowsTokenRoleProvider"
createPersistentCookie="false"
maxCachedResults="25">
      <providers>
        <!-- FBA -->
        <clear />
        <add connectionStringName="FBADBConnection" applicationName="/" name="FBARoleProvider" type=" System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a " />
      <add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />  
      <!-- FBA end -->
      </providers>
    </roleManager>
    <membership defaultProvider="FBAMembershipProvider" userIsOnlineTimeWindow="15" hashAlgorithmType="">
      <providers>
        <!-- FBA -->
        <clear />
        <add connectionStringName="FBADBConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" passwordAttemptWindow="10" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" name="FBAMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <!-- FBA end -->
      </providers>
    </membership>
…
</system.web>

Security Token Service web.config

<configuration>
….
<!-- FBA -->
  <connectionStrings>
    <clear />
    <add name="FBADBConnection" connectionString="data source=SP2013; Integrated Security=SSPI; Initial Catalog=FBADB" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <membership>
      <providers>
        <add connectionStringName="FBADBConnection"
        enablePasswordRetrieval="false"
        enablePasswordReset="true"
        requiresQuestionAndAnswer="false"
        passwordAttemptWindow="10"
        applicationName="/"
        requiresUniqueEmail="true"
        passwordFormat="Hashed"
        name="FBAMembershipProvider"
        type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </membership>

    <roleManager enabled="true">
      <providers>
        <add connectionStringName="FBADBConnection" applicationName="/"
        name="FBARoleProvider"
        type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </roleManager>
  </system.web>
  <!-- FBA end -->
</configuration>

Web Application Web.config file
"ConnectionStrings" Entry
<!-- FBA -->
  <connectionStrings>
    <clear />
    <add name="FBADBConnection" connectionString="data source=SP2013; Integrated Security=SSPI; Initial Catalog=FBADB" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <!-- FBA End -->

<PeoplePickerWildcards>
      <clear />
      <add key="AspNetSqlMembershipProvider" value="%" />
      <!-- FBA -->
      <add key="FBAMembershipProvider" value="%" />
      <!-- FBA end-->
    </PeoplePickerWildcards>

<membership defaultProvider="i">
      <providers>
         <!-- FBA -->
        <clear />
        <add connectionStringName="FBADBConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" passwordAttemptWindow="10" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" name="FBAMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <!-- FBA end -->
        <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      </providers>
    </membership>
    <roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
      <providers>
        <!-- FBA -->
        <clear />
        <add connectionStringName="FBADBConnection" applicationName="/" name="FBARoleProvider" type=" System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a " />
        <!-- FBA end -->
        <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
     </providers>
    </roleManager>
  </system.web>


Save all the web.config files and do an IISRESET ;


Add admin user for FBA site
  • Open SharePoint Central Administration Site
  • Open Application Management page -  Central administration -> application managmenet
  • Select your web application - e.g. SharePoint-80
  • Click ok "userpolicy" button in the Ribbon control 
  • On User-Policy window , click on Add Users, then Next [default all zone]
  • Search for your FBA admin user , e.g. fbaadmin, and add it
  • Give full control permission to the user.
Now open your FBA site in new browser , it  will open login form - 
  • In case of single site with dual authentication , form ,will allow You to select authentication type while login - Form or window 
  • In Case of extended site with single FBA authentication , it will open directly the FBA default login form

Sunday, October 20, 2013

Install SharePoint 2013 on a single server by using machine user

This installation guide will help in installation of SharePoint 2013 on a single server non-domain environment. Especially for development environment we need to install SharePoint, SQLServer and other required software on a single machine. The default SharePoint installation require domain accounts and environment, but for development purpose we will do some trick to do the installation by using machine user in non –domain environment. This guide is not recommended for production or staging environment.

The Installation steps includes :
  1.     Preparation of Virtual Machine
  2.     Installing SQL Server 2012
  3.     Installing SharePoint 2013

Preparation of Windows server 2008 R2 Virtual Machine


  • Open VMWare Player and click on "Create a New Virtual Machine".
  • Select the "Installer disc image file (iso)" radio button and browse for the Windows server 2008 R2  .iso file.
  • Don't provide any product key, you can update it later.
  • Provide other VM details e.g. –
    • Administrator password,
    • OS version,
    • Virtual machine name and location,
    • Hard Disk settings[If you are using single disk then use size something around 100GB ],
    • Use a single file option for disk,
    • RAM , use at-least 6GB for the VM
    • Set the same number of processors as your host
    • For best performances disconnect blue tooth , USB, sound card, printer etc.
  • Complete the wizard. It will start Installation of OS - Windows server 2008 R2 
  • Once OS is installed, configure your VM so you can have internet connection on your guest VM.I usually set default VMNet8 adaptor for my VM.
  • Once you have Internet access on your VM, activate your window version.
  • Change Computer Name for your VM Machine- e.g. SP2013
  • Install all latest update for Windows and SP1. [Windows Server 2008 R2 Service Pack 1 (SP1)  - http://www.microsoft.com/en-us/download/details.aspx?id=5842 ]
  • For development environment disable Enhanced Security Configuration for IE. = > "Start -> Administrative Tools -> Server Manager -> Under Security Information, click Configure IE ESC. -> Set Configuration OFF for Administrator and Users"
  • Other optional configuration for Best VM Performance, recommended only for development environment  –
    • Open your Network {Local Area Network} Property and in the network configuration options, uninstall the QoS Packet Scheduler and the Link Layer Topology Discovery components, and uncheck IPv6. => "On Network Adaptors page -> Right Click your network  {Local Area Network} -> open Property."
    • Turn off all firewalls ( Private, domain, Public) => "Start -> Administrative Tools -> Server Manager ->Go To WindowsFirewall-> Open Advance Security Property -> Set Firewall State to OFF"
    • Set the system properties for best performances => "computer -> Right Click properties -> Open Setting in Performance section -> In Visual Effect tab , select ‘Adjust for best performance’ -> in Advanced tab , select program in ‘adjust for best performances’"
    • Activate the Desktop Experience feature => "Initial Configuration tasks -> Add feature -> Desktop Experience"
  • Create Following accounts –
    • SQL_Service account - Create the SQL_Service account : "Control Panel -> User Accounts -> Create Standard User e.g. SQLServiceAdmin -> Set a password ,e.g. P@ssword1"
    • SharePoint Server Farm Account – Create the database access account account : "Control Panel -> User Accounts -> Create Standard User e.g. SPFarmAdmin -> Set a password ,e.g. P@ssword1"

Installing SQL Server 2012


  • Run the the SETUP of SQL Server 2012
  • On the SQL Server Installation Center, select Installation and "New SQL Server Stand alone installation"
  • Set the License key / Terms
  • Select “SQL Server Feature Installation” on Setup Role
  • Select features;  required are - Database Engine Services, Management Tools – Basic. You can choose other features also if you are planning to use ,e.g SSRS, SSAS etc.
  • Set root directory , SQL Instance details [Use Default Instance]
  • Set service account [SQLServiceAdmin] for the SQL Server Agent and the SQL Server Browser services.
  • Then set the collation for SharePoint , I used default one
  • On the Database Engine Configuration Screen, choose mixed mode and set password for sa user , e.g. P@ssword1
  • Add the current user as SQL Server administrator.
  • Then Set Data Directories , Data File locations
  • Complete the wizard, it will install SQL Server 2012 on your VM
  • Configuring SQL Server 2012
    • Open SQL Server management studio
    • Right click the Database engine and click "Properties".
    • Set the maximum Server Memory [e.g. 500 MB]
    • In the "Advanced" screen set the "Maximum Degree of Parallelism" to 1.
    • Configuration for Database : Once you install the SharePoint 2013 , then for each Content DB, Search Db, Temp DB , configure these settings –
      • Locate the database node, right click it and click properties
      • In the "Files" screen,
      • Set data files [Ideally, use one data file for each CPU cores]
      • Set the initial size of the files [e.g. 1000 MB].
      • Set the auto-growth [e.g 512 MB]
    • Open SQL Configuration Manager.- Locate Protocols for MSSQLSERVER and enable "Named pipes"
  • Optionally Install SQL Server 2008 R2 Service Pack 1 - http://www.microsoft.com/en-us/download/details.aspx?id=26727

Installing SharePoint 2013


  • Start SharePoint 2013 Server installation wizard.
  • Click the "install software prerequisites" link, and pass the License terms and summary.
  • After prerequisites installed, reboot your virtual machine
  • After reboot,  complete the installation wizard.
  • Running the Software Update - you must also install the following [if not already installed].
    • SharePoint parsing process crashes in Windows Server 2008 R2 (KB 2554876) [Included in Windows 2008 Server R2 SP1]
    • IIS 7.5 configurations changes (KB 2708075) [Included Windows 2008 Server R2 SP1]
    • .NET Framework version 4.5 hotfix KB 2759112 [http://go.microsoft.com/fwlink/p/?LinkId=267536]
  • Go back to the SharePoint 2013 installation screen and click on the "Install SharePoint Server" link. Pass the License terms
  • In the "Server Type" screen, choose the "Complete" installation.
  • In the File Location screen, set the search index files location. I used default locations.
  • Then, launch the installation.
  • On the Run Configuration Wizard, UNCHECK the check box and CLOSE the wizard
  • Using SharePoint 2010 Management Shell to create the SharePoint 2010 Configuration databases
    • Open the SharePoint 2013 Management Shell
    • Run this command - New-SPConfigurationDatabase
    • Enter parameter values : The database name e.g. SharePoint_Config, The database Server name e.g. SP2013, Enter Farm credentials e.g. SP2013\SPFarmAdmin , P@ssword1.
    • Then enter passphrase e.g. P@ssword1.
    • PowerShell command will take a long time (>15 minutes) to create the SharePoint Farm databases.
  • Now Open SharePoint 2013 Products Configuration Wizard from start menu to Finalizing the SharePoint installation.
  • Click, yes on the warning dialog
  • Select “Do not disconnect from this server farm”
  • Specify a port number [e.g. 1111] for SharePoint 2013 central administration site.
  • Complete the configuration wizard. After Completion, the Central Administration site for SharePoint 2013 automatically opens. Enter your credentials.
  • The SharePoint 2013 Central Administration site is displayed and you are asked to participate to the Customer Experience Improvment Program.
  • Then you are asked to use the configuration wizard. If you want the minimal services and processes to run in your development environment then do not run this wizard.

Troubleshooting SharePoint 2013 Installation


  • Issue # 1: "New" ribbon icon disabled in central admin, when you are trying to create any new web application or new service. Resolution: Open the Internet Explorer with "Run as Administrator" privileges.
  • Issue # 2:  Central admin site launched with a blank page. Resolution:
    • Enable “Basic Authentication” for Central administration site in IIS.[ IIS-> Sites-> SharePoint Central administration-> Authentication] and reset IIS.
    • Add the Central Admin app pool user to the local admins group in machine (if they are different) and Reset iis .
    • Another Reason may be that some of the authentication providers may not be installed in IIS properly. If you cannot see windows/Basic/Digest authentication mechanisms in authentication list. Then add these authentications in IIS and enable windows authentication for your site, if not work then try for basic authentication.
  • Issue # 3:  could not load file or assembly 'Microsoft.IdentityModel. Resolution: Download the pack from  http://www.microsoft.com/downloads/details.aspx?FamilyID=eb9c345f-e830-40b8-a5fe-ae7a864c4d76&displaylang=en and install it in your machine.
  • Issue # 4: An exception of type Microsoft.SharePoint.Upgrade.SPUpgradeException. Resolution: You may get this error, when you are trying to configure the SharePoint central admin (SharePoint product configuration wizard). So, download the chart control from http://go.microsoft.com/fwlink/?LinkID=122517  and install it.


Thursday, August 29, 2013

Create New Secure Store Service Application ID in SharePoint 2010 using PowerShell


Use CreateSecureStoreApplicationID function to new SharePoint Secure Store Application ID using Powershell.

Parameters : 
  1. $sssName - Mandatory - SharePoint Web Url - e.g. http://server:port/ 
  2. $sssFriendlyName - Mandatory - SharePoint Library Name 
  3. $sssContactEmail - Mandatory - File Path on hard drive , e.g. .\abc.xlsx
  4. $sssAdminIdentity
  5. $sssAdminPassword
  6. $defaultServiceContextUrl


function CreateSecureStoreApplicationID
{

[CmdletBinding()]
    Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string]
$sssName,
    [Parameter(Mandatory=$true)]
    [string]
$sssFriendlyName,
    [Parameter(Mandatory=$true)]
    [string]
$sssContactEmail,
    [Parameter(Mandatory=$true)]
     [string]$sssAdminIdentity,
    [Parameter(Mandatory=$true)]
    [string]
$sssAdminPassword,
    [Parameter(Mandatory=$true)]
    [string]
$defaultServiceContextUrl
    )
    


    Start-SPAssignment -Global  
    $SecureStoreServiceInstances = Get-SPServiceInstance | ? {$_.GetType().Equals([Microsoft.Office.SecureStoreService.Server.SecureStoreServiceInstance])}
    $SecureStoreServiceInstance = $SecureStoreServiceInstances | ? {$_.Server.Address -eq $env:COMPUTERNAME}
    If (-not $?)
    {
    Throw " - Failed to find Secure Store service instance"
    }  

    if ($SecureStoreServiceInstance.Status -eq "Disabled")
    {
        Throw "-Secure Store Service Application is disabled"
    }
       
    $defaultServiceContext = Get-SPServiceContext $defaultServiceContextUrl
    try
    {
    $ssApp = Get-SPSecureStoreApplication -ServiceContext $defaultServiceContext -Name $sssName -ea "SilentlyContinue"
    if ($?)
    {
      Write-Host "."
    }
    else
    {
       Write-Host "."
       throw $error[0].Exception
    }
    }
    catch
    {
        $ssApp = $null
    }
    if ($ssApp -ne $null)
    {
    Write-Host -f yellow "Secure Store Service Application $sssName already exists"
    return
    }
    Write-Host -f yellow "Creating new Secure Store Application Id"
    $UserNameField = new-spsecurestoreapplicationfield -name "Windows UserName" -type WindowsUserName -masked:$false
    $PasswordField = new-spsecurestoreapplicationfield -name "Windows Password" -type WindowsPassword -masked:$true
    $fields = $UserNameField, $PasswordField   
   
    $targetApp = new-spsecurestoretargetapplication -Name $sssName -FriendlyName $sssFriendlyName -ContactEmail $sssContactEmail -ApplicationType Group

    $targetAppAdminAccount = New-SPClaimsPrincipal -Identity $sssAdminIdentity -IdentityType WindowsSamAccountName
   
   
    $ownerClaims = New-SPClaimsPrincipal -EncodedClaim "c:0(.s|true"  
   
    $ssApp = new-spsecurestoreapplication -ServiceContext $defaultServiceContext -TargetApplication $targetApp -Administrator $targetAppAdminAccount -Fields $fields -CredentialsOwnerGroup $ownerClaims
      
    # Set credential (username, password) for SSS
    $ssApp = Get-SPSecureStoreApplication -ServiceContext $defaultServiceContext -Name $sssName
    $credSecValue1 = ConvertTo-SecureString $sssAdminIdentity -AsPlainText -Force
    $credSecValue2 = ConvertTo-SecureString $sssAdminPassword -AsPlainText -Force
    $credentialValues = $credSecValue1,$credSecValue2
    write-host -f Green "Success"   
    # Fill in the values for the fields in the target application 
    Write-Host -f yellow "Updating Secure Store Application $sssName Identity Credential Values"
    Update-SPSecureStoreGroupCredentialMapping -Identity $ssApp -Values $credentialValues 
    write-host -f Green "...Success"


    Stop-SPAssignment -Global 

}


Function  Calling -


$sssName = "SecureStoreName"$sssFriendlyName = "Secure Store Friendly Name"
$sssContactEmail = "Email@abc.com"
$sssAdminIdentity = "domain\user"
$sssAdminPassword = "Password"
$defaultServiceContextUrl = "http://server:port/" 
   
CreateSecureStoreApplicationID $sssName $sssFriendlyName $sssContactEmail $sssAdminIdentity $sssAdminPassword $defaultServiceContextUrl


Monday, August 26, 2013

Add Excel Web Access WebPart Using PowerShell


Use Add-EWAWebPart function to add a Excel Web Access webpart in a SharePoint page using PowerShell script.

Parameters : 
  1. $webUrl - Mandatory - SharePoint Web Url - e.g. http://server:port/ 
  2. $ExcelFileURL - Mandatory - Excel File URL 
  3. $pageRelativeUrl - Mandatory - SharePoint WebPart Page Relative Url , e.g. "Library/page.aspx"
  4. $zone - Mandatory -  The WebPartZoneBase that webPart is being added to.e.g. Left, Right
  5. $zoneIndex - Mandatory - An integer that represents the ordinal position that webPart occupies in zone, relative to other controls in zone.
function Add-EWAWebPart
{   
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string]$webUrl,
    [Parameter(Mandatory=$true)]
    [string]
$ExcelFileURL,
    [Parameter(Mandatory=$true)]
    [string]
$pageRelativeUrl,
    [Parameter(Mandatory=$true)]
    [string]
$
zone,
     [Parameter(Mandatory=$true)]
    [int]
$
zoneIndex
)     
  
    Start-SPAssignment -Global 

    $spWeb = Get-SPWeb -Identity $webUrl
   
    $newXml = "<?xml version='1.0' encoding='utf-8'?><webParts><webPart xmlns='http://schemas.microsoft.com/WebPart/v3'><metaData><type name='Microsoft.Office.Excel.WebUI.ExcelWebRenderer, Microsoft.Office.Excel.WebUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' /><importErrorMessage>Cannot import this Web Part.</importErrorMessage></metaData><data><properties><property name='Title' type='string'>EWAWP</property><property name='WorkbookUri' type='string'>"+ $ExcelFileURL +"</property></properties></data></webPart></webParts>"
   
    $webpartmanager=$spWeb.GetLimitedWebPartManager($pageRelativeUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
    $errorMsg =""
    $sr = new-object System.IO.StringReader $newXml
    $xr = new-object System.Xml.XmlTextReader $sr
    $myCustomWP = $webpartmanager.ImportWebPart($xr,[ref]$errorMsg)  
        
    if(!$webpartmanager.WebParts.Contains($myCustomWP))
    {
        Write-Host -NoNewLine -f yellow "Adding Webpart - $($myCustomWP.title)"       
        $webpartmanager.AddWebPart($myCustomWP, $zone, $zoneIndex)
        write-host -f Green "...Success!"
    }

    Stop-SPAssignment -Global 


}



Function  Calling -

$webUrl = "http://sever:port"
$ExcelFileURL = "http://sever:port/DocLib1/excel.xslx"
$pageRelativeUrl =  "DocLib1/abc.aspx"
$zone = "Left"
$zoneIndex = 1

Add-EWAWebPart $webUrl  $ExcelFileURL $pageRelativeUrl $zone $zoneIndex


Friday, August 23, 2013

Create Blank WebPart Page Using PowerShell


Use CreateBlankWebpartPage function to create blank webpart page in a Non-Publishing SharePoint web.

Parameters : 
  1. $webUrl - Mandatory - SharePoint Web Url - e.g. http://server:port/ 
  2. $WebPartPageName - Mandatory - New page name
  3. $WebPartPageLibraryName - Mandatory - Parent Library name for new page
  4. $pageLayout - Mandatory - Page Layout code - Int


function CreateBlankWebpartPage

{
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string]$webUrl,
    [Parameter(Mandatory=$true)]
    [string]
$WebPartPageName,
    [Parameter(Mandatory=$true)]
    [string]
$WebPartPageLibraryName,
    [Parameter(Mandatory=$true)]
    [int]
$pageLayout    )     

   Start-SPAssignment -Global 
    $spWeb = Get-SPWeb -Identity $webUrl   
    $pagesLibrary = $spWeb.Lists | Where { $_.Title -eq $WebPartPageLibraryName }  
    if ($pagesLibrary -eq $null) {
    Write-Host -f red "WebPart Page Library - $WebPartPageLibraryName  Not exists." 
    return  
    }
   
    Write-Host -f yellow "Creating New Webpart page $WebPartPageName in library $WebPartPageLibraryName"
    [Microsoft.SharePoint.SPFile]$spFile = $spWeb.GetFile("/" + $pagesLibrary.RootFolder.Url + "/" + $WebPartPageName + ".aspx")
    $flagConfirm = 'y'
    if($spFile.Exists -eq $true)
    {
        $flagConfirm = Read-Host "Page $WebPartPageName already exists in library $WebPartPageLibraryName, do you want to recreate(y/n)?"
    }
   
    if ($flagConfirm -eq 'y' -or $flagConfirm -eq 'Y')
    {
        Write-Host -NoNewLine -f yellow "Creating New Webpart page $WebPartPageName "

        $cmd ='<?xml version="1.0" encoding="UTF-8"?><Method ID="0,NewWebPage"><SetList Scope="Request">' + $pagesLibrary.ID + '</SetList><SetVar Name="Cmd">NewWebPage</SetVar><SetVar Name="ID">New</SetVar><SetVar Name="Type">WebPartPage</SetVar><SetVar Name="WebPartPageTemplate">' + $pageLayout + '</SetVar><SetVar Name="Overwrite">true</SetVar><SetVar Name="Title">'+ $WebPartPageName +'</SetVar></Method>';

        $spWeb.ProcessBatchData($cmd)
        write-host -f Green "...Success!"
        #Add weppart in Webpart page
   
        foreach($listItem in $pagesLibrary.Items)
        {
            if($($listitem.URL).Contains("$WebPartPageName" + ".aspx"))
            {           
                $myListItem = $listItem
                break;
            }
        }
        $pageUrl =  $($myListItem.URL)
        Write-Host -f yellow "New page Url -  $pageUrl"       
    }
    Stop-SPAssignment -Global 


}

Function  Calling -

$webUrl = "http://sever:port"
$WebPartPageLibraryName = "DocLib1"
$WebPartPageName =  "MyWPPage"
$pageLayout = 1
CreateBlankWebpartPage $webUrl  $WebPartPageName $WebPartPageLibraryName $pageLayout

These are page layouts available for New page.

  1. Full Page, Vertical
  2. Header, Footer, 3 Columns
  3. Header, Left Column, Body
  4. Header, Right Column, Body
  5. Header, Footer, 2 Columns, 4 Rows
  6. Header, Footer, 4 Columns, Top Row
  7. Left Column, Header, Footer, Top Row, 3 Columns
  8. Right Column, Header, Footer, Top Row, 3 Columns
 For more details on NewWebPage method , please check this -
 

Monday, August 19, 2013

Upload File In Document Library Using PowerShell


Use UploadFileInLibrary function to upload a file in SharePoint document Library.

Parameters : 
  1. $webUrl - Mandatory - SharePoint Web Url - e.g. http://server:port/ 
  2. $DocLibName - Mandatory - SharePoint Library Name 
  3. $FilePath - Mandatory - File Path on hard drive , e.g. .\abc.xlsx

function UploadFileInLibrary
{
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string]$webUrl,
    [Parameter(Mandatory=$true)]
    [string]$
DocLibName,
    [Parameter(Mandatory=$true)]
    [string]$
FilePath
    )
    

  
    Start-SPAssignment -Global 
    $spWeb = Get-SPWeb -Identity $webUrl
    $spWeb.AllowUnsafeUpdates = $true;
    $List = $spWeb.Lists[$DocLibName]
    $folder = $List.RootFolder
    $FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
    $File= Get-ChildItem $FilePath
    [Microsoft.SharePoint.SPFile]$spFile = $spWeb.GetFile("/" + $folder.Url + "/" + $File.Name)
    $flagConfirm = 'y'
    if($spFile.Exists -eq $true)
    {
        $flagConfirm = Read-Host "File $FileName already exists in library $DocLibName, do you    want to upload a new version(y/n)?"
    }
   
    if ($flagConfirm -eq 'y' -or $flagConfirm -eq 'Y')
    {
        $fileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
        #Add file
        write-host -NoNewLine -f yellow "Copying file " $File.Name " to " $folder.ServerRelativeUrl "..."
        [Microsoft.SharePoint.SPFile]$spFile = $folder.Files.Add($folder.Url + "/" + $File.Name, [System.IO.Stream]$fileStream, $true)
        write-host -f Green "...Success!"
        #Close file stream
        $fileStream.Close()
        write-host -NoNewLine -f yellow "Update file properties " $spFile.Name "..."
        $spFile.Item["Title"] = "Document Metrics Report"
        $spFile.Item.Update()
        write-host -f Green "...Success!"
    }  
    $spWeb.AllowUnsafeUpdates = $false;



    Stop-SPAssignment -Global  
}


Function  Calling -

$webUrl = "http://sever:port"
$DocLibName = "DocLib1"
$filePath =  ".\text.xlsx"
UploadFileInLibrary $webUrl  $DocLibName $filePath

Friday, August 16, 2013

Create SharePoint List / Library Using PowerShell


Use CreateSharePointLibrary function to create a new SharePoint List or Library.

Parameters : 
  1. $webUrl - Mandatory - SharePoint Web Url - e.g. http://server:port/ 
  2. $LibraryName - Mandatory - SharePoint Library Name 
  3. $Discription - Mandatory - SharePoint Library Description 
  4. $LibraryTemplate - Mandatory - SharePoint Library Template 



function CreateSharePointLibrary
{  
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string]$webUrl,
    [Parameter(Mandatory=$true)]
    [string]$LibraryName,
    [Parameter(Mandatory=$true)]
    [string]$Discription,
    [Parameter(Mandatory=$false)]
    [string]$LibraryTemplate
    )
   Start-SPAssignment -Global 

   $spWeb = Get-SPWeb -Identity $webUrl    
   $spListCollection = $spWeb.Lists  
   $spLibrary=$spWeb.Lists.TryGetList($LibraryName)
    if($spLibrary -ne $null)
    {
        write-host -f yellow "Library $LibraryName already exists in the site"
    }
    else
    {       
        Write-Host -NoNewLine -f yellow "Creating  Library - $LibraryName"
        $spListCollection.Add($LibraryName, $Discription, $LibraryTemplate)
        $spLibrary = $spWeb.GetList("$LibraryName")
        write-host -f Green "...Success!"
    }         
    Stop-SPAssignment -Global  
}


Function  Calling - 

$webUrl = "http://sever:port"

#-----------Document Library------------
$DocLibName = "DocLib1"
$LibraryTemplateDL = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
CreateSharePointLibrary $webUrl  $DocLibName  $DocLibName  $LibraryTemplateDL

# -------Data Connection Library-----------
$DataConnLibName = "DataConnLib1"
$LibraryTemplateDCL = [Microsoft.SharePoint.SPListTemplateType]::DataConnectionLibrary
CreateSharePointLibrary $webUrl  $DataConnLibName  $DataConnLibName $LibraryTemplateDCL


Similarly you can create any type of SharePoint List or Libraries , here are the details of List/Library Templates -
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splisttemplatetype.aspx

 

Thursday, August 1, 2013

Configure SSRS in SharePoint 2010

Here are the required steps for configuring SQL Server Reporting Services in SharePoint 2010 integrated mode.

My Test Environment : Single Server For SharePoint And SQL/SSRS Server , e.g. Server Name - GJ-PC

Prerequisites : Make sure you installed Reporting Service feature during SQL Server 2008 R2 Installation. Else add Reporting Services features to your existing SQL installation.
  • SQL/Report Server Configuration : 
    • Open Reporting Services Configuration Manager: Start->All Programs->Microsoft SQL Server 2008 R2 ->Configuration Tools ->Reporting Service Configuration Manager
    • Enter SSRS instance details, Service Account Details and click on Connect.[Required in case if SSRS service instance is not started].
    • Confirm that "Server Status" tab will show the status of SSRS , start the service if it is not started
    • Open "Web Service URL" tab: Configure report server web service virtual directory.Enter the details , e.g.
      • Virtual Directory : ReportServer
      • IP Address: All Assigned (Recommended)
      • TCP Port : 1110
      • Apply setting , 
      • It will create a new web service at http://GJ-PC:1110/ReportServer
    • Open "Database" tab :  
      • Click on change database link
      • Select "Create a new report server database". Click next
      • Enter the details e.g. Server name : GJ-PC , authentication: Current User - Integrated Security
      • Click on Test Connection link. If succeeded then Click next
      • Enter the details e.g. Database Name:Report Server , Report server Mode: SharePoint Integrated Mode
      • Click Next
      • Specify the credentials that the report server will use to connect to the database.You can use Service Credentials.
    • That’s all in SSRS configuration. In next step we will Configure SharePoint to use SSRS.
    •  
  • SharePoint Central Admin Configuration:
    • Open SharePoint 2010 Central Administration Site
    • Click on "General Application Settings", then select "Reporting Services Integration" in "Reporting Services" section.
    • Enter the following details on "Reporting Services Integration" form :
      • Report Server Web Service URL : http://GJ-PC:1110/ReportServer
      • Authentication Mode - Windows Authentication
      • Credential - Domain\User , password
      • Activate the Reporting Services Feature - Activate feature in all existing site collections or Activate feature in specified site collections.E.g. in my case i have activated it only for one site http://GJ-PC:8009
      • Once done, you will see the Activation State message.
    • Open SharePoint 2010 Central Administration -> General Application Settings -> "Add a Report Server to the Integration"
    • Specify the server and instance name of the report server database
  • Verify SSRS and SharePoint Integration
    • Open your SharePoint 2010 site collection
    • Go to Site Settings -> Site Collection Features.
    • Check if the Report Server Integration Feature is Active, if not just click activate.
    • Now upload any sample ssrs report file in SharePoint document library.
    • And open this report. It should show the report data
    •  
  • Create a sample SSRS report to show SharePoint List data into Report and publish it on SharePoint Library-
    • Open SQL Server Business Intelligence Development Studio from:  Start -> "All Programs" -> "Microsoft SQL Server 2008 R2" - SQL Server Business Intelligence Development Studio
    • Create New SSRS Project in Visual Studio : File -> New -> Project...
    • Select “Report Server project” template and create new project.
    • In solution explorer , Right click Reports folder and select Add New Report
    • Click Next to continue
    • Select New data source
      • Name - SPListDataSource
      • Type-Microsoft SharePoint List
      • Connection String - Local SharePoint - http://GJ-PC:8009
      • Credentials - select use Windows Authentication (Integrated Security)
      • Next
    • Click Query Builder
      • Select List - e.g. "MyList"
      • Test Query by "Run Query"
      • Ok -> Next
    • Select Tabular then click Next
    • Drag drop field in detail section , e.g Title, ID
    • Select Style then click Next
    • Enter Report name, Finish
    • Publish Report : 
      • Build Project - Right Click Project name - Build
      • Right Click Project name - Property
      • Set Target Report Folder -  Parent document library for report e.g. http://GJ-PC:8009/SSRS
      • Target Server URL - Site Url e.g. http://GJ-PC:8009/
      • Deploy - Right Click Project name - Deploy
    • Open your document library -  http://GJ-PC:8009/SSRS and check the report.

Wednesday, May 25, 2011

Customization Using JQuery

Client-Side Programming in Sharepoint # 5 - Customization Using JQuery



Save jquery-1.3.2.js in local document library (Jquery) , and update jquery file references in below scripts.You can placed these script either on the page in SPD editor or in CEWP.

  • List Forms (Edit/Display) - Hide created and modified by block from list forms (Edit, Display)

    <script type="text/javascript" src="/Jquery/jquery-1.3.2.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $('#onetidinfoblockV').hide();
    $('#onetidinfoblock1').hide();
    $('#onetidinfoblock2').hide();
    });
    </script>


  • List Forms (Edit/Display) - Replace created and modified by links with *** in list forms(Edit, Display)

    <script type="text/javascript" src="/Jquery/jquery-1.3.2.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $('a[href*="userdisp.aspx?ID="]').each(function(index) {
    var link = $(this);
    $(this).after("***");
    $(this).remove();
    });
    });</script>



  • List Forms (Edit/Display) - Hide Spell Check image and list from list forms(Edit, Display)

    <script type="text/javascript" src="/Jquery/jquery-1.3.2.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $('a[title*="Spelling..."]').each(function(index) {
    var link = $(this);
    link.parent().parent().hide();
    });

    });</script>


  • Site Header / Logo - Hide Title text from logo -
    Publishing Master Page- e.g. Blueband.master


    <script type="text/javascript" src="/Jquery/jquery-1.3.2.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $('a[class*="zz1_logoLinkId_1"]').each(function(index) {
    var link = $(this);
    if (link.text() == "Employee Portal")
    link.text(link.text().replace("Employee Portal", ""));
    });
    });</script>

    Default Master page - default.master

    <style type="text/css">
    .ms-sitetitle h1
    {
    display:none
    }
    </style>