Tuesday, 28 August 2012

Grouping in SPGridView

Grouping in SPGridView


 spgv = new SPGridView();
            spgv.AutoGenerateColumns = false;
            spgv.RowEditing += new GridViewEditEventHandler(spgv_RowEditing);
            spgv.RowCancelingEdit += new GridViewCancelEditEventHandler(spgv_RowCancelingEdit);
            spgv.RowUpdating += new GridViewUpdateEventHandler(spgv_RowUpdating);
            spgv.RowUpdated += new GridViewUpdatedEventHandler(spgv_RowUpdated);
            spgv.AutoGenerateEditButton = true;
            spgv.AllowGrouping = true;
            spgv.AllowGroupCollapse = true;
            spgv.GroupField = "category";
            spgv.GroupDescriptionField = "category";
            spgv.GroupFieldDisplayName = "Category";

            this.Controls.Add(spgv);




SPGridView grouping not working with sorting or paging



After several tests, I found that if you disable the ViewState of the SPGridView the storing or paging  will work.
           
 gridViewResult = newSPGridView();
            gridViewResult.ID = "gridViewResult";
            gridViewResult.DataSourceID = dataSource.ID;
            gridViewResult.AutoGenerateColumns = false;
gridViewResult.EnableViewState = false;
//paging
            gridViewResult.AllowPaging = true;
            gridViewResult.PageSize = 3;
Cheers

 



 


How to display rowcount with Grouping SPGridview

 <script src="\_layouts\jquery-1.4.2.min.js" type="text/javascript"></script> 

<script type="text/javascript"> 

 $(document).ready(function() {

   $(".ms-gb").each(function()
   {
            var rowNums=$(this).nextUntil(".ms-gb").length;
     $(this).children(0).append("("+rowNums+")");
             $(this).children(0).children(0).trigger("onclick");
   });
 });
</script>

 


 



 



 

Friday, 24 August 2012

Building A SPGridView Control: ASPGridView

The SPGridView is one of the most ubiquitous controls used in SharePoint. Every single list in SharePoint (and as we all know there’s lots of those!) uses the SPGridView to display its data in neatly formatted rows. We’re able to sort its data, filter it and click on an item to choose from any options available on that item, amongst other options.
When we build a custom Web Part, we suddenly find ourselves without all that SharePoint goodness. The standard GridView (found in System.Web.UI.WebControls) gives us all the abilities we look for, but it takes a lot of effort to make it look like a SharePoint grid. Luckily, there’s the SPGridView (found in Microsoft.SharePoint.WebControls). It inherits from the GridView so can do whatever the GridView can do. But it does it in style – SharePoint style.

The ASPGridView in action
Getting the SPGridView to look and perform just like the standard SharePoint grids does require some work but with the right choices we can limit this to the absolute minimum. Let’s get started.
To host our SPGridView control we’ll need a basic Web Part skeleton which you can find as part of the files attached to this post. There’s nothing special about it, it serves simply as a place to drop our control. You can of course also use the standard Web Part-User Control pattern.
We’ll use a standard DataTable as the data source for our SPGridView which we’ll bind to an ObjectDataSource (found in System.Web.UI.WebControls). I’ve found the ObjectDataSource easier to use than a DataSet (for example, sorting and paging require no additional code whatsoever) and I haven’t quite had time to dive into using the SPDataSource. Once I have, I’ll be sure to update this post as needed.
Our SelectData method will look as follows:

public DataTable SelectData()
{
    DataTable dataSource = new DataTable();
 
    dataSource.Columns.Add("ID");
    dataSource.Columns.Add("Name");
    dataSource.Columns.Add("Region");
    dataSource.Columns.Add("Total Sales");
 
    dataSource.Rows.Add(1, "J. Smith", "Europe", 10000);
    dataSource.Rows.Add(2, "J. Smith", "North America", 15000);
    dataSource.Rows.Add(3, "J. Smith", "Asia", 5000);
    dataSource.Rows.Add(4, "S. Jones", "Europe", 7000);
    dataSource.Rows.Add(5, "S. Jones", "North America", 30000);
    dataSource.Rows.Add(6, "S. Jones", "Asia", 8700);
    dataSource.Rows.Add(7, "W. Nguyen", "Europe", 3000);
    dataSource.Rows.Add(8, "W. Nguyen", "North America", 50000);
    dataSource.Rows.Add(9, "W. Nguyen", "Asia", 25000);
 
    return dataSource;
}
 
We’ll be initializing our objects in the CreateChildControls method:

protected sealed override void CreateChildControls()
{
    const string GRIDID = "grid";
    const string DATASOURCEID = "gridDS";
 
    gridDS = new ObjectDataSource();
    gridDS.ID = DATASOURCEID;
    gridDS.SelectMethod = "SelectData";
    gridDS.TypeName = this.GetType().AssemblyQualifiedName;
    gridDS.ObjectCreating += new ObjectDataSourceObjectEventHandler(gridDS_ObjectCreating);
    this.Controls.Add(gridDS);
 
    grid = new SPGridView();
    grid.ID = GRIDID;
    grid.DataSourceID = gridDS.ID;
    grid.AutoGenerateColumns = false;
 
    // Paging
    grid.AllowPaging = true;
    grid.PageSize = 5;
 
    // Sorting
    grid.AllowSorting = true;
 
    this.Controls.Add(grid);
 
    SPGridViewPager pager = new SPGridViewPager();
    pager.GridViewId = grid.ID;
 
    this.Controls.Add(pager);
}
 
There are a few things to note here. One, I am setting the DataSourceID property of the SPGridView control instead of the DataSource property. This is required to enable filtering later on. I’ve no idea why, but I am grateful to Robert Fridén for figuring this out.
Second, I am setting the TypeName of the ObjectDataSource to the ASPGridView control itself. This allows us to access all the properties of the ASPGridView in our GetDataSource method which will prove useful when we’ll perform data binding against a SPList. It does introduce a problem where the ObjectDataSource “cannot find a non-generic method ‘GetDataSource’ …”. It also introduces a problem with the ObjectDataSource creating a fresh instance of our ASPGridView control, which resets our sorely-needed properties. Fortunately, the fix is surprisingly simple.
When ObjectDataSource creates an instance of the type specified through its TypeName property it raises the ObjectCreating event. In this event, we simply assign our current object instance to the object instance the ObjectDataSource is expecting to use:
private void gridDS_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
    e.ObjectInstance = this;
}
Finally, most blogs will tell you that you need to set the PagerTemplate property of the SPGridView to null. I am using the SPGridViewPager here so we don’t need to. In addition, we get the actual paging behavior used by SharePoint without having to implement any of the Paging events.
If you have read other articles which describe the SPGridView you’ll have noticed that I am not creating the columns for the SPGridView here. I used to until I discovered a strange problem when using more than one ASPGridView on the same page. When I’d set the Visible property of one of the controls to False, the headers of the other control would disappear! To prevent this, I’m generating my columns and performing data binding in the Render method:
protected sealed override void Render(HtmlTextWriter writer)
{
    GenerateColumns();
    grid.DataBind();
    base.Render(writer);
}
And that’s all we need to create a simple SPGridView that supports paging and sorting out-of-the-box.
You can see our progress so far here. Also, you can download the solution I created for this part of the series here. The solution uses the WSPBuilder. To install the demo Web Part, simply build the solution and run the Setup.exe file. Then activate the newly created feature in your SharePoint site and add the Web Part to the page.





How can I get the DateTime for the start of the week?

How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?
Something like:
 
DateTime.Now.StartWeek(Monday);
 
 
ANS 
 
  
Using an extension method. They're the answer to everything you know! ;)
public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
            diff += 7;
        }

        return dt.AddDays(-1 * diff).Date;
    }
}
 
Which is used thusly:
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
 

Friday, 17 August 2012

Delete SharePoint List using PowerShell

Delete SharePoint List using PowerShell.
 
$SPWeb = Get-SPWeb http://virtual:8001/
$List = $SPWeb.Lists["Test"]
$List.Delete()   
$SPWeb.Dispose()

Monday, 6 August 2012

Deploy Resource Files in SharePoint…

While doing SharePoint projects definitely you will have to use resource files to well mange and localize your resources. Not like an ASP.net application SharePoint requires you to deploy resource files to different locations.
To be clear, different operations will look the resource files in two different locations(Web parts refer one location and the resource entries in a feature manifest file looks in another etc…). The two resource locations SharePoint will look into are,
1) C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Resources\
2) The web application Virtual Directory (typically C:\inetpub\wwwroot\wss\VirtualDirectories\ {the web application port number}\App_GlobalResources\
So when we deploy a solution what typically done is coping the resource files to these locations manually.

How to overcome these manual steps?

Option 01
But with the VS 2010 SharePoint project templates, we have two options that we can use. One is mapped folders.
image
By adding a mapped folder for 14\Resources folder and placing your resource file inside that will automatically deploy the resource file in to the above mentioned first (1) location. But you have to copy the file manually to the (2) location.

Option 02
Or else VS2010 allows you to include element files to the project.
image
What you have to do is add a element file to to the project and add your resource file underneath it. Then select the resource file and set the properties as bellow.
image
OK and the second option will allow you to deploy the resource file to the application Virtual directory (2), but not to the SharePoint resource folder (1).

Option 03 – The Solution
So how to copy the file to the both locations without much effort???
If you see carefully into your VS SharePoint project, for each element, module, feature, web part etc.. has a SharePointProjectItem.spdata file an associated with it. This file is hidden when you view it from VS. By selecting the Show All Files option in solution explorer you can view these files as well.
1) Follow the above Option 02 steps (the steps that will create a element file and place the file in application virtual directly only)
2) Navigate and open the SharePointProjectItem.spdata file associated with your newly created element file
3) You will be viewing something like this
image
4) Edit the file manually and add the bellow entry to it
<ProjectItemFile Source=”MyResources.resx” Target=”Resources\” Type=”RootFile” />
5) So now it will look like,
image

Compile, Package the solution and try deploy. Verify the two resource locations that you expect the resource files should be. Smile
Happy Resource Deployment!!!