Wednesday, June 29, 2011

[Silverlight] How to make a simple PivotTable extended from Silverlight DataGrid

Recently, I have recieved a few questions about Silverlight DataGrid. It's about how to change one row to be columns just like we see in an Excel book sheet. Actually, we call this kind of table as a PivotTable or PivotGrid.
As this is another control which has not been included as a build-in control, so the best way is to create this kind of controls by ourselves, but it need a lot of labor time. By the way, there are many third-part Silverlight control manufactures have already create it, if you need good support, good built-in styles for your control and also you have the budget, then buy one and you don't need to read the later part of this blog.
This is a simple sample which talked about how to extend the build-in DataGrid to be a PivotTable for those people who has no spare money or a Silverlight-lover.
So let's start the topic and show the preview image.









The left part of the preview image is the PivotDataGrid, the right part is a common datagrid with the same ItemsSource.
Step 1, please open the Visual Studio, and create a Silverlight Application project, and also you need to install the Silverlight toolkit(http://silverlight.codeplex.com/)
Step 2, please create a Silverlight Class Library for the PivotDataGrid class, name it and change the namespace.
Step 3, let me post all the codes and please read the comments in the codes.





namespace System.Windows.Controls.Extend
{
public class PivotDataGrid : DataGrid
{
// tempdata used to make a new pivoted collection and bind it
// to the datagrid.
private ObservableCollection<PivotDataGridItem> tempdata;
// columnHeaderValues used temporarily to store the all the data
// which used to be the new headers.
private List<object> columnHeaderValues;
// rowdata used temporarily to store the other data which used
// to be the left rows.
private Dictionary<object, List<object>> rowdata;

private IEnumerable _workSource;
// we hide the base ItemsSource because we need to make them two
// available at the same time.
public new IEnumerable ItemsSource
{
get
{
return _workSource;
}
set
{
_workSource = value;
// we pivot the collection here and
// create the new collection to bind.
ApplyWorkDataSource(value);
}
}

// we should know which property will be changed to column header.
public string HeaderProperty { get; set; }

public PivotDataGrid()
: base()
{

this.HeadersVisibility = DataGridHeadersVisibility.All;
this.LoadingRow += new EventHandler<DataGridRowEventArgs>(PivotGrid_LoadingRow);
}


private void ApplyWorkDataSource(IEnumerable source)
{
// generate the new source
this.convertItemsSourceForPivotGrid(source);
this.AutoGenerateColumns = false;
int i = 0;
// generate the new columns according to the new source
foreach (object obj in columnHeaderValues)
{

this.Columns.Add(new DataGridTextColumn()
{
Header = obj.ToString(),
Binding = new Binding("Cells[" + i.ToString() + "]")
});

i++;
}
// generate the new collection
tempdata = new ObservableCollection<PivotDataGridItem>();
foreach (object objkey in rowdata.Keys)
{
PivotDataGridItem item = new PivotDataGridItem();
foreach (object obj2 in rowdata[objkey])
{
item.Cells.Add(obj2);
}
item.RowHeader = objkey;
tempdata.Add(item);
}
// bind the source to the base datagrid
base.ItemsSource = tempdata;
}

private void convertItemsSourceForPivotGrid(IEnumerable original)
{
this.columnHeaderValues = new List<object>();
this.rowdata = new Dictionary<object, List<object>>();
// the principle is to use Reflection to get all the public
// properties which need to be show in the columns.
// we can extend this part to meet different requirements.
foreach (object obj in original)
{
if (obj == null)
continue;

foreach (PropertyInfo pinfo in obj.GetType().GetProperties())
{
if (pinfo != null)
{
if (pinfo.Name == this.HeaderProperty)
{
this.columnHeaderValues.Add(pinfo.GetValue(obj, null));
}
else
{
if (!rowdata.ContainsKey(pinfo.Name))
{
this.rowdata.Add(pinfo.Name, new List<object>());
}
this.rowdata[pinfo.Name].Add(pinfo.GetValue(obj, null));
}
}
}
}
}

private void PivotGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
// set the new row header.
if (tempdata != null && tempdata.Count >= e.Row.GetIndex() + 1)
e.Row.Header = tempdata[e.Row.GetIndex()].RowHeader;
}
}
}

namespace System.Windows.Controls.Extend
{
public class PivotDataGridItem
{
private ObservableCollection<object> _items = new ObservableCollection<object>();
public ObservableCollection<object> Cells { get { return _items; } }
public object RowHeader { get; set; }
}
}





Step 4, then we can test the control.




<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
</Grid>




public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
// generate a sample data
ObservableCollection<PivotGridSampleItem> source = new ObservableCollection<PivotGridSampleItem>();
DateTime nextMonday = DateTime.Now.AddDays((double)((8 - (int)DateTime.Now.DayOfWeek) % 7));
for (int i = 0; i < 10; i++)
{
source.Add(new PivotGridSampleItem()
{
Date = nextMonday.AddDays(28 * i),
RowA = "RowA_" + i,
RowB = new Random(i).Next(100, 9999),
RowC = Convert.ToBoolean(i % 2)
});
}

// create a PivotDataGrid
PivotDataGrid pGrid = new PivotDataGrid();
pGrid.HeaderProperty = "Date";
pGrid.ItemsSource = source;
pGrid.Loaded += (se, ev) =>
{
foreach (DataGridColumn dgc in pGrid.Columns)
{
dgc.Header = DateTime.Parse(dgc.Header.ToString()).ToString("yyyy-MM-dd");
}
};
Grid.SetColumn(pGrid, 0);
this.LayoutRoot.Children.Add(pGrid);

// create a common DataGrid
DataGrid dg = new DataGrid();
dg.ItemsSource = source;
Grid.SetColumn(dg, 1);
this.LayoutRoot.Children.Add(dg);
}
}

public class PivotGridSampleItem
{
public DateTime Date { get; set; }
public string RowA { get; set; }
public int RowB { get; set; }
public bool RowC { get; set; }
}
That's all, hope this is helpful.
Attach the sample project:



Tuesday, August 17, 2010

How to force the IE8 emulate IE7 feature

Just add this line to the head block of the page.



<head>
<!-- Mimic Internet Explorer 7 -->
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
<title>My Web Page</title>
</head>

More details:
http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx

Monday, August 16, 2010

Important notes when we create web service methods for some extenders in AjaxControlToolkit package

AjaxControlToolkit is a useful package for us to work with ASP.NET AJAX. There some extenders and controls need webservice to return the data. For example, AutoCompleteExtender, CascadingDropDown, NumericUpDownExtender and so on.
Here we talked about the AutoCompleteExtender as an example.
There are two ways to create a webservice method for the extender, in an isolated web service page(*.asmx), in the code-behind of the page which use the extender.

A) Create an isolated web service page
Here is a full web service page for an AutoCompleteExtender.

Some tips we need to pay attention:

  • First, we need [System.Web.Script.Services.ScriptService] for the service class.
  • Second, we need [WebMethod] for the method.
  • Third, all the parameters names could not be changed.
  • Forth, in a web service page, we Don't Need the "static" qualifier.


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : WebService
{
public AutoComplete()
{
}

[WebMethod]
public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}

if (prefixText.Equals("xyz"))
{
return new string[0];
}

Random random = new Random();
List<string> items = new List<string>(count);
for (int i = 0; i < count; i++)
{
char c1 = (char) random.Next(65, 90);
char c2 = (char) random.Next(97, 122);
char c3 = (char) random.Next(97, 122);

items.Add(prefixText + c1 + c2 + c3);
}

return items.ToArray();
}
}

B) Service method in the page code behind

Here is a code snippet for the service method in the page.
Some tips need to pay attention here.
  • First, we need [System.Web.Services.WebMethod] for the service method.
  • Second, we need [System.Web.Script.Services.ScriptMethod] for the service method.
  • Third, all the parameters names could not be changed.
  • Forth, in an inline web service method, we NEED the "static" qualifier.


public partial class getcustomer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}

if (prefixText.Equals("xyz"))
{
return new string[0];
}

Random random = new Random();
List<string> items = new List<string>(count);
for (int i = 0; i < count; i++)
{
char c1 = (char) random.Next(65, 90);
char c2 = (char) random.Next(97, 122);
char c3 = (char) random.Next(97, 122);

items.Add(prefixText + c1 + c2 + c3);
}

return items.ToArray();
}
}

Sunday, August 15, 2010

How to register javascript functions after UpdatePanel updated

As an ASP.NET fellow, UpdatePanel just like one artifacts. It can make all the contents in one UpdatePanel get an partial-refresh(AJAX) feature.
Usually, we need to call a javascript function after we update the content in the UpdatePanel. Without UpdatePanel, we could add onclick attribute to one button or use Page.ClientScript to register the script in code-behind. But in the UpdatePanel, Page.ClientScript will lose efficacy.
In this document, I want to discuss some methods to register javascript functions after the UpdatePanel updated.
ASP.NET Extension provide us some useful and direct ways to call a javascript function both in client-side and server-side.
Client-side:
Method A:
Look at this code snippet:

01 <form id="form1" runat="server">
02 <asp:ScriptManager ID="ScriptManager1" runat="server">
03 </asp:ScriptManager>
04
05 <script type="text/javascript">
06 function pageLoad(sender, e) {
07 alert("Page is re-loaded!");
08 }
09 </script>
10
11 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
12 <ContentTemplate>
13 <%=DateTime.Now.ToString() %>
14 </ContentTemplate>
15 <Triggers>
16 <asp:AsyncPostBackTrigger ControlID="TriggerTimer" EventName="Tick" />
17 </Triggers>
18 </asp:UpdatePanel>
19
20 <asp:Timer ID="TriggerTimer" runat="server" Interval="5000">
21 </asp:Timer>
22 </form>


In this snippet, we could see we register the pageLoad function directly in the page. the function pageLoad will be executed when the page first load and each asynchronous postback which caused by UpdatePanel.

Method B:

The code above in pageLoad is same as the code below.


1 <script type="text/javascript">
2 window.onload = function () {
3 Sys.Application.add_load(function () {
4 alert("Page re-loaded!");
5 });
6 }
7 </script>

Server Side:

For server side, we need to use a method, ScriptManager.RegisterClientScriptBlock, for more details about this method, please view this link in MSDN:http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerclientscriptblock.aspx. This method registers a client script block with the ScriptManager control for use with a control that is inside an UpdatePanel control, and then adds the script block to the page.

For example,


1 protected void TriggerTimer_Tick(object sender, EventArgs e)
2 {
3 ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "RegScript",
4 "alert('Page re-loaded!');", true);
5 }
The result is same as the methods which talked above.

Monday, March 8, 2010

Regular Expression for validating Password

^(?=.*\d)(?=.*[~!@#$%^*?=])(?=.*[a-z])(?=.*[A-Z]).{8,10}$
Description:
1, words length:8~10;
2, at least 1 digital;
3, at least 1 special character([~!@#$%^*?=]);
4, at least 1 low case letter;
5, at least 1 upper case letter;