Tuesday, May 29, 2012

ECMA SCRIPT SHAREPOINT 2010

SharePoint provides two sets of JavaScript file: minified and unminified/debug version.
For example sp.js file is minified and sp.debug is minified and debug version. The default master page in SharePoint has a scriptmanager in the page and whose ScriptMode is set to auto, as a result the minified version of js file loaded.
If you want to use debug version you can add the <deployment retail="false" /> in the <system.web> section of the web.config. In the production you need to remove this entry to make sure minified version is used.

Managed Client
DLL's needed : Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll. Find these files in the 14/ISAPI folder. Usually, the location would be at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI".

Silverlight
Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll. They find at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin".

ECMAScript
SP.js file - The file fund at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS".

SharePoint object model syntax:-
Server side syntax        Client side syntax 
SPContext                    ClientContext
SPSite                          Site
SPWeb                        Web
SPList                          List

After saving the .js file, press Ctrl + Shift + J to update the JavaScript IntelliSense.
Tip: Sometimes, you might have to press Ctrl + Shift + J for each .js file referenced.

please replace the below lines.... : http://msdn.microsoft.com/en-us/library/ee535709.aspx
{code}
<script type=”text/ecmascript” src=”/_layouts/SP.Core.js” />
<script type=”text/ecmascript” src=”/_layouts/SP.Debug.js” />
<script type=”text/ecmascript” src=”/_layouts/SP.Runtime.Debug.js” />
{code}
With
{code}
<SharePoint:ScriptLink ID=”ScriptLink1″ Name=”sp.debug.js” LoadAfterUI=”true” Localizable=”false” runat=”server” />
{code}

<!-- http://msdn.microsoft.com/en-us/library/ff798328.aspx -->
    <script type="text/javascript" src="/_layouts/SP.debug.js" ></script>
    <%--  CreateList --%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            var itemCreateInfo = new SP.ListItemCreationInformation();
            var listCreationInfo = new SP.ListCreationInformation();
            listCreationInfo.set_title('My Custom Generic List');
            listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
            this.oList = web.get_lists().add(listCreationInfo);

            clientContext.load(oList, 'Title', 'Id');

            clientContext.executeQueryAsync(Function.createDelegate(this, this.onListCreateSuccess),
Function.createDelegate(this, this.onQueryFailed));
        }
        function onListCreateSuccess(sender, args) {
            alert("List title : " + this.oList.get_title() + "; List ID : " + this.oList.get_id());
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    ​
    <%--  CreateSite --%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            var webCreateInfo = new SP.WebCreationInformation();
            webCreateInfo.set_description("All about Rare solutions.");
            webCreateInfo.set_language(1033);
            webCreateInfo.set_title("Rare Solutions - SharePoint and .NET");
            webCreateInfo.set_url("RareSolutionsSharePoint");
            webCreateInfo.set_useSamePermissionsAsParentSite(true);
            webCreateInfo.set_webTemplate("BLOG#0");

            this.oNewWebsite = this.web.get_webs().add(webCreateInfo);

            clientContext.load(this.oNewWebsite, 'ServerRelativeUrl', 'Created');

            clientContext.executeQueryAsync(Function.createDelegate(this, this.onCreateWebSuccess),

Function.createDelegate(this, this.onQueryFailed));
        }
        function onCreateWebSuccess(sender, args) {
            alert("Web site url : " + this.oNewWebsite.get_serverRelativeUrl());
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    ​
    <%--     DeleteList--%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            this.list = web.get_lists().getByTitle('My custom generic list');
            list.deleteObject();

            clientContext.executeQueryAsync(Function.createDelegate(this, this.onListDeleteSuccess),

Function.createDelegate(this, this.onQueryFailed));
        }
        function onListDeleteSuccess(sender, args) {
            alert("list deleted");
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    ​
    <%-- DeleteListItem --%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            this.list = web.get_lists().getByTitle('My custom generic list');
            this.oListItem = list.getItemById(1);
            oListItem.deleteObject();

            clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemDeleteSuccess),

Function.createDelegate(this, this.onQueryFailed));
        }
        function onListItemDeleteSuccess(sender, args) {
            alert("list item deleted");
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    ​
    <%--  DeleteSite --%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            this.website = web.get_webs().getByTitle('Rare Solutions');
            website.deleteObject();

            clientContext.executeQueryAsync(Function.createDelegate(this, this.onSiteDeleteSuccess),

Function.createDelegate(this, this.onQueryFailed));
        }
        function onSiteDeleteSuccess(sender, args) {
            alert("site deleted");
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    ​
    <%-- LoadListData --%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            this.list = web.get_lists().getByTitle("Images");
            clientContext.load(list, 'Title', 'Id');
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onListLoadSuccess),
Function.createDelegate(this, this.onQueryFailed));
        }
        function onListLoadSuccess(sender, args) {
            alert("List title : " + this.list.get_title() + "; List ID : " + this.list.get_id());
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    ​
    <%-- LoadListItemsData --%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            var list = web.get_lists().getByTitle("Pages");
            var camlQuery = new SP.CamlQuery();
            var q = '<View><RowLimit>5</RowLimit></View>';
            camlQuery.set_viewXml(q);
            this.listItems = list.getItems(camlQuery);
            clientContext.load(listItems, 'Include(DisplayName,Id)');
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess),
Function.createDelegate(this, this.onQueryFailed));
        }
        function onListItemsLoadSuccess(sender, args) {
            var listEnumerator = this.listItems.getEnumerator();
            //iterate though all of the items
            while (listEnumerator.moveNext()) {
                var item = listEnumerator.get_current();
                var title = item.get_displayName();
                var id = item.get_id();
                alert("List title : " + title + "; List ID : " + id);
            }
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    ​
    <%-- LoadSiteData --%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            clientContext.load(web, 'Title');
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onSiteLoadSuccess), Function.createDelegate(this, this.onQueryFailed));
        }
        function onSiteLoadSuccess(sender, args) {
            alert("site title : " + web.get_title());
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    ​
    <%--  UpdateList --%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            this.list = web.get_lists().getByTitle('My custom generic list');
            list.set_description('My custom generic list description');
            list.update();
            clientContext.load(list, 'Description');
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onSiteLoadSuccess), Function.createDelegate(this, this.onQueryFailed));
        }
        function onSiteLoadSuccess(sender, args) {
            alert("list description : " + this.list.get_description());
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    ​
    <%--  UpdateListItem --%>
    <script type="text/javascript">
        var clientContext = null;
        var web = null;
        ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
        function Initialize() {
            clientContext = new SP.ClientContext.get_current();
            web = clientContext.get_web();
            this.list = web.get_lists().getByTitle('My custom generic list');
            this.oListItem = list.getItemById(1);
            oListItem.set_item('Title', 'Praveen Battula Updated');
            oListItem.update();

            clientContext.executeQueryAsync(Function.createDelegate(this, this.onUpdateListItemSuccess), Function.createDelegate(this, this.onQueryFailed));
        }
        function onUpdateListItemSuccess(sender, args) {
            alert("list item updated");
        }

        function onQueryFailed(sender, args) {
            alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
        }
</script>

Date Comparison ASP.NET + JAVA SCRIPT

Download Ajax Control Tool Kit form here
http://ajaxcontroltoolkit.codeplex.com/releases/view/33804

How to Add Ajax Toolkit to SharePoint Web.Config Refer below Link
http://inspiredbytechnology.com/using-ajax-control-toolkit-sharepoint-2010/

<%@ Register Assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"
    Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>


<script type="text/javascript">
        function ValidateDates(sender, args) {
            var fromDate = document.getElementById('<%= txtMyDate.ClientID %>').value;

            var validformat = /^\d{2}\/\d{2}\/\d{4}$/
            if (!validformat.test(fromDate)) {

                sender.errormessage = "Invalid Date Format. Please correct and submit again. ";
                args.IsValid = false;
                return false;
            }
            else {
                var dayfield = fromDate.split("/")[0]
                var monthfield = fromDate.split("/")[1]
                var yearfield = fromDate.split("/")[2]
                var dayobj = new Date(yearfield, monthfield - 1, dayfield)
                if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {

                    sender.errormessage = "Invalid Day, Month, or Year range detected. Please correct and submit again. ";
                    args.IsValid = false;
                    return false;
                }
                else {
                    var dtToday = new Date();
                    if (dayobj > dtToday) {
                        args.IsValid = false;
                        return false;
                    }
                    else {
                        args.IsValid = true;
                        return true;
                    }
                }
            }
        };  
    </script>


 <asp:ValidationSummary ID="ValidationSummary1" HeaderText="Please enter valid values for the following field(s)"
                    DisplayMode="BulletList" EnableClientScript="true" runat="server" ValidationGroup="valGroup1"
                    CssClass="error_msg" />



 <asp:TextBox ID="txtMyDate" runat="server" CssClass="myDesign"></asp:TextBox>


<img id="imgMyImage" src="/_layouts/images/MyProject/calander.png" width="20"
                                                height="20" alt="" class="icon" />
                                            <div style="width: 50px; position: relative;">
                                                <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtMyDate "
                                                    Format="dd/MM/yyyy" PopupButtonID="imgMyImage" CssClass="cal_Theme1" />
                                            </div>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txtMyDate"
                                                ErrorMessage="Date of Purchase" Display="None" ValidationGroup="valGroup1" Text="*">
                                            </asp:RequiredFieldValidator>
                                            <asp:CustomValidator ID="CustomDateValidator" runat="server" ErrorMessage="Please ensure that 'Date of Purchase' is lesser than or equal to 'Current Date'."
                                                ClientValidationFunction="ValidateDates" Display="None" ValidationGroup="valGroup1"> </asp:CustomValidator>



<asp:Button ID="btnSave" runat="server" Text="Add" OnClick="btnSave_Click" CssClass="button"
                                                ValidationGroup="valGroup1" />
-----------------------------------------------------------------------------------------------------------


<html>
<head>
<script  language="javascript">
function cal()
{
document.f1.y1.value= mydiff(document.f1.n1.value,document.f1.n2.value,"days");
}
function mydiff(date1,date2,interval) {
var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
    date1 = new Date(date1);
    date2 = new Date(date2);
    var timediff = date2 - date1;
        return Math.floor(timediff / day);
}        
</script>
</head>
<body>

<form name="f1">
       enter From Date:<input type="text" name="n1">
   <br>enter To Date:<input type="text" name="n2">
   <br>No Of Days: <input type="text" name="y1">
   <input type="button"  value="Get Days"  name="ab" onclick="cal();">
</form>
</body>
</html>




Monday, May 28, 2012

Property or indexer 'Microsoft.SharePoint.SPListItem.Title' cannot be assigned to -- it is read only


Property or indexer 'Microsoft.SharePoint.SPListItem.Title' cannot be assigned to -- it is read only :-



 protected void btn1_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Announcements"];
                    SPListItem item = list.AddItem();
                    item["Title"] = "New Announcement";
                    item.Update();
                }
            }
        }


SharePoint Version


Friday, December 23, 2011

Create BAT File in MOSS 2007 / SharePoint 2007


To ease the deployment process, create a batch file called InstallAll.bat in the folder that contains the FormDataWorkflow.sln Visual Studio solution file. Add the following code to the InstallAll.bat file.
iisreset /stop

"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -uf FormDataAspxPages
"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -if FormDataASPXPages\bin\Debug\FormDataAspxPages.dll

"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -uf FormDataWorkflow
"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -if FormDataWorkflow\bin\Debug\FormDataWorkflow.dll

iisreset /start

copy /Y "FormDataAspxPages\FormDataAssocForm.aspx" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS"
copy /Y "FormDataAspxPages\FormDataInitForm.aspx" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS"

mkdir  %SystemDrive%"\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\FormDataWorkflow"

copy "FormDataWorkflow\Feature.xml" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\FormDataWorkflow"
copy "FormDataWorkflow\workflow.xml" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\FormDataWorkflow" 

pushd "%programfiles%\common files\microsoft shared\web server extensions\12\bin"

stsadm -o deactivatefeature -filename "FormDataWorkflow\feature.xml" -url http://localhost -force
stsadm -o uninstallfeature -filename "FormDataWorkflow\feature.xml" -force

stsadm -o installfeature -filename "FormDataWorkflow\feature.xml" -force
stsadm -o activatefeature -filename "FormDataWorkflow\feature.xml" -url http://localhost -force

popd

PAUSE

Friday, December 9, 2011

Debugging Feature Receivers


Feature receivers can be difficult because they are often executed within a separate process. To see an example of this problem put a breakpoint on the first line of our FeatureActivated method and try debugging using Visual Studio.  The code will be deployed and the feature will be activated, but execution will not stop at the breakpoint.  Visual Studio makes use of a separate process, VSSPHost.exe, to automate the deployment only, and therefore the breakpoint is never hit but the code still execures.
        We can work around this issue in one of two ways: we can either attach a debugger to the appropriate process, or we can ensure that our feature receiver runs in the W3SVC process. To ensure  that a debugger is attached to the correct process, we can take the following steps:
   
            1.   Add the following line of code to the method to be debugged:
    Debugger.Break();

   When error window open then select “Debug the Program”
 

Friday, September 9, 2011

Machine Caching in SharePoint 2010

Some caching techniques in SharePoint 2010:-

1. Object Caching (Configurable)
2. BLOB Cache (Configurable) :  Open web.config in SharePoint Root Hive:
<BlobCache location="D:\BLOB\" path="\.(gif|jpg|jpeg|jpe|jfif|bmp|dib|tif|tiff|ico|png|wdp|hdp|css|js|asf|avi|flv|m4v|mov|mp3|mp4|mpeg|mpg|rm|rmvb|wma|
wmv)$" maxSize="10" enabled="true" />

3. Caching in code (Programmable)

Important Links about Caching in SharePoint
http://msdn.microsoft.com/en-us/library/aa661294.aspx
http://msdn.microsoft.com/en-us/library/aa661294.aspx
http://msdn.microsoft.com/en-us/library/ms550239.aspx
http://msdn.microsoft.com/en-us/library/aa622758.aspx
http://technet.microsoft.com/en-us/library/cc770229.aspx
http://technet.microsoft.com/en-us/library/cc770229.aspx#BLOB
http://www.zimmergren.net/archive/2008/10/07/web-part-caching-%E2%80%93-a-simple-approach.aspx
http://msdn.microsoft.com/en-us/library/bb687949%28office.12%29.aspx#UsingSPData
http://technet.microsoft.com/en-us/library/ee424404.aspx#Section1c


Web Part Caching – A simple approach:-

Open Visual Studio2010 and select a WebPart form SharePoint 2010 Template:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;

namespace VisualWebPartProject1.VisualWebPart1
{
    [ToolboxItemAttribute(false)]
    public class VisualWebPart1 : WebPart
    {       
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebPartProject1/VisualWebPart1/VisualWebPart1UserControl.ascx";
       
        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);

            List<SPList> lists = new List<SPList>();
            string status = "";

            if (HttpRuntime.Cache["SimpleSampleCache"] == null)
            {
                status = "The following items are <strong>NOT</strong> fetched from the cache<br/><br/>";

                SPWeb web = SPContext.Current.Web;
                foreach (SPList list in web.Lists)
                    lists.Add(list);

                HttpRuntime.Cache.Add("SimpleSampleCache",
                lists,
                null,
                DateTime.MaxValue,
                TimeSpan.FromMinutes(10),
                System.Web.Caching.CacheItemPriority.Default, null);
            }
            else
            {
                status = "The following items <strong>ARE</strong> fetched from the cache!<br/><br/>";
                lists = (List<SPList>)HttpRuntime.Cache["SimpleSampleCache"];
            }
           
            Controls.Add(new LiteralControl(status));

            foreach (SPList l in lists)
                Controls.Add(new LiteralControl(l.Title + " - " + l.ItemCount + " items<br/>"));   
        }
    }
}

Press F5 and add WebPart to an WebPart Page and Show the Result as follows:-




Thank You.
 

Developer Dashboard

Activating the Developer Dashboard

•    PowerShell
•    STSADM.exe
•    SharePoint Object Model (API's)

Activate the Developer Dashboard using PowerShell:-
$devdash = [Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$devdash.DisplayLevel = 'OnDemand';
$devdash.TraceEnabled = $true;
$devdash.Update()

Activate the Developer Dashboard using STSADM.EXE:-
STSADM.EXE -o setproperty -pn developer-dashboard -pv ondemand

Activate the Developer Dashboard using the SharePoint Object Model:-
using Microsoft.SharePoint.Administration;
SPWebService svc = SPContext.Current.Site.WebApplication.WebService;
svc.DeveloperDashboardSettings.DisplayLevel =
    SPDeveloperDashboardLevel.Off;
svc.DeveloperDashboardSettings.Update();

•    Off (Disables the Developer Dashboard)
•    On (Enables the Developer Dashboard)
•    OnDemand (Enables the Developer Dashboard upon request by clicking the icon in the upper right corner)

SPMonitoredScope to track performance in your applications:-
 using (new SPMonitoredScope("Monitoring"))
{
    Controls.Add(new Literal { Text = "When the awesomeness is flying... " });
               
    using (new SPMonitoredScope("Sub-Monitoring"))
    {
        Controls.Add(new Literal { Text = "Hello this is --Sub-Monitoring! " });

        using (new SPMonitoredScope("Sub-Sub-Monitoring"))
        {
            Controls.Add(new Literal { Text = "<br/>Hello this is Sub-Sub-Monitoring!" });
        }

        using (new SPMonitoredScope("Sub-Sub-Monitoring_1"))
        {
            Controls.Add(new Literal { Text = "Hello this is Sub-Sub-Monitoring_1" });
        }
    }
}

Now go and test Doveloper Dashboard to find the Result with about scope names
0.Monitoring
1. Sub-Monitoring
2. Sub-Sub-Monitoring
3. Sub-Sub-Monitoring_1
  

Friday, September 2, 2011

SharePoint 2010 Backup and Recovery

Initial Backup Configuration
•    Farm, Service Applications, Content Databases: Local Administrator Group Member
•    Site collections, sites, lists, document libraries: Farm Administrator Group Member

Backing Up the Farm
following services must be running at the time you are issuing the backup command from CA:
•    Timer Service
•    SharePoint Foundation Administration Service

    In order to be able to back up the content databases, you must have the db_backupoperator role assigned to the user you are trying to perform the backup with.
Backing Up Content Databases
Backup-SPFarm -Directory "path" -BackupMethod "Full|Differential" -Item

•    Directory: Set the backup folder
•    BackupMethod: Specify whether to run a full or differential backup
•    Item: Specify the farm, web application or (shared) service application you want to backup

    At the end of the backup/restore operation you will find either spbackup.log or sprestore.log.
Backing Up Site Collection, Lists and Document Libraries
    The preferred file extension is .bak.
Backup-SPSite -Identity "Site Collection Name" -Path "path"  [-UseSqlSnapshot] [-NoSiteLock]

we can back up single sites, lists or document libraries:
Export-SPWeb -Identity "Site/List/Library name" -Path "path" [-IncludeUserSecurity] [-GradualDelete] [-IncludeVersions]

Backing Up Log Files
Merge-SPLogFile -Path"path" -Overwrite

Initial Restore Configuration
1.    Start the SharePoint Foundation Administration Service on all farm servers
2.    Do not restart services using the Product Configuration Wizard (which causes custom configuration of the service apps to be lost).

Restoring an Entire Farm
1.    Restore-SPFarm –Directory "path" –RestoreMethod Overwrite [-BackupId "guid"]
2.    Get-SPBackupHistory -Directory "path"

Start and Stop Service using Powershell
1.    Get-SPServiceInstance | Stop-SPServiceInstance
2.    Get-SPServiceInstance | Start-SPServiceInstance

Restore Using the SQL Server Tools
•    You cannot restore the SharePoint 2010 configuration data.
•    You cannot restore SharePoint 2010 search.

Backing Up and Restoring Configuration Settings on Another Farm
What you need to bear in mind for the mentioned scenario is that you must copy and restore the configuration settings for the following elements:
•    The farm
•    Web applications
•    Service applications
1.    Get-SPWebApplication | %{$_.Name;$_.Url;%{$_.ContentDatabases|%{$_.Name}; Write-Host “” }}
2.    Get-SPContentDatabase | Dismount-ContentDatabases3.   
4.    Backup-SPFarm –Directory "path" -BackupMethod "Full | Differential"
5.    Mount-SPContentDatabase –Name "WSS_Content" -WebApplication "URL"
6.    Restore-SPFarm –Directory "path" -RestoreMethod Overwrite -ConfigurationOnly
7.    Restore-SPFarm –Directory <backup folder> -RestoreMethod Overwrite –ConfigurationOnly –Item "web app | service app"
8.    Update-SPSecureStoreApplicationServerKey –Passphrase <passphrase>
9.    Mount-SPContentDatabase –Name <db name> -WebApplication <web app URL>

Restoring Site Collections
1.    Restore-SPSite –Identity <site_collection_url> -Path <network_shared_path>\newteamsite.bak -Force

Import list and libraries
1. Import-SPWeb –Identity <site_collection_url> -Path <network_shared_path>\listname.cmp

Create a network shared folder
1. Start, Command Prompt
2. cd /
3. mkdir SPBackupFolder
4. Cacls SPBackupFolder /G <DomainName>\Administrator:F
5. Net Share SPBackupFolder=C:\SPBackupFolder /GRANT:<DomainFolder>\Adminstrator,FULL
-----------------------------------------------------------------------
Get-Help Restore-SPSite -detailed
Get-Help Import-SPWeb -detailed
Get-Help Get-SPBackupHistory -detailed
Get-SPBackupHistory –Directory <network_shared_path>\SPBackup
Get-SPBackupHistory –Directory <network_shared_path>\SPBackup -ShowBackup
Get-SPBackupHistory –Directory <network_shared_path>\SPBackup -ShowRestore
-----------------------------------------------------------------------

Thursday, September 1, 2011

People Search in Silverlight WebPart



Step1: File->New Project->Silverlight->Silverlight Application->SP_SilverligetApplication1
(Name)->click OK

Pleas make sure check the box "Host the silverlight application in a new web site"->Click OK

Step2: Right clink on SP_SilverlightApplication1->Add service referece->Address as type "http://servername/_vti_bin/People.asmx"->click on "Go" and select an service "People" and give namespace as "PeopleWS"

Step3: Open SP_SilverlightApplication1->MainPage.xml and type following code.

<UserControl x:Class="SP_SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="240" d:DesignWidth="280">
    <Grid x:Name="LayoutRoot" Background="White">
        <Border BorderThickness="4" BorderBrush="Black">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="30" />
                    <RowDefinition Height="145" />
                    <RowDefinition Height="25" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="3" VerticalAlignment="Top">
                    <TextBlock HorizontalAlignment="Left" Name="textBlock1" Text="Search:" VerticalAlignment="Center" />
                    <TextBox x:Name="SearchTxt" Width="200" KeyUp="SearchTxt_KeyUp" />
                    <Button x:Name="SearchBtn" Click="SearchBtn_Click">
                        <Image Source="/SilverSite;component/Images/search32x32.png" Width="16" Height="16" />                    </Button>
                </StackPanel>
                <StackPanel Grid.Row="1" Orientation="Vertical" HorizontalAlignment="Left" Margin="3">
                    <ListBox x:Name="ResultsLst" Width="265" Height="135" />
                </StackPanel>
                <StackPanel Grid.Row="2" Orientation="Horizontal" Margin="3">
                    <Button x:Name="AddNameBtn" Content="Add ->" Click="AddNameBtn_Click" />
                    <TextBlock x:Name="UserNameTxt" Width="143" Padding="5" VerticalAlignment="Center" />
                </StackPanel>
                <StackPanel Grid.Row="3" Orientation="Horizontal" Margin="3" HorizontalAlignment="Right">
                    <Button x:Name="OKBtn" Content="OK" Width="75" Click="OKBtn_Click" Height="20" Padding="3" />
                    <Button x:Name="CancelBtn" Content="Cancel" Width="75" Height="20" Padding="3" Click="CancelBtn_Click" />
                </StackPanel>
            </Grid>
        </Border>
    </Grid>
</UserControl>

Step4: open SP_SilverlightApplication1->MainPage.xaml.cs and type the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Diagnostics;


namespace SP_SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public string HostName { get; set; }
        public string SelectedAccountName { get; set; }
        public MainPage HostControl { get; set; }
        public enum AddressType
        {
            Primary,
            Secondary
        }
        public AddressType PickerAddressType { get; set; }
        private class PickerEntry
        {
            public string DisplayName { get; set; }
            public string AccountName { get; set; }
            public PickerEntry() { }
            public PickerEntry(string displayName, string accountName)
            {
                this.DisplayName = displayName;
                this.AccountName = accountName;
            }
            public override string ToString()
            {
                return this.DisplayName;
            }
        }
        public MainPage()
        {
            InitializeComponent();
            UserNameTxt.TextDecorations = TextDecorations.Underline;
        }       
        private void OKBtn_Click(object sender, RoutedEventArgs e)
        {
            //make sure a value was selected
            if (string.IsNullOrEmpty(UserNameTxt.Text))
            {
                MessageBox.Show("You must select a user before clicking OK; if you wish to " +
                    "cancel this operation then click the Cancel button.", "Select User",
                    MessageBoxButton.OK);
                CancelBtn.Focus();
                return;
            }
            //plug in the values
            if (PickerAddressType == AddressType.Primary)
            {
                HostControl.PrimaryAdmin = SelectedAccountName;
                HostControl.PrimaryDisplayName = UserNameTxt.Text;
            }
            else
            {
                HostControl.SecondaryAdmin = SelectedAccountName;
                HostControl.SecondaryDisplayName = UserNameTxt.Text;
            }

            CloseDialog();
        }
        private void CloseDialog()
        {
            //clear out selections for next time
            SearchTxt.Text = string.Empty;
            UserNameTxt.Text = string.Empty;
            ResultsLst.Items.Clear();

            //cast the parent to popup and close; don't set visibility or it
            //causes more code the next time you want to open it up
            Popup p = (Popup)this.Parent;
            p.IsOpen = false;          
        }
        private void SearchBtn_Click(object sender, RoutedEventArgs e)
        {
            //make sure a search value was entered
            if (string.IsNullOrEmpty(SearchTxt.Text))
            {
                MessageBox.Show("You must enter a search term.", "Missing Search Term",
                    MessageBoxButton.OK);
                SearchTxt.Focus();
                return;
            }
            try
            {
                //change the cursor to hourglass
                this.Cursor = Cursors.Wait;
               
                //the main control has code like this to get the HostName
                //get info on the current host
                //string curUrl = HtmlPage.Document.DocumentUri.AbsoluteUri.ToString();

                //get the host name; note that this assumes the user has rights to the root site
                //site collection; that may not be true in your scenario
                //Uri curUri = new Uri(curUrl);
                //HostName = curUri.Scheme + "://" + curUri.Host + ":" + curUri.Port.ToString();
                //set the search request
                PeopleWS.PeopleSoapClient ps = new PeopleWS.PeopleSoapClient();
                //use the host name property to configure the request against the site in
                //which the control is hosted
                ps.Endpoint.Address =
                    new System.ServiceModel.EndpointAddress(HostName + "/_vti_bin/People.asmx");

                //create the handler for when the call completes
                ps.SearchPrincipalsCompleted +=
                    new EventHandler<PeopleWS.SearchPrincipalsCompletedEventArgs>(ps_SearchPrincipalsCompleted);               
                //execute the search
                ps.SearchPrincipalsAsync(SearchTxt.Text, 50, PeopleWS.SPPrincipalType.User);
            }
            catch (Exception ex)
            {
                //ERROR LOGGING HERE
                Debug.WriteLine(ex.Message);

                MessageBox.Show("There was a problem executing the search; please try again " +
                    "later or contact your Help Desk if the problem continues.", "Search Error",
                    MessageBoxButton.OK);
                //reset cursor
                this.Cursor = Cursors.Arrow;
            }
        }
        void ps_SearchPrincipalsCompleted(object sender, PeopleWS.SearchPrincipalsCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    MessageBox.Show("An error was returned: " + e.Error.Message, "Search Error",
                        MessageBoxButton.OK);
                else
                {
                    System.Collections.ObjectModel.ObservableCollection<PeopleWS.PrincipalInfo>
                        results = e.Result;
                    //clear the search results listbox
                    ResultsLst.Items.Clear();
                    foreach (PeopleWS.PrincipalInfo pi in results)
                    {
                        ResultsLst.Items.Add(new PickerEntry(pi.DisplayName, pi.AccountName));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error processing the search results: " + ex.Message,
                    "Search Error", MessageBoxButton.OK);
            }
            finally
            {
                //reset cursor
                this.Cursor = Cursors.Arrow;
            }
        }
        private void AddNameBtn_Click(object sender, RoutedEventArgs e)
        {
            //see if an item is selected
            if ((ResultsLst.Items.Count == 0) || (ResultsLst.SelectedItem == null))
            {
                MessageBox.Show("You must run a search and select a name first.",
                    "Add User Error", MessageBoxButton.OK);
                return;
            }

            AddPickerEntry();
        }
        private void AddPickerEntry()
        {
            //cast the selected name as a PickerEntry
            PickerEntry pe = (PickerEntry)ResultsLst.SelectedItem;
            UserNameTxt.Text = pe.DisplayName;
            SelectedAccountName = pe.AccountName;
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            CloseDialog();
        }
        private void SearchTxt_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                SearchBtn_Click(sender, new RoutedEventArgs());
        }

        public string PrimaryAdmin { get; set; }
        public string PrimaryDisplayName { get; set; }
        public string SecondaryAdmin { get; set; }
        public string SecondaryDisplayName { get; set; }
    }
}

Step5: Right Click SP_SilverlightApplication->Properties->Build->Output->Output path->"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin\silverlight\"

save all and build the solution

Step6: go to sharepoint application and edit any page and add a silverlight webpart from Categories->Media and Content->Silverlight web part->Add->Url->"_LAYOUTS/ClientBin/silverlight/SP_SilverlightApplication1.xap"->click OK.

Setp7: Test the Application






Featured Post

Reassign a Copilot Studio Agent Owner Using PowerShell and the Dataverse Web API

Reassign a Copilot Studio Agent Owner Using PowerShell and the Dataverse Web API Every Copilot Studio agent is a row in the Dataverse bot t...

Popular posts