Tuesday, June 19, 2012

SharePoint 2010 - Show/Hide Left Navigation


Issue:   Show/Hide Left Navigation-SharePoint 2010


Solution:

Place below code before the closing tag </head> in your customized v4.master

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
// do stuff when DOM is ready

LeftNavCollapsible();
}); 
var flg = 0;
function LeftNavCollapsible()
{
$("#s4-leftpanel-content ul.root>li.static>a").toggle(
 function () {
$(">ul", $(this).parent()).show("fast");
 },
 function () {
$(">ul", $(this).parent()).hide("fast");
 }
);
$("#s4-leftpanel-content li.static>ul.static").css("display","none");
}
</script>

Monday, April 9, 2012

SharePoint 2010 - Central Admin Create/Extend Web Application button on Ribbon are disabled

Issue:


Dev Environment is  SharePoint 2010 on WIN 7. 
  • sp\sharepoint – member of FARM Administrator


Now when I Sign-in with sp\sharepoint and use Manage Web Application link, on the Top Ribbon none of Button is enabled. I can not create Web APP nor Extend it.

Solution:
There can be more than one scenario for this issue.
Scenario 1
The Internet explorer is not opened using the administrator privileges. So, Open the Internet Explorer with "Run as Administrator" privileges. How to do this?
1. Just right click on the IE icon.
2. There you can see a menu as "Run as Administrator".



Scenario 2
This may be due to security problem on Win 7. Follow the steps below to solve the issue.
  1. Login as Administrator to the machine where SharePoint is installed.
  2. Open User Account Control Setting from C ontrol Panel -->System and Security-->Change User Account Control settings and set the Slider bar to "Never Notify "

SharePoint 2010 - Increase maximum size of List Template

If you try to save a list as a list template, you may see the following error due to the list being too large: 
The list is too large to save as a template. The size of a template cannot exceed 10485760 bytes.

You can increase the maximum size of a list / site template by running the following command (note that 500mb is the largest you can go):

stsadm -o setproperty -propertyname max-template-document-size -propertyvalue 50000000

Thursday, April 5, 2012

MSExcel - Large value comma separation using macros

Write the below code into the VB editor, that opens after creating a new macro.


For Each c In Selection
Select Case Abs(c.Value)
Case Is < 100000
c.Cells.NumberFormat = "##,##0"
Case Is < 10000000
c.Cells.NumberFormat = "#\,##\,##0"
Case Is < 1000000000
c.Cells.NumberFormat = "#\,##\,##\,##0"
Case Is < 1000000000
c.Cells.NumberFormat = "#\,##\,##\,##0"
Case Is < 100000000000#
c.Cells.NumberFormat = "#\,##\,##\,##\,##0"
Case Else
c.Cells.NumberFormat = "#\,##\,##\,##\,##\,##0"
End Select
Next c

Wednesday, April 4, 2012

.Net - code snippet to find and replace in any physical file

This is the code snippet to find and replace the content of the physical file.

using System;
using System.IO;
using System.Text.RegularExpressions;

/// <summary>
/// Replaces text in a file.
/// </summary>
/// <param name="filePath">Path of the text file.</param>
/// <param name="searchText">Text to search for.</param>
/// <param name="replaceText">Text to replace the search text.</param>
static public void ReplaceInFile( string filePath, string searchText, string replaceText )
{
   StreamReader reader = new StreamReader( filePath );
   string content = reader.ReadToEnd();
   reader.Close();

   content = Regex.Replace( content, searchText, replaceText );

   StreamWriter writer = new StreamWriter( filePath );
   writer.Write( content );
   writer.Close();
}

LINQ - Reading a csv file using LINQ

reading a csv file using LINQ.

Sample Data
I will use a sample file which contains a data about customers. When working with text files we must know the number of columns and the data contained in each column. Below is a list of columns in their right order for our file.
1.      First Name
2.      Last Name
3.      Job Title
4.      City
5.      Country
The file itself will contain this data. I have pulled this out of Employees table in Northwind database.

First Name  Last Name  Job Title  City  Country
Sharan       Raj              SE           Bang India

Reading Data
Before we start reading our csv file we will create a class which will hold a record we will read from our csv file. For this I will create a customer class which looks like this.


public class Customer
{
   string Firstname { get; set; }
   string Lastname { get; set; }
   string JobTitle { get; set; }
   string City { get; set; }
   string Country { get; set; }
}


Reading Entire File
Now we are ready to read data from our file using LINQ. Using this code we can read the entire file. I am also using a foreach statement to output the results.


var query =
       from line in File.ReadAllLines(filePath)
       let customerRecord = line.Split(',')
       select new Customer()
           {
               Firstname = customerRecord[0],
               Lastname = customerRecord[1],
               JobTitle = customerRecord[2],
               City = customerRecord[3],
               Country = customerRecord[4]
           };
foreach (var item in query)
{
   Console.WriteLine("{0}, {1}, {2}, {3}, {4}",
       item.Firstname, item.Lastname, item.JobTitle, item.City, item.Country);
}


File.ReadAllLines() returns an array of lines and we then use the split function of array to split it by a comma. Its just that simple.
Reading selected records
We can use this code to read all customers who live in UK.


var query =
       from c in
           (from line in File.ReadAllLines(filePath)
            let customerRecord = line.Split(',')
            select new Customer()
                {
                    Firstname = customerRecord[0],
                    Lastname = customerRecord[1],
                    JobTitle = customerRecord[2],
                    City = customerRecord[3],
                    Country = customerRecord[4]
                })
       where c.Country == "UK"
       select c;


This code can be used to read customers who have sales in their job title.


var query =
       from c in
           (from line in File.ReadAllLines(filePath)
            let customerRecord = line.Split(',')
            select new Customer()
                {
                    Firstname = customerRecord[0],
                    Lastname = customerRecord[1],
                    JobTitle = customerRecord[2],
                    City = customerRecord[3],
                    Country = customerRecord[4]
                })
       where c.JobTitle.Contains("Sales")
       select c;

Tuesday, April 3, 2012

SharePoint 2010 - Where my versions get stored

Once enabled for a library or list, major and minor versions of documents and items can be kept; the number of which can be specified in the library or list settings:
Versions
The version history for items or documents can be viewed, and old versions can be opened and inspected. But where are these old versions stored?
Version histories are maintained for files and for property (column) values. In the case of a document library both a file and a property history is maintained, but for a list item only a property history is kept. The SharePoint class libraries or web services can be used to programmatically access this information, and also determine the URL where a pervious version of a document is located.
So, on a SharePoint server create a new Visual Studio project and add a reference to the “Microsoft.SharePoint.dll” library. Then add a using statement to “Microsoft.SharePoint.” Assuming you have already a reference to a SPList object representing the list or library you can obain a reference to the collection of previous file versions:
            SPFileVersionCollection theFileVersions = lstItem.File.Versions;
The collection can be iterated, and in this case, the version label and URL are added to a WinForm data grid view control:
            foreach (SPFileVersion liVer in theFileVersions)
            {
               int rowID = dgvVersions.Rows.Add();
               dgvVersions.Rows[rowID].Cells[0].Value = liVer.VersionLabel;
               dgvVersions.Rows[rowID].Cells[1].Value = liVer.Url;
            }
The output will look like the following:
Versions2
You can see from this that the previous versions are stored in a virtual folder called “_vti_history” under the site in which the library is located. The virtual folder “512” represents the version number (taking into account other versioned documents in the site). This URL together with the URL for the site can be used to directly open previous versions.
The SPFileVersion object can also be used to access the contents of the file. In this code, the bytes associated with the version are obtained and then saved to a file:
            byte[] outBytes = liVer.OpenBinary();
            using (BinaryWriter binWriter =
               new BinaryWriter(File.Open(@”C:\Temp\MyFile.xlsx”,
                    FileMode.Create)))
            {
               binWriter.Write(outBytes);
            }
This works well with documents, but the situation is much more complex with pages, content and web parts. Navigating to the URL for pages will result in an HTTP 404 – “file not found”.

Friday, February 10, 2012

SharePoint 2010 - Programmatically delete SharePoint file versions in a Document Library


SPSite site = new SPSite(“http://yoursite/”);
SPWeb web = site.AllWebs["TestSite"];
SPDocumentLibrary mylib= (SPDocumentLibrary)web.Lists["mylib"];
foreach(SPListItem folder in mylib.Folders)
{
deleteVersions(SPFolder folder);
}
protected void deleteVersions (SPFolder folder)
{
foreach (SPFile file in folder.Files.Count)
{
foreach(SPFileVersion version in file.Versions)
{
Version.Delete();
}
}
}
Well, unfortunately, it is not quite that simple. This will throw an error and notify you that the enumeration has been modified. The count is read dynamic, and on next iteration it does not sync since you have deleted something.
In order to overcome this issue we will take a different approach:

SPSite site = new SPSite(“http://yoursite/”);
SPWeb web = site.AllWebs["TestSite"];
SPDocumentLibrary mylib= (SPDocumentLibrary)web.Lists["mylib"];
foreach(SPListItem folder in mylib.Folders)
{
deleteVersions(SPFolder folder);
}
protected void deleteVersions (SPFolder folder)
{
for (int i = 0; i < folder.Files.Count; i++)
{
SPFile file = folder.Files[i];
int counter = file.Versions.Count;
for (int j = 0; j < counter – 1; j++)
{
if (file.Versions[0] != null)
{
file.Versions[0].Delete();
}
}
}
}
In this snippet we are saving the count to local variable to make it static
int counter = file.Versions.Count;
Then iterating through the collection and subtracting counter – 1” from static enumeration. Which allows us to iterate through collection of files delete without getting that annoying error.

Infopath 2010 - Code Snippet to get User Profile Picture of current user


Below is the code to get User Profile Picture from User Profile database using object model.

SPSite siteColl = SPContext.Current.Site;

                    SPServiceContext serviceContext = SPServiceContext.GetContext(siteColl);
                    UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                    UserProfile profile = null;

                    bool existingUser = userProfileManager.UserExists(SPContext.Current.Web.CurrentUser.LoginName);
                    if (existingUser)
                    {
                        profile = userProfileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.LoginName);
                    }
                    imgProfile.ImageUrl = profile[PropertyConstants.PictureUrl].Value.ToString();
                    lblName.Text = SPContext.Current.Web.CurrentUser.Name;


You can add this to a visual web part and to show profile picture on any page. Don’t forget add reference to Microsoft.Office.Server

Thursday, February 2, 2012

SharePoint 2010 - Integration of SharePoint2010 with Team Foundation Server 2010

image11



The Extensions that you need are on the same installation media as the main TFS install and the only difference is the options you pick during the install.
Once it is installed you need to run the configuration. This will add all of the Solution and Templates that are needed for SharePoint to work properly with TFS.
image14
image17

Configuring the SharePoint 2010 Managed path for Team Foundation Server 2010

In order for TFS to automatically create your project portals you need a wildcard managed path setup. This is where TFS will create the portal during the creation of a new Team project.

To find the managed paths page for any application you need to first select the “Managed web applications”  link from the SharePoint 2010 Central Administration screen.
image

On you are there you will see that the “Managed Paths” are there, they are just greyed out and selecting one of the applications will enable it to be clicked.
image
image

Now we need to add a managed path for TFS 2010 to create its portals under. I have gone for the obvious option of just calling the managed path “TFS02” as the TFS 2010 server is the second TFS server that the client has installed, TFS 2008 being the first. This links the location to the server name, and as you can’t have two projects of the same name in two separate project collections there is unlikely to be any conflicts.
image

Configure the Team Foundation Server 2010 connection to SharePoint 2010

In order to have you new TFS 2010 Server talk to and create sites in SharePoint 2010 you need to tell the TFS server where to put them. As this TFS 2010 server was installed in out-of-the-box mode it has a SharePoint Services 3.0 (the free one) server running on the same box. But we want to change that so we can use the external SharePoint 2010 instance. Just open the “Team Foundation Server Administration Console” and navigate to the “SharePoint Web Applications” section. Here you click “Add” and enter the details for the Managed path we just created.
image

Before we can se this new SharePoint 2010 instance to be the default for our upgraded Team Project Collection we need to configure SharePoint to take instructions from our TFS server.

Configure SharePoint 2010 to connect to Team Foundation Server 2010

On your SharePoint 2010 server open the Team Foundation Server Administration Console and select the “Extensions for SharePoint Products and Technologies” node. Here we need to “grant access” for our TFS 2010 server to create sites. Click the “Grant access” link and  fill out the full URL to the  TFS server, for example http://servername.domain.com:8080/tfs, and if need be restrict the path that TFS sites can be created on. Remember that when the users create a new team project they can change the default and point it anywhere they like as long as it is an authorised SharePoint location.
image

Now that we have an authorised location for our team project portals to be created we need to tell our Team Project Collection that this is where it should stick sites by default for any new Team Projects created.

Configure the Team Foundation Server 2010 Team Project Collection to create new sites in SharePoint 2010

Back on out TFS 2010 server we need to setup the defaults for our upgraded Team Project Collection to the new SharePoint 2010 integration we have just set up. On the TFS 2010 server open up the “Team Foundation Server Administration Console” again and navigate to the “Team Project Collections” node. Once you are there you will see a list of all of your TPC’s and in our case we have a DefaultCollection as well as out named and Upgraded collection for TFS 2008.
If you select the “SharePoint Site” tab we can see that it is not currently configured.
image
Select to “Edit Default Site Location” and select the new integration point that we just set up for SharePoint 2010. Once you have selected the “SharePoint Web Application” (the thing we just configured) then it will give you an example based on that configuration point and the name of the Team Project Collection that we are configuring.
image

This is where the reason for configuring the Extensions on the SharePoint 2010 server before doing this last bit becomes apparent. TFS 2010 is going to create a site at our http://sharepointserver/tfs02/ location called http://sharepointserver/tfs02/[TeamProjectCollection], or whatever we had specified, and it would have had difficulty doing this if we had not given it permission first.
image

This will create a nice Team Project Collection parent site to contain the Portals for any new Team Projects that are created. It is with noting that it will not create portals for existing Team Projects as this process is run during the Team Project Creation wizard.
image

You will need to add all of the users that will be creating Team Projects to be Administrators of this site so that they will not get an error during the Project Creation Wizard. You may also want to customise this as a proper portal to your projects if you are going to be having lots of them, but it is really just a default placeholder so you have a top level site that you can backup and point at.
You have now integrated SharePoint 2010 and team Foundation Server 2010!
You can now go forth and multiple your Team Projects for this Team Project Collection or you can continue to add portals to your other Collections.