Wednesday, June 12, 2013

Tips and Tricks

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\CONFIG
C:\inetpub\wwwroot\wss\VirtualDirectories\80
and central admin web config file, web application config file which is we working on it.

1. <SafeMode MaxControls="200" CallStack="true" DirectFileDependencies="10" TotalFileDependencies="50" AllowPageLevelTrace="false">
2. <customErrors mode="Off" />
3. <compilation batch=”false” debug="true">
------------------------------------------------------------------------------------------------------------
SharePoint 2010 Solution : Getting items from any list between two dates:-
string startDate = dtDateTimeControl1.SelectedDate.ToString("yyyy-MM-dd");
//Start Date ID : dtDateTimeControl1.
query.Query = "<Where><And><Geq><FieldRef Name='Created' /><Value IncludeTimeValue='TRUE' Type='DateTime'>" + startDate + "T00:00:00Z" + "</Value></Geq><Leq><FieldRef Name='Created' /><Value IncludeTimeValue='TRUE' Type='DateTime'>" + endDate + "T00:00:00Z" + "</Value></Leq></And></Where>";
------------------------------------------------------------------------------------------------------------
#Get the search service application
#You will need to specify the -Identity switch and a name if you have more than one
$sa = Get-SPEnterpriseSearchServiceApplication

#Reset index with the following options in brackets:
#Disable Alerts $true/$false
#Ignore unreachable server $true/$false
try
{
Write-Host "Attempting to reset the index...please wait"
$sa.Reset($false, $false)
Write-Host "Index successfully reset" -ForegroundColor Blue
}
catch
{
Write-Host "There was a problem resetting the index:" $_ -ForegroundColor Red
}
------------------------------------------------------------------------------------------------------------
SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
diagSvc.WriteTrace( 0, // custom trace id
new SPDiagnosticsCategory("My category",
TraceSeverity.Monitorable,
EventSeverity.Error), // create a category
TraceSeverity.Monitorable, // set the logging level of this record
"Writing to the ULS log: {0}", // custom message
new object[] { "SharePoint rocks!"} // parameters to message
);
------------------------------------------------------------------------------------------------------------
SPDiagnosticsService diagnosticsService = SPDiagnosticsService.Local;
SPDiagnosticsCategory cat = diagnosticsService.Areas["SharePoint Foundation"].Categories["Unknown"];
string format = "Test trace logging for category {0} in area {1}";
diagnosticsService.WriteTrace(1, cat, TraceSeverity.Medium, format, cat.Name, cat.Area.Name);
Console.WriteLine(format, cat.Name, cat.Area.Name);
Console.ReadLine();
------------------------------------------------------------------------------------------------------------
using Microsoft.SharePoint.Administration;
SPDiagnosticsService diagnosticsService = SPDiagnosticsService.Local;
string errorMsg = ex.Message;
diagnosticsService.WriteTrace(0,

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\CONFIG
C:\inetpub\wwwroot\wss\VirtualDirectories\80
and central admin web config file, web application config file which is we working on it.

1. <SafeMode MaxControls="200" CallStack="true" DirectFileDependencies="10" TotalFileDependencies="50" AllowPageLevelTrace="false">
2. <customErrors mode="Off" />
3. <compilation batch=”false” debug="true">
------------------------------------------------------------------------------------------------------------
SharePoint 2010 Solution : Getting items from any list between two dates:-

string startDate = dtDateTimeControl1.SelectedDate.ToString("yyyy-MM-dd");
//Start Date ID : dtDateTimeControl1.
query.Query = "<Where><And><Geq><FieldRef Name='Created' /><Value IncludeTimeValue='TRUE' Type='DateTime'>" + startDate + "T00:00:00Z" + "</Value></Geq><Leq><FieldRef Name='Created' /><Value IncludeTimeValue='TRUE' Type='DateTime'>" + endDate + "T00:00:00Z" + "</Value></Leq></And></Where>";
------------------------------------------------------------------------------------------------------------
#Get the search service application
#You will need to specify the -Identity switch and a name if you have more than one
$sa = Get-SPEnterpriseSearchServiceApplication

#Reset index with the following options in brackets:
#Disable Alerts $true/$false
#Ignore unreachable server $true/$false
try
{
Write-Host "Attempting to reset the index...please wait"
$sa.Reset($false, $false)
Write-Host "Index successfully reset" -ForegroundColor Blue
}
catch
{
Write-Host "There was a problem resetting the index:" $_ -ForegroundColor Red
}
------------------------------------------------------------------------------------------------------------
SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
diagSvc.WriteTrace( 0, // custom trace id
new SPDiagnosticsCategory("My category",
TraceSeverity.Monitorable,
EventSeverity.Error), // create a category

TraceSeverity.Monitorable, // set the logging level of this record
"Writing to the ULS log: {0}", // custom message
new object[] { "SharePoint rocks!"} // parameters to message
);
------------------------------------------------------------------------------------------------------------
SPDiagnosticsService diagnosticsService = SPDiagnosticsService.Local;
SPDiagnosticsCategory cat = diagnosticsService.Areas["SharePoint Foundation"].Categories["Unknown"];
string format = "Test trace logging for category {0} in area {1}";
diagnosticsService.WriteTrace(1, cat, TraceSeverity.Medium, format, cat.Name, cat.Area.Name);
Console.WriteLine(format, cat.Name, cat.Area.Name);
Console.ReadLine();
------------------------------------------------------------------------------------------------------------
using Microsoft.SharePoint.Administration;
SPDiagnosticsService diagnosticsService = SPDiagnosticsService.Local;
string errorMsg = ex.Message;
diagnosticsService.WriteTrace(0,
new SPDiagnosticsCategory("My Category", TraceSeverity.Monitorable, EventSeverity.Error),
TraceSeverity.Monitorable, "Writing to the ULS log: {0}", new object[] { errorMsg });
diagnosticsService.WriteEvent(0,
new SPDiagnosticsCategory("My Category", TraceSeverity.Monitorable, EventSeverity.Error),
EventSeverity.Error, "Writing to the Event Viewer log: {0}", new object[] { errorMsg });
------------------------------------------------------------------------------------------------------------
FullTextSqlQuery qry = new FullTextSqlQuery(SPContext.Current.Site);
qry.ResultTypes = ResultType.RelevantResults;
qry.QueryText = "SELECT preferredname,workemail,description ";
qry.QueryText += " FROM SCOPE() WHERE \"scope\" = '" + "People" + "' ";
qry.QueryText += " AND FREETEXT(*, '" +yourSearchQuery + "')";
ResultTableCollection rtq = qry.Execute();
if (rtq.Count > 0)
{
ResultTable queryResultsTable = rtq[ResultType.RelevantResults];
int totalResults = queryResultsTable.TotalRows;
DataTable tableResults = new DataTable();
tableResults.Load(queryResultsTable, LoadOption.OverwriteChanges);
}
------------------------------------------------------------------------------------------------------------
timer job:-
-------------
Get-SPTimerJob | ? {$_.LockType -eq "Job"}
Get-SPTimerJob | ? {$_.LockType -eq "None"}
Get-SPTimerJob | ? {$_.LockType -eq "ContentDatabase"} | Select-Object -Unique | Sort-Object Name | Format-Table Name
------------------------------------------------------------------------------------------------------------
Get DropDownList selected Text Value using javascript:-
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Java Script Code:-
[Get Index Value: 2]
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
[Get Index Value Text: test2]
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
------------------------------------------------------------------------------------------------------------
Edit a page that has no “Edit Page” menu option in WSS / MOSS / SharePoint:-
http://blogs.msdn.com/b/danielmcpherson/archive/2004/10/11/240863.aspx //SharePoint and Querystrings

To change everyone’s view of a particular page:-
http://servername:1111/Pages/Rating.aspx?PageView=Shared&ToolPaneView=2

To change your private view of a particular page:-
http://servername:1111/Pages/Rating.aspx?PageView=Personal&ToolPaneView=2

Web Part Maintenance Page:-
http://servername:1111/Pages/Rating.aspx?contents=1 

Querystring:-
-------------
Contents=1 //"Web Part Page Maintenance" page
Mode=Edit //"Web Part Page" into edit mode
Mode=View //"Web Part Page" into view mode
PageView=Personal //Displays your Personal view of a "Web Part Page"
PageView=Shared //Displays the Shared view of a web part page
ToolPaneView=2 //Shows the "Add Web Parts" toolpane
ToolPaneView=3 //Shows the "Search" toolpane
------------------------------------------------------------------------------------------------------------
How to Enable Sign in as Different User Option in SharePoint 2013:-
Go to this Path:-
C:\Program Files\Common Files\microsoft shared\Web ServerExtensions\15\TEMPLATE\CONTROLTEMPLATES
and open "welcome.ascx" in notepad.
<SharePoint:MenuItemTemplate runat="server" ID="ID_LoginAsDifferentUser"
Text="<%$Resources:wss,personalactions_loginasdifferentuser%>"
Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>"
MenuGroupId="100"
Sequence="100"
UseShortId="true"/>
------------------------------------------------------------------------------------------------------------
new SPDiagnosticsCategory("My Category", TraceSeverity.Monitorable, EventSeverity.Error),
TraceSeverity.Monitorable, "Writing to the ULS log: {0}", new object[] { errorMsg });
diagnosticsService.WriteEvent(0,
new SPDiagnosticsCategory("My Category", TraceSeverity.Monitorable, EventSeverity.Error),
EventSeverity.Error, "Writing to the Event Viewer log: {0}", new object[] { errorMsg });
------------------------------------------------------------------------------------------------------------
FullTextSqlQuery qry = new FullTextSqlQuery(SPContext.Current.Site);
qry.ResultTypes = ResultType.RelevantResults;
qry.QueryText = "SELECT preferredname,workemail,description ";
qry.QueryText += " FROM SCOPE() WHERE \"scope\" = '" + "People" + "' ";
qry.QueryText += " AND FREETEXT(*, '" +yourSearchQuery + "')";

ResultTableCollection rtq = qry.Execute();
if (rtq.Count > 0)
{
ResultTable queryResultsTable = rtq[ResultType.RelevantResults];
int totalResults = queryResultsTable.TotalRows;
DataTable tableResults = new DataTable();
tableResults.Load(queryResultsTable, LoadOption.OverwriteChanges);
}
------------------------------------------------------------------------------------------------------------
timer job:-
-------------
Get-SPTimerJob | ? {$_.LockType -eq "Job"}
Get-SPTimerJob | ? {$_.LockType -eq "None"}
Get-SPTimerJob | ? {$_.LockType -eq "ContentDatabase"} | Select-Object -Unique | Sort-Object Name | Format-Table Name
------------------------------------------------------------------------------------------------------------
Get DropDownList selected Text Value using javascript:-
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Java Script Code:-
[Get Index Value: 2]
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
[Get Index Value Text: test2]
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
------------------------------------------------------------------------------------------------------------
Edit a page that has no “Edit Page” menu option in WSS / MOSS / SharePoint:-
http://blogs.msdn.com/b/danielmcpherson/archive/2004/10/11/240863.aspx //SharePoint and Querystrings
To change everyone’s view of a particular page:-
http://servername:1111/Pages/Rating.aspx?PageView=Shared&ToolPaneView=2
To change your private view of a particular page:-
http://servername:1111/Pages/Rating.aspx?PageView=Personal&ToolPaneView=2
Web Part Maintenance Page:-
http://servername:1111/Pages/Rating.aspx?contents=1
Querystring:-
-------------
Contents=1   //"Web Part Page Maintenance" page
Mode=Edit   //"Web Part Page" into edit mode
Mode=View   //"Web Part Page" into view mode
PageView=Personal  //Displays your Personal view of a "Web Part Page"
PageView=Shared  //Displays the Shared view of a web part page
ToolPaneView=2  //Shows the "Add Web Parts" toolpane
ToolPaneView=3  //Shows the "Search" toolpane
------------------------------------------------------------------------------------------------------------
How to Enable Sign in as Different User Option in SharePoint 2013:-
Go to this Path:-
C:\Program Files\Common Files\microsoft shared\Web ServerExtensions\15\TEMPLATE\CONTROLTEMPLATES
 and open  "welcome.ascx" in notepad.
<SharePoint:MenuItemTemplate runat="server" ID="ID_LoginAsDifferentUser"
  Text="<%$Resources:wss,personalactions_loginasdifferentuser%>"
  Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>"
  MenuGroupId="100"
  Sequence="100"
  UseShortId="true"/>
------------------------------------------------------------------------------------------------------------
public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb)properties.Feature.Parent;
            SPList list = web.Lists["customList"];

            //Remove permissions from the list
            list.BreakRoleInheritance(false);

            //Make site owners the list administrators
            SPPrincipal principal = web.AssociatedOwnerGroup as SPPrincipal;
            SPRoleAssignment assignment = new SPRoleAssignment(principal);
            assignment.RoleDefinitionBindings.Add(web.RoleDefinitions.GetByType(SPRoleType.Administrator));
            list.RoleAssignments.Add(assignment);

            //update list changes
            list.Update();
        }
------------------------------------------------------------------------------------------------------------
Attach Database in SQL Server 2012 using .mdf file without .ldf file:-
CREATE DATABASE AdventureWorks2012 ON
(FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\AdventureWorks2012_Data.mdf')
FOR ATTACH_REBUILD_LOG;
------------------------------------------------------------------------------------------------------------
Sharepoint 2013: Create a site template:-
site template creation is disabled by default.
This property can be easily changed through Sharepoint Designer.
step1:- in the Site Options button -> change the value of 'SaveSiteAsTemplateEnabled' to 'true'
step2:- Navigate to ~site/_layouts/15/savetmpl.aspx and create the template.
------------------------------------------------------------------------------------------------------------
Prevent field validators from firing when editing a web part:-
protected override void OnPreRender(EventArgs e)
        {
            WebPartManager mgr = WebPartManager.GetCurrentWebPartManager(Page);
            if (mgr.DisplayMode.Equals(mgr.SupportedDisplayModes["Browse"]))
            {
                myValidator.Enabled = true;
            }
            else
            {
                myValidator.Enabled = false;
            }
            base.OnPreRender(e);
        }
------------------------------------------------------------------------------------------------------------
Strict mode in JavaScript:-
Strict mode makes several changes to normal JavaScript semantics.
1. First, strict mode eliminates some JavaScript silent errors by changing them to throw errors.
2. Second, strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.
3. Third, strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
Strict mode for scripts:-
// Whole-script strict mode syntax
"use strict";
var v = "Hi!  I'm a strict mode script!";

Strict mode for functions:-
function strict(){
  // Function-level strict mode syntax
  'use strict';
  function nested() { return "And so am I!"; }
  return "Hi!  I'm a strict mode function!  " + nested();
}
function notStrict() { return "I'm not strict."; }
------------------------------------------------------------------------------------------------------------
SPPersistedObject as SPTimerJob parameters
The SPPersistedObject class provides a base class for all administration objects. It serializes all fields marked with the Persisted attribute to XML and writes the XML blob to the configuration database. The SPPersistedObject class contains code to serialize all its members that are base types, other persisted objects, and collections of persisted objects. Configuration data that is stored in persisted objects is automatically made available to every process on every server in the farm.

How to use the SPPersistedObject
public class TimerJobSet: SPPersistedObject
{
   [Persisted]
   public string siteName;

   [Persisted]
   public bool Debug;

   public TimerJobSet(string name, SPPersistedObject parent) : base(name,parent) {}
}

SPWeb web = properties.Feature.Parent;
SPSite site = web.Site;
SPPersistedObject parent = site.WebApplication;
CustomTimerJobSettings settings =new TimerJobSet("TimerJobSet", parent, Guid.NewGuid());
settings.Debug =false;
settings.siteName="host.com";
settings.Update();

TimerJobSet settings =this.WebApplication.GetChild<TimerJobSet>("TimerJobSet");  string siteName = settings.SiteName;
bool debug = settings.Debug;
------------------------------------------------------------------------------------------------------------
Changing the properties of an existing Web Part using PowerShell:
$site = new-object Microsoft.SharePoint.SPSite("http://spserver:9999")
$web = $site.OpenWeb("Sites/Test/")
$page = $web.GetFile("Pages/default.aspx")
$page.CheckOut()
$wpm = $web.GetLimitedWebPartManager("Pages/default.aspx",[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

$wpm.WebParts | ft

$wp = $wpm.WebParts[1]
$wp.EnableRedirect = $false
$wp.Url = "http://www.google.com"
$wpm.SaveChanges($wp)
$page.CheckIn("Test")
$page.Publish("Test")
$web.Close()
$site.Close() 
------------------------------------------------------------------------------------------------------------
To refresh parent page code is:

<script src="/SiteAssets/jquery.min.js"></script>
<Sharepoint:ScriptLink ID="ScriptLink1" Name="SP.js" LoadAfterUI="true" Localizable="false" runat="server"></Sharepoint:ScriptLink>
<Sharepoint:ScriptLink ID="ScriptLink1" Name="sp.ui.dialog.js" LoadAfterUI="true" Localizable="false" runat="server"></Sharepoint:ScriptLink>
<Sharepoint:ScriptLink ID="ScriptLink1" Name="SP.Core.js" LoadAfterUI="true" Localizable="false" runat="server"></Sharepoint:ScriptLink>
<SharePoint:FormDigest runat="server" />
<script type="text/javascript" language="javascript">
$(function() {
$("#clickMe").click(function(){
OpenDialog();        });   });
function OpenDialog() {      
          var options = {
            url: '/SitePages/test3.aspx',
            title: 'Test Modal Dialog',
            width: 800,
            height: 600,
            dialogReturnValueCallback: RefreshOnDialogClose
          };
          SP.UI.ModalDialog.showModalDialog(options);
        }
</script>
<div id="clickMe">Click Me to open test3 page</div>
----------------------------------------------------------------------
If you want to track whether click on 'ok' or 'close' button then

<script src="/SiteAssets/jquery.min.js"></script>
<Sharepoint:ScriptLink ID="ScriptLink1" Name="SP.js" LoadAfterUI="true" Localizable="false" runat="server"></Sharepoint:ScriptLink>
<Sharepoint:ScriptLink ID="ScriptLink1" Name="sp.ui.dialog.js" LoadAfterUI="true" Localizable="false" runat="server"></Sharepoint:ScriptLink>
<Sharepoint:ScriptLink ID="ScriptLink1" Name="SP.Core.js" LoadAfterUI="true" Localizable="false" runat="server"></Sharepoint:ScriptLink>
<SharePoint:FormDigest runat="server" />
<script type="text/javascript" language="javascript">          
            $(function() {
            $("#clickMe").click(function(){
                        OpenDialog();            });            });      
function OpenDialog() {      
          var options = {
            url: '/SitePages/test3.aspx',
            title: 'Test Modal Dialog',
            width: 800,
            height: 600,
            dialogReturnValueCallback: CloseCallback
          };
          SP.UI.ModalDialog.showModalDialog(options);
        }    
        function CloseCallback(result, returnValue) {
          alert('Result from dialog was: ' + result);
          if (result == SP.UI.DialogResult.Ok) {
            alert('You clicked Ok');
          }
          else if (result == SP.UI.DialogResult.cancel) {
            alert('You clicked Cancel');
          }
        }
</script>
<div id="clickMe">Click Me to open test3 page</div>
------------------------------------------------------------------------------------------------------------
To Close Popup window add this button in "/SitePages/test3.aspx"

<input type="button" id="Button1" value="OK" onclick="window.frameElement.commitPopup();" />
------------------------------------------------------------------------------------------------------------
Hide New Item, Edit Item, View Item in Ribbon in SharePoint using CSS
<style type="text/css">
#Ribbon\.ListItem\.New
{
       display: none !important;
}
#Ribbon\.ListItem\.Manage-LargeMedium-0
{
      display: none !important;
}
</style>
------------------------------------------------------------------------------------------------------------
Hide Delete Item, Edit Item, View Item in ECB Menu in SharePoint using JQuery
Add below script using content editor webpart CEWP.
<script src="/sites/equotation/SiteAssets/Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('.ms-MenuUIPopupBody').live('mouseover', function() {        
 $('#ID_DeleteItem').parent().hide();
 $('#ID_DeleteItem').remove();  
 $('#ID_ViewItem').parent().hide();
 $('#ID_ViewItem').remove();
 $('#ID_EditItem').parent().hide();
 $('#ID_EditItem').remove();
});</script>
------------------------------------------------------------------------------------------------------------

Friday, June 7, 2013

Custom Timer Job Sharepoint

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace GENERAL_CustomTimerJob
{
    class GENERAL_CustomTimerJob : SPJobDefinition
    {
        #region Constructors
        public GENERAL_CustomTimerJob()
            : base()
        {
        }
        public GENERAL_CustomTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {
        }
        public GENERAL_CustomTimerJob(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Simple Example Timer Job";
        }
        #endregion

        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication webApp = this.Parent as SPWebApplication;
            SPSiteCollection timerSiteCollection = webApp.ContentDatabases[targetInstanceId].Sites;
            SPList timerJobList = null;
            foreach (SPSite site in timerSiteCollection)
            {
                timerJobList = site.RootWeb.Lists.TryGetList("Announcements");
                if (timerJobList != null)
                {
                    SPListItem newItem = timerJobList.Items.Add();
                    newItem["Title"] = "Today is " + DateTime.Today.ToLongDateString();
                    newItem.Update();
                }
            }
        }
    }
}
-----------------------------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;

namespace GENERAL_CustomTimerJob.Features.CustomTimerJobFeature
{
    [Guid("1b45bf8b-f5e2-4155-8f7f-999b1163c3d1")]
    public class CustomTimerJobFeatureEventReceiver : SPFeatureReceiver
    {
        const string TIMER_JOB_NAME = "DemoTimerJob";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == TIMER_JOB_NAME)
                {
                    job.Delete();
                }
            }
            GENERAL_CustomTimerJob newTimerJob = new GENERAL_CustomTimerJob(TIMER_JOB_NAME, site.WebApplication);
            SPMinuteSchedule jobSchedule = new SPMinuteSchedule();
            jobSchedule.BeginSecond = 0;
            jobSchedule.EndSecond = 59;
            jobSchedule.Interval = 5;
            newTimerJob.Schedule = jobSchedule;
            newTimerJob.Update();
        }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == TIMER_JOB_NAME)
                {
                    job.Delete();
                }
            }
        }
    }
}
-----------------------------------------------------------------------------------------------------------

Wednesday, May 22, 2013

Add the client-side People Picker control to apps in SharePoint 2013

VS2012-> file -> new project -> c# -> Office/SharePoint -> Apps -> Apps for SharePoint 2013 -> "clientPeoplePickerApp"


Default.aspx:-
<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>

<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />

    <!-- Add your JavaScript to the following file -->
    <script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Page Title
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <SharePoint:ScriptLink ID="ScriptLink1" Name="clienttemplates.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink ID="ScriptLink2" Name="clientforms.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink ID="ScriptLink3" Name="clientpeoplepicker.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink ID="ScriptLink4" Name="autofill.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink ID="ScriptLink5" Name="sp.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink ID="ScriptLink6" Name="sp.runtime.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink ID="ScriptLink7" Name="sp.core.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <div>
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
    </div>
    <div id="peoplePickerDiv"></div>
    <div>
        <br />
        <input type="button" value="Get User Info" onclick="getUserInfo()"></input>
        <br />
        <h1>User info:</h1>
        <p id="resolvedUsers"></p>
        <h1>User keys:</h1>
        <p id="userKeys"></p>
    </div>
</asp:Content>
------------------------------------------------------------------------------------
App.js:-
'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    getUserName();
    initializePeoplePicker('peoplePickerDiv');
});

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}

// Render and initialize the client-side People Picker.
function initializePeoplePicker(peoplePickerElementId) {

    // Create a schema to store picker properties, and set the properties.
    var schema = {};
    schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
    schema['SearchPrincipalSource'] = 15;
    schema['ResolvePrincipalSource'] = 15;
    schema['AllowMultipleValues'] = true;
    schema['MaximumEntitySuggestions'] = 50;
    schema['Width'] = '280px';

    // Render and initialize the picker.
    // Pass the ID of the DOM element that contains the picker, an array of initial
    // PickerEntity objects to set the picker value, and a schema that defines
    // picker properties.
    this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}

// Query the picker for user information.
function getUserInfo() {

    // Get the people picker object from the page.
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;

    // Get information about all users.
    var users = peoplePicker.GetAllUserInfo();
    var userInfo = '';
    for (var i = 0; i < users.length; i++) {
        var user = users[i];
        for (var userProperty in user) {
            userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
        }
    }
    $('#resolvedUsers').html(userInfo);

    // Get user keys.
    var keys = peoplePicker.GetAllUserKeys();
    $('#userKeys').html(keys);
}
Now Click on F5 to deploy...



Thank You.

Featured Post

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide Version: July 2026 | Audience: Beginners, Citizen Developers, Busine...

Popular posts