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>
------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment