Thursday, May 31, 2012

HTTP 400 Bad Request (Request Header Too Long) - Error in SharePoint

One of the End-User started seeing this error in SharePoint 2007 - InfoPath form submission.
Bad Request (Request Header Too Long)
bad request request header too long sharepoint
Resolution:
1. Try deleting the browser cookies at the Client browser first. See whether it helps.

2. If not, implement the fix as per KB: http://support.microsoft.com/kb/920862/en-us
Save the below registry entries to .Reg file and merge it simply!
http 400 bad request error sharepoint
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters]
"MaxRequestBytes"=dword:00500000
"MaxFieldLength"=dword:00065534

Restart the server for the changes to take effect, and as always take backup before making any registry change.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, May 30, 2012

SharePoint Site Users & Hits Count Report for the past 30 days

Another SharePoint Report Requirement: Need count of users & hits on each site (not for site collection - site collection has OOTB report! but at site level) for a particular web application for past 30 days!

No worries! My code goes here:

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

namespace AdminReports
{
    class GetSiteUsageReport
    {
        //Method to Get Usage Data
        public static int GetUserCount(SPWeb oSPWeb)
        {
            try
            {
                //Get the Usage Details 
                object userCount = null;
                //DataTable for users set - Because GetUsageData returns DataTable!
                DataTable dtUsers = new DataTable();
                dtUsers = oSPWeb.GetUsageData(SPUsageReportType.user, SPUsagePeriodType.lastMonth);
                if (dtUsers != null)
                {
                    userCount = dtUsers.Compute("Count(user)", string.Empty);
                    return (Convert.ToInt32(userCount));
                }
                else
                {
                    return (0);
                }
            }
            catch (Exception Ex1)
            {
                return (0);
            }
        }

        //Method to Get Hits Data
        public static int GetHitsCount(SPWeb oSPWeb)
        {
            try
            {
                //DataTable for Hits set - Because GetUsageData returns DataTable!
                object totalHits = null;
                DataTable dtHits = new DataTable();
                dtHits = oSPWeb.GetUsageData(SPUsageReportType.url, SPUsagePeriodType.lastMonth);
                if (dtHits != null)
                {
                    totalHits = dtHits.Compute("Sum([Total Hits])", string.Empty);
                    return (Convert.ToInt32(totalHits));
                }
                else
                {
                    return (0);
                }
            
            }
            catch (Exception Ex2)
            {
                return (0);
            }
        }


        static void Main(string[] args)
        {
            string site;

            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Enter the Web Application URL:");
                    site = Console.ReadLine();
                }
                else
                {
                    site = args[0];
                }

                SPSite tmpRoot = new SPSite(site);
                SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;

                //objects for the CSV file generation
                StreamWriter SW;
                SW = File.AppendText("c:\\SiteUsageReport.csv");

                //Write the CSV Header
                SW.WriteLine("Site Name, URL, No. of Users, Hits Count");

                //Enumerate through each site collection
                foreach (SPSite tmpSite in tmpRootColl)
                {
                    //Enumerate through each sub-site
                    foreach (SPWeb tmpWeb in tmpSite.AllWebs)
                    {
                            //Get the Site Name
                            string siteName;
                            if (tmpWeb.IsRootWeb)
                            {
                                siteName = tmpWeb.Title + " - Root";
                            }
                            else
                            {
                                siteName = tmpSite.RootWeb.Title + " - " + tmpWeb.Title;
                            }

                            //Log the retrieved details to a CSV file
                            SW.WriteLine(siteName.Replace(",", " ") + "," + tmpWeb.Url  + "," + GetUserCount(tmpWeb) + "," + GetHitsCount(tmpWeb) );
                        
                    }
                }

                //Dispose of the Root Site Object
                SW.Close();
                tmpRoot.Dispose();
            }

            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Site Usage Report Report", ex.Message);
            }
               
        }
    }
}

SharePoint Site Hits Report: and my report output: Raw data
sharepoint site hits report
 After adding a Pivot Table: SharePoint site usage report total hits and users:
sharepoint site usage report total hits and users


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Remove Faulty Webpart with Web Part Page Maintenance Mode

There was a custom web part deployed in our environment. For some reasons, web part encountered some issue and made the pages crashed!. Ideally, The developer should have handled the error in web part to avoid page crash! but it didn't happen! how to remove faulty web part in SharePoint 2007 or in SharePoint 2010?

Alright, to fix the issue, I get into Maintenance mode (by just appending "?contents=1" to the end of URL)  E.g. http://sharepoint.company.com/sites/sales/reports.aspx?contents=1

Deleted the particular faulty web part, and we are back to business!
web part maintenance mode sharepoint

In a another case, When we migrated from MOSS 2007 to SharePoint 2010 with 1000+ sites.

After the upgrade for some reasons, we wanted to delete a particular web part (Tip of the day web part) from the home page of All migrated sites' default.aspx page of the many sites. So I wrote the PowerShell code to delete error Web parts programmatically.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Find Large SharePoint Lists & Generate Report with PowerShell

This is the PowerShell version of my existing work: Find Large Lists in SharePoint

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#For Output file generation
$OutputFN = "LargeListsData.csv"
#delete the file, If already exist!
if (Test-Path $OutputFN)
 { 
    Remove-Item $OutputFN 
 }
#Write the CSV Headers
Add-Content $OutputFN "List Name , site Collection , Site URL , Item count"

#Get the Web Application URL
$WebAppURL = Read-Host "Enter the Web Application URL:"
$SPwebApp = Get-SPWebApplication $WebAppURL

#Loop through All Site collections, Sites, Lists
      foreach($SPsite in $SPwebApp.Sites) 
      {
        foreach($SPweb in $SPSite.AllWebs) 
        {
          foreach($SPlist in $SPweb.Lists) 
             {
                if($splist.ItemCount -gt 2000) 
                  {
                    $content = $SPlist.Title + "," + $SPsite.Rootweb.Title +"," + $SPweb.URL + "," + $SPlist.ItemCount
                    add-content $OutputFN $content
                   }
              }
           $SPweb.Dispose()
         }
         $SPsite.Dispose()
       }
write-host "Large List report generated successfully!"

PowerShell script to find large lists and export to CSV:
Lets do it in one line! Here is the PowerShell one-liner to find Large lists (Lists with more than 2000 items) and export to CSV:
Get-SPWebApplication http://intranet.crescent.com | Get-SPSite -Limit All | Get-SPWeb -Limit All `
    | Foreach-object { $_.Lists | Select @{N="Url";E={$_.ParentWeb.url+$_.RootFolder.Url} }, Title, ItemCount } `
        | Where {$_.ItemCount -gt 2000} | sort ItemCount -Descending | Export-csv -Path "c:\largeLists.csv" -NoTypeInformation


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, May 29, 2012

How to Disable Default Out of the Box Workflows in SharePoint?

For some weird reasons, site owner wanted to disable out of the box workflow: Collect Signature from a particular site collection.
sharepoint 2007 disable workflows

In SharePoint 2010, These workflows can be simple activated/deactivated from Site collection features. Refer my post Unable to find OOTB Workflows - Approval, Collect Signatures, Feedback for more info.

But in MOSS, Its little tricky. This workflows(Almost all others too) are deployed as a Feature and lives in 12 Hive.
sharepoint remove default workflows

So we can manually deactivate these features to remove default workflows in SharePoint . Here is how:

stsadm -o deactivatefeature -filename SignaturesWorkflow\Feature.xml -url http://Site-collection-URL

And if you want to enable it back:
stsadm -o activatefeature -filename SignaturesWorkflow\Feature.xml -url http://Site-collection-URL

Here is the screen once deactivated:
sharepoint 2007 disable workflows



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, May 26, 2012

Solution Successfully Deployed but deployment status shows: Not deployed!

Recently, while deploying a Solution, It happened to me! Solution was successfully deployed with out any issues. But couldn't see the features in Site!!
Solution Successfully Deployed but deployment status shows: Not deployed!


See the workarounds here:
http://blogs.technet.com/b/manjesh/archive/2009/10/13/solution-package-gets-deployed-successfully-but-status-shows-not-deployed.aspx


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, May 24, 2012

Site Collection Locks in SharePoint 2010

Some time back, I ran into a issue where a particular site collection was in read-only mode to every one including site collection admin, certain options such as site action menus were in disabled state!. Then I realized site collection backup process was interrupted due to disk-space issue and it left the site collection in "Read-only" mode! which was documented in my post SharePoint site is read-only to everyone

Screenshot from Read-only locked Site collection: Note that ribbon items are disabled!
SharePoint Ribbon controls are disabled in a Read-only locked Site collection
Screenshot from Unlocked site:
SharePoint Ribbon controls Enabled in a Normal SharePoint Site collection
SharePoint 2010 Locks can be Set/Reset in 4 ways:
  1. Using Web User Interface - Through Central Administration
  2. Using STSADM 
  3. Using PowerShell
  4. Using Object Model
    1. By .Net code
    2. By PowerShell
Lets Look at the examples:

Using Web User Interface:
Where to Look? Go to Central Administration > Application Management > Configure Quotas and Locks
SharePoint 2010 Site Collection Quotas and locks
 Under Site Collection Quotas and locks, set the site collection to "Not locked" will release the site.
Setting SharePoint 2010 Site Collection Quotas and locks

STSADM:
To lock site collection:
stsadm -o setsitelock -url <Site-collection-url> -lock <Lock-Type>

To get site lock status information of SharePoint site collection:
stsadm -o getsitelock -url <Site-collection-url>

Where <Lock-Type> can take one of the following value:
  • none  - Removes all the locks
  • noadditions  - Prevents from Addition
  • readonly - Can't add/Update/Delete content
  • noaccess - You can't view the site at all
More info: http://technet.microsoft.com/en-us/library/cc262811.aspx

PowerShell to Set Site collection Lock:
Set-SPSite -Identity <Site-collection-url> -LockState <Lock-State>

Where: <Lock-State> can be:
  •     ReadOnly
  •     Unlock
  •     NoAdditions
  •     NoAccess 
More Info: http://technet.microsoft.com/en-us/library/cc263238.aspx

SharePoint Site Collection Locks Programmatically with Object Model:
You can Programmatically set the Lock status using SPSite object's Properties:
  •     SPSite.ReadLocked
  •     SPSite.WriteLocked
  •     SPSite.ReadOnly
E.g:
using (SPSite site = new SPSite("http://sharepoint.com/sites/sales"))
            {            
                site.ReadOnly = true;
                //Set lock comments
                site.LockIssue = "Maintenance";
            }

PowerShell To Handle SharePoint Site Collection Locks:
$SPSite = Get-SPSite -Identity http://SharePoint
#Check whether the site collection is read-only
$SPSite.readonly
#Remove the site collection's read-only lock
$SPSite.readonly = $false

SharePoint 2010 Site Collection Quotas and locks using PowerShell, Stsadm, Object Model

BTW, SharePoint Site collections may be locked automatically, when they exceeds the Site collection Quota!

Backup LIVE Site collection with out Locks:  
STSADM:   stsadm -o backup -url <Site-collection-url> -filename <Backup-File> -nositelock
PowerShell: Backup-SPSite -Identity <Site-collection-url> -Path <Backup-File> -NoSiteLock

PowerShell Script to check lock Status of All site collections: http://salaudeen.blogspot.com/2012/12/check-lock-status-for-all-site.html


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Error When trying to access listdata.svc: Could not load type 'System.Data.Services.Providers.IDataServiceUpdateProvider' from assembly 'System.Data.Services, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

When trying to access: http://sharepoint.com/_vti_bin/listdata.svc , Received this Error message:

Error: 
Could not load type 'System.Data.Services.Providers.IDataServiceUpdateProvider' from assembly 'System.Data.Services, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
Error When trying to access listdata.svc
Fix:
Install the ADO.NET Data Services Update for .NET Framework 3.5 SP1 - KB976127
http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=2343
ADO.NET Data Services Update for .NET Framework 3.5 SP1 - KB976127


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, May 20, 2012

How to Create a Feature in SharePoint 2010 - Step by Step

In this article, I'm demonstrating how to create a feature in SharePoint 2010 using Visual Studio 2010 in 10 easy steps:

Step 1: Create a new project in Visual Studio 2010, Choose SharePoint 2010 - Empty SharePoint Project Template, Name the project. Here I've named it as: Crescent.TitleChanger.Featurehow to create a feature in sharepoint 2010
 Step 2: Enter the existing SharePoint 2010 site's URL for debugging, Choose the solution type as "Deploy as a farm solution"
how to create a custom feature in sharepoint 2010
On clicking Finish button, Visual Studio will create a project structure as below.
how to create a new feature in sharepoint 2010
 Step 3: Right click the Features node, Choose "Add Feature"
how to create a feature receiver sharepoint 2010
Step 4: This will add a feature with name "Feature1" to the project. Rename "Feature1", it give it some meaning . I've named it as "Crescent.TitleChanger"
how to create a sharepoint feature in visual studio 2010
 Step 5: Change the Title, Descriptions of the feature accordingly. Set the Scope of the project to "Web"
how to create and deploy a feature in sharepoint 2010
Step 6: Add a Event Receiver to the project by right clicking "Crescent.TitleChanger" and choose "Add Event Receiver"
how to create a feature for sharepoint 2010
 Now, we'll get the Feature code(Crescent.EventReceiver.CS) added to our project.
how to create sharepoint feature in sharepoint 2010

Step 7: Open the Feature's event receiver code, Un-comment These two methods:
  • FeatureActivated  - We'll place the code to change the Site title to "Feature Activated" inside.
  • FeatureDeactivating  - To change the Site title to "Feature De-Activated"how to create sharepoint feature in vs 2010
 Step 8. Update the code for Feature receiver as:
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using(SPWeb web = (SPWeb)properties.Feature.Parent)
                {
                  //Change the Web's Title Property and update 
                    web.Title = "Feature Activated";
                    web.Update();
                }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            using (SPWeb web = (SPWeb)properties.Feature.Parent)
            {
                //Set the Title from Property
                web.Title = "Feature De-Activated"; 
                web.Update();
            }
        } 

Step 9: Build and deploy the Projecthow to deploy a feature in sharepoint 2010
Step 10: Activate the feature by going to Site Actions >> Site Settings >> Manage Site Features
Click on "Activate" next to our feature "Crescent - Title Changer"
how to deactivate a feature in sharepoint 2010
 See it in action! Site title has been changed to "Feature Activated"how to activate feature in sharepoint 2010 That's all! we've created a custom feature in SharePoint 2010!!

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, May 17, 2012

Synchronize Between SharePoint Lists and Microsoft Excel

Requirement: End-User has a Excel file, wants to Create a SharePoint list with data from Excel file and Synchronize between SharePoint Lists and Microsoft Excel. Fairly Simple,The very first option comes to our mind is: Import Spreadsheet,  isn't it? nope, That can be used to Create List and import data but not when it comes to sync. Here the requirement is to synchronize SharePoint list excel 2007.

Solution: Use the "Excel 2007 Add-in: Synchronizing Tables with SharePoint Lists" to synchronize SharePoint list with excel.


1. Download and install the Add-on from http://www.microsoft.com/en-us/download/details.aspx?id=9345 . This will create SynchronizeWSSandExcel.xlam under: C:\2007 Office System Developer Resources\Code Samples\XL2007SynchronizeWSSandExcel

2. Open Excel, Go to File >> Options >> Add-Ins and click on Go button next to "Manage: Excel Add-ins Drop down.
synchronize sharepoint list excel 2007
3. Click on Browse Button and locate the SynchronizeWSSandExcel.xlam file, on the above location.synchronize excel sheet with sharepoint list 

4. Now in Excel, Convert the data to table (If its not table already) by selecting the data, click on Insert Tab, and choose "Table".
synchronize sharepoint list excel 2010

5. Now, Place the cursor on the your table. In design tab will see "Publish and allow Sync" button and fill SharePoint site details as below:

6. That's all! You can now update data either from Excel or from SharePoint list. Once you update data, You have to manually sync by right-clicking within the Excel table and select Table >> Synchronize with SharePoint. This will synchronize SharePoint list and excel data.

synchronize excel list with sharepoint 2010 list

I verified that it works with MS Excel 2010 and SharePoint Server 2010 as well.

Limitation: 
Existing SharePoint list cannot be used! Doesn't work when you close and Re-open. Oops!!
The above method works only when you create List from scratch and update/sync it further.  If you've a List already in SharePoint and want to Import to Excel, to do some update, This method will not help. Also, This will work until you close the excel. If you re-open, it won't work!!!

Want to keep One way sync from SharePoint List to Excel Sheet? Yes! its possible even when you close and reopen. How? Just export the List "Export to Spreadsheet" option from SharePoint list. Then from Excel, click on "Refresh" under data tab to get the latest data from SharePoint list.

More Info:


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, May 14, 2012

Creating Custom Timer Job for Automations in SharePoint 2010

Business Scenario:

We have a Project collaboration environment with 5000+ site collections. This environment has been primarily used for managing project artifacts by various teams. Every day, We - Admin Team, get lot of requests to create site collections, Change Owners of the site collections, Increase the Site quota for the existing site collection and requests for deleting site collections once the project is closed.

Earlier, as part of process automation, what I've done is: Created a dedicated site collection (Named it as "Self Service site") where users will come and fill the above requests in separate lists. Then I wrote  .Net console applications, placed them under task scheduler. The task scheduler will run these executable once a day. Refer my old posts for the process flow and complete code.
When the End-user fills the request forms (Say, Request for creating a new site collection), We capture the related details such as Site Name, URL, Site Primary & Secondary Owners, Purpose of the site, Site's category,etc. My .Net console application reads the pending requests, validate and then and programmatically perform the tasks (such as creating site collections). 


Solution:

This time, instead of creating a .Net console application/PowerShell and placing them in Task scheduler, Why don't we create a custom SharePoint timer job to do the automation? Alright, I decided to make use of SharePoint 2010's custom timer jobs. By this way, we can have this as a Solution package. 

How to Create a Custom Timer Job in SharePoint 2010?

What is Timer Job? As per MSDN: "A timer job runs in a specific Windows service for SharePoint. Timer jobs also perform infrastructure tasks for the Timer service, such as clearing the timer job history and recycling the Timer service; and tasks for Web applications, such as sending e-mail alerts. A timer job contains a definition of the service to run and specifies how frequently the service is started."

What we need to get a Custom timer job created?

1. Custom Timer Job Class:
Custom timer jobs are created by creating a class which extends "SPJobDefinition" class inside Microsoft.SharePoint.Administration namespace. Also we have to create few constructors and override the Execute() method.

2. Feature Receiver:
To associate the timer job with web application and delete it when we don't need it anymore, we'll have to deal with these two event receiver methods.
  • featureActivated event - To instantiate the timer job created. Assign a schedule for it.
  • featureDeactivating event - To delete the timer job when the feature is deactivated.

Step by Step Instructions to Create a Custom Timer Job:

Here is the step by step procedure to create a custom timer job for SharePoint 2010 using Visual Studio 2010. 

1. Create a new Project in Visual studio
sharepoint 2010 create timer job
2. Select the  Empty SharePoint Project as project type, Give it a name. say "SPAdmin.QuotaChange.TimerJob"
sharepoint 2010 create timer job c#
3. Enter the URL for debugging. Select "Deploy as a Farm solution" since timer jobs are not available in sandbox solutions.
sharepoint 2010 create timer job programmatically
 4. Add a new Item to the project
sharepoint 2010 create timer job visual studio
 5. Select Class and give it a name, say :QuotaChangeTimerJob.cs
sharepoint 2010 create custom timer job
 6. Right click on the Features and click on Add Feature.
sharepoint 2010 timer job feature
 7. Add an event receiver to the project. Set the title, Description and Scopes for the Project.
 Now the project structure will be like this.
sharepoint 2010 timer job feature scope
SharePoint 2010 timer job feature scope

8. Now, the Most important part: Update the code for Custom timer job Class and Feature Receivers as below:

Update the Class File: (create SharePoint 2010 custom timer job coded in c#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SPAdmin.QuotaChange.TimerJob
{
    //Timer job Class should be public
    public class QuotaChangeTimerJob : SPJobDefinition
    {
        public const string JOB_NAME = "QuotaChangeTimerJob";

        //Create necessary Constructors
        public QuotaChangeTimerJob() : base() { }

        public QuotaChangeTimerJob(SPWebApplication webApp)
            : base(JOB_NAME, webApp, null, SPJobLockType.ContentDatabase)
        {
            // Assign the title
            this.Title = "Quota Change Timer Job";
        }

        //Override the Execute method
        public override void Execute(Guid targetInstanceId)
        {
            try
            {
                //SPWebApplication webApp = this.Parent as SPWebApplication;

                //Temporary Code placed to Test the timer job - Insert new item to Task List
                SPSite oSPSite = new SPSite("http://sharepoint");
                SPWeb oSPWeb = oSPSite.RootWeb;
                oSPWeb.AllowUnsafeUpdates = true;

                SPList taskList = oSPWeb.Lists["Tasks"];
                SPListItem newTaskItem = taskList.Items.Add();
                newTaskItem["Title"] = DateTime.Now.ToString();
                newTaskItem.Update();

                oSPWeb.AllowUnsafeUpdates = false;

                //Method to Handle the Quota change Automation
                // HandleQuotaChangeRequests();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Quota Change Timer Job", ex.Message);
            }

        }
    }
}

9. We have our timer job ready. Next step? Associate the timer job using feature activation code.

Update the Feature Receiver Code:
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SPAdmin.QuotaChange.TimerJob.Features.ProcessQuotaRequests
{
   
    [Guid("5c0c3568-31c4-4f1e-800f-690a2e499c5c")]
    public class SPAdminQuotaChangeTimerJobEventReceiver : SPFeatureReceiver
    {
       const string JOB_NAME = "QuotaChangeTimerJob";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            // create the timer job when the feature is activated
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication; // get the web application reference

            // Delete the job, If its already created
            foreach (SPJobDefinition job in webApp.JobDefinitions)
                if (job.Name == JOB_NAME)
                {
                    job.Delete();
                }

            //Create the timer job by creating the instance of the class we have created
            QuotaChangeTimerJob customTimerJob = new QuotaChangeTimerJob(webApp);

            // Create a schedule interval for timer job
            SPMinuteSchedule customSchedule = new SPMinuteSchedule();  // You can create Hourly, Daily,  Weekly schedules as well
            customSchedule.BeginSecond = 0;
            customSchedule.EndSecond = 59;
            customSchedule.Interval = 15;  //Run every 15 minutes

            // assign the schedule to the timer job
            customTimerJob.Schedule = customSchedule;
            customTimerJob.Update(); 

        }


      public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
       {
        SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

        foreach (SPJobDefinition job in webApp.JobDefinitions) 
            { 
             if (job.Name == JOB_NAME)
                {
                     job.Delete();
                 }
             }
        }
    
    }
    }
Build and Deploy the project.

10. Verify the timer job created in Central Admin:
Go to Go to central administration  >> Monitoring >>  Timer Jobs >> Review Job Definitions
and you should See our Custom Timer Job "Quota Change Timer Job"
sharepoint 2010 how to create timer job
SharePoint 2010 timer job in central admin
sharepoint 2010 timer job frequency
SharePoint 2010 timer job interval
Click on the timer job "Quota Change Timer Job" to get into the properties page of it. From here, we can change the interval parameter, Enable/Disable or run the timer job on demand.


Debugging:

Important: If you make changes to your code, you need to restart the SharePoint Timer service. Which can be done by restarting SharePoint Timer job from Services console (Go to Run >> Type "Services.msc")
sharepoint 2010 timer job restart

Or it can be done by command lines:

net stop SPTimerV4 – Its' good to add this in Pre-build command in visual studio.
net start SPTimerV4 – Add this as Post build command

How to Debug Custom Timer Job:
Set a break point in code and go to Debug menu, choose Attach to Processsharepoint 2010 timer job debug 
Select the OWSTIMER.EXE process(Make sure you have both the Show Process from All users and Show Process in All sessions checked) and click on Attach.
sharepoint 2010 custom timer job visual studio
debug SharePoint 2010 timer job

Click on Run now button from Timer job's property page in Central Administration, Now visual studio will take you to the code where you set break-point.sharepoint 2010 timer job tutorial

 MSDN Link: How to Create a Timer Job - http://msdn.microsoft.com/en-us/library/ff798313.aspx


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, May 13, 2012

Find All Sites Created with a Specific Site Template

Requirement is to find all blogs created in a SharePoint environment, to apply a fix. Sure, PowerShell can help to find all sites created with a specific site template:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get All Blog sites
Get-SPWebApplication "http://SharePoint.crescent.com" | Get-SPSite -Limit All | Get-SPWeb -Limit ALL | Where-Object {$_.WebTemplate -eq "BLOG"} | ForEach-Object {
  Write-Host "Site: $($_.Title) at $($_.URL)"
  }


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, May 12, 2012

SharePoint 2010 Content Type IDs - How to Find / Create

SharePoint 2010 Content Type IDs - Reference

Here is the reference for SharePoint 2010 Parent content type id format:

Content Type ID
 System 0x
 Item 0×01
 Document 0×0101
 Event 0×0102
 Issue 0×0103
 Announcement 0×0104
 Link 0×0105
 Contact 0×0106
 Message 0×0107
 Task 0×0108
 Workflow History 0×0109
 Post 0×0110
 Comment 0×0111
 East Asia Contact 0×0116
 Folder 0×0120

How to find content type id in SharePoint 2010?
Go to: Site Settings >> Site Content Type Gallery and pick your content type. The url will be something like:
http://sharepoint.yourcompany.com/_layouts/ManageContentType.aspx?ctype=0x01013216CC96666E954646548B24654

Get the Content Type ID from URL Parameter Ctype.


Using Powershell in SharePoint 2010 to Get Content type ids
We can retrieve all the available content type IDs using Object Model. Here is the PowerShell snippet
$SPsite = Get-SPSite "http://sharepoint.crescent.com"
$SPweb=$SPsite.RootWeb
  write-host "Content Type Name ,  ID "
  write-host "------------------------ "
     $SPContentTypeCollection = $SPweb.AvailableContentTypes; #Get All available Conent Types
            foreach ($SPContentType in $SPContentTypeCollection)
            { 
                write-host $SPContentType.Name "," $SPContentType.id  
            } 
sharepoint 2010 content type id format

How to create content type id in SharePoint 2010.
Just Append a GUID with Parent Content Type IDs (As provided in above table)

MSDN Reference: http://msdn.microsoft.com/en-us/library/aa543822.aspx

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, May 11, 2012

SharePoint Content Databases Size - Storage Report

To get the sizes of all your SharePoint content databases, use this PowerShell script:
Get-SPContentDatabase | foreach { $_.Name;[Math]::Round(($_.disksizerequired/1GB),2) }

Every Month I've had to generate the Storage report for SharePoint Content Databases. How about automating it with PowerShell? Sure, Here is my code:

Get SharePoint Content Database Size using PowerShell:
#SharePoint Content Database Sizes - Storage Report
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

$ReportDate=get-date -Format "MMM-dd-yyyy"

$OutputFN = "D:\Database_Storage_$ReportDate.csv"

#If the File already exists remove it
if (Test-Path "D:\Database_Storage_$ReportDate.csv")
{
    Remove-Item "D:\Database_Storage_$ReportDate.csv"
}

#Write CSV Header
 Add-Content -Path $OutputFN -Value "Web Application Name, URL, Database Name, Database Size-GB"
    
#Get All Web Applications
$webapps = Get-SPWebApplication
foreach($webapp in $webapps)
{
    $ContentDatabases = $webapp.ContentDatabases
    
    foreach($ContentDatabase in $ContentDatabases)
    {
        $ContentDatabaseSize = [Math]::Round(($ContentDatabase.disksizerequired/1GB),2)

        Add-Content -Path $OutputFN " $($webapp.Name),  $($webapp.url) , $($ContentDatabase.Name) , $ContentDatabaseSize"
    }
} 

#Code To mail the Report
$SMTPClient = new-object System.Net.Mail.smtpClient
$SMTPClient.host = "smtp.crescent.org"

$MailMessage = new-object System.Net.Mail.MailMessage
$MailMessage.Subject = "SharePoint Storage Report - $ReportDate"
$MailMessage.Body = "Please find attached Database storage report as on $ReportDate"
$MailMessage.From = "SharePoint-Reports@Crescent.com"
$MailMessage.To.add("Salaudeen.Rajack@Crescent.com")
$Attachment = new-object System.Net.Mail.Attachment($OutputFN)
$MailMessage.Attachments.Add($Attachment)
$SMTPClient.Send($MailMessage)

$Attachment.Dispose();
$MailMessage.Dispose();

#Remove the Report from Server once mailed!
Remove-Item "D:\Database_Storage_$ReportDate.csv"

Output: (After adding a Pivot Table)
sharepoint content database report
Tail: Once you have the script ready, You can place it under Task scheduler to run the script on scheduled basis! like: PowerShell.exe D:\Reports\StorageReport.ps1

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


You might also like:

Related Posts Plugin for WordPress, Blogger...