Friday, September 7, 2012

Powershell error : Execution of script is disabled on system

1 comment
Got below error while executing powershell script on Windows 7 x64 machine


It can be easily identified from error that i have to enable script execution.

To enable it, execute following command in powershell :

PS > Set-ExecutionPolicy -ExecutionPolicy UnRestried

After hitting Enter it will asked for confirmation. Press 'Y' and enter .

Now powershell script execution on system is enabled.
Read More...

Sunday, September 2, 2012

SharePoint 2013 Managed Account Error - Requested registry access is not allowed

1 comment

This is first time I came across error saying "Requested registry access is not allowed".  Error was thrown while creating managed account for User profile application.  As every SharePoint error is tied up with correlation id, was the closed to get clue about potential problem. Check below snapshot of error thrown.














Found one entry from all other  related to the issue by matching correlation id, which was signaling issue due to authentication.

Application error when access /_admin/registeraccount.aspx, Error=Requested registry access is not allowed.   at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)     at Microsoft.SharePoint.Administration.SPCredentialManager.GetMasterKey(SPFarm farm)     at Microsoft.SharePoint.Administration.SPCredentialManager.GetFarmEncryptionKey(SPFarm farm)     at Microsoft.SharePoint.Administration.SPCredentialManager.EncryptWithMasterKey(SecureString sstrPassphrase)     at Microsoft.SharePoint.Administration.SPEncryptedString.SetSecureStringValue(SecureString sstrValue)     at Microsoft.SharePoint.Administration.SPManagedAccount.Update()     at Microsoft.SharePoint.WebControls.RegisterAccountControl.BtnSubmit_Click(Object sender, EventArgs args)     at System.Web.UI.WebControls....        208dc99b-07aa-10f5-0000-0a031a12d122

After searching on the same on web, I was able to find that there is some registry entry which do not have access  rights.  Which means that while creating managed account it uses information from this registry, but as user under which managed account was created do not have access to this registy.

One can open registry using regedit command. In Registery editor go to 

HKEY_LOCAL_MACHINE\Software\Microsoft\Shared Tools\15\Secure\FarmAdmin

Check central  administration app pool Identity  have permission on FarmAdmin. Permission can be check on right clicking FarmAdmin --> Permissions.

After adding admin app  pool identity and giving full rights , I was able to create managed account.


Note : Wrong changes in registry might affect your system, so make yourself 100% sure before doing any changes.
Read More...

Sunday, June 24, 2012

Page Layout not available in Site

Leave a Comment
SharePoint is so huge that sometime you forget things which you did some time before. (Bad memory). So it is better to blog so that i can easily find it next time or someone can save their time by searching on web.

Today i was working to create site content type and deploy it to the site. By the way, every site in site collection has its own content type gallery. By default every child sites will inherit parent content type but there are settings available  to restricted this inheritance. 

User can manage site content types through Site --> Site Settings -->  Look and Feel --> Page layouts and site templates. 


Make sure "SharePoint Server Publishing" feature is activated on site otherwise this settings wont appear in Site Settings.

So after creating page layout, deploy it to the site and see whether it is available inside  Site Settings --> Galleries --> Master pages and page layouts. 

Everything in my case worked fine but still page layout was not available in options while creating new page. 

Problem was within  the settings of Page Layouts of the Site. Three kind of settings can be done on page layouts
  1. Pages inherit  preferred layouts from parent site (disabled for parent site)
  2. Pages in this site can use any layout
  3. Pages in this site can only use the following layouts
Also any of the above settings can be pushed to child site/sites by selecting check box for "Reset all subsites to inherit these preferred page layouts settings"




If option  "Pages in this site can only use the following layouts" is selected then make sure layout is available  on the right side box. Above snapshot shows that items on left is a pool of items and items on right are the available items in site. If any of the item you want to add to current site then select item from left and hit "Add" . After this click OK to apply settings.

Now page layout is available in the site.

Read More...

Wednesday, June 6, 2012

Implementing jquery in SharePoint Web Part

Leave a Comment

JQuery is JavaScript library which comes with many in build methods.  To use jquery methods, it is mandatory to add jQuery to the page.  Once it is added on the page then selector can be wrapped with either $ or jQuery to make jquery object. 

We can add jquery.js by downloading from jquery.com  or giving web reference to various jquery CDN(Content delivery network).

Make sure you analyze all the cases if you deciding to add CDN reference to the page. Because it is hosted at web , which is all meant to be up 99% time but you never know when it goes down. So I will suggest to download jquery from http://www.jquery.com site and add reference to the page.

User can directly add jquery  in master page, page layouts or page  OR it could be added programmatically.

So before we start with the implementation lets take a case scenario : We want image scroller inside webpart.

For this i will refer SimplyScroll  JavaScript file  which can be download from here. http://logicbox.net/jquery/simplyscroll/

So lets implement this Step by Step

Step 1 : Create empty SharePoint project, because it will help to structure the solution and allow us to extend project with other SharePoint artifacts in future.


Step 2 : Add Layouts mapped folder to the Project. To create this right click VS project ->; Add ->  SharePoint Layouts mapped Folder.

Step 3:  Create Folder with name ImageScroller inside Layouts mapped Folder. One can directly add to the folder but too keep in structured way it is better to keep all custom artifacts in one Folder, so that it makes easier to locate file while trobuleshooting.

Step 4:   Download jquery file from jquery.com and add to the ImageScroller folder

Step 5:   Download simplyscroll plugin and add to the ImageScroller Folder

Step 6:  Create stylesheet file and add to the folder. Copy below stylesheet


.simply-scroll-container { 

    position: relative;

}

/* Clip DIV - automatically generated */

.simply-scroll-clip { 

    position: relative;

    overflow: hidden;

}

/* UL/OL/DIV - the element that simplyScroll is inited on

Class name automatically added to element */

.simply-scroll-list { 

    overflow: hidden;

    margin: 0;

    padding: 0;

    list-style: none;

}
  

.simply-scroll-list li {

    padding: 0;

    margin: 0;

    list-style: none;

}

    

.simply-scroll-list li img {

    border: none;

    display: block;

}

/* Custom class modifications - adds to / overrides above
.simply-scroll is default base class */
/* Container DIV */

.simply-scroll { 

    width: 576px;

    height: 200px;

    margin-bottom: 1em;

}
/* Clip DIV */

.simply-scroll .simply-scroll-clip {

    width: 576px;

    height: 200px;
}
/* Explicitly set height/width of each list item */    

.simply-scroll .simply-scroll-list li {

    float: left; /* Horizontal scroll only */

    width: 290px;

    height: 200px;
}


Step 6 :  Create new js file with name GetImages.js.

              Here curiously creating custom plugin to showcase how we can extend jquery by implementing new plugin.  To create plugin at javascript file to the ImageScroller Folder.

Add following code snippet 
        
(function ($) {
    $.fn.GetImages  = function () {
        return this.each(function () {
            $(this).simplyScroll();
        });
    };
})(jQuery);

To start creating plugin certain basic steps are needed to follow. Firstly warp the function with jQuery so that it can available if reference is added to the page.

New method is added by prefixing $.fn.  Here GetImages is new method .

Plugin execution starts with return this.each(function(){});  code block. Here we will bind simplyScroll plugin to the base selector i.e. this

Step 7 : Create a class to the project , let say UserImages.cs . This will hold user images struct objects. Structure objects are easily cleaned by Garbage Collector process so it is light weight then class.

public struct UserImages
  {
    public string ImageUrl;
    public UserImages(string imageUrl)
    {
      ImageUrl = imageUrl;
    }
  }

Step 8: Create a Picture Library to the SharePoint Site. Let say it "MyTeam". Add images to the library so that it could be used for the scroller.

Step 9 : Add Webpart to the project . Let say  ImageScrollerWebpart

Add following code blocks to the CreateChildControls method

Firstly add script and style reference to the page

Controls.Add(new ScriptLink() { Name = "/_layouts/ImageScroller/jquery-1.4.1.min.js" });

      Controls.Add(new ScriptLink()
                     {
                       Name = "/_layouts/ImageScroller/jquery.simplescroll.js"
                     });
      Controls.Add(new ScriptLink()
                     {
                       Name = "/_layouts/ImageScroller/GetPeoples.js"
                     });

      CssRegistration.Register("/_layouts/ImageScroller/scroll.css");
    

Create html structure

var div = new HtmlGenericControl("div");
      var ul = new HtmlGenericControl("ul id='scroller'");
      div.Controls.Add(ul);
      foreach (var userImages in GetUserImages())
      {
        var li = new HtmlGenericControl("li");
        li.Controls.Add(new HtmlImage { Src = userImages.ImageUrl,Height = 290 , Width = 200});
        ul.Controls.Add(li);
      }
      Controls.Add(div);

Add custom javascript file to the page to call GetPeoples.js plugin.

 
var script = new StringBuilder();
      script.Append("<script language='javascript'>");
      script.Append("$(document).ready(function(){");
      script.Append("$('#scroller').GetImages();");
      script.Append("});");
      script.Append("</script>");

      if (!Page.ClientScript.IsStartupScriptRegistered("GetPeopleScript"))
      {
        Page.ClientScript.RegisterStartupScript(GetType(), "GetPeopleScript", script.ToString());
      }

Here you will find a method GetUserImages() . This method will return userImages objects of all images to be referred in scroll webpart

  private List<UserImages> GetUserImages()
    {
      var images = new List();
      SPWeb web = SPContext.Current.Web;
      var userList = web.Lists["MyTeam"];

      foreach (SPListItem userItem in userList.Items)
      {
        images.Add(new UserImages{ ImageUrl = web.Url + "/" + userItem.File.Url});
      }
      return images;
    }

Deploy webpart and add ImageScrollerWebpart to the page. You will able to see images scrolling. You can also control other scrolling attributes. Visit http://logicbox.net/jquery/simplyscroll/ to see other options

Cheers !


Read More...

Monday, May 28, 2012

Out of Box Search WebParts in SharePoint 2010

Leave a Comment


View more presentations from milanchauhan
Read More...

Tuesday, May 15, 2012

Search Options in SharePoint 2010

Leave a Comment



View more PowerPoint from milanchauhan
Read More...

Monday, May 7, 2012

Get Root Organization using Powershell Script

Leave a Comment

To create this script, open notepad or any other text editor and save it as .ps1

To start with, we need to get reference of site through which we can get reference for ServiceContext

$site = Get-SPSite("site url")

$serviceContext = Get-SPServiceContext($site)

$opm = New-Object 
Microsoft.Office.Server.UserProfiles.OrganizationProfileManager($servicecontext)

// Here Root organization can be referred by 2 ways either my passing ID as 1, because root organization ID is always 1.

$orgProfile = $opm.GetOrganizationProfile(1)

// Or it can be referred with RootOrganization Property

$orgProfile = $opm.RootOrganization

Write-Host $orgProfile.ID

Read More...

Friday, April 20, 2012

Write text log entry inside 14 Hive logs from SharePoint Timer job

Leave a Comment
This blog will demonstrate, how to create/write log file in text format inside 14\Hive folder. Idea behind this is to register error in text format inside 14\Hive folder.

Lets consider this problem statement : Get list of Organization Profiles where  value of property "OrganizationMotto" is null or Empty. "OrganizationMotto" is custom property, created through UI. To create custom property follow this steps.
  1.  Go to User profile application
  2.  Under Organizations --> Click Manage Organizations Properties
  3.  From Top bar click "New Property"
  4. Specify Name  and Display Name. Name cannot be changed but display name can be. So make sure you giving correct name.
  5. Specify Type and length.
  6. Hit Save. There are other settings you can do while create property. Such as replicating property to user information list , showing in profile page etc.
After saving you can see custom property in Manage Organizations properties section.

Now you need to create SharePoint , which will be deployed to the share point webapplication level.
Below article showcase step by step guide to create timer job. Kindly review that if audience is new to SharePoint.


Now after creating timer job, you can find Execute method which will contain core body for logic.  Below is the code reference

 public override void Execute(Guid targetInstanceId)
 {
SPWebApplication webApplication = this.Parent as SPWebApplication;
using (var rootSite = new SPSite(webApplication.Sites[0].Url))
{

// Get reference for Service Context
SPServiceContext serviceContext = SPServiceContext.GetContext(spSite);

//Get reference of OrganizationProfileManager which contains all Organization Profile objects
OrganizationProfileManager orgProfileManager = new OrganizationProfileManager(serviceContext);

//Now we want to create file under 14\Hive, so this path can be easily retrieved using GetGenericSteupPath method of SPSUtility. This will get path Program files\Common Files\Microsoft Shared\Web Service Extensions\14\Logs

      string logsPath = SPUtility.GetGenericSetupPath("Logs");
      string filepath = logsPath + @"\OrganizationProfileLog.txt";

// Get object of StreamWriter to create and write file
      StreamWriter streamWriter = File.CreateText(filepath);
      string orgDisplayName = string.Empty;

//iterate each object of OrganizationProfile to check OrganizationMotto value.
      foreach (OrganizationProfile orgProfile in orgProfileManager)
      {
        try
        {
          orgDisplayName = orgProfile.DisplayName;
          if (orgProfile["OrganizationMotto"].Value == null)
          {
            //WriteLine method will write string to the new line.
            streamWriter.WriteLine("OrganizationMotto property value of "+ orgDisplayName +" is empty");
          }
          else
          {
            if (!string.IsNullOrEmpty(orgProfile["OrganizationMotto"].Value.ToString()))
            {
              streamWriter.WriteLine("OrganizationMotto property value of " + orgDisplayName + " is empty");
            }
          }
        }
        catch (Exception exception)
        {
          streamWriter.WriteLine(exception.Message);
        }
      }
      streamWriter.Flush();
      streamWriter.Close();
}
}

After adding this code. Deploy timer job and execute it.  Then go to 14\Logs folder and search for OrganizationProfileLog.txt file.  Open this file to see if there is any issue registered . 

Cheers !


Read More...

Tuesday, April 17, 2012

Few Web Part operations using PowerShell

Leave a Comment

To create this script, open notepad or any other text editor and save it as .ps1

            1.   Firstly lets show up list of web parts from web on power shell Console

$site = Get-SPSite("site  url");
$web = $site.RootWeb;
$list = $web.Lists["Web Part Gallery"]
$listItems = $list.GetItems()

$listitems | ForEach-Object{ Write-Host $_.Title -Foregroundcolor red -Backgroundcolor green};


2.  Lets get list of web parts on page using Power shell

$site = Get-SPSite("site url");
$web = $site.RootWeb;
$webpartManager = $web.GetLimitedWebPartManager("SitePages/MyPage.aspx",[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webparts = $webpartManager.Webparts

           $webparts | ForEach-Object { Write-Host $_.DisplayTitle }

             3.   Remove WebPart from Page

 $site = Get-SPSite("site url");
 $web = $site.RootWeb;

// Get instance of WebPart Manager on the page
 $webpartManager = $web.GetLimitedWebPartManager("SitePages/MyPage.aspx",[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

// Get all the webparts on page
$webparts = $webpartManager.Webparts

//Get id of webpart to be deleted.
$webpartID = $webparts[1].ID

$webpartManager.DeleteWebPart($webparts[$webpartID]);
Read More...

Tuesday, April 10, 2012

Delete File from SharePoint document library using Client context

Leave a Comment
Following blog spot shows how to delete file from sharepoint site document library using client context. To demonstrate this, we will delete first file from file collection.


To start with the code, we will create console application.
Add 2 assemblies to the sharepoint project
(1) Microsoft.Sharepoint.Client
(2) Microsoft.SharePoint.Client.Runtime

Both assemblies resides inside 14 hive\ISAPI Folder

Inside Main Function write following code.

         // Get Web object

          ClientContext clientContext = new ClientContext("site url");
          Web web = clientContext.Web;


          // Get List Object
          List list = web.Lists.GetByTitle("ListName");
          clientContext.Load(list);
   
          // Get Root Folder for the List
          Folder folder = list.RootFolder;
          clientContext.Load(folder);


          // Get File Collection
          FileCollection files = folder.Files;
          clientContext.Load(files);
          clientContext.ExecuteQuery();


         //Delete first file from the collection
          File file = files[1];          
          file.DeleteObject();
          clientContext.ExecuteQuery();


Read More...

Saturday, April 7, 2012

Get Root Organization from Organization Profile

Leave a Comment

When user profile service application is created. Organization profile architecture creates Default organization which is Root Organization.  Logically every organization needs to have at least one department. So having Root Organization makes easy to extend by creating child organization or immediate members

To get Root Organization  one can use following code block

SPSite site = new SPSite("site url");
SPServiceContext serviceContext = SPServiceContext .GetContext(site);
OrganizationProfileManager organizationProfileManager = new OrganizationProfileManager(serviceContext);
OrganizationProfile orgProfile = organizationProfileManager .RootOrganization;

But when you modify name of the Root Organization, property returns null.

So when Root Organization returns null, how to get the Root Organization. ?

OrganizationProfileManager has method GetOrganizationProfile .  Root Organization is default organization which has ID 1. So you can get OrganizationProfile instance by ID 1.

OrganizationProfile orgProfile = organizationProfileManager GetOrganizationProfile(1);

Other way to get Organization Profile would be to Search all the ProfileBase .

For a case I want to search Organization Profile "SharePoint"
 var results = organizationProfileManager.Search("SharePoint");

      OrganizationProfile orgProfile;
      foreach (var profile in results)
      {
        if(profile is OrganizationProfile)
        {
          if(profile.DisplayName == "SharePoint")
          {
            orgProfile = profile as OrganizationProfile;
          }
        }
      }

Thanks.
Read More...

Tuesday, April 3, 2012

Get SiteUsers and SiteGroups in PowerShell

Leave a Comment
To create this script, open notepad or any other text editor and save it as .ps1


Script to get SiteUsers. 

$site = Get-SPSite("site url");
$web = $site.OpenWeb();
$users = $web.SiteUsers;

$users | ForEach-Object{ Write-Host $_.Name -Foregroundcolor red};

After saving this file, open powershell and run this ps1 file.


Script to get SiteGroups


$site = Get-SPSite("site url");

$web = $site.OpenWeb();
$groups = $web.SiteGroups

$groups | ForEach-Object{ Write-Host $_.Name -Foregroundcolor red};




Read More...

Monday, April 2, 2012

Get all SharePoint document library objects in descending order using ClientContext

Leave a Comment

To demonstrate this task we will create Console Application in Visual  Studio 2010. 
Add Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime assemblies to the references.
This assemblies resides inside 14 hive ISAPI folder.

Refer Web from ClientContext

 ClientContext clientContext = new ClientContext("siteurl");
 Web web = clientContext.Web;

Get list collection from web

 ListCollection listCollection = web.Lists;
 clientContext.Load(listCollection);
 clientContext.ExecuteQuery();


Iterate through listcollection to get lists of Base Type: document library

System.Collections.Generic.List documentlists = new List();
         
          foreach (List list in listCollection)
          {
            if(list.BaseType == BaseType.DocumentLibrary)
            {
                documentlists.Add(list);             
            }
          }

Using linq extension get all the objects in descending order.

      var sortedlist = documentlists.OrderByDescending(p => p.Title);

sortedlist will contain list of sorted document library in descending order by its title. 
Read More...

Sunday, April 1, 2012

Create local active directory group and add it to sharepoint site.

Leave a Comment

This post will explain how to  create security group  and assign permission to the group in SharePoint Site.

So before we proceed forward to create security group, we will create a user in local active directory

Firstly we need to get object for the computer on which user is going to be created

 var directoryEntry= new DirectoryEntry("WinNT://" + Environment.MachineName + ",Computer");

Now lets create user with name "TestUser"

DirectoryEntry newUser= directoryEntry.Children.Add("TestUser", "User");
newUser.CommitChanges();

This will create user in local active directory. Now you have to assign values to the properties. For example we will assign password to the user.

newUser.Password = "Password";
newUser.CommitChanges();

Next Step will be to create security group.

We already have directoryEntry object so now we can add new object of type Group to create security group

DirectoryEntry  groupEntry = directoryEntry.Children.Add("TestGroup", "Group");
groupEntry.CommitChanges();

Now we will add newuser to the new Group

groupEntry .Invoke("Add", new object[] { newUser.Path });

We have now created new user and group,  also added new user to the new group. So we are all set to add this group  to the SharePoint. By adding this security group will automatically assign the group permission to the each and every user inside this security group.  We will create a new Group in Sharepoint and add this security group to that group. This way we can control broad level SharePoint group entity.

SPSite site = new SPSite("site url");
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
 web.SiteGroups.Add("MyGroup", web.CurrentUser,web.CurrentUser,"MyGroup users");

SPGroup gGroup = web.SiteGroups["MyGroup"];
SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
var roleAssignment = new SPRoleAssignment(gGroup);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
web.RoleAssignments.Add(roleAssignment);

SPUser spUser = web.EnsureUser(SecurityGroupName);
gGroup.Users.Add(spUser.LoginName, "", "", "");
web.Update();
web.AllowUnsafeUpdates = false;

This will assign permission to the group in SharePoint Site
Read More...

OrganizationProfile.AddMember throws Attempted to perform an unauthorized operation error

Leave a Comment

Organization Profile is the new feature of SharePoint 2010. This feature is part of SharePoint 2010 server edition.  We had task to create organization profile and add member through timer job. But even after writing down code correctly , Organization Profile.Addmember method throwed "Attempted to perform an unauthorized operation error."

Not much reference was available on web to track down problem. Only one technet forum thread  was closely related to the issue, which gave clue on the problem http://social.technet.microsoft.com/Forums/en/sharepoint2010programming/thread/67ff7a0c-cd68-45a4-baea-60e5b24b8e0b 

As suggested  in  above forum thread we gave Manage profile permissions to the account but error remained same. I tried luck by giving FULL Control but  error was same.

Timer job executes under the SPTimerV4 service account.  And same user need to have access to the content database.  SPTimerV4 user account was already db owner at content database but still error remain same.

This made me to change the local admin user account  as SPTimerV4 user account and Adding same user account as db owner in content database.. This made OrganizationProfile.Add member code working correctly.
Reference technet forum thread
Read More...

Thursday, February 23, 2012

Update Choice Column value in Item Updating Event

Leave a Comment
One of my friend was facing issue to update value of choice column in Item Updating event.  Founded solution that if value of list item is needed to be change in item updating event then set after properties of property  and then fire base item updating event.

Reference Code  :

       public override void ItemUpdating(SPItemEventProperties properties)
       {
           properties.AfterProperties["Status"] = "Item1";
           base.ItemUpdating(properties);
       }
Read More...

Show list of files from Document Library in webpart as Sandboxed Solutions

1 comment
In this example, we will learn how to show  file name,  server relative url , extension and document icon type of all files present in sharepoint document library in Webpart as a Sandboxed solution.

Step 1. First of all create a SharePoint Empty Project through Visual Studio deployed as sandboxed solution.

Step 2. Then add Web Part to empty project.

Step 3.  Declare global variable under Web part class

             readonly DataTable _dt = new DataTable();       

Step  4 .  Create method to get all the files from the root folder of document library  to put information inside data table. 

        "MyDocuments" is the name of share point document library.
         
         public void PopulateDataTable()
        {
            var documentLibrary = SPContext.Current.Web.Lists["MyDocuments"] as SPDocumentLibrary;

            if (documentLibrary != null && documentLibrary.ItemCount > 0)
            {
                _dt.Columns.Add(new DataColumn("Title", typeof(string)));
                _dt.Columns.Add(new DataColumn("Url", typeof(string)));
                _dt.Columns.Add(new DataColumn("Extension", typeof(string)));
                _dt.Columns.Add(new DataColumn("ImageUrl", typeof (string)));

                foreach (SPFile file in documentLibrary.RootFolder.Files)
                {
                    DataRow dataRow = _dt.NewRow();
                    dataRow[0] = file.Name;
                    dataRow[1] = file.ServerRelativeUrl;
                    dataRow[2] = file.Name.Substring(file.Name.LastIndexOf(".") + 1);
                    dataRow[3] = "_layouts/images/lg_IC" + file.Name.Substring(file.Name.LastIndexOf(".") + 1).ToUpper() + ".png" ;
                    _dt.Rows.Add(dataRow);
                }

            }  

Many files types icons are already available in 14/Images Folder with type name lg_ICExtension.png or gif.
For example if file is of type docx then icon will be of name lg_ICDOCX.PNG.

If images of certain file types are not present at that location then , then he/she can create and copy icon to 14 hive images folder, so that gridview will able to show file icons.   

Step 6. Create GridView infrastructure to show information.

            var gridView = new GridView {ID = "MyGridView", AutoGenerateColumns = false};

            var imageField = new ImageField { HeaderText = "", DataImageUrlField = "ImageUrl"};
            gridView.Columns.Add(imageField);

            var fileName = new BoundField {HeaderText = "File Name", DataField = "Title"};
            gridView.Columns.Add(fileName);

            var url = new BoundField {DataField = "Url", HeaderText = "Url"};
            gridView.Columns.Add(url);

            var extension = new BoundField {DataField = "Extension", HeaderText = "Extension"};
            gridView.Columns.Add(extension);

            gridView.DataSource = _dt;
            gridView.DataBind();
            Controls.Add(gridView);


Complete Code

[ToolboxItemAttribute(false)]
    public class MyGridView : WebPart
    {
        readonly DataTable _dt = new DataTable();

        protected override void CreateChildControls()
        {
            PopulateDataTable();

            var gridView = new GridView {ID = "MyGridView", AutoGenerateColumns = false};

            var imageField = new ImageField { HeaderText = "", DataImageUrlField = "ImageUrl"};
            gridView.Columns.Add(imageField);

            var fileName = new BoundField {HeaderText = "File Name", DataField = "Title"};
            gridView.Columns.Add(fileName);

            var url = new BoundField {DataField = "Url", HeaderText = "Url"};
            gridView.Columns.Add(url);

            var extension = new BoundField {DataField = "Extension", HeaderText = "Extension"};
            gridView.Columns.Add(extension);

            gridView.DataSource = _dt;
            gridView.DataBind();
            Controls.Add(gridView);
        }

        public void PopulateDataTable()
        {
            var documentLibrary = SPContext.Current.Web.Lists["MyDocuments"] as SPDocumentLibrary;

            if (documentLibrary != null && documentLibrary.ItemCount > 0)
            {
                _dt.Columns.Add(new DataColumn("Title", typeof(string)));
                _dt.Columns.Add(new DataColumn("Url", typeof(string)));
                _dt.Columns.Add(new DataColumn("Extension", typeof(string)));
                _dt.Columns.Add(new DataColumn("ImageUrl", typeof (string)));

                foreach (SPFile file in documentLibrary.RootFolder.Files)
                {
                    DataRow dataRow = _dt.NewRow();
                    dataRow[0] = file.Name;
                    dataRow[1] = file.ServerRelativeUrl;
                    dataRow[2] = file.Name.Substring(file.Name.LastIndexOf(".") + 1);
                    dataRow[3] = "_layouts/images/lg_IC" + file.Name.Substring(file.Name.LastIndexOf(".") + 1).ToUpper() + ".png" ;
                    _dt.Rows.Add(dataRow);
                }

            }
        }
    }






Read More...