Subscribe:

Labels

Showing posts with label sps2010. Show all posts
Showing posts with label sps2010. Show all posts

Thursday, September 27, 2018

Clear sharepoint cache


## SharePoint Server 2013: PowerShell Script To Reset The Config Cache On All Servers In A Farm ##


Add-PSSnapin Microsoft.SharePoint.PowerShell
$Servers = Get-SPServer | ? {$_.Role -ne "Invalid"} | Select -ExpandProperty Address
Write-Host "This script will reset the SharePoint config cache on all farm servers:"
$Servers | Foreach-Object { Write-Host $_ }
Write-Host "Press enter to start."
Read-Host
Invoke-Command -ComputerName $Servers -ScriptBlock {
    try {
        Write-Host "$env:COMPUTERNAME - Stopping timer service"
        Stop-Service SPTimerV4
        $ConfigDbId = [Guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\15.0\Secure\ConfigDB' -Name Id).Id #Path to the '15 hive' ConfigDB in the registry
        $CacheFolder = Join-Path -Path ([Environment]::GetFolderPath("CommonApplicationData")) -ChildPath "Microsoft\SharePoint\Config\$ConfigDbId"
        Write-Host "$env:COMPUTERNAME - Clearing cache folder $CacheFolder"
        Get-ChildItem "$CacheFolder\*" -Filter *.xml | Remove-Item
        Write-Host "$env:COMPUTERNAME - Resetting cache ini file"
        $CacheIni = Get-Item "$CacheFolder\Cache.ini"
        Set-Content -Path $CacheIni -Value "1"
        }
    finally{
        Write-Host "$env:COMPUTERNAME - Starting timer service"
        Start-Service SPTimerV4
        }
}


Remove IIS logs

cls
$limit = (Get-Date).AddDays(-7)

Import-Module WebAdministration
$iisdir = (Get-WebConfigurationProperty "/system.applicationHost/sites/siteDefaults" -name logfile.directory).Value

if($iisdir.Contains("%SystemDrive%"))
{

$iisdir = $iisdir.Replace("%SystemDrive%","C:");
}
Write-Host "iisdirectory path : "$iisdir

Get-ChildItem $iisdir -Recurse | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

Write-host "Deledted files which are before date :"$limit -ForegroundColor Green
write-host "Completed Successfully Deleting Files from Path: " $iisdir -ForegroundColor Green

Monday, June 3, 2013

Create a mysite(personal site) Using the Object Model


Below code is using object model creating the my sites dynamically.


            SPSite site = new SPSite("http://win-rgqt3bch3nk:22929/sites/Test");

            SPWeb web = site.OpenWeb();
            // SPWeb web = SPContext.Current.Web;


            web.AllowUnsafeUpdates = true;

         
            if (ApproveitemId > 0)
            {
                SPList thislist = web.Lists["Requests"];
                SPListItem item = thislist.Items.GetItemById(ApproveitemId);
                string AStatus = item["Approval_Status"].ToString();
                string strYes = "Yes";
                if (AStatus == strYes)
                {
                    string mysiteusername = item["Username"].ToString();
                     //SPUser mysiteuname = web.AllUsers[mysiteusername];

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                         {
                             using (SPSite spSite = new SPSite("http://win-rgqt3bch3nk:38562"))
                             {
                                 spSite.AllowUnsafeUpdates = true;
                                 SPContext.Current.Web.AllowUnsafeUpdates = true;
                                 SPServiceContext siteContext = SPServiceContext.GetContext(spSite);
                                 //UserProfileManager up = new UserProfileManager(siteContext,true);
                                 UserProfileManager up = new UserProfileManager(siteContext);
                                 //string sAccount = "WIN-RGQT3BCH3NK\\test1";
                                 //UserProfile uprof = up.GetUserProfile(sAccount.Trim());
                                 UserProfile uprof = up.GetUserProfile(mysiteusername);
                                 uprof.CreatePersonalSite();
                             }
                         });
                }
            }
         
        }

Thursday, February 9, 2012

Document ID in SharePoint 2010

SharePoint 2010 includes a new Site Collection scoped Feature called the Document ID Service.  As most of you might be aware that in a traditional ECM [Enterprise Content Management] application each content object has its own unique ID, which is used by that object throughout its lifetime in the ECM system, no matter where the file was placed in the system. Once enabled all your documents within a Site Collection will have a unique ID and can be located using the ID no matter where the file is located in your Site Collection.
To enable the Document ID Feature
1. Go to Site Settings > Site Collection Features and Activate the Document ID Service.

2. Or you can use the following SharePoint 2010 Management Shell cmdlet to Activate the Document ID Service.
Enable-SPFeature -id docid -url <site collection url>
After Activating the Feature you can find the “Document ID settings” under Site Collection Administration

3. To customize the Document ID and apply Document ID to all existing Documents in the Site Collection. Go to Site Settings > Document ID Settings and provide the String with which the Document ID will begin. I have provided SP2010 for this example. Click Ok.
You might see this message, "Configuration of the Document ID feature is scheduled to be completed by an automated process." as highlighted in the image:
This message is shown because the timer job called Document ID enable/disable job has been activated. 
Run the Document ID assignment job under Central Administration > Monitoring > Review Job Definitions Once the job completes at the scheduled time, the message will go away or else you may run the timer job and put it to completion forcibly by clicking "Run Now". Or you can run the following SharePoint 2010 Management Shell cmdlet to trigger the same.
Start-SPTimerJob -Identity DocIdAssignment


Now if you go to your document properties you should see, it has a new property called Document ID followed by a Unique ID for that document

4. The above document now has a unique ID and we can use the following link to locate the document no matter where the document is in the Site Collection
http://SP2010:1234/_layouts/DocIdRedir.aspx?ID=SP2010-1-1

Wednesday, January 18, 2012

Programmatically Create a Site from Custom Site Template in SharePoint 2010


Here is the code snippet to create a Site using a Custom Site Template in SharePoint 2010.
      
using (SPSite site = new SPSite("http://sp2010:1234/"))
      {
                    using (SPWeb newWeb = site.OpenWeb())
                    {                         
                        newWeb.AllowUnsafeUpdates = true;                      
                        SPWebCollection subsites = newWeb.Webs;
                        SPWeb newSubWeb = subsites.Add("Site url", " Site name ", "Site description", 1033, {Name of the Site Template}, true, false);
                        newWeb.Update();
                    }
                }


 for eg: {Name of the Site Template} --> "{9D26F676-B943-451B-BED4-A8657A9C0FDF}#1InternalProject"


To get the custom Site Template GUID and Site Template Name you can use the below code in SharePoint 2010. If the Template is in Solution Gallery. 
SPWebTemplateCollection templates = newWeb.GetAvailableWebTemplates(1033, true);
                        foreach (SPWebTemplate template in templates)
                        {
                           lblTemplate.Text=  template.Name;
                        }

Sunday, December 11, 2011

check the condition the group in exist or not


these 2 metod are using for check the condition the group in exist or not

private bool isGroupAlreadyExist(SPWeb web, string groupName)
        {
            bool isExist = false;

            try
            {
                SPGroup group = web.SiteGroups[groupName];
                isExist = true;
            }
            catch (SPException)
            {
                isExist = false;
            }
            catch (Exception)
            {
                isExist = false;
            }
            return isExist;
        }


if (!isGroupAlreadyExist(web, groupName))
                {
                   
                }


get spsuer using object model

this is for get spuser... code using object model

 /// <summary>
        /// Returns the SPUser Object built based on the OOTB people or groups field type of sharepoint.
        /// Get SPUser Object from a SharePoint list item people or group field value.
        /// Can be used to get the user object properties, e.g. email of the user.
        /// </summary>
        /// <param name="spListItem">Source list item</param>
        /// <param name="fieldName">column/field name, e.g., "PersResponsible"</param>
        /// <returns></returns>

        public SPUser GetSPUserObject(SPListItem spListItem, String fieldName)
        {
            SPUser spUser = null;
            try
            {
                if (fieldName != string.Empty)
                {
                    SPFieldUser field = spListItem.Fields[fieldName] as SPFieldUser;
                    if (field != null && spListItem[fieldName] != null)
                    {
                        SPFieldUserValue fieldValue = field.GetFieldValue(spListItem[fieldName].ToString()) as SPFieldUserValue;
                        if (fieldValue != null)
                        {
                            spUser = fieldValue.User;

                        }
                    }
                }
            }
            catch (Exception ex)
            {
              
            }

            return spUser;
        }

Customize Top Navigation Bar - Horizontal Orientation for second level


Add Css in core4.css

.s4-toplinks {
    padding-bottom: 20px; /* create space to fit the 2nd level nav */
    position: relative;
}
 
.s4-toplinks .s4-tn li {
    position: static !important; /* 2nd level will be positioned relative to .s4-toplinks container */
float:left;
}
 


Add this in Master page 


<SharePoint:AspMenu
 ID="TopNavigationMenuV4"
 Runat="server"
 EnableViewState="false"
 DataSourceID="topSiteMap"
 AccessKey="<%$Resources:wss,navigation_accesskey%>"
 UseSimpleRendering="true"
 UseSeparateCss="false"
 Orientation="Horizontal"
 StaticDisplayLevels="2"
 MaximumDynamicDisplayLevels="4"
 SkipLinkText=""
 CssClass="s4-tn"/>

<Template_Controls>
<asp:SiteMapDataSource
 ShowStartingNode="true"(change here)
 SiteMapProvider="SPSiteMapProvider"(change here)
 id="topSiteMap"
 runat="server"
 />



Create a mysite(personal site) Using the Object Model

Below code is using object model creating the my sites dynamically.


            SPSite site = new SPSite("http://win-rgqt3bch3nk:22929/sites/Test");

            SPWeb web = site.OpenWeb();
            // SPWeb web = SPContext.Current.Web;


            web.AllowUnsafeUpdates = true;

         
            if (ApproveitemId > 0)
            {
                SPList thislist = web.Lists["Requests"];
                SPListItem item = thislist.Items.GetItemById(ApproveitemId);
                string AStatus = item["Approval_Status"].ToString();
                string strYes = "Yes";
                if (AStatus == strYes)
                {
                    string mysiteusername = item["Username"].ToString();
                     //SPUser mysiteuname = web.AllUsers[mysiteusername];

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                         {
                             using (SPSite spSite = new SPSite("http://win-rgqt3bch3nk:38562"))
                             {
                                 spSite.AllowUnsafeUpdates = true;
                                 SPContext.Current.Web.AllowUnsafeUpdates = true;
                                 SPServiceContext siteContext = SPServiceContext.GetContext(spSite);
                                 //UserProfileManager up = new UserProfileManager(siteContext,true);
                                 UserProfileManager up = new UserProfileManager(siteContext);
                                 //string sAccount = "WIN-RGQT3BCH3NK\\test1";
                                 //UserProfile uprof = up.GetUserProfile(sAccount.Trim());
                                 UserProfile uprof = up.GetUserProfile(mysiteusername);
                                 uprof.CreatePersonalSite();
                             }
                         });
                }
            }
         
        }

Thursday, November 24, 2011

Retention Policy for document library in SharePoint 2010


One of the major improvements in SharePoint 2010 compared to prior version is the improvements in information management policies. SharePoint 2010 can apply the expiration policy in multiple stages, where each stage can do some specific actions such as deleting draft versions, deleting previous versions, deleting the record etc. In SharePoint 2010 you can apply the retention policy to a content type, to a list or document library, to a folder.
How to create own retention policies on a Document Library
1. If a document is not modified for 2 years delete its previous versions
2. Any document created here to be deleted after 3 years.
Here are the steps to navigate to the “Shared Documents” document library to set the retention policy.
Before doing Retention policies, it requires some Configuration settings in Site and SharePoint Central Administration.
Essentially, you have to Activate the "Content Organizer" feature at the Site Level. Once that is done, you get the "Drop off Library" as well as 2 new options in the Site Settings. Content Organizer Rules and Content Organizer Settings. In that, you can take the .asmx link and then paste it in the Central Admin Configure Send to Connections. After that, the routing should work fine. Using the Rules and that is mostly using Content Types, you can route the document to the right library instead of letting it stay in the Drop off Library.

In the SharePoint Central Administration, under General Application Settings
External Service Connections, select Configure send to connections.

Here you have to configure the “Send to Connections”. After giving the URL, check to verify whether it is valid or not.

From the top ribbon, navigate to the Library tab, and then click on Library settings.
It will be navigated to the document library settings page. Click on the Information management policy settings from this page.


By default a library will inherit its policies from the content type, so that the policies set for the content type will be applied. You can change this by overriding “Source of retention for this library” property. set up retention policy for “Shared Documents” library . Click on the “change source” link.
 
You will reach the configuration page for the retention schedule. Select the libraries and folders radio button. You will receive a warning alert stating the content type retention policy will be ignored. Click ok here.
You can see the configuration options available for document library/list here. Click on “add a retention stage" link
Based on Created and Modified, a Document can be Moved to Recycle or Delete or can be transferred to another locationas shown



Based on the requirement we can create the Retention Policies. 

Thursday, November 3, 2011

Sandbox Solutions in SharePoint 2010

Sandbox solution is a new feature introduced in SharePoint 2010. It's a secured wrapper around webparts and other elements with limitations. There is no thumb rule that every webpart in SharePoint 2010 belongs to Sandbox Solution. But it's recommended to develop webparts with Sandbox solution. It allows administrators to monitor the solutions and control as required. SharePoint Site Collection administrators can view the resource utilization of each solution and can block if it consumes too much resources. Usually when sites working slow, developers complain the server is slow whereas site/server administrators blame on Develepor code/solutions. Now Microsoft put a Full Stop to that.


SharePoint solutions run in seperate worker processes and not in w3wp.exe. So It doesn't require IIS Reset or Application Pool Recycling. Without disturbing the SharePoint site, Sandbox solutions can be deployed. Only thing while deploying new version of Sandbox solution over existing solution, SharePoint will display No Solution found error in Sandbox Webparts on the page. However within seconds sandbox solutions getting deployed and it'll start working. In SharePoint 2007, only farm administrators can install/deploy developer solutions. But Now site collection administrators can deploy solutions with web based interface. This reduces the dependency of Farm Administrator and improves rapid deployment.


Sandbox Processes
Here the processes which required for Sandbox solutions.
  1. SPUCWorkerprocess.exe - Sandbox Worker process service which is a Seperate Service Application which actually executes Sandbox code. It should be started in every farm to use Sandbox solutions.
  2. SPUCWorkerProcessProxy.exe - Sandbox Worker process proxy which is working as a proxy for Worker process and takes care of Sandbox code execution. It can also serve to other farms if configured. Basically it helps site administrator for load balancing.
  3. SPUCHostService.exe - Sandbox User Code Service takes care of user code in Sandbox amd it can be started in the farms where to use Sandbox solutions.
Sandbox Limitations
 Sandbox is a secured wrapper and it has restrictions on code to run in SharePoint environment. Few Key limitations which developers should know are listed below.
  1. No Security Elevation - RunWithElevatedPrivileges which runs the specified block of code in application pool account(typically System Account) context is not allowed in Sandbox code. SPSecurity class also not allowed to use in Sandbox.
  2. No Email Support - SPUtility.SendMail method has been blocked explicitly in Sandbox, However .Net mail classes can be used to send mails. Additionaly sandbox won't allow to read Farm SMTP address. So developers has to specify the SMTP address in code itself(may be some other workaround).
  3. No Support to WebPartPages Namespace - Sandbox won't allow to use Microsoft.SharePoint.WebPartPages namespace.
  4. No Support to external Webservice - Internet web service calls are not allowed to ensure security in Sandbox solutions. Allow Partially Trusted code also can't be accessed within Sandbox.
  5. No GAC Deployment - Sandbox solutions are not stored in File System(Physical path) and assemblies can't be deployed to Global Assembly Cache(GAC). But it's available on C:\ProgramData\Microsoft\SharePoint\UCCache at runtime. Note the ProgramData is a hidden folder.
  6. No Visual Webparts - Visual Studio 2010 by default won't allow to create Visual Webparts to deploy as sandbox solution. But with Visual Studio PowerTools extensions(downloadable from Microsoft MSDN website) Visual Webparts can be developed and deployed as sandbox Solutions.
SharePoint Online which is SharePoint environment provided by Microsoft to manage SharePoint Sites in internet accepts only Sandbox solutions. Because SharePoint Online sites are Windows Servers at Microsoft Datacenters, Microsoft won't allow GAC deployment or file system access. In future Sandbox solution will give more features for developers. 

Configuring Sandboxed Solutions - Cannot start service SPUserCodeV4 on computer

When you built and deploy SharePoint 2010 solution using Farm it will deploy successfully.

But when you create a SharePoint 2010 solution using Sandboxed it may throw an Error

Error occurred in deployment step 'Activate Features': Cannot start service SPUserCodeV4 on computer 

The error can be easily resolved by starting the Microsoft SharePoint Foundation Sandboxed Code Service which can be accessed through the Central Administration site in SharePoint.   Open the Central Administration site and go to System Settings and click on Manage Service on server:

image

Check to see if Microsoft SharePoint Foundation Sandboxed Code Service  is running

image

If it is Stopped, then Start the Service and Deploy the Sandboxed Solutions.

Tuesday, November 1, 2011

Adding\Updating\Retriving\SPquery Lookup fields in Sharepoint

Adding a Lookup Item -
SPListItem listItem = myList.Items[0];
listItem["Departments"] = new SPFieldLookupValue(10, “Operations”); // Adding Operations as text and 10 as ID
listItem.Update();
Retrieving Lookup field for an item-
SPListItem listItem = myList.Items[0];
SPFieldLookupValue lookupFieldText = new SPFieldLookupValue(listItem["Departments"].ToString());
string lookUpValue = lookupFieldText .LookupValue;
Updating Lookup field for an item -
SPListItem listItem = myList.Items[0];
SPFieldLookupValue lookupFieldText = new SPFieldLookupValue(listItem ["Departments"].ToString());
lookupFieldText .LookupValue = 11; -> updates the value of the Lookup field for listItem
Retrieving all the values in the Lookup Field -
DropDownList res = new DropDownList();
SPWeb web = SPControl.GetContextWeb(Context);
web = web.ParentWeb;
SPLookupField myLookup = (SPLookupField)web.Fields[str];
SPSite site = web.Site;
SPWeb lookupWeb = site.AllWebs[myLookup.LookupWebId];
SPList lookupList = lookupWeb.Lists[myLookup.LookupList];
foreach(SPListItem lookupItem in lookupList.Items)
{
res.Items.Add(lookupItem[myLookup.LookupField];
}

Finally, SPquery for Lookup field by ID in sharepoint -
<Query>
<Where>
<Eq>
<FieldRef Name=’Departments’ LookupId=’TRUE’ />
<Value Type=’Lookup’>10</Value>
</Eq>
</Where>
</Query>