Thursday, June 6, 2013

SharePoint rename web application

Here is the small powershell script which will rename your SharePoint web application.


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Point to the site your web application hosts to grab a reference to the web application
$SPSite = new-object Microsoft.SharePoint.SPSite("http://servername:114")
$WebApp = $SPSite.WebApplication

$WebApp.Name = "New webapplication name"

#Update Web Application
$WebApp.Update()


Thank you !!



Tuesday, June 4, 2013

sharepoint task list progress bar

Here is a requirement to display progress bar in sharepoint list.

I got this reference from the below blog.

Please see the screenshot below the result of this approach :



To achieve this we have to do couple of configuration changes.

1. Create a Calculated column on the list with name pb . In my case i have taken Tasks list for this example. Below is the forumla for the calculated column

="
"&[% Complete]*100&"%
"

Note : % Complete is the numeric column which has the data to display on progress bar.

2. Add a Content Editor WebPart to the same page just below to list view and paste the below code in the web part in source editor.





That's it. It should display the progress bar as i have given the screenshot.



sharepoint full crawl vs incremental crawl

Here is the theoritical explanation of the diffarences between Full crawl and Incremental crawl in point wise.



1. If the incremental crawl failed to crawl content for errors , Incremental crawl removes the content from index until next full crawl

2. When a software update for SharePoint or service pack is installed on servers in the farm, full crawl is required

3. Metadata property updates in search results

4. Creating server name mappings

5. Crawl rules will be ignored until the next full crawl.

6. Full crawl is required to repair corrupted index which is failed in incremental crawl.

7. To detect security changes those were made on file shares after the last full crawl of the file share

8. The crawler cannot discover when ASPX pages on sites has changed.

9. When a content database is restored full crawl is required.

Thank You !!



SharePoint CPU 100% by mssearch and mssdmn

Issue : CPU utilization 100% on SharePoint server

Root cause : This is causing because of the search crawl is running at backend. That's why Task manager showing that mssearch and mssdmn process are taking maximum CPU utilization.

Resolution :

1.With reference of msdn blogs this behavior can be fixed by installing KB article 941274 from msdn please find the

screenshot below :

2. This is the issue from OSearch in this case.

3. service which is taking lot of CPU utilization. Please find the screenshot below :



This service is used by the process mssearch.exe which is taking huge CPU usage in our case.

4. Apart from this there is one more setting we can try to fix this issue is Central Administration > Operations > Services on Server > Office SharePoint Server Search Service Settings > Indexer Performance Here we need to change the setting from Partly reduced to Reduced

Here are some of the msdn blogs giving the same solution for this issue.

http://social.msdn.microsoft.com/Forums/en-US/sharepointsearchlegacy/thread/1859bfba-b383-45c4-8d76-a5f1b6a8411f

http://social.msdn.microsoft.com/Forums/en-US/sharepointsearch/thread/504dcc9e-e138-428f-9939-0585d4c6acb0

http://social.technet.microsoft.com/Forums/en-US/sharepointadmin/thread/17d0522e-8548-4aa1-a912-45e66a275474

Thank you !!



SharePoint Calculate size of site collection sub sites

Here is the sample code to get the size of site collections and sub sites programatically.

We have multiple ways to do this.

1. STSADM
2. Console application using Object model.

STSADM :
stsadm -o enumsites -url http://Server > C:\SizeOfSites.xml
This will create a xml file in your local drive with all the required information. We can not modify the output format for this approach.


Console Application :

Here is the code sample for the same using Console application.


static void Main(string[] args)
{
    long siteCollectionSize = 0;
    string baseUrl = "http://Servername : 10000";


    using (SPSite mainSite = new SPSite(baseUrl))
    {
        foreach (SPWeb web in mainSite.AllWebs)
        {
            long webSize = GetSPFolderSize(web.RootFolder) + web.RecycleBin.Cast<SPRecycleBinItem>().Sum(r => r.Size);

            if (web.Url.StartsWith(baseUrl))
            {
                Console.WriteLine(string.Format("({0} {1}", web.Url, FormatSize(webSize)));

                siteCollectionSize += webSize;
            }
        }
    }

    Console.WriteLine("Total Size: " + FormatSize(siteCollectionSize));
    Console.WriteLine("Operation Completed successfully..");
    Console.ReadKey(false);
}

public static long GetSPFolderSize(SPFolder folder)
{
    long folderSize = 0;

    foreach (SPFile file in folder.Files)
        folderSize += file.TotalLength
            + file.Versions.Cast<SPFileVersion>().Sum(f => f.Size);

    folderSize += folder.SubFolders.Cast<SPFolder>().Sum(sf => GetSPFolderSize(sf));

    return folderSize;
}

public static string FormatSize(long size)
{
    if (size > Math.Pow(1024, 3))
        return (size / Math.Pow(1024, 3)).ToString("#,#.##") + " GB";

    else if (size > Math.Pow(1024, 2))
        return (size / Math.Pow(1024, 2)).ToString("#,#.##") + " MB";

    else if (size > 1024)
        return (size / 1024).ToString("#,#.##") + " KB";

    else
        return size.ToString("#,#.##") + " Bytes";
}

Thank you !!!



RunWithElivatedPrivilages in SharePoint event handler

Here is the small code sample which will execute Event handler code with Elevated privilages.

Note : Usually Event receivers will not accept RunWithElivatedPrivilages deligate to write because of the inbuildt secutiry framework.

The only workaround for this is to use SPUserToken.

SPUserToken : This object is will work same like RunWithElivatedPrivilages but with desired user name permissions.

Here is the sample code for the same.

public override void ItemAdding(SPItemEventProperties properties)  
        {  
            SPSite site = properties.Web.Site;  
            SPUserToken sysToken = site.SystemAccount.UserToken;  
            site.Dispose();  
  
            using (SPSite mySite = new SPSite(properties.SiteId, sysToken))  
            {  
                using (SPWeb myWeb = systemSite.OpenWeb(properties.Web.ID))  
                {  
                       // Code goes here   
                }  
            }  
        }

Thank You !!!



powershell send email with attachment

function sendEmailWithReport()
{
    ###########Define Variables########
       
    $fromaddress = "fromaddress@gmail.com"
    $toaddress = "toaddress@gmail.com"
    $Subject = "sample subject"
    $body = "sample body"
    $attachment = "attachment path"
  
    $smtpserver = "smtp server name"
   
    ####################################
   
    $message = new-object System.Net.Mail.MailMessage
    $message.From = $fromaddress
    $message.To.Add($toaddress)
    $message.IsBodyHtml = $True
    $message.Subject = $Subject
    $attach = new-object Net.Mail.Attachment($attachment)
    $message.Attachments.Add($attach)
    $message.body = $body
    $smtp = new-object Net.Mail.SmtpClient($smtpserver)
    $smtp.Send($message)
    $attach.Dispose()

}




Call powershell from batch file

Here is the small example of how to call powershell script file from batch file.

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -command "< Path of your ps1 file>"

NOTE : Here you need to put -command , If not batch file will just load the ps1 file will not execute.



PowerShell cannot be loaded because the execution of scripts is disabled on this system

Here is the error which you will face when you run powershell first time on any new envrionment.

By default execution policy for powershell will be disabled in any server. This can be enabled through script property.

Run Powershell as administrator and type

Set-ExecutionPolicy Unrestricted
Thank you !!

C# code to get the count of files in sharepoint list

Here is a simple console application. Which will loop through the all the lists.

This console loop through all the items in the list and fetch the count of files are attached to the list.

Here is the peace of code :
foreach (SPList list in listColl)
           {
                                        
if (list.BaseTemplate == SPListTemplateType.GenericList || list.BaseTemplate == SPListTemplateType.Links || list.BaseTemplate == SPListTemplateType.Announcements)
{
if (list.EnableAttachments)
{

int ItemCount = 0;
foreach (SPListItem item in list.Items)
{
if (item.Attachments != null && item.Attachments.Count > 0)
{
foreach (var attachment in item.Attachments)
{
 sAttNames.Append(attachment.ToString());
}
ItemCount += item.Attachments.Count;
}
}
}
}
}