Tuesday, November 18, 2014

AD Users not getting resolved in People Picker

Issue:- Any New User or Group created in Active Directory is not getting resolved in a specific SharePoint Site collection People Picker. It works fine for other Web Applications and if you create a new Site Collection in the same Web app, People Picker is resolving new Users and Groups there.
For the problematic Site Collection, the old Existing User accounts and Groups are resolving fine, only the New ones are not getting resolved in People Picker.




Resolution:-
Get-SPSite "http://SharePoint/sites/collection" | fl > C:\props.txt
If you open the Props.txt file, you will see the properties for this site collection. Look for "UserAccountDirectoryPath" property. By Default it should be blank, if it is not, that is causing new Users in AD not to be resolved in People Picker.

To Change the Property value to Blank, follow as below.


$Site = Get-SPSite "http://SharePoint/sites/collection"
$Val=""

Saturday, November 8, 2014

Microsoft.SharePoint.SPException

Following is code is working in console application but , it is not working in aspx page.

SPSite site = http://localhost:9292;
    SPSecurity.RunWithElevatedPrivileges(() =>
    {
        SPSiteSubscription subscription = SPSiteSubscription.Create();
       site = webApp.Sites.Add(subscription, siteUrl, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, null, null, null, useHostHeaderAsSiteName); // exception
       site.AdministrationSiteType = SPAdministrationSiteType.TenantAdministration;
   });

Exception Details : 

Microsoft.SharePoint.SPException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. ---> System.Runtime.InteropServices.COMException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.
at Microsoft.SharePoint.Library.SPRequestInternalClass.SetSiteQuota(String bstrUrl, UInt16 quotaId, Int64 diskQuota, Int64 diskWarning, Int32 userQuota, Double resourceUsageMaximum, Double resourceUsageWarning, Boolean bForSSC)
at Microsoft.SharePoint.Library.SPRequest.SetSiteQuota(String bstrUrl, UInt16 quotaId, Int64 diskQuota, Int64 diskWarning, Int32 userQuota, Double resourceUsageMaximum, Double resourceUsageWarning, Boolean bForSSC)
   --- End of inner exception stack trace ---
at Microsoft.SharePoint.SPGlobal.HandleComException(COMException comEx) at Microsoft.SharePoint.Library.SPRequest.SetSiteQuota(String bstrUrl, UInt16 quotaId, Int64 diskQuota, Int64 diskWarning, Int32 userQuota, Double resourceUsageMaximum, Double resourceUsageWarning, Boolean bForSSC) at Microsoft.SharePoint.Administration.SPQuota.Update() at Microsoft.SharePoint.SPSite.set_Quota(SPQuota value) at Microsoft.SharePoint.Administration.SPSiteCollection.Add(SPContentDatabase database, SPSiteSubscription siteSubscription, String siteUrl, String title, String description, UInt32 nLCID, String webTemplate, String ownerLogin, String ownerName, String ownerEmail, String secondaryContactLogin, String secondaryContactName, String secondaryContactEmail, String quotaTemplate, String sscRootWebUrl, Boolean useHostHeaderAsSiteName)   at Microsoft.SharePoint.Administration.SPSiteCollection.Add(SPSiteSubscription siteSubscription, String siteUrl, String title, String description, UInt32 nLCID, String webTemplate, String ownerLogin, String ownerName, String ownerEmail, String secondaryContactLogin, String secondaryContactName, String secondaryContactEmail, Boolean useHostHeaderAsSiteName)    at WSS4WS.ProvisioningService.<>c__DisplayClass5.<CreateSite>b__0() in C:\Projects\Web Services\WSS4WS\WSS4WS\ProvisioningService.asmx.cs:line 77    at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2()    at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)    at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)    at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)    at WSS4WS.ProvisioningService.CreateSite(String webApplicationName, String siteUrl, String title, String description, UInt32 lcid, String webTemplate, String ownerLogin, String ownerName, String ownerEmail, Boolean useHostHeaderAsSiteName)
Though the above code snippet works perfectly fine in console application but aspx is webrequest and SharePoint handles web request differently. All the webrequest validated with the FromDigest control. To get rid-off from this error message, we can change the web application validation settings in Central Administration > Web Application General Settings Page.
image
Enjoy this will solve your problem.

Tuesday, October 28, 2014

An error occurred whilst trying to load some required components, Please ensure the following prerequisite components are installed. Microsoft Web Developer Tools Microsoft Exchange Web Services”

Visual Studio 2012 provides a great environment for dev/test SharePoint 2013 Apps.
This is true both for scenarios where you want to dev/test in the cloud and then run the app in the cloud, as well as for scenarios where you want to dev/test in the cloud and then run the app using an existing on-premises environment.
If you want to create a SharePoint 2013 app and your receive the following exception, follow the next step by step guide to resolve this issue.


ewserror
  1. Close the messagebox and Visual Studio.
  2. Type appwiz.cpl in Run, this will open the Add/Remove Programs control window.
  3. Uninstall Microsoft Exchange Web Services Managed API 2.0
  4. Right click the EwsManagedApi32.msi link and use the Save link as option to store the msi in c:\downloads
  5. Navigate to c:\downloads and type cmd in the adres bar (this will open the command prompt with c:\downloads as location)


  1. Type dir and make sure EwsManagedApi32.msi is listed in the console window
  2. Type EwsManagedApi32.msi addlocal=”ExchangeWebServicesApi_Feature,ExchangeWebServicesApi_Gac”
  3. complete the installation procedure
  4. Open Visual Studio 2012 and start a new SharePoint 2013 App project.




Ref :


http://blogs.msdn.com/b/timquin/archive/2013/01/22/setting-up-visual-studio-2012-for-sharepoint-2013-development-offline.aspx




 http://leonzandman.com/2013/02/07/prerequisite-components-error-when-creating-a-visual-studio-2012-sharepoint-2013-app-project/




http://tomvangaever.be/blogv2/2013/06/an-error-occurred-whilst-trying-to-load-some-required-components-please-ensure-the-following-prerequisite-components-are-installed-microsoft-web-developer-tools-microsoft-exchange-web-services/

Monday, October 27, 2014

CSV File to Excel XLS



Open the CSV File
When you select the option to open a file in Excel, you will see the option Text Files that includes CSV files. The CSV file has an icon indicating that it is supported by Excel. This is the fastest method and the default action when you double click on a CSV file, although it does not work with all CSV files.

excel2010-file-open-csv
Open file in Excel 2010
excel2010-open-dialog-csv
Open file of CSV type in Excel 2010
Depending on the CSV file contents and the regional settings configuration of Windows, the data in the CSV file may not show correctly in Excel. The most common errors are:
- data is shown on a single column
- date columns are shown as text
- text columns containing only numbers are treated as number with leading zero removed
- currency values treated as text
Download the file advanced-csv-sample.csv to reproduce some of these errors.
excel2010-csv-format-error
CSV data incorrectly formatted: Order ID without leading zeroes and Order Date and EUR Amount as text instead of date and number
Open the CSV file in Notepad and notice that the leading zeroes in the Order ID field were removed by Excel. The Order Date value in the date format YYYYMMDD (year, month and day) wasn’t automatically recognized. Neither was the Amount in EUR value because this computer is configured to use period as decimal symbol. Both values appear as text instead of their correct formats, limiting the use of the data.
Use the Text Import Tool described below to mitigate these errors.
Import CSV File using Excel Text Import Tool
Click the Data tab on the Excel ribbon, then click the Get External Data option and select From Text on the popup menu, as shown below:
excel2010-get-external-data-text
Get External Data From Text function on Data tab
Select the CSV file to import with the Import Text File dialog and click Import button:
excel2010-external-data-open-csv
Use Import Text File dialog to open CSV file
Define the import settings (step 1 of 3). The contents of the file are shown, notice the use of comma to separate values and double quotes enclosing the EUR amount value because it contains a comma. Keep the data type as delimited to configure the delimiter in the next screen. You may need to change the File Origin to Windows (ANSI) depending on the file contents. Change it only if you notice weird characters in the processed data.
excel2010-text-import-wizard-1
Configure CSV file as delimited
Define the import settings (step 2 of 3). Select the right separator, comma in this example, to show the values into columns.
excel2010-text-import-wizard-2
Configure delimiter of CSV file with data preview
Define the import settings (step 3 of 3 – part 1). Review and if necessary change the data format of each column. As the column Order Id contains only numbers Excel treats it as number and removes the leading zeros. If we change the column data format to text Excel will not change its contents.
excel2010-text-import-wizard-31
Configure data format for text value in CSV file
Define the import settings (step 3 of 3 – part 2). Excel recognizes some date formats. If it does not, change the data format manually defining one of the supported formats. In the example we change the column Order Date to the right format. YMD means that the date is in the format Year – Month – Day.
excel2010-text-import-wizard-32
Configure data format for date value in CSV file
Define the import settings (step 3 of 3 – part 3). Sometimes even number columns need to be configured. In this example the Amount EUR column is using a different decimal symbol than the system’s configuration. To configure these cases, keep the data format as General, click the Advanced button and configure the decimal and thousands separators used in the column.
excel2010-text-import-wizard-33
Configure data format for amount value in CSV file
Define the destination of the imported data. After you finish configuring the wizard, Excel opens the Import Data dialog asking where to put the results. Select the proper location but do not click the OK button yet, as there is still one step left.
excel2010-text-import-data-sheet
Import Data dialog to define where to put the imported data
Click the Properties button to define the properties of the import process, so it can be used more times without the need of reconfiguring everything:
Query Definition
Keep it checked to save the import configuration (delimiter, column formats)
Refresh Control
The refresh control defines if the sheet will be automatically refreshed, if the file name changes and if the sheet should be refreshed and emptied when opened or closed. Uncheck the “Prompt for file name on refresh” option if the file always have the same name and location.
Data formatting and layout
Normally nothing to change
If the number of rows in the data range changes upon refresh
This configuration depends on the source file, if it always contain all data use the overwrite option, the insert options will move existing data down and load the new data above it
Fill down formulas in columns adjacent to data
Check this option if the sheet contains columns with formulas alongside imported data. Its recommended to use another sheet to process the imported data.
excel2010-external-data-range
External Data Range Properties dialog to define where to put the imported data
Click OK to close the External Data Range Properties dialog and click OK to close the Import Data dialog and import the data on the selected destination. If the data is formatted correctly, save the sheet.
excel2010-csv-format-right
CSV file imported with data formatted correctly
To refresh the data, importing a new file with the same format, click on any of the cells that holds data of a previous import. Then on the Data tab, click on the Refresh All Icon or the Refresh All option on its popup menu.
excel2010-text-import-data-refresh
Refresh All function to import CSV file again and refresh data

Monday, October 20, 2014

SharePoint 2013 updates Installation with less Time



1. Disable the IISAdmin and SPTimerV4 service
2. Shut down IIS Admin and Timer Services if they are running                                                                                                            
3. Give you the option to Pause the Search Service Application (see search notes below)                                                                                      
4. Stop Search Services (see search notes below)                                                                                                                                                     
5. Install the patch in passive mode (No user interaction required but will witness the patch install in the UI)
Note:  Power Shell should remain open in the background while patch is running


6. Upon completion of the patch, the Power Shell script, services in step 1 are set to Automatic                                                                          
7. Starts up IIS Admin and Timer Services                                                                      
                                                                        
8. Starts up Search Services            
                                                                                                                                                                    9. Resume the Search Service Application if it was paused   
                                                                                                                   
10. Finally, the script will display the Start Time and End Time for patch install
 
Instructions for Running the Power Shell Script


In order to run the script, save the flow script to a text editor like notepad.   Save the file with a .ps1 extension to a folder on the SharePoint Server.   Drop the SharePoint cumulative update in the same folder as the script.   In my example, I created a scripts folder where I dropped the powershell script and the cumulative update.
For Example:




 image


Important:  Only one update should be placed here and the file extension should be .exe. 
Finally,


 to run the script from c:\scripts using SharePoint Management Shell.  This script is tested on Windows 2012 running SharePoint 2013




image






Script :


<# ==============================================================
  //
  // Microsoft provides programming examples for illustration only,
  // without warranty either expressed or implied, including, but not
// limited to, the implied warranties of merchantability and/or
  // fitness for a particular purpose.
  //
  // This sample assumes that you are familiar with the programming
  // language being demonstrated and the tools used to create and debug
  // procedures. Microsoft support professionals can help explain the
  // functionality of a particular procedure, but they will not modify
  // these examples to provide added functionality or construct
  // procedures to meet your specific needs. If you have limited
  // programming experience, you may want to contact a Microsoft
  // Certified Partner or the Microsoft fee-based consulting line at
  //  (800) 936-5200 .
  //
  // For more information about Microsoft Certified Partners, please
  // visit the following Microsoft Web site:
  // https://partner.microsoft.com/global/30000104
  //
  // Author: Russ Maxwell (russmax@microsoft.com)
  //
  // ---------------------------------------------------------- #>

###########################
##Ensure Patch is Present##
###########################
$patchfile = Get-ChildItem | where{$_.Extension -eq ".exe"}
if($patchfile -eq $null)
{
  Write-Host "Unable to retrieve the file.  Exiting Script" -ForegroundColor Red
  Return
}

########################
##Stop Search Services##
########################
##Checking Search services##
$srchctr = 1
$srch4srvctr = 1
$srch5srvctr = 1
$srv4 = get-service "OSearch15"
$srv5 = get-service "SPSearchHostController"
If(($srv4.status -eq "Running") -or ($srv5.status-eq "Running"))
  {
    Write-Host "Choose 1 to Pause Search Service Application" -ForegroundColor Cyan
    Write-Host "Choose 2 to leave Search Service Application running" -ForegroundColor Cyan
    $searchappresult = Read-Host "Press 1 or 2 and hit enter" 
    Write-Host
   
   if($searchappresult -eq 1)
    {
        $srchctr = 2
        Write-Host "Pausing the Search Service Application" -foregroundcolor yellow
        Write-Host "This could take a few minutes" -ForegroundColor Yellow
        $ssa = get-spenterprisesearchserviceapplication
        $ssa.pause()
    }
   
    elseif($searchappresult -eq 2)
    {
        Write-Host "Continuing without pausing the Search Service Application"
    }
    else
    {
        Write-Host "Run the script again and choose option 1 or 2" -ForegroundColor Red
        Write-Host "Exiting Script" -ForegroundColor Red
        Return
    }
  }
Write-Host "Stopping Search Services if they are running" -foregroundcolor yellow
if($srv4.status -eq "Running")
  {
    $srch4srvctr = 2
    set-service -Name "OSearch15" -startuptype Disabled
    $srv4.stop()
  }
if($srv5.status -eq "Running")
  {
    $srch5srvctr = 2
    Set-service "SPSearchHostController" -startuptype Disabled
    $srv5.stop()
  }
do
  {
    $srv6 = get-service "SPSearchHostController"
    if($srv6.status -eq "Stopped")
    {
        $yes = 1
    }
    Start-Sleep -seconds 10
  }
  until ($yes -eq 1)
Write-Host "Search Services are stopped" -foregroundcolor Green
Write-Host

#######################
##Stop Other Services##
#######################
Set-Service -Name "IISADMIN" -startuptype Disabled
Set-Service -Name "SPTimerV4" -startuptype Disabled
Write-Host "Gracefully stopping IIS W3WP Processes" -foregroundcolor yellow
Write-Host
iisreset -stop -noforce
Write-Host "Stopping Services" -foregroundcolor yellow
Write-Host
$srv2 = get-service "SPTimerV4"
  if($srv2.status -eq "Running")
  {$srv2.stop()}
Write-Host "Services are Stopped" -ForegroundColor Green
Write-Host
Write-Host

##################
##Start patching##
##################
Write-Host "Patching now keep this PowerShell window open" -ForegroundColor Magenta
Write-Host
$starttime = Get-Date
$filename = $patchfile.basename
$arg = "/passive"
Start-Process $filename $arg
Start-Sleep -seconds 20
$proc = get-process $filename
$proc.WaitForExit()
$finishtime = get-date
Write-Host
Write-Host "Patch installation complete" -foregroundcolor green
Write-Host

##################
##Start Services##
##################
Write-Host "Starting Services Backup" -foregroundcolor yellow
Set-Service -Name "SPTimerV4" -startuptype Automatic
Set-Service -Name "IISADMIN" -startuptype Automatic
##Grabbing local server and starting services##
$servername = hostname
$server = get-spserver $servername
$srv2 = get-service "SPTimerV4"
$srv2.start()
$srv3 = get-service "IISADMIN"
$srv3.start()
$srv4 = get-service "OSearch15"
$srv5 = get-service "SPSearchHostController"
###Ensuring Search Services were stopped by script before Starting"
if($srch4srvctr -eq 2)
{
    set-service -Name "OSearch15" -startuptype Automatic
    $srv4.start()
}
if($srch5srvctr -eq 2)
{
    Set-service "SPSearchHostController" -startuptype Automatic
    $srv5.start()
}
###Resuming Search Service Application if paused###
if($srchctr -eq 2)
{
    Write-Host "Resuming the Search Service Application" -foregroundcolor yellow
    $ssa = get-spenterprisesearchserviceapplication
    $ssa.resume()
}
Write-Host "Services are Started" -foregroundcolor green
Write-Host
Write-Host
Write-Host "Script Duration" -foregroundcolor yellow
Write-Host "Started: " $starttime -foregroundcolor yellow
Write-Host "Finished: " $finishtime -foregroundcolor yellow
Write-Host "Script Complete" 






Ref : http://blogs.msdn.com/b/russmax/archive/2013/04/01/why-sharepoint-2013-cumulative-update-takes-5-hours-to-install.aspx

Thursday, October 2, 2014

Uploading Large Files in sharepoint 2013/2010/2007

  • Change the maximum upload size on the web application level


  • Central Admin>Application Management>Manage Web Applications> Select the desired web app and click General Settings on the ribbon







  • Modify the web.config file for the appropriate web application, this is located by default at C:\inetpub\wwwroot\wss\VirtualDirectories\web application name or port

      • Make a backup copy of the web.config, then open it
      • Do a Ctrl+f to find this element 


    <httpRuntime maxRequestLength="51200" requestValidationMode="2.0" />











    Modify the above element to match the following

    <httpRuntime executionTimeout="999999" maxRequestLength="2048000" requestValidationMode="2.0" />

    In the above step we added executionTimeout="999999" and we set the maxRequestLength to what we set the maximum upload size on the web application general settings, which is 2048000 (2000mb * 1024 = 2048000)



    Ref Links :


    http://blogs.technet.com/b/sammykailini/archive/2013/11/06/how-to-increase-the-maximum-upload-size-in-sharepoint-2013.aspx




    http://blogs.technet.com/b/praveenh/archive/2012/11/16/issues-with-uploading-large-documents-on-document-library-wss-3-0-amp-moss-2007.aspx













    Tuesday, September 30, 2014

    Project Server 2013 migration between environments.

    Project Server Migration required 2 databases ( PWA database + web application DB)




    Step 1 :  Dismounting Project web instance.


    Dismount-SPProjectWebInstance -SiteCollection  <URL of Test / Dev PWA site that you want to refresh with the Production data and config>




    image




    Step2 :


     Dismount-SPContentDatabase “<Database name here>”




    Step3 : Mounting Production Content DB 


    Mount-SPContentDatabase “<content database name restored in previous step>” -DatabaseServer “<Test / DEV SQL Server>” –WebApplication <web application URL>




    Step4 :  Mounting Project Database




    Mount-SPProjectDatabase -Name “Name of the restored Project Web App database to mount” –WebApplication “Web Application ULR that the Project Web App database will mount to” –DatabaseServer “Test / Dev SQL Server where the database was restored




    Step5  : Mounting Project database to web instance.


    Mount-SPProjectWebInstance –DatabaseName “Name of the restored Project Web App database to mount” –SiteCollection “web application URL + PWA path” –DatabaseServer “Test / Dev SQL Server where the database was restored




    NOTE : For example if the instance is called /PWA in Production, use /PWA in the command below on the Test / Dev environment.




    Verification :


    Get-SPProjectWebInstance –URL <PWA URL> | Select ProvisioningStatus




    Source of article is : http://pwmather.wordpress.com/2013/05/02/projectserver-2013-environment-migration-rollover-steps-powershell-ps2013-msproject-sp2013/


    Other Links :


    http://technet.microsoft.com/en-us/library/ee890097(v=office.15).aspx









    Wednesday, September 24, 2014

    Cannot Remove Server Reference from Farm CacheHostInfo is null

    He states “We can’t provision, unprovision, start, or stop a Cache Service because we still have a Cache Service that has no server attached.”
    Not exactly my problem, as I had a Cache Service that seemed to have two non-existent servers semi-attached. But his Scripts were the starting point for resolving my issue. I ran them in this order:
    Need the Farm name:


    $SPFarm = Get-SPFarm


    Need the Cache Name:


    $cacheClusterName = "SPDistributedCacheCluster_" + $SPFarm.Id.ToString()


    Need to use local (only) server as ClusterManager:


    $cacheClusterManager = [Microsoft.SharePoint.DistributedCaching.Utilities.SPDistributedCacheClusterInfoManager]::Local


    Need the Cluster name:
    
    
    $cacheClusterInfo = $cacheClusterManager.GetSPDistributedCacheClusterInfo($cacheClusterName)


    Need the Instance name:
    
    
    $instanceName ="SPDistributedCacheService Name=AppFabricCachingService"


    Need the service instance for the missing <computername>
    
    
    $serviceInstance = Get-SPServiceInstance | ? {($_.Service.Tostring()) -eq $instanceName -and ($_.Server.Name) -eq "<computername>"}


    Need to delete the instance reference:


    $serviceInstance.Delete()


    Repeat last two steps for second non-existent server.
    Set new information: 
    $cacheClusterInfo.CacheHostsInfoCollection
    Just for good measure, on the Services on Servers page, stopped and started Distributed Cache Service. 
    Then went to Servers in the Farm page and manually remove the servers successfully.
    Back in PowerShell console, I used Install-SPSolution to manually redeploy the solutions again even though they displayed as deployed on Solutions Management page.
    Everything is back and working correctly
    For your farm you may need to re-add instances of the Distributed Cache Service on existing servers in your farm with PowerShell:
    Add-SPDistributedCacheServiceInstance
    At least I am learning. The last time the Distributed Cache Service was corrupted, I just gave up and re-built my farm.




    Ref:
    http://summit7systems.com/cannot-remove-server-reference-from-farm-cachehostinfo-is-null/#comment-1962





    Monday, June 16, 2014

    CSOM in Sharepoint 2013


    CSOM made accessible through client.svc

    Direct access to client.svc not supported

    Calls to client.svc must go through supported entry points

    Supported entry points:
    Silverlight
    JavaScript
    .NET


    In Sharepoint 2013 Client.svc is extented to REST(HTTP GET, PUT, POST requests) API also.

    that means Client.svc is accepts HTTP GET, PUT, POST requests

    OData Protocal is also implemented.

    Sharepoint 2013  CSOM Support following server side functionality.

    User Profiles

    Search

    Taxonomy

    Feeds

    Publishing

    Sharing

    Workflow

    E-Discovery

    IRM

    Analytics

    Business Data



    Sharepoint 2010 CSOM diagram:




    Sharepoint 2013 CSOM Diagram:


    ListData.svc added REST support for reading & writing to SharePoint lists in SharePoint 2010

    it is still present in SP 2013 for backward capability.

    SP 2013 new development is done through REST or OData API.



    In Sharepoint 2010 CSOM Development following DLL we need to add

    Microsoft.Sharepoint.Client.dll
    Microsoft.Sharepoint.Client.Runtime.dll

    in Sharepoint 2013 CSOM Development( REST   is new features).


    Microsoft.Sharepoint.Client.dll
    Microsoft.Sharepoint.Client.Runtime.dll

    Microsoft.Sharepoint.Client.DocumentManagement.dll
    Microsoft.Sharepoint.Client.Publishing.dll
    Microsoft.Sharepoint.Client.Taxonomy.dll
    Microsoft.Sharepoint.Client.UserProfiles.dll


    Example :

                ClientContext SSite = new ClientContext("http://localhost");
                SSite.Credentials = CredentialCache.DefaultCredentials;
                Web site = SSite.Web;
                ListCollection lists = site.Lists;

                // load site info

                SSite.Load(site, SiteTitle => SiteTitle.Title);
                SSite.ExecuteQuery();
                Console.WriteLine("Site Title: " + site.Title);
             
                // create list

                ListCreationInformation newList = new ListCreationInformation();
                newList.Title = "Clients";
                newList.Url = "Lists/Clients";
                newList.QuickLaunchOption = QuickLaunchOptions.On;
                newList.TemplateType = (int)ListTemplateType.Contacts;
                site.Lists.Add(newList);

                 // lists collection
                SiteTitle.Load(lists);


                SiteTitle.ExecuteQuery();
                foreach (List list in lists)
                {
                    Console.WriteLine(list.Title);
                }



    CSOM Using Java script  :

    var ctx;
    var web;
    var lists;
    $(onPageLoad);
    function onPageLoad() {
        ExecuteOrDelayUntilScriptLoaded(LoadSiteCSOM, "sp.js");
    }
    function LoadSiteCSOM() {
        // here we can't pass site URL ,due to cross site scripting.
        
        ctx = SP.ClientContext.get_current();
        web = ctx.get_web();
        ctx.load(web);
        ctx.load(web.get_currentUser());
        lists = web.get_lists();
        ctx.load(lists);
        ctx.executeQueryAsync(onDisplaySiteInfo, onError);
    }
    function onDisplaySiteInfo() {
        var siteTitle = web.get_title();
        var siteId = web.get_id().toString();
        var siteUrl = web.get_url();
        var currentUser = web.get_currentUser().get_loginName();
    }
    function onError(sender, args) { alert(JSON.stringify(args)); }


    CSOM URL is Changes in with respective Sp2010 and Sp2013

    SP 2010 : http://localhost/_vti_bin/client.svc/web

    sp 2013 : http://localhost/_api/web

    SharePoint 2013 REST and OData fundamentals



    OData URIs :











    URI has three significant parts – service root URI up to entry point, resource path for SharePoint list or SQL Server table, Query string parameters
    Service URL –http://services.odata.org/odata/odata.svc, Resource – category(1)/products, and Query Option – $top=2&$orderby=name
    REST URLs in SharePoint 15








    Making REST calls with C# and JavaScript for SharePoint 2013
    • Returning ATOM XML vs JSON
      • SharePoint returns REST based data in two formats – ATOM XML and JSON
      • ATOM XML is preferred format in .NET Managed code and JSON is preferred format in JavaScript
      • To get ATOM XML, response use MIME type “application/atom+xml”, This is ideal for .NET managed code, you can also use in JavaScript but use XSLT in conjunction with parsing XML to format it properly
      • To get JSON, response use MIME type “application/json”, ideal in JavaScript in conjunction with jQuery
      • Response data format selected in ACCEPT header, ATOM XML is default option for data format returned by REST based calls in SharePoint, for JSON response, you must pass “application/json” MIME type in ACCEPT header
    • REST Query from Managed code – Tips for making REST calls from managed code
      • in .NET 4.0 or later, use the HTTPWebRequest and HTTPWebResponse objects instead of WebRequest or WebResponse classes which would allow you to specify Accept property for required MIME string
      • Use LINQ-to-XML to get data from XML in response body by loading XML response stream in XDocument object and using XDocument.Descendants method to query data
    • REST Query using JavaScript and jQuery
      • Use #.getJSON to request the JSON response if you are using jQuery
    • Updating using REST based API and Form Digest
      • Updates using REST requires Form Digest to protect against replay attack
      • Form Digest is available on the SharePoint since MOSS 2007 days, Form Digest is a special value created using cryptography, SharePoint Pages have control holding Form Digest
      • The Form Digest control does this by using cryptography to create a special value that is passed to the client browser. This value must be passed back to SharePoint and validated on requests that update objects or content within a SharePoint site
      • Add X-RequestDigest header which includes value of form digest
        • In the Managed code, form digest can be acquired through _vti_bin/sites.asmxand pass it to the REST based call,
        • In the JavaScript, assign the value from the control – $(“#_REQUESTDIGEST).val()
    XML Syntax:
    ACCEPT = application/atom+xml
    JSON  Syntax:
    ACCEPT = application/json;odata=verbose
    REST calls from Managed code :
               // build request
                Uri uri = new Uri(siteUrl + "/_api/web/lists/getByTitle('Documents')/?&select=Title");
                HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
                request.Credentials = CredentialCache.DefaultCredentials;
                request.Accept = "application/atom+xml";

                // send request

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                // use LINQ to XML to get data

                XDocument doc = XDocument.Load(response.GetResponseStream());
                XNamespace nsDataService = "http://schemas.microsoft.com/ado/2007/08/dataservices";
                string title = doc.Descendants(nsDataService + "Title").First().Value;
     REST call from Java script :
     $(onPageLoad);
    function onPageLoad() {
        $("#GetSiteInfo").click(onGetSiteInfo);
    }
    function onGetSiteInfo() {
        var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/Web?$select=Title";
        // execute AJAX request
        jqxhr = $.getJSON(requestUri, null, OnDataReturned);
        jqxhr.error(onError);
    }
    function OnDataReturned(data) {
        var odataResults = data.d
        var siteTitle = odataResults.Title;
        $("#results").html("Title: " + siteTitle);
    }
    function onError(err) {
        $("#results").text("ERROR: " + JSON.stringify(err));
    }
    Creating List with Managed code and REST API :
    // build request
    Uri uri = new Uri(siteUrl + "/_api/web/lists");
    HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
    request.Accept = "application/atom+xml";
    request.Headers["X-RequestDigest"] = FormDigest;
    request.Method = "POST";
    string body = Properties.Resources.CreateList_atom;
    body = body.Replace("@Title", listTitle);
    request.ContentLength = body.Length;
    StreamWriter writer = new StreamWriter(request.GetRequestStream());
    writer.Write(body);
    writer.Flush();
    // send request
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    Reference : http://nikpatel.net/2012/09/23/whats-new-in-sharepoint-2013-csom-and-rest-apis/

    http://msdn.microsoft.com/en-us/library/office/fp142380(v=office.15).aspx




    More Information :






    Sharepoint Elements :

    _spPageContextInfo  this will be very useful while doing app model development.

    spPageContextInfo, you’ll find it very helpful when writing SP JavaScript code






    
    By using IE we can inspect  _spPageContextInfo   values.












    Sunday, June 15, 2014

    Server side Developerment using CAML and Linq

    Server side API is only supported in Farm solution and sandbox solution.'

    Client side(Sharepoint Apps) code development requires  ECMAScript library such as jQuery or Microsoft AJAX .

    Debugging Tools : IE developer Tools, firefox  fire bug adon.

    Server side Development :
    CAML (Collaborative Application Markup Language (CAML) is an XML-based language)
    LINQ (Language-Integrated Query)

    Most common object in  CAML  : SpQuery,SpSiteDataQuery

    Search API is usefull when you query against cross site or large list.

    Example of Spquery :

     
     using (SPWeb web = site.OpenWeb())
                {
                   // Build a query.
                   SPQuery query = new SPQuery();
                   query.Query = string.Concat(
                                  "<Where><Eq>",
                                     "<FieldRef Name='Status'/>",
                                     "<Value Type='CHOICE'>Not Started</Value>",
                                  "</Eq></Where>",
                                  "<OrderBy>",
                                     "<FieldRef Name='DueDate' Ascending='TRUE' />",
                                     "<FieldRef Name=’Priority’ Ascending='TRUE' />",
                                  "</OrderBy>");                   

                   query.ViewFields = string.Concat(
                                       "<FieldRef Name='AssignedTo' />",
                                       "<FieldRef Name='LinkTitle' />",
                                       "<FieldRef Name='DueDate' />",
                                       "<FieldRef Name='Priority' />");

                   query.ViewFieldsOnly = true; // Fetch only the data that we need.
                   // Get data from a list.
                   string listUrl = web.ServerRelativeUrl + "/lists/tasks";
                   SPList list = web.GetList(listUrl);
                   SPListItemCollection items = list.GetItems(query);

                   // Print a report header.
                   Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                      "Assigned To", "Task", "Due Date", "Priority");

                   // Print the details.
                   foreach (SPListItem item in items)
                   {
                      Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                         item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);
                   }
                }
             }
     using (SPWeb web = site.OpenWeb())
                {
                   // Build a query.
                   SPQuery query = new SPQuery();
                   query.Query = string.Concat(
                                  "<Where><Eq>",
                                     "<FieldRef Name='Status'/>",
                                     "<Value Type='CHOICE'>Not Started</Value>",
                                  "</Eq></Where>",
                                  "<OrderBy>",
                                     "<FieldRef Name='DueDate' Ascending='TRUE' />",
                                     "<FieldRef Name=’Priority’ Ascending='TRUE' />",
                                  "</OrderBy>");                   

                   query.ViewFields = string.Concat(
                                       "<FieldRef Name='AssignedTo' />",
                                       "<FieldRef Name='LinkTitle' />",
                                       "<FieldRef Name='DueDate' />",
                                       "<FieldRef Name='Priority' />");

                   query.ViewFieldsOnly = true; // Fetch only the data that we need.
                   // Get data from a list.
                   string listUrl = web.ServerRelativeUrl + "/lists/tasks";
                   SPList list = web.GetList(listUrl);
                   SPListItemCollection items = list.GetItems(query);

                   // Print a report header.
                   Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                      "Assigned To", "Task", "Due Date", "Priority");

                   // Print the details.
                   foreach (SPListItem item in items)
                   {
                      Console.WriteLine("{0,-25}  {1,-20}  {2,-25}  {3}",
                         item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);
                   }
                }
             }



    SpsiteDataQuery:

    This is used to get the data frorm multiple list across multiple sites.


    SPSiteDataQuery query = new SPSiteDataQuery();
                query.Webs = "<Webs scope='SiteCollection' />";
                query.ViewFields = @"<FieldRef Name='Title' /> <FieldRef Name='FirstName' />";
                query.Query = @"<Where> <FieldRef Name='ContentType'/> <Value Type='Computed'>Contact</Value> </Where>";
                DataTable results = SPContext.Current.Web.GetSiteData(query);
                foreach (DataRow item in results.Rows)
                {
                   Console.Write(item["FirstName"].ToString());
                }



    Linq query will return IEnumerable<T> interface. Example :


    All collection will implement IEnumerable<T>

    // string array


    String[] Col1 = new string[] { "a", "b", "c" };
    // list collection
    List<string> Col2 = new List<string>()
    { "a", "b", "c"};
    // queue collection
    Queue<string> Col3 = new Queue<string>();

    Col3.Enqueue("a");Col3.Enqueue("bCol3.Enqueue("c);

    Displaycol1(Col1); // This method will  IEnumerable type.
    Displaycol1(Col2);
    Displaycol1(Col3);




    Linq Extension method :

    Extension methods feature added to .NET 3.0
    Allows developers to extend existing types
    LINQ adds extension methods to IEnumerable<T>

    Out put of Extension method :










    Linq default it provide nearly 50 extension methods .



    More Enumerable Methods method are found in : http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods%28v=vs.110%29.aspx




    Where Condition in LinQ can be used in following technique.


    Anonymous Delegate
    Lambda expression
    Explicit delegate
     



                IEnumerable<string> cal1, cal2, cal3, cal4;
                cal1 = new List<string>() { "a", "b", "c", "d" };

       // technique : named delegate & WHERE method

                Func<string, bool> delegateFilterMethod = StringHasFourCharacters;
                cal2 = cal1.Where(delegateFilterMethod);
     
        // technique : anonymous delegate
        
                cal3 = cal1.Where(delegate(string value)
                {
                    return (value.Length == 4); }
                );
       // technique : lambda
                cal4 = cal1.Where(value => value.text =="txt" );
            }

    Linq support  custom object :

    class Customer
    {
        // Auto-Impl Properties for trivial get and set 
        public double TotalPurchases { get; set; }
        public string Name { get; set; }
        public int CustomerID { get; set; }
    }


    OLD way of creaating initial objects 


     Customer c2 =new  customer();
    c2.TotalPurchases ="34.45";
    c2.Name="text";
    c2.CustomerID=20;


    New way of creaating initial objects 
    Customer c2 =new customer
    {
    c2.TotalPurchases ="34.45";
    c2.Name="text";
    c2.CustomerID=20;
    };




    LinQ Sample Example  : 

     Click Here  : http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b







    Linq to Sharepoint  :


    SPMetal.exe generate strongly-typed entity classes

    Each entity class represents one SharePoint list

    SPMetal.exe also generates DataContext class


    Some Example :



    // Get DataContext from page context
    DataContext data = new DataContext(SPContext.Current.Web.Url);

    // Get the SharePoint list
    EntityList<Customer> Customers = data.GetList<Customer>("Customers");

    // Query for customers from London
    var londonCustomers = from customer in Customers
                          where customer.City == "London"
                          select customer;

    foreach (var londonCust in londonCustomers)
    {
        Console.Writeline("id = {0}, City = {1}",
                          londonCust.CustomerId,
                          londonCust.City);
    }



    The following is an example of using LINQ to add an item to a SharePoint Foundation list




    // Get DataContext from page context
    DataContext data = new DataContext(SPContext.Current.Web.Url);

    // Get the SharePoint list
    EntityList<Customer> Customers = data.GetList<Customer>("Customers");

    // Create the item to be added
    Customer newCustomer = new Customer() { CustomerId=36, City=”Madrid” };

    // Mark the item to be added on the next call of Submit
    Customers.InsertOnSubmit(newCustomer);

    // Submit all changes
    data.SubmitChanges();

    More information About Linq to sharepoint : http://msdn.microsoft.com/en-us/library/office/ee535491(v=office.14).aspx