Tuesday, June 29, 2010

JQuery - Hide the fields from the SharePoint form

<script language="javascript" type="text/javascript" src="/_LAYOUTS/JQuery/jquery-1.3.2.min.js">
</script>
<script language="javascript" type="text/javascript" src="/_LAYOUTS/JQuery/jquery.SPServices-0.5.4.min.js">
</script>
<script language="javascript" type="text/javascript" src="/_LAYOUTS/JQuery/SPAPI_Lists.js">
</script>
<script language="javascript" type="text/javascript" src="/_LAYOUTS/JQuery/SPAPI_Core.js">
</script>
<script type="text/javascript" language="javascript" >
$(":input[title='Title']").parent().parent().parent().hide();
$(":input[title='Task Name']").parent().parent().parent().hide();
</script>

Friday, June 25, 2010

Very good JQuery Sample

http://www.bitsofsharepoint.com/BlogPoint/Lists/Categories/Category.aspx?Name=SP-Javascript%2FJQuery

Thursday, June 24, 2010

JQuery-SharePoint Samples

Get Data From a SharePoint list using JQuery

<%@ Page Language="C#" %>
<html dir="ltr">
<head runat="server">
<META name="WebPartPageExpansion" content="full">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled 1</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="button" onclick="test()"/>
<input type="text" id="output"/>
</div>
</form>
<script language="javascript" type="text/javascript" src=
"/_LAYOUTS/JQuery/jquery-1.3.2.min.js">
</script>
<script language="javascript" type="text/javascript" src=
"/_LAYOUTS/JQuery/jquery.SPServices-0.5.4.min.js">
</script>
<script language="javascript" type="text/javascript" src=
"/_LAYOUTS/JQuery/SPAPI_Lists.js">
</script>
<script language="javascript" type="text/javascript" src=
"/_LAYOUTS/JQuery/SPAPI_Core.js">
</script><script type="text/javascript" language="javascript">
function test()
{
// Return all items in the default view of MyList
var lists = new SPAPI_Lists('http://Test:1659/TestSite');
var items = lists.getListItems('Origin');
if (items.status == 200)
{
var rows = items.responseXML.getElementsByTagName('z:row');

$(items.responseXML).find("z\\:row").each(function()
{
var liHtml = $(this).attr("ows_First_x0020_Name") ;
alert(liHtml);
});

}
else
{
alert('There was an error: ' + items.statusText);
}
}
</script>
</body>
</html>

Monday, June 21, 2010

JQuery + SharePoint + API

http://darrenjohnstone.net/2008/07/22/examples-for-the-sharepoint-and-office-live-javascript-api/

Tuesday, June 15, 2010

JQuery to Display Image from a link

http://sharepointjavascript.wordpress.com/2010/04/29/image-preview-on-hover-over-a-hyperlink-field/

Thursday, June 3, 2010

Code Sample to reuse

ALL POWER SHELL
=================

List all files hierarchically

dir /s /b /a-d>dirall.txt

Powershell to add user to farm admin group
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$newFarmAdministrator = Read-Host -Prompt 'Name of the new Farm Administrator, Format - DOMAIN\Username'
$caWebApp = Get-SPWebApplication -IncludeCentralAdministration | where-object {$_.DisplayName -eq "SharePoint Central Administration v4"}
$caSite = $caWebApp.Sites[0]
$caWeb = $caSite.RootWeb
$farmAdministrators = $caWeb.SiteGroups["Farm Administrators"]
$farmAdministrators.AddUser($newFarmAdministrator, "", $newFarmAdministrator, "Configured via PowerShell")
$caWeb.Dispose()
$caSite.Dispose()
$caDB = Get-SPContentDatabase -WebApplication $caWebApp

Add-SPShellAdmin -Database $caDB -Username $newFarmAdministrator

Powershell to add user to Full control permission to all web apps 
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

$userOrGroup = Read-Host -Prompt 'New user name , format - DOMAIN\Username'

Get-SPWebApplication | foreach {
    $webApp = $_
    $policy = $webApp.Policies.Add($userOrGroup, $userOrGroup)
    $policyRole = $webApp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullControl)
    $policy.PolicyRoleBindings.Add($policyRole)
    $webApp.Update()
}

PS To Delete all the doclibs unders a site

        Add-PSSnapin "Microsoft.SharePoint.PowerShell"
         $site = Get-SPSite("http://site.domain.com");
         $web =  $site.OpenWeb();
         $lists = $web.Lists
         $ary = @()
         foreach($list in $lists )
         {
             if($list.TemplateFeatureId -eq "00bfea71-e717-4e80-aa17-d0c71b360101")
             {
                $ary = $ary + $list.Title
             }
             $ary
         }

foreach($obj in $ary)
{
        $library = $web.Lists[$obj]
        $library.Delete()
}


#Get SharePoint Version
(Get-PSSnapin microsoft.sharepoint.powershell).Version.Major

#Get the list of webs using GUID and Title with AutoSize
Get-SPSite 'http://sp2010test:5555/sites/test' | Get-SPWeb -Limit All | Select Id, Title, Url | Format-Table -AutoSize

#Create WEb App and Site Col
New-SPWebApplication -Name 'testname' -HostHeader sp2010devserver  -URL "http://sp2010devserver:11111" -ApplicationPool testnamepool -ApplicationPoolAccount (Get-SPManagedAccount 'contoso\xuwian') -DatabaseName testnamedb -DatabaseServer sp2010devserver


# Create a new Sharepoint Site Collection
New-SPSite -URL "http://sp2010devserver:11111/sites/testname" -OwnerAlias "contoso\xuwian" -Language 1033 -Template "STS#1" -Name "MyBlank site"

#Add Site Coll Admin
Set-SPSite -Identity "http://spsite:3500/sites/abcsite" -SecondaryOwnerAlias "contoso/abc"

#Get ALl Web App
Get-SPWebApplication

#Get All Site Col
Get-SPSite

#Verifying current credentials
1. runas /user:Domain\UserName notepad.exe
2. whoami

Display file as a response of page/webpart:

        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("content-disposition", "attachment; filename=FilaName1.docx");
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.TransmitFile("FilanmePath OR Name.docx");
        Response.Flush();
        Response.Close();


Sandbox solution: Delete all subwebs in hierarchical manner
======================================

 public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb  objSCSPWeb  = properties.UserCodeSite.RootWeb;

           for (int i = 0; i < objSCSPWeb.Webs.Count; i++)
            {
                SPWeb objspw1 = objSCSPWeb.Webs[i];
                if (objspw1.Webs.Count != 0)
                {
                    for (int j = 0; j < objspw1.Webs.Count; j++)
                    {
                        SPWeb objspw2 = objspw1.Webs[j];
                        objspw2.Delete();
                        objspw2.Dispose();
                    }
                }
                    objspw1.Delete();
                    objspw1.Dispose();
            }
        }

Sample code for CustomAction
=======================

<CustomAction
  Id="testContextMenu"
  Location="EditControlBlock"
  Title="Test context menu"
  RegistrationType="ContentType"
  ShowInLists="FALSE"
ImageUrl ="~Site/_layouts/images/Testing/TestFolder/Testing.PNG"
  RegistrationId="0x0101">
  <UrlAction Url="javascript:window.location= '{SiteUrl}/_layouts/Testing/TestFolder/Page1.aspx?ID={ItemId}&amp;Source=' + window.location"/>
</CustomAction>





Add Document Set via Client Object Model and Server Object Model.
====================================================

1.       With Client Object Model

public void AddDocSet(string siteUrl, string listName, string docSetContentTypeName, string newDocSetName)
        {
            using (ClientContext clientContext = new ClientContext(siteUrl))
            {
                Web web = clientContext.Web;
                List list = clientContext.Web.Lists.GetByTitle(listName);

                clientContext.Load(clientContext.Site);

                ContentTypeCollection listContentTypes = list.ContentTypes;
                clientContext.Load(listContentTypes, types => types.Include
                                                  (type => type.Id, type => type.Name,
                                                  type => type.Parent));

                var result = clientContext.LoadQuery(listContentTypes.Where(c => c.Name == docSetContentTypeName));
                clientContext.ExecuteQuery();

                ContentType targetDocumentSetContentType = result.FirstOrDefault();

                ListItemCreationInformation newItemInfo = new ListItemCreationInformation();
                newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                newItemInfo.LeafName = newDocSetName;
                ListItem newListItem = list.AddItem(newItemInfo);


                newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString();
                newListItem["Title"] = newDocSetName;
                newListItem.Update();


                clientContext.Load(list);
                clientContext.ExecuteQuery();
                MessageBox.Show("New Document Set created with the ID : " + newListItem.Id.ToString());
            }
        }


2.       With Object Model

private static void AddDocSet(SPDocumentLibrary docSetLibrary, string newDocSetName, SPContentType targetDocumentSetContentType, string rootFolderUrl)
        {
            SPFolder targetFolder = docSetLibrary.ParentWeb.GetFolder(rootFolderUrl + "/" + newDocSetName);
            if (!targetFolder.Exists)
            {
                DocumentSet targetDocSet = DocumentSet.Create(docSetLibrary.RootFolder, newDocSetName, targetDocumentSetContentType.Id, new Hashtable(), true);
           
            }           
        }

Hide SharePoint Ribbon Control
=========================


SPRibbon.GetCurrent(this.Page).CommandUIVisible = false;


Logging in ULS Log
==============
SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
diagSvc.WriteTrace( 0, new SPDiagnosticsCategory("test category", TraceSeverity.Monitorable, EventSeverity.Error), TraceSeverity.Monitorable, "Writing to the ULS log: {0}", new object[] { "SharePoint 2010 is gr8!"});

or

try
{
var i = 0;
var a = 2 / i;
}
catch (Exception ex)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("Test Category", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}


or
$diagSvc = [Microsoft.SharePoint.Administration.SPDiagnosticsServices]::Local
$category = new-object Microsoft.SharePoint.Administration.SPDiagnosticsCategory(“test Category”,
                                   [Microsoft.SharePoint.Administration.TraceSeverity]::Monitorable,
                                  [Microsoft.SharePoint.Administration.EventSeverity]::Error )
$diagSvc.WriteTrace(0, $category, [Microsoft.SharePoint.Administration.TraceSeverity]::Monitorable, “Test logging” )

Get list item collections from List

SPWeb objSpWeb = properties.OpenWeb();
objSpWeb.AllowUnsafeUpdates = true;
SPList splDetails = objSpWeb.Lists["Details"];
SPQuery spqDetails = new SPQuery();
spqDetails.Query = "In Process" + currentFlatNumber + "";
SPListItemCollection splicDetails = splDetails.GetItems(spqDetails);

Register Event Handlers
-- to blog --

Adding Web User Controls in ControlTemplates and using it in Aspx form.

<%@ Register TagPrefix="TestUserControlPrefix" TagName="TEstUserControlName" src="~/_controltemplates/MyUserControl/TestUserControl.ascx" %>

Add ViewFields to the SPQuery

public static string CreateViewFieldsString(params string[] fieldNames)
{
StringBuilder strb = new StringBuilder();
foreach (string fieldName in fieldNames)
strb.AppendFormat("<fieldref name="'{0}'/">", fieldName);
return strb.ToString();
}

SPQuery query = new SPQuery();
query.ViewFields = CreateViewFieldsString("Field1", "Field2", "Field3");

Enable/Disable Event Firing in Page.

public static class SPEventManagerWrapper
{
private static readonly string _className = "Microsoft.SharePoint.SPEventManager";
private static readonly string _eventFiringSwitchName = "MakeEventFiringDisabled";
private static Type _eventManagerType;

/// gets the status of event firing on the current thread
public static bool MakeEventFiringDisabled
{
get { return GetEventFiringSwitchValue(); }
}

private static Type EventManagerType
{
get
{
if (_eventManagerType == null)
GetEventManagerType();
return _eventManagerType;
}
}

/// enables event firing on the current thread
public static void MakeEnableEventFiring()
{
SetEventFiringSwitch(false);
}

/// disables sharepoint event firing on the current thread
public static void MakeDisableEventFiring()
{
SetEventFiringSwitch(true);
}


/// sets the event firing switch on Microsoft.SharePoint.SPEventManager class using reflection
private static void SetEventFiringSwitch(bool value)
{
PropertyInfo pi = EventManagerType.GetProperty(_eventFiringSwitchName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
pi.SetValue(null, value, null);
}

private static bool GetEventFiringSwitchValue()
{
PropertyInfo pi = EventManagerType.GetProperty(_eventFiringSwitchName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
object val = pi.GetValue(null, null);
return (bool)val;
}


private static Type GetEventManagerType()
{
_eventManagerType = typeof(SPList).Assembly.GetType(_className, true);
return _eventManagerType;
}
}


Shrink SharePoint Content DB
=====================

USE WSS_Content_a978b1b0c113419883f8e47589e20e6d;
GO
-- Truncate the log changing the database recovery model to SIMPLE.
ALTER DATABASE WSS_Content_a978b1b0c113419883f8e47589e20e6d
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (WSS_Content_a978b1b0c113419883f8e47589e20e6d_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE WSS_Content_a978b1b0c113419883f8e47589e20e6d
SET RECOVERY FULL;
GO


Delete SharePoint List Item using WebService
///














/// Deletes List Item from SharePoint list using Web Service.
///
///
ListItemID
///
Name of the LIST in text format, NOT GUID.
///
List.asmx ws url like - http://www.sitename.com/sites/web1/_vti_bin/lists.asmx
/// True/false
public bool DeleteListItem(string listItemID, string ListName, string strUrl)
{
bool retVal = true;
try
{
DEVLists.Lists listService = new DeleteDuplicateProjects.DEVLists.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = strUrl;
System.Xml.XmlNode ndListView = listService.GetListAndView(ListName, "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;

StringBuilder strbBatch = new StringBuilder();
string strBatchFormat = "{0}";
strbBatch.AppendFormat(strBatchFormat, Convert.ToInt32(listItemID));

XmlDocument xmlDoc = new System.Xml.XmlDocument();

System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");

elBatch.SetAttribute("OnError", "Continue");
elBatch.SetAttribute("ListVersion", "1");
elBatch.SetAttribute("ViewName", strViewID);

elBatch.InnerXml = strbBatch.ToString();

XmlNode ndReturn = listService.UpdateListItems(strListID, elBatch);
}
catch
{
retVal = false;
}
return retVal;
}


SQL Rows Limited
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY <SORT FIELD> DESC) AS RowNumber, * FROM <TABLE or VIEW NAME>) AS Rows WHERE RowNumber between 49 and 50

Find SQL Columns from DataBase


SELECT name FROM sysobjects WHERE id IN ( SELECT id FROM syscolumns WHERE name = 'THE_COLUMN_NAME' )

OR

SELECT name FROM sysobjects WHERE id IN ( SELECT id FROM syscolumns WHERE name like '%PART_OF_NAME%' )

Disconnect sessions from remote machine
http://kodethoughts.blogspot.com/2006/12/kill-remote-user-session-remotely.html

Script for SharePoint automation testing and many more potential features


Go to http://www.autohotkey.com/
Go to Downloads link and download - "Installer for AutoHotkey Basic" from "http://www.autohotkey.com/download/AutoHotkeyInstall.exe"
Install with default options in installer.
Create a file called "test.ahk" on desktop.
Paste following code to open www.google.com on key strokes of WINDOWS + Z
#z::Run www.google.com
Just save the "test.ahk"
Right click the file and click on "Run Script" menu.
And script is setup!!

To test-

Just hit WINDOWS key + z

You will fine www.google.com opened in your default browser. Isnt great?

You can play with following alternative script to test with.

^!n::
IfWinExist Untitled - Notepad
WinActivate
else
Run Notepad
return

SharePoint 2010 Best practices
http://technet.microsoft.com/en-us/sharepoint/hh189420.aspx
http://channel9.msdn.com/Events/TechDays/TechDays-2011-Belgium/TD018
http://channel9.msdn.com/blogs/kreekman/techdays-2010-best-practices-for-sandboxed-solution-development
http://channel9.msdn.com/posts/Joel-Oleson-SharePoint-2010-Upgrade--Migration-Best-Practices-SharepointPTDay-29102010
http://channel9.msdn.com/Blogs/matthijs/Lessons-Learned-and-Best-Practices-from-Enterprise-Deployments-of-SharePoint
http://channel9.msdn.com/Events/TechEd/Australia/2010/OFS304
http://channel9.msdn.com/Events/TechEd/Australia/Tech-Ed-Australia-2011/OFS306
http://channel9.msdn.com/Events/TechDays/TechDays-2011-Belgium/TD018
http://channel9.msdn.com/events/MIX/MIX10/PR02
http://channel9.msdn.com/blogs/matthijs/fast-search-for-sharepoint-2010-capabilities-deep-dive
http://channel9.msdn.com/Blogs/funkyonex/Implementing-a-Silverlight-SharePoint-WebPart-with-Visual-Studio-2010
http://channel9.msdn.com/Events/TechEd/NorthAmerica/2011/OSP317
http://channel9.msdn.com/Events/TechDays/TechDays-2011-Belgium/TD018