Pages

Search This Blog

Wednesday, June 29, 2011

SharePoint Server 2010 SP1 released

Microsoft SharePoint Server 2010 Service Pack 1 (SP1) is released with the latest updates for SharePoint Server 2010. This service pack includes two main categories of fixes:
  • Previously unreleased fixes that were made specifically for this service pack. In addition to general product fixes, these fixes include improvements in stability, performance, and in security.
  • All the public updates that were released through June 2011, and all the cumulative updates that were released through April 2011. 
The key areas of improvement are:
  • Improved support for Internet Explorer 9.
  • Recycle bin: Lets you restore a site collection or a web that was deleted.
  • Remote Backup Systems (RBS) and shallow copy can decrease downtime and increase efficiency by moving pointers to databases instead of moving databases.
  • You can see which folders are taking up valuable space with the improved Storage Management feature in site settings.
  • Support for Microsoft SQL Server 2011.
  • A more robust Search Host Distribution service that improves error recovery and performance during the search crawl.
  • Adds backup and restore functionality to recover deleted site collections and webs.
For more details you can visit the link: 



Monday, June 20, 2011

Assigning Multiple values to "Person and Group" Column Type programatically

Many times we have requirement of adding multiple values to a column of type "Persons and Group" through object model. There's a way to do that very easily.

public void AssignMultipleValues(String strSemicolonSeperatedMulipleUsers)
{
   String[] userName;
   SPUser objSPUser = null;
   SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();

   if (!string.IsNullOrEmpty(strSemicolonSeperatedMulipleUsers))
  {
   userName = StringToArray(strSemicolonSeperatedMulipleUsers, ";");
   foreach (string strUserName in userName)
   {
      objSPUser = SPContext.Current.Web.EnsureUser(strUserName);
       if (objSPUser != null)
      {
         userCollection.Add(new SPFieldUserValue(SPContext.Current.Web, objSPUser.ID, objSPUser.Name));
       }
    }
  if (userCollection.Count > 0)
  item[field.ColumnName] = userCollection;
  item.Update();
 }
}


public string[] StringToArray(string input, string separator)
{
string[] stringList = input.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
return stringList;
}

Thanks

How to: Remove Server from MOSS Farm


In one of my project, I was stuck while uninstalling MOSS from one of the servers. After struggling with the issues, I found some solutions that were helpful in resolving the issue. I am putting those resolutions that may be helpful for you also.

I found four way to remove the server from MOSS server farm.
  • First one is disconnect by running the configuration wizard from the start menu. This is the same way to use if you want to leave MOSS 2007 installed on the server but disjoined from the farm.
1.        Run the Configuration Wizard and, on the second page, select Disconnect from this server farm and click Yes on the warning dialog. This will delete the IIS web site and the application pool.
2.        Then, run the uninstall from the Control Panel's Features and Programs application and click Yes on the warning dialog. This will take a reboot.
3.        Then, if you really want to get rid of it all, go to the database server and delete the Config and Admin Content databases
  • Second on is removes the server if you want to clean up the serer when it can contact the configuration database. This method also uninstalls the SharePoint from the server.
    • Use Add/Remove Programs in the control panel.
    • In "Add/Remove Programs", you can remove "Microsoft Office SharePoint 2007", and it wills pop-up a warning, Click Ok to continue.
  • The third method is removing the server from the server farm in the SharePoint Central Administration site. This way is easy and quickly, almost no latency, the action was completed. But this way don’t disconnect the server from the SharePoint database.
  • The last method is more advanced, it will disconnecting the server from the SharePoint configuration database. And then you can format the server or re-install MOSS, whatever you want for the server. The step is very easy:
    • Open a command prompt to c:\program files\common files\Microsoft shared\web server extensions\12\bin (the SharePoint installed path)
    • Run following command:
      psconfig -cmd adminvs -unprovision
      psconfig –cmd configdb –disconnect
Actually, I do server remove by the third and last one method, remove the server from MOSS farm by Central administration site, and then disconnected the server from configuration database. It is easy and cleanly, and without reset anything/reboot machine.

UNIQUE Query in Sharepoint, CAML

Sharepoint doesnot provides any API through which we can retrieve unique records, nor we can do this by CAML. Although we can use LINQ, but there is another way to make the records unique after retreiving from sharepoint.

We can use method of DataView to make the data unique, Then this dataView can be converted to DataTable with unique values. Below is the example to do this:


public System.Data.DataTable GetUniqueData()
       {
           SPQuery objSPQuery = null;
           SPListItemCollection objSPListItemCollection;
           SPList objSPList;
           System.Data.DataTable objDataTable;
           DataView objDataView;

           using (SPSite objSPSite = new SPSite("<Your Site URl>"))
            {
                using (SPWeb objSPWeb = objSPSite.OpenWeb())
                {

                    try
                    {
                        objSPQuery = new SPQuery();

                        //write your query here
                        objSPQuery.Query = @"<Where>
                                              <IsNotNull>
                                                 <FieldRef Name='ID' />
                                              </IsNotNull>
                                           </Where>";

                        objSPList = objSPWeb.Lists["<List Name>"];
                        //Fill the list item collection
                        objSPListItemCollection = objSPList.GetItems(objSPQuery);
                       
                        if (objSPListItemCollection.Count > 0)
                        {
                            //convert the SPListItemCollection to Datatable
                            objDataTable = objSPListItemCollection.GetDataTable();

                            //Create a Dataview for applying UNIQUE
                            objDataView = new DataView(objDataTable);

                            //Convert the datatview to Table again by
specifying paramater 'distict' to true.
                            // the second parameter should be the column to be
checked for unique.
objDataTable = objDataView.ToTable(true, "<column                                  name(s) that you want to check for unique>");
                        }
                    }
                    catch(Exception Ex)
                    {
                        throw Ex;
                    }
                }
           }
           return objDataTable;
       }

Creating site column using powershell script : SharePoint 2010

Quite often during deployment in sharepoint projects, we come across a requirement wherein we have to create a no. of site columns and content types on the root site of the site collection.

If done through the UI,this task takes some time and is also prone to errors. This can be done in a repetitive fashion easily using powershell scripts.

This powershell script shows how to create a site column using the field xml for the site column.

The same script can also be used to create site column in a content type hub site from where the site columns
can be propagated to all site collections.

Add-PSSnapIn "Microsoft.SharePoint.Powershell"
#Get the site collection and web object
$siteColl = Get-SPSite -Identity "http://br-pc-341:2222/"
$rootWeb = $siteColl.RootWeb
#Assign fieldXMLString variable with field XML for site column
$fieldXMLString = '<Field Type="Text"
Name="TextColPowershell"
Description="This is a single line of text column created with powershell script."
DisplayName="Text Column Powershell"
StaticName="TextColPowershell"
Group="Test Custom Columns"
Hidden="FALSE"
Required="FALSE"
Sealed="FALSE"
ShowInDisplayForm="TRUE"
ShowInEditForm="TRUE"
ShowInListSettings="TRUE"
ShowInNewForm="TRUE"></Field>'
#See field XML on console
write-host $fieldXMLString
#Create site column from XML string
$rootWeb.Fields.AddFieldAsXml($fieldXMLString)

This will create a single line of text column with the name 'TextColPowershell' in the root site of the specified site collection as is shown in the screenshot:


Tuesday, June 14, 2011

Custom List forms - Change Newform.aspx or Editform.aspx with Custom Webpart

In this article I will show you how to use custom webpart as a replacement for NewForm.aspx or EditForm.aspx.
Sometimes we have a scenario like we have a dropdown box and the data-items coming for this dropdown has to come from a SQL Server database or some other database.
Or we have some business validations to put on the controls present in NewForm.aspx page or Editform.aspx page i.e. in List Forms.
So to tackle these kind of situations we need to customize our List forms.
We can customize the List-forms in two ways.
· Customize the List form through XSLT
· Change the Listforms with custom webpart which is having all your business requirements and a mechanism to add or edit items in List. This custom webpart we can build in Visual Studio through Sharepoint Object Model.
In this article I will tell you how to change the newform.aspx or editform.aspx with custom webpart.
Here I believe that you all know how to build custom webpart for Sharepoint 2007.
When we are click New button to add a new item




We are getting NewForm.aspx page. Now to change the list forms with some other webpart we need to edit the page in the same way which we are doing for a normal web part page but the problem here is we do not have Edit Page option under Site Action tab. Now what to do? How to open edit page mode?
The answer is very simple and little bit tricky also.


The URL for newform.aspx page will be like this:
just add ?&Toolpaneview=2 above URL. Now your URL becomes like this.
Now click on Go button in Internet Explorer and you will see the NewForm.aspx page like this:




Just close this webpart and add your new custom webpart here.
So after that whenever you will click on new button for adding a new item you will see your custom webpart instead of default Newform.aspx page.
In the same way we can change editform.aspx page with our custom webpart by adding the ?&Toolpaneview=2 to the url.
Hope this article would be a help to you.









 

Reading Sharepoint Audience using object model

Use the follwing code snipt to read sharpeoint audience using object model

using (SPSite objSpSite = new SPSite("http://servername"))
{
// Get the audience manager
AudienceManager objAudienceManager = new AudienceManager(ServerContext.GetContext(objSpSite));

//Get the audience group
Audience objAudience = objAudienceManager.Audiences["HR"];

//Get the members list of the audience
ArrayList objUserInfoCollection = objAudience.GetMembership();

foreach(UserInfo userInfo in objUserInfoCollection)
{
// the user email of the respective audience group
string sUserEmail=userInfo.Email;
}
}

Validate Browsable Property of a Web Part and show exception message in the Webpart’s Tool Pane

Many a times we are into a situation where we have to apply some validations on the custom browsable property of a webpart and if the value in the property is not valid than we need to show Exception message in the ToolPane of the webpart itself.
We can validate these properties and can show the exception message also. To do this we need to put the validation part in the “SET” part of Property definition itself as show below.
Suppose we have to create a property which will accept the XML strings only and we want to restrict the user to enter invalid XML string and show error message on the ToolPane of the webpart.
This requirement we can achieve by using Regular Expression. Below is the code snippet by which we can do this.
private string _QueryFilter;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [Category("Display")]
        [WebDisplayName("CheckProperty")]
        [Description("Description of the Webpart")]
        public string QueryFilter
        {
            get { return _QueryFilter; }
            set
            {
                string pattern = @"<where><[^>]+>[^<]*</[^>]+></where>";
                System.Text.RegularExpressions.Match match =
                Regex.Match(value.Trim(), pattern, RegexOptions.IgnoreCase);
               
if (!match.Success)                  
                        throw new WebPartPageUserException("The query filter is not a valid Caml query string");
               

                _QueryFilter = value;
            }
        }

Now when we deploy this webpart property it will look like this


And after writing the XML string it will validate the string based upon our regular expression. If the expression is not valid than it will throw the WebPartPageUserException as shown below:


In this way we can validate the browsable property of the webpart.
Hope it will be a help to you!
Ravish

To know if the variation exists (programmatically)

Sometimes we need to perform some action if the variations are present on that web. So, to identify this programmatically we need to find the count of the “Variation LabelsLists ,
Code Sample:
using (SPSite objSite = new SPSite("URL"))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
SPList objList = objSite.RootWeb.Lists.TryGetList("Variation labels");
if (objList != null)
{
if (objList.ItemCount > 0)
{
//Variation Present
}
}
}
}

Debugging Javascript code in Sharepoint

In order to debug Javascript code, you will first need to check the Internet options for Enabling/Disabling script debugging. You can follow below mentioned steps in order to do this:

In Internet Explorer, go to "Tools"-->"Internet Options", Under "Advanced" tab, look for the two options:

Disable Script Debugging (Internet Explorer)
Disable Script Debugging (Other)

Ensure that the two options are not checked (refer to the below screen shot).
























Now you can debug your javascript code by writing a word as "debugger;" anywhere in your javascript code. It will create a breakpoint automatically.When this breakpoint gets hit, your debugger will launch. You will see an error message that says “a runtime error’ has occurred in script”. There is nothing to worry about this, this actually allows you to select the application for debugging the javascript code.

There might be the case that even after doing above settings, you are not able to attach the debugger. For this you may need to check the Registry key for the appropriate dword settings.

Set the HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings named value JITDebug to 1 (DWORD).

Note: You might have to add both the Settings key and the JITDebug key if its not already there.

Sandboxed Solutions Validator

Sandbox framework provides excellent way for farm administrators to validate solutions that run in the sandbox. Farm administrators need to deploy sandboxed solution validator that run when a sandboxed solution is uploaded to a Solution Gallery. Sandboxed solution validator is called when a solution is activated. The validator class inherits from SPSolutionValidator. We need to override ValidateSolution and ValidateAssembly methods. The ValidateSolution method is called once for each solution, and ValidateAssembly is called once for each assembly in each solution.
Thanks

Creating a web application and site collection using powershell scripts : SharePoint 2010

Hi,

Often, we come across requirements where we have to do some stuff on the staging or the production servers again and again like creating web applications/site collections in a fresh deployment.

Powershell is of great use here.It allows administrators to write scripts which can do all these tasks quickly.In this blog, I have provided powershell scripts that automate creation of a Sharepoint web application and a site collection.

The script to create a web application is as follows:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue"
$name = "Sharepoint 2010 test web application"
$port = 4444
$hostHeader = "Sharepoint2010Tricks.com"
$url = "http://sharepoint2010tricks.com/"
$appPoolName = "SharePoint-4444"
$appPoolAccount = Get-SPManagedAccount "<Your Domain>\<account name>"New-SPWebApplication -Name $name -Port $port -HostHeader $hostHeader -URL $url -ApplicationPool $appPoolName -ApplicationPoolAccount $appPoolAccount

Once the web application has been created , powershell will display the web application url as shown below:


Perform an iisreset now so that sharepoint detects the new web application.

After this , in order to create a site collection,run the following script:

$title= "Sharepoint 2010 test site"
$url = "http://sharepoint2010tricks.com:4444/"
$owner = "<Your Domain>\<account name>"
$template = "STS#1"
New-SPSite -URL $url -Name $title -OwnerAlias $owner -Template $template

The result will be the site collection url as shown below: