A couple of nights ago I was reading about some of the new features in Windows 7 SDK and I can honestly say “They’re a lot”, as a matter of fact, I mentioned some of them in one of my previous Tech-Ed session this year. Despite of all these new features, there’s one that got my attention from the beginning and it was WWSAPI, because there wasn’t any support for Web Service from native code, except for a couple of existing toolkits including gSOAP that can be implemented on Windows, Linux and Mac OSX. WWSAPI was first introduced at PDC 2008 and it will be formally released along Windows 7, although previous versions of the operating system starting from XP SP2 can get it via Windows Update when becomes available. I first tested it when Windows 7 was still RC but I didn’t post about it because I was expecting for Windows 7 to be released or about to be released.
Having said that, last weekend I created a solution to demo WWSAPI in conjunction with .NET. The solution structure is depicted below
-
NativeTester: Console application (C++) which calls our Dynamic Link Library (DLL)
-
RSSFeedService: Web Service (C#) which retrieves RSS feeds, parse them and returns a well-formed XML
-
RSSViewer: WPF application (C#) which consumes the Web Service plus invokes our Dynamic Link Library (DLL)
-
Tester: WinForm application (C#) which consumes the Web Service plus invokes our Dynamic Link Library (DLL)
-
WWSAPIDemo: Dynamic Link Library (C++) which implements WWSAPI and it’s invoked from .NET via Interop
Along with the code you can find MSDN.xml which contains the RSS feeds from MSDN Australia, even when the code references http://localhost/MSDN.xml, you can change the Url and retrieve any given RSS, in my case I deployed the previously mentioned file to my local IIS.
Many of you might be wondering about, how can I generate a proxy based on the Web Service via C++? and the answer is quite simple, the new Windows 7 SDK provides us with an utility that does this for us, WSUTIL.exe. After executing it, we have as a result two files (an .H and a .CPP). The strings are treated as WCHAR* by default which in turn is Unicode and every single string in .NET are Unicode as well, I’ll comment a bit more about this later.
Having the Web Service published already on IIS, we better start working on the Dynamic Link Library which implements WWSAPI. Below we can see its header file
#include "stdafx.h"
#define EXPORT extern "C" __declspec(dllexport)
#define MAX_SIZE 128000 //128Kb
#define TRIM_SIZE 512
EXPORT WCHAR* GetFeeds(WCHAR* szUrl, int cbResults);
EXPORT void GetItem(WCHAR* szUrl, WCHAR* szItemName);
And this is the method responsible for connecting against the Web Service and retrieves the RSS feeds
// Get feeds from a given Url through WWSAPI
EXPORT WCHAR* GetFeeds(WCHAR* szUrl, int cbResults) {
WCHAR* temp = NULL;
WS_HEAP* heap = NULL;
WCHAR retval[MAX_SIZE]; // 128Kb (It should be enough to avoid WS_E_QUOTA_EXCEEDED error)
WS_ERROR* error = NULL;
ULONG propertiesCount = 0;
WS_SERVICE_PROXY* proxy = NULL;
WS_CHANNEL_PROPERTY channelProps[2];
WS_STRING serviceUrl = WS_STRING_VALUE(L"http://localhost/DemoSvc/RSSFeedService.asmx");
WS_ENDPOINT_ADDRESS endpoint = { serviceUrl};
WS_ENVELOPE_VERSION soapVersion = WS_ENVELOPE_VERSION_SOAP_1_1; // Our Webservice is WsiProfiles.BasicProfile1_1 compliant
WS_ADDRESSING_VERSION addressingVersion = WS_ADDRESSING_VERSION_TRANSPORT;
// Set channel's properties
channelProps[propertiesCount].id = WS_CHANNEL_PROPERTY_ENVELOPE_VERSION;
channelProps[propertiesCount].value = &soapVersion;
channelProps[propertiesCount].valueSize = sizeof(soapVersion);
propertiesCount++;
// Set addressing's properties
channelProps[propertiesCount].id = WS_CHANNEL_PROPERTY_ADDRESSING_VERSION;
channelProps[propertiesCount].value = &addressingVersion;
channelProps[propertiesCount].valueSize = sizeof(addressingVersion);
propertiesCount++;
// Can we create an WsError and WsHeap objects?
if (SUCCEEDED(WsCreateError(NULL, NULL, &error)) && SUCCEEDED(WsCreateHeap(MAX_SIZE, TRIM_SIZE, NULL, NULL, &heap, error))) {
// Can we create a proxy based on the service?
if (SUCCEEDED(WsCreateServiceProxy(WS_CHANNEL_TYPE_REQUEST, WS_HTTP_CHANNEL_BINDING, NULL, NULL, NULL,
channelProps, propertiesCount, &proxy, error))) {
// Can we open the proxy object?
if (SUCCEEDED(WsOpenServiceProxy(proxy, &endpoint, NULL, error))) {
// If we're able to invoke the service then copy the results to another variable because if
// we don't we lose the response after freeing the heap
if (SUCCEEDED(RSSFeedServiceSoap12_RetrieveFeeds(proxy, szUrl, cbResults, &temp, heap, NULL, NULL, NULL, error)))
wcscpy_s(retval, temp);
}
}
}
// Deallocate and free resources
if (error != NULL)
WsFreeError(error);
if (proxy != NULL) {
WsCloseServiceProxy(proxy, NULL, error);
WsFreeServiceProxy(proxy);
}
if (heap != NULL)
WsFreeHeap(heap);
return retval;
}
Please note the following:
-
We must specify the version of SOAP to use (otherwise, the client is going to complain about it, because it will use 1.2, as evidence check the RSSFeedServiceSoap12 method name)
-
I return a WCHAR* and it works without issues, even when the right way to do it is returning an HRESULT or an integer, accept a pointer as an argument which at the same time it’s an output parameter. There’s a document about best practices for creating DLLs which can be downloaded from here
Our implementation from the console application is shown below
#include "stdafx.h"
typedef WCHAR* (*myCallback) (WCHAR*, int);
int _tmain(int argc, _TCHAR* argv[]) {
HINSTANCE hInstance;
myCallback ptrToFunc;
WCHAR* results = NULL;
if ((hInstance = LoadLibrary(L"C:\\Users\\angel.hernandez\\Desktop\\WWSAPI\\WWSAPIDemo\\x64\\Debug\\WWSAPIDemo.dll")) != NULL) {
if ((ptrToFunc = (myCallback) GetProcAddress(hInstance, "GetFeeds")) != NULL) {
results = ptrToFunc(L"http://localhost/MSDN.xml", -1);
wprintf(L"\n%ls\n", results);
FreeLibrary(hInstance);
printf("\n\nPress any key to exit...\n");
_getch();
}
}
return 0;
}
After compiling, linking and executing our NativeTester application, we can see how the RSS feeds are displayed on the console.
GetItem is another exported function in our DLL which displays a found element (if any) after executing an XPath query and using the starts-with function (as if it was the Like % operator). GetItem retrieves the RSS feeds by previously calling the GetFeeds function.
// Execute XPATH Query based on feeds retrieved through WWSAPI
EXPORT void GetItem(WCHAR* szUrl, WCHAR* szItemName) {
WCHAR retval[TRIM_SIZE];
WCHAR* results = NULL;
BSTR nodeContent = NULL;
WCHAR xPathQueryBuffer[TRIM_SIZE];
IXMLDOMDocumentPtr docPtr = NULL;
IXMLDOMNodePtr selectedNode = NULL;
if ((results = GetFeeds(szUrl, -1)) != NULL && wcslen(results) > 0) {
CoInitialize(NULL);
docPtr.CreateInstance("Msxml2.DOMDocument.6.0");
wsprintf(xPathQueryBuffer, L"/rss/items/item[starts-with(@title,'%ls')]", szItemName);
if (SUCCEEDED(docPtr->loadXML(_bstr_t(results), NULL))) {
if (SUCCEEDED(docPtr->selectSingleNode(_bstr_t(xPathQueryBuffer), &selectedNode))) {
nodeContent = SysAllocString(retval);
selectedNode->get_xml(&nodeContent);
MessageBox(NULL, nodeContent, L"XPath Query Results", NULL);
SysFreeString(nodeContent);
}
}
}
}
So far we’ve been able to implement and use WWSAPI from native code, however we haven’t tested our Dll’s functionality from .NET, in that case the first thing to do is, “to import” the function we’re interested on by specifying the DllImport attribute.
[DllImport(@"C:\Users\angel.hernandez\Desktop\WWSAPI\WWSAPIDemo\x64\Debug\WWSAPIDemo.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr GetFeeds(IntPtr szUrl, int cbResults);
The GetFeeds function returns a WCHAR* which in turn is interpreted by .NET as an IntPtr. We also need to use the Marshal class to convert it from WCHAR* to an Unicode string and to pass a WCHAR* as parameter to the function
private void btnTestWWSAPI_Click(object sender, EventArgs e) {
IntPtr szUrl = Marshal.StringToBSTR("http://localhost/MSDN.xml");
MessageBox.Show(Marshal.PtrToStringUni(GetFeeds(szUrl, -1)));
Marshal.FreeBSTR(szUrl);
}
and Voila!!! I have my WWSAPI implementation being consumed and used from .NET, well.. from a WinForm application, but what about a WPF application? The answer is… the implementation remains the same except for the XAML code required plus the databinding process is quite simple if an XmlDataProvider is used because the data is extracted and assigned based on an XPath syntax.
<!-- Data Provider-->
<Window.Resources>
<XmlDataProvider x:Key="xmlFeeds" IsAsynchronous="True" XPath="/rss/items/item"/>
</Window.Resources>
<Grid Name="grdFeeds" Margin="0,75,0,12">
<!-- Binding Source-->
<ListView Margin="11.432,6" Name="lstFeeds"
ItemsSource="{Binding Source={StaticResource xmlFeeds} }" MouseDoubleClick="lstFeeds_MouseDoubleClick">
<ListView.View>
<GridView x:Name="grdFeedItems">
<GridViewColumn Header="Title" x:Name="grcTitle" Width="100" DisplayMemberBinding="{Binding XPath=@title}"/>
<GridViewColumn Header="Publishing Date" x:Name="grcPublishingDate" Width="100" DisplayMemberBinding="{Binding XPath=@publishingDate}"/>
<GridViewColumn Header="Url" x:Name="grcUrl" Width="100" DisplayMemberBinding="{Binding XPath=@url}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
The Button Click event handler is shown below
private void btnExecuteOperation_Click(object sender, RoutedEventArgs e) {
XmlDocument feeds = new XmlDocument();
IntPtr szUrl = IntPtr.Zero, szItemName = IntPtr.Zero;
XmlDataProvider xmlFeeds = TryFindResource("xmlFeeds") as XmlDataProvider;
try {
switch (cboOperations.SelectedIndex) {
case 0:
using (RSSFeedService proxy = new RSSFeedService())
feeds.LoadXml(proxy.RetrieveFeeds("http://localhost/MSDN.xml", -1));
xmlFeeds.Document = feeds;
break;
case 1:
szUrl = Marshal.StringToBSTR("http://localhost/MSDN.xml");
feeds.LoadXml(Marshal.PtrToStringUni(GetFeeds(szUrl, -1)));
Marshal.FreeBSTR(szUrl);
xmlFeeds.Document = feeds;
break;
case 2:
szUrl = Marshal.StringToBSTR("http://localhost/MSDN.xml");
szItemName = Marshal.StringToBSTR(!string.IsNullOrEmpty(txtItemTitle.Text) ? txtItemTitle.Text : "Windows");
GetItem(szUrl, szItemName);
Marshal.FreeBSTR(szUrl);
Marshal.FreeBSTR(szItemName);
break;
}
} catch (Exception ex) {
MessageBox.Show(string.Format("Oops! Something wrong just occurred\n{0}", ex.Message),
"Exception caught", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
Attached to this post you can find the code, please feel free to download it, modify it and play with it. I hope you consider this information useful and always remember one thing… The only possible way to learn is by playing with the technology and feel confident about taking risks.
God bless you
Regards,
Angel
Hace un par de noches atrás estaba leyendo sobre las características nuevas del SDK de Windows 7 y puedo decir que son bastantes, de hecho en una de las sesiones que tuve en Tech-Ed este año mencioné algunas de ellas. Sin embargo, una que llamó mi atención fue WWSAPI pues hasta ahora no existía soporte para código nativo, excepto por un par de Toolkits existentes entre ellos gSOAP que puede utilizarse con Windows, Linux y Mac OSX. WWSAPI fue presentado en el PDC del año pasado (2008) y será liberado formalmente con Windows 7 aunque versiones anteriores del sistema operativo, a partir de XP SP2. Yo lo probé inicialmente cuando Windows 7 estaba en RC sin embargo no había posteado al respecto por esperar que Windows 7 fuese liberado o cerca de serlo.
Una vez dicho esto, durante el fin de semana creé una solución para demostrar WWSAPI en conjunto con .NET. La solución tiene la estructura mostrada a continuación
-
NativeTester: Aplicación de Consola (C++) que llama a la biblioteca de enlace dinámico (DLL)
-
RSSFeedService: Servicio Web (C#) que recupera entradas RSS, las parsea y regresa el resultado como XML
-
RSSViewer: Aplicación basada en WPF (C#) que consume el servicio Web e invoca a la biblioteca de enlace dinámico (DLL)
-
Tester: Aplicación basada en WinForm (C#) que consume el servicio Web e invoca a la biblioteca de enlace dinámico (DLL)
-
WWSAPIDemo: Biblioteca de enlace dinámico (C++) que implementa WWSAPI y es invocada desde .NET a través de Interop
Así mismo con el código pueden encontrar MSDN.xml que son las entradas RSS de la página de MSDN Australia, aunque el código apunta a http://localhost/MSDN.xml, ustedes pueden cambiar dicho Url y apuntar al RSS que gusten, en mi caso guardé el archivo de entradas RSS y lo pusé en my IIS local.
Muchos de ustedes se preguntarán, ¿cómo genero el proxy del servicio Web desde C++? Y la respuesta es muy simple, el nuevo SDK de Windows 7 trae consigo un utilitario que lo hace por nosotros, WSUTIL.exe. La ejecución nos da como resultado dos archivos (uno .H y otro .CPP). Las cadenas por defecto son tratadas como WCHAR* que es Unicode y todas las cadenas en .NET son interpretadas como Unicode, más adelante comentaré un poco de esto.
Con el servicio Web ya publicado en IIS, entonces nos queda comenzar a trabajar en la biblioteca de enlace dinámico que será cliente e implementará WWSAPI. A continuación el archivo de cabecera de la biblioteca
#include "stdafx.h"
#define EXPORT extern "C" __declspec(dllexport)
#define MAX_SIZE 128000 //128Kb
#define TRIM_SIZE 512
EXPORT WCHAR* GetFeeds(WCHAR* szUrl, int cbResults);
EXPORT void GetItem(WCHAR* szUrl, WCHAR* szItemName);
así como el método que se conecta al servicio Web y recupera las entradas de RSS
// Get feeds from a given Url through WWSAPI
EXPORT WCHAR* GetFeeds(WCHAR* szUrl, int cbResults) {
WCHAR* temp = NULL;
WS_HEAP* heap = NULL;
WCHAR retval[MAX_SIZE]; // 128Kb (It should be enough to avoid WS_E_QUOTA_EXCEEDED error)
WS_ERROR* error = NULL;
ULONG propertiesCount = 0;
WS_SERVICE_PROXY* proxy = NULL;
WS_CHANNEL_PROPERTY channelProps[2];
WS_STRING serviceUrl = WS_STRING_VALUE(L"http://localhost/DemoSvc/RSSFeedService.asmx");
WS_ENDPOINT_ADDRESS endpoint = { serviceUrl};
WS_ENVELOPE_VERSION soapVersion = WS_ENVELOPE_VERSION_SOAP_1_1; // Our Webservice is WsiProfiles.BasicProfile1_1 compliant
WS_ADDRESSING_VERSION addressingVersion = WS_ADDRESSING_VERSION_TRANSPORT;
// Set channel's properties
channelProps[propertiesCount].id = WS_CHANNEL_PROPERTY_ENVELOPE_VERSION;
channelProps[propertiesCount].value = &soapVersion;
channelProps[propertiesCount].valueSize = sizeof(soapVersion);
propertiesCount++;
// Set addressing's properties
channelProps[propertiesCount].id = WS_CHANNEL_PROPERTY_ADDRESSING_VERSION;
channelProps[propertiesCount].value = &addressingVersion;
channelProps[propertiesCount].valueSize = sizeof(addressingVersion);
propertiesCount++;
// Can we create an WsError and WsHeap objects?
if (SUCCEEDED(WsCreateError(NULL, NULL, &error)) && SUCCEEDED(WsCreateHeap(MAX_SIZE, TRIM_SIZE, NULL, NULL, &heap, error))) {
// Can we create a proxy based on the service?
if (SUCCEEDED(WsCreateServiceProxy(WS_CHANNEL_TYPE_REQUEST, WS_HTTP_CHANNEL_BINDING, NULL, NULL, NULL,
channelProps, propertiesCount, &proxy, error))) {
// Can we open the proxy object?
if (SUCCEEDED(WsOpenServiceProxy(proxy, &endpoint, NULL, error))) {
// If we're able to invoke the service then copy the results to another variable because if
// we don't we lose the response after freeing the heap
if (SUCCEEDED(RSSFeedServiceSoap12_RetrieveFeeds(proxy, szUrl, cbResults, &temp, heap, NULL, NULL, NULL, error)))
wcscpy_s(retval, temp);
}
}
}
// Deallocate and free resources
if (error != NULL)
WsFreeError(error);
if (proxy != NULL) {
WsCloseServiceProxy(proxy, NULL, error);
WsFreeServiceProxy(proxy);
}
if (heap != NULL)
WsFreeHeap(heap);
return retval;
}
Por favor, nótese lo siguiente:
-
Debemos especificar la versión de SOAP (de lo contrario, el cliente se va a quejar al respecto, porque va a utilizar 1.2. Prueba de esto, es el nombre del método RSSFeedServiceSoap12)
-
Regreso un WCHAR* y funciona sin problemas, aunque la manera correcta debería ser es regresar un HRESULT o un entero, tomar un puntero como parámetro que al mismo tiempo sirve de valor de retorno. Un documento sobre las mejores prácticas de desarrollo de DLLs puede encontrarse aquí
Nuestra implementación desde la aplicación de consola es mostrada a continuación
#include "stdafx.h"
typedef WCHAR* (*myCallback) (WCHAR*, int);
int _tmain(int argc, _TCHAR* argv[]) {
HINSTANCE hInstance;
myCallback ptrToFunc;
WCHAR* results = NULL;
if ((hInstance = LoadLibrary(L"C:\\Users\\angel.hernandez\\Desktop\\WWSAPI\\WWSAPIDemo\\x64\\Debug\\WWSAPIDemo.dll")) != NULL) {
if ((ptrToFunc = (myCallback) GetProcAddress(hInstance, "GetFeeds")) != NULL) {
results = ptrToFunc(L"http://localhost/MSDN.xml", -1);
wprintf(L"\n%ls\n", results);
FreeLibrary(hInstance);
printf("\n\nPress any key to exit...\n");
_getch();
}
}
return 0;
}
Al compilar y ejecutar nuestra aplicación de prueba NativeTester, podemos ver como se muestran las entradas recuperadas en la consola.
La otra función contenida en la biblioteca de enlace dinámico es GetItem, que muestra el elemento encontrado tras la ejecución de una consulta de XPath y haciendo uso de la función starts-with (como si fuera el operador Like %). La función GetItem recupera las entradas RSS al llamar previamente a la función GetFeeds.
// Execute XPATH Query based on feeds retrieved through WWSAPI
EXPORT void GetItem(WCHAR* szUrl, WCHAR* szItemName) {
WCHAR retval[TRIM_SIZE];
WCHAR* results = NULL;
BSTR nodeContent = NULL;
WCHAR xPathQueryBuffer[TRIM_SIZE];
IXMLDOMDocumentPtr docPtr = NULL;
IXMLDOMNodePtr selectedNode = NULL;
if ((results = GetFeeds(szUrl, -1)) != NULL && wcslen(results) > 0) {
CoInitialize(NULL);
docPtr.CreateInstance("Msxml2.DOMDocument.6.0");
wsprintf(xPathQueryBuffer, L"/rss/items/item[starts-with(@title,'%ls')]", szItemName);
if (SUCCEEDED(docPtr->loadXML(_bstr_t(results), NULL))) {
if (SUCCEEDED(docPtr->selectSingleNode(_bstr_t(xPathQueryBuffer), &selectedNode))) {
nodeContent = SysAllocString(retval);
selectedNode->get_xml(&nodeContent);
MessageBox(NULL, nodeContent, L"XPath Query Results", NULL);
SysFreeString(nodeContent);
}
}
}
}
Hasta ahora hemos logrado implementar y utilizar WWSAPI desde código nativo, sin embargo aún no hemos probado la funcionalidad de nuestra biblioteca de enlace dinámico desde .NET, en ese caso lo primero que debemos hacer es importar la función que nos interesa a través de DllImport
[DllImport(@"C:\Users\angel.hernandez\Desktop\WWSAPI\WWSAPIDemo\x64\Debug\WWSAPIDemo.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr GetFeeds(IntPtr szUrl, int cbResults);
La función GetFeeds retorna un WCHAR* que es traducido a NET como un IntPtr, así mismo hacemos uso de la clase Marshal para traducir el WCHAR* a una cadena Unicode y para pasar un WCHAR* a la función, como es mostrado a continuación
private void btnTestWWSAPI_Click(object sender, EventArgs e) {
IntPtr szUrl = Marshal.StringToBSTR("http://localhost/MSDN.xml");
MessageBox.Show(Marshal.PtrToStringUni(GetFeeds(szUrl, -1)));
Marshal.FreeBSTR(szUrl);
}
Y Voila!!! Tengo mi implementación de WWSAPI siendo utilizada desde .NET, bueno al menos desde una aplicación Windows Form, pero ¿cómo será con una aplicación WPF? Pues… la respuesta es será igual, a diferencia de que debes escribir el XAML y que hacer binding a los objetos es más sencillo si se utiliza un XmlDataProvider pues los datos se extraen y asignan utilizando una sintaxis basada en XPath.
<!-- Data Provider-->
<Window.Resources>
<XmlDataProvider x:Key="xmlFeeds" IsAsynchronous="True" XPath="/rss/items/item"/>
</Window.Resources>
<Grid Name="grdFeeds" Margin="0,75,0,12">
<!-- Binding Source-->
<ListView Margin="11.432,6" Name="lstFeeds"
ItemsSource="{Binding Source={StaticResource xmlFeeds} }" MouseDoubleClick="lstFeeds_MouseDoubleClick">
<ListView.View>
<GridView x:Name="grdFeedItems">
<GridViewColumn Header="Title" x:Name="grcTitle" Width="100" DisplayMemberBinding="{Binding XPath=@title}"/>
<GridViewColumn Header="Publishing Date" x:Name="grcPublishingDate" Width="100" DisplayMemberBinding="{Binding XPath=@publishingDate}"/>
<GridViewColumn Header="Url" x:Name="grcUrl" Width="100" DisplayMemberBinding="{Binding XPath=@url}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
El manejador del evento Click del botón para llamar a nuestra biblioteca de enlace dinámico es mostrado a continuación
private void btnExecuteOperation_Click(object sender, RoutedEventArgs e) {
XmlDocument feeds = new XmlDocument();
IntPtr szUrl = IntPtr.Zero, szItemName = IntPtr.Zero;
XmlDataProvider xmlFeeds = TryFindResource("xmlFeeds") as XmlDataProvider;
try {
switch (cboOperations.SelectedIndex) {
case 0:
using (RSSFeedService proxy = new RSSFeedService())
feeds.LoadXml(proxy.RetrieveFeeds("http://localhost/MSDN.xml", -1));
xmlFeeds.Document = feeds;
break;
case 1:
szUrl = Marshal.StringToBSTR("http://localhost/MSDN.xml");
feeds.LoadXml(Marshal.PtrToStringUni(GetFeeds(szUrl, -1)));
Marshal.FreeBSTR(szUrl);
xmlFeeds.Document = feeds;
break;
case 2:
szUrl = Marshal.StringToBSTR("http://localhost/MSDN.xml");
szItemName = Marshal.StringToBSTR(!string.IsNullOrEmpty(txtItemTitle.Text) ? txtItemTitle.Text : "Windows");
GetItem(szUrl, szItemName);
Marshal.FreeBSTR(szUrl);
Marshal.FreeBSTR(szItemName);
break;
}
} catch (Exception ex) {
MessageBox.Show(string.Format("Oops! Something wrong just occurred\n{0}", ex.Message),
"Exception caught", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
El post tiene adjunto el código mostrado, pueden descargarlo, modificarlo y jugar con él. Espero que sea de utilidad y recuerden, la única manera de aprender es jugar con la tecnología y no tener miedo para asumir nuevos retos.
Que Dios los bendiga.
Saludos,
Angel
A couple of weeks ago I was attending and presenting at Microsoft TechEd on Gold Coast, when I got a phone call from our Sales Manager. The mission: Develop a new webpart for an existing B2B portal which integrates SAP, MQ, CRM and webMethods through SharePoint. The challenge: Write some Javascript code to do some processing on the server-side based on the user’s input.
I’ve been doing some SharePoint development for a while and if you know how to do things on ASP.NET then is not that hard to leverage those skills and use them on SharePoint. The requirements were:
-
Allow user input and perform some validation on the browser-side
-
Add AJAX capabilities to deliver a responsive UI to the users
-
Grab information stored on the client-side (browser) from the server-side and do some processing against CRM
So let’s start from the beginning explaining how I got this done
Properties required
private DataTable SearchResults {
get {
return (ViewState["block_orders"] != null ?
(DataTable)ViewState["block_orders"] : null);
}
set {
ViewState["block_orders"] = value;
}
}
private string GridViewSortCondition {
get {
if (ViewState["SortCondition"] == null)
ViewState["SortCondition"] = "sapSearch ASC";
return ViewState["SortCondition"].ToString();
}
set {
ViewState["SortCondition"] = value;
}
}
private SortDirection GridViewSortDirection {
get {
if (ViewState["SortDirection"] == null)
ViewState["SortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["SortDirection"];
}
set {
ViewState["SortDirection"] = value;
}
}
private string SortExpression {
get {
return (ViewState["sort_exp"] != null ?
ViewState["sort_exp"].ToString() : string.Empty);
}
set {
ViewState["sort_exp"] = value;
}
}
private string SelectedCheckBoxes {
get {
return (ViewState["selected_check_boxes"] != null ?
ViewState["selected_check_boxes"].ToString() : string.Empty);
}
set {
ViewState["selected_check_boxes"] = value;
}
}
I need to store the search results so the user can perform paging and sorting operations on the result set
Now, let’s proceed to the code required to add AJAX functionality, I usually break down the UI code into pieces, I mean, a method to generate the top, middle and bottom parts of a webpart. Since I’m implementing some AJAX I enclose everything inside a <DIV> so the code required looks like this
private void AddAJAXControls() {
Controls.Add(new Literal() { Text = "<div>", ID = "mainDiv" });
Controls.Add(new ScriptManager() { ID = "scriptManager_OrderBlock" });
Controls.Add(new Literal() { Text = InjectScriptToDisableDoublePostBack() });
Controls.Add(new UpdatePanel() { ID = "updatePanel_OrderBlock" });
}
Please note the call to “InjectScriptToDisableDoublePostback” method, it’s responsible for disabling the control which has triggered the postback (e.g.: a submit button) so the user won’t be able to “re-submit” the form more than once, the code is shown below
private string InjectScriptToDisableDoublePostBack() {
StringBuilder retval = new StringBuilder();
retval.AppendLine("<script type='text/javascript'>");
retval.AppendLine("var pbControl = null;");
retval.AppendLine("var prm = Sys.WebForms.PageRequestManager.getInstance();");
retval.AppendLine("prm.add_beginRequest(BeginRequestHandler);");
retval.AppendLine("prm.add_endRequest(EndRequestHandler);");
retval.AppendLine("function BeginRequestHandler(sender, args) {");
retval.AppendLine("//the control causing the postback");
retval.AppendLine("pbControl = args.get_postBackElement();");
retval.AppendLine("if (pbControl.id.indexOf('btnSearch') > -1 || ");
retval.AppendLine("pbControl.id.indexOf('btnUpdate') > -1 )");
retval.AppendLine("pbControl.disabled = true;");
retval.AppendLine("}");
retval.AppendLine("function EndRequestHandler(sender, args) {");
retval.AppendLine("pbControl.disabled = false;");
retval.AppendLine("pbControl = null;");
retval.AppendLine("}");
retval.AppendLine("</script>");
return retval.ToString();
}
The method responsible for putting all of the pieces together and rendering the webpart is
protected virtual void CreateUI() {
UpdatePanel panel = null;
// Add AJAX controls
AddAJAXControls();
if ((panel = FindControl("updatePanel_OrderBlock") as UpdatePanel) != null) {
// Top Table
panel.ContentTemplateContainer.Controls.Add(GetTopTable());
// Bottom Table
panel.ContentTemplateContainer.Controls.Add(GetBottomTable());
}
// Close Div containing AJAX controls
Controls.Add(new Literal() { Text = "</div>" });
}
This approach gives me a clean and tidy HTML when rendered plus it’s easy to follow, debug and maintain. Now, I have all of the objects required inside a <DIV> and it’s AJAX enabled… The only missing thing is our UpdateProgress template (code is attached) which uses an animated GIF bundled in SharePoint.
Table retval = new Table() {
ID = "tblTopTable", CellPadding = 1,
CellSpacing = 0, Width = Unit.Percentage(100)
};
retval.Rows.AddRange(new TableRow[] {new TableRow(), new TableRow(),
new TableRow(), new TableRow(),
new TableRow(), new TableRow(),
new TableRow(), new TableRow(),
new TableRow()});
retval.Rows[ 8 ].Cells.AddRange(new TableCell[] { new TableCell() {
Width=Unit.Percentage(20)},
new TableCell() {
Width=Unit.Percentage(60)}});
// Update Progress
retval.Rows[ 8 ].Cells[0].ColumnSpan = 2;
retval.Rows[ 8 ].Cells[0].HorizontalAlign = HorizontalAlign.Left;
retval.Rows[ 8 ].Cells[0].Controls.Add(new UpdateProgress() {
ID = "workProgress",
ProgressTemplate = new UpdateProgressTemplate()
});
Ok… so far we’ve got AJAX working but what’s special about that? Well.. not much really but now we need to synchronize user’s selection on the client-side and reflect these changes on the server-side and to accomplish that we need some scripts (code is attached) and a couple of hidden fields which are referenced from our JavaScript as well as from our webpart code and for the sake of keeping things tidy we add them to the controls collection right after creating everything else (as depicted below)
protected override void CreateChildControls() {
CreateUI();
Controls.Add(new HiddenField() { ID = "selected_checkboxes",
EnableViewState = true });
Controls.Add(new HiddenField() { ID = "checkboxes_cleared",
EnableViewState = true });
ChildControlsCreated = true;
}
We also need to add some Javascript to support client-side operations so we do this on the OnPreRender method (AddJavaScriptToWebpart method is attached to the post)
protected override void OnPreRender(EventArgs e) {
if (!Page.ClientScript.IsClientScriptBlockRegistered(JSCRIPT_NAME))
Page.ClientScript.RegisterClientScriptBlock(typeof(string),
JSCRIPT_NAME, AddJavaScriptToWebpart());
}
Up to now we’ve met some of the user’s requirements but what about the GridView? Let’s talk about it then. The GridView is created by the following method
private GridView GetSearchResultsGrid() {
GridView retval = new GridView() {
ID = "grdSearchResults", AutoGenerateColumns = false,
AllowPaging = true, AllowSorting = true, Width = Unit.Percentage(100),
PageSize = 100,
EmptyDataText="<font color='red'><b>No results found</b></font>"
};
// Add Columns to the GridView
retval.Columns.Add(new BoundField() { DataField = "sapSearch",
HeaderText = "SAP Search",
SortExpression = "sapSearch" });
retval.Columns.Add(new BoundField() { DataField = "accountNo",
HeaderText = "Account No.",
SortExpression = "accountNo" });
retval.Columns.Add(new BoundField() { DataField = "accountName",
HeaderText = "Account Name",
SortExpression = "accountName" });
retval.Columns.Add(new BoundField() { DataField = "state",
HeaderText = "State",
SortExpression = "state" });
retval.Columns.Add(new TemplateField() {
ItemTemplate = new CheckBoxTemplate(ListItemType.Item),
HeaderTemplate = new CheckBoxTemplate(ListItemType.Header)
});
// Let's align to the centre the Order Block and State Columns
retval.Columns[3].ItemStyle.HorizontalAlign = HorizontalAlign.Center;
retval.Columns[4].ItemStyle.HorizontalAlign = HorizontalAlign.Center;
// Subscribe to events
retval.Sorting += grdSearchResults_Sorting;
retval.RowCreated += grdSearchResults_RowCreated;
retval.PageIndexChanging += grdResults_PageIndexChanging;
retval.RowDataBound += grdSearchResults_RowDataBound;
return retval;
}
The ticking/unticking of the checkboxes is handled by a Javascript call from CheckBoxTemplate (attached to the post) as shown below
private CheckBox GetTemplateContents() {
CheckBox retval = null;
switch (_type) {
case ListItemType.Header:
retval = new CheckBox() { ID = "chkHeader",
Text = "Account Block",
EnableViewState = true };
retval.Attributes["onclick"] = "BLOCKED SCRIPTcheckUncheckHeader(this);";
break;
case ListItemType.Item:
retval = new CheckBox() {ID = "chkItem_", EnableViewState = true };
retval.Attributes["onclick"] = "BLOCKED SCRIPTcheckUncheckItem(this);";
break;
}
return retval;
As previously mentioned, our Gridview had to support paging and sorting plus display an indicator for the current sorting criteria so I had to handle the RowCreated event as depicted below
private void grdSearchResults_RowCreated(object sender,
GridViewRowEventArgs e) {
int rowIndex = 0;
DataView sorted = null;
string strSortedHeader = string.Empty;
// Header
if (e.Row.RowType == DataControlRowType.Header) {
foreach (TableCell tc in e.Row.Cells) {
if (tc.Controls.Count > 0 && tc.Controls[0].GetType().ToString() ==
"System.Web.UI.WebControls.DataControlLinkButton") {
strSortedHeader = ((LinkButton)tc.Controls[0]).Text;
// Sort indicator (Webdings font does the job for us)
if (((LinkButton)tc.Controls[0]).CommandArgument ==
SortExpression) {
if (GridViewSortDirection == SortDirection.Descending)
((LinkButton)tc.Controls[0]).Text =
strSortedHeader.Replace(strSortedHeader,
strSortedHeader + "<font face='Webdings'>5</font>");
else
((LinkButton)tc.Controls[0]).Text =
strSortedHeader.Replace(strSortedHeader,
strSortedHeader + "<font face='Webdings'>6</font>");
}
}
}
} else if (e.Row.RowType == DataControlRowType.DataRow) { // DataRow
if (e.Row.Cells[e.Row.Cells.Count - 1].Controls.Count > 0 &&
SearchResults != null && SearchResults.Rows.Count > 0) {
sorted = new DataView(SearchResults);
sorted.Sort = GridViewSortCondition;
rowIndex = e.Row.DataItemIndex;
((CheckBox)e.Row.Cells[e.Row.Cells.Count - 1].Controls[0]).ID +=
sorted[e.Row.DataItemIndex]["accountNo"].ToString();
((CheckBox)e.Row.Cells[e.Row.Cells.Count - 1].Controls[0]).
Checked = (bool) sorted[e.Row.DataItemIndex]["isSelected"];
// Is it checked? (Non user interaction)
if (((CheckBox)e.Row.Cells[e.Row.Cells.Count - 1].
Controls[0]).Checked)
SelectedCheckBoxes += string.Format("{0};",
((CheckBox)e.Row.Cells[e.Row.Cells.Count - 1].
Controls[0]).ClientID);
}
}
}
Please note that we make a difference when creating/rendering the rows based on their type, for instance, the header is going to display an arrow to indicate sorting direction, otherwise we grab the values retrieved from the database (CRM) and change the checkboxes’ ID on the fly, by adding the account number to it (this is required to keep track of the user selection).
At this moment you’ll be wondering about, where is this guy grabbing the values set already from the client side and calling CRM? I’m pretty sure that many of you know the answer… The button click event handler.
private void btnUpdate_Click(object sender, EventArgs e) {
int rowIndex = 0;
int selectedCell = 0;
DataView sorted = null;
string[] splitData = null;
string selectedControl = string.Empty;
HiddenField clientSideSelection = null;
StringBuilder userSelection = new StringBuilder();
GridView grdSearchResults = FindControl("grdSearchResults") as GridView;
HiddenField checkboxes_cleared = FindControl("checkboxes_cleared") as
HiddenField;
// Is there any data to continue?
if ((SearchResults != null && SearchResults.Rows.Count > 0) &&
(grdSearchResults != null && grdSearchResults.Rows.Count > 0)) {
// Let's create a view to deal with the data as it is displayed
sorted = new DataView(SearchResults);
sorted.Sort = GridViewSortCondition;
// Let's sync both server and client checkboxes selection
ManageDeselectedItemsOnClientSide();
// Should we combine client-side selection with data from the DB?
if ((clientSideSelection = FindControl("selected_checkboxes") as HiddenField) != null
&& !string.IsNullOrEmpty(clientSideSelection.Value)) {
splitData = clientSideSelection.Value.Split(';');
var includeQuery = from checkBoxName in splitData.ToList()
.Where(controlName => !string.IsNullOrEmpty(controlName) &&
SelectedCheckBoxes.IndexOf(controlName) == -1 &&
controlName.IndexOf("_REMOVED") == -1)
select checkBoxName;
// Is there any item we must include?
if (includeQuery.ToList().Count > 0)
includeQuery.ToList().ForEach(controlToInclude =>
userSelection.Append(string.Format("{0};",
controlToInclude.Substring(controlToInclude.IndexOf("chkItem")))));
// Let's combine it with the information coming from the DB
userSelection.Append(SelectedCheckBoxes);
} else if (checkboxes_cleared != null && // Has the user interacted with the UI?
string.IsNullOrEmpty(checkboxes_cleared.Value))
userSelection.Append(SelectedCheckBoxes);
// Accounts to update
splitData = userSelection.ToString().Split(';');
// We loop through the control names collection
// (by default, we unblock those unselected checkboxes)
foreach (string checkBoxId in splitData) {
rowIndex = 0;
foreach (GridViewRow selectedRow in grdSearchResults.Rows) {
selectedCell = selectedRow.Cells.Count - 1;
// Is it the right one?
if (selectedRow.Cells[selectedCell].Controls.Count > 0 &&
selectedRow.Cells[selectedCell].Controls[0] is CheckBox) {
selectedControl = ((CheckBox)selectedRow.Cells[selectedCell].Controls[0]).ID;
if (selectedControl.Equals(checkBoxId)) {
// Account to block
sorted[rowIndex]["isSelected"] = true;
break;
} else if (!splitData.Contains(selectedControl)) {
// Account to unblock (default behaviour)
sorted[rowIndex]["isSelected"] = false;
}
}
rowIndex++;
}
}
// Block/Unblock accounts based on the user's selection
var accountsToProcess = from currentSelection in sorted.Table
.AsEnumerable()
select new {
AccountId = currentSelection["accountId"].ToString(),
IsSelected = (bool)currentSelection["isSelected"]
};
accountsToProcess.ToList().ForEach(account =>
OrderBlockManagement.updateAccount(account.AccountId,
account.IsSelected));
// Let's clear DB selection information
SelectedCheckBoxes = string.Empty;
// Let's reflect the changes on the UI
GridBindingHelper();
}
}
The final result is shown below

Our webpart integrating different systems as mentioned at the beginning of this post plus providing a responsive UI to the user.
Regards,
Angel
Hace un par de semanas atrás estaba atendiendo y presentando en Microsoft TechEd en Gold Coast, cuando de repente recibí una llamada del Gerente de Mercadeo y Ventas. La misión: Desarrollar un nuevo webpart para un portal B2B existente que integra SAP, MQ, CRM y webMethods a través SharePoint. El reto: Escribir código en Javascript para luego realizar operaciones del lado del servidor en base a la selección realizada por el usuario.
He estado desarrollando para SharePoint por un rato ya, pero si sabes como hacer las cosas con ASP.NET entonces no es díficil utilizar ese conocimiento y aplicarlos con SharePoint. Los requerimientos eran :
-
Permitir la entrada del usuario y validar del lado del navegador
-
Agregar AJAX para ofrecer una interfaz rápida a los usuarios
-
Obtener información almacenada del lado del cliente (navegador) desde el lado del servidor para realizar operaciones contra CRM
Así que comencemos por el principio explicando como lo hice
Propiedades requeridas
private DataTable SearchResults {
get {
return (ViewState["block_orders"] != null ?
(DataTable)ViewState["block_orders"] : null);
}
set {
ViewState["block_orders"] = value;
}
}
private string GridViewSortCondition {
get {
if (ViewState["SortCondition"] == null)
ViewState["SortCondition"] = "sapSearch ASC";
return ViewState["SortCondition"].ToString();
}
set {
ViewState["SortCondition"] = value;
}
}
private SortDirection GridViewSortDirection {
get {
if (ViewState["SortDirection"] == null)
ViewState["SortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["SortDirection"];
}
set {
ViewState["SortDirection"] = value;
}
}
private string SortExpression {
get {
return (ViewState["sort_exp"] != null ?
ViewState["sort_exp"].ToString() : string.Empty);
}
set {
ViewState["sort_exp"] = value;
}
}
private string SelectedCheckBoxes {
get {
return (ViewState["selected_check_boxes"] != null ?
ViewState["selected_check_boxes"].ToString() : string.Empty);
}
set {
ViewState["selected_check_boxes"] = value;
}
}
Necesito guardar los resultados de la búsqueda para que el usuario pueda paginar y ordenar estos
Ahora, prosigamos con el código requerido para agregar AJAX, en mi caso siempre separo/distribuyo el código que genera la interfaz de usuario en partes, es decir, tengo un método para generar la parte superior, media e inferior del webpart y como estoy implementando AJAX me gusta encerrar todo dentro de un <DIV> por lo que el código requerido es como éste
private void AddAJAXControls() {
Controls.Add(new Literal() { Text = "<div>", ID = "mainDiv" });
Controls.Add(new ScriptManager() { ID = "scriptManager_OrderBlock" });
Controls.Add(new Literal() { Text = InjectScriptToDisableDoublePostBack() });
Controls.Add(new UpdatePanel() { ID = "updatePanel_OrderBlock" });
}
Por favor nótese la llamada al método “InjectScriptToDisableDoublePostback”, el cuál es responsable de deshabilitar el control que generó el postback (por ejemplo, un botón enviar) así evito que el usuario lo presione más de una vez, el código es mostrado abajo
private string InjectScriptToDisableDoublePostBack() {
StringBuilder retval = new StringBuilder();
retval.AppendLine("<script type='text/javascript'>");
retval.AppendLine("var pbControl = null;");
retval.AppendLine("var prm = Sys.WebForms.PageRequestManager.getInstance();");
retval.AppendLine("prm.add_beginRequest(BeginRequestHandler);");
retval.AppendLine("prm.add_endRequest(EndRequestHandler);");
retval.AppendLine("function BeginRequestHandler(sender, args) {");
retval.AppendLine("//the control causing the postback");
retval.AppendLine("pbControl = args.get_postBackElement();");
retval.AppendLine("if (pbControl.id.indexOf('btnSearch') > -1 || ");
retval.AppendLine("pbControl.id.indexOf('btnUpdate') > -1 )");
retval.AppendLine("pbControl.disabled = true;");
retval.AppendLine("}");
retval.AppendLine("function EndRequestHandler(sender, args) {");
retval.AppendLine("pbControl.disabled = false;");
retval.AppendLine("pbControl = null;");
retval.AppendLine("}");
retval.AppendLine("</script>");
return retval.ToString();
}
El método responsable de poner todas las piezas juntas y dibujar el webpart es
protected virtual void CreateUI() {
UpdatePanel panel = null;
// Add AJAX controls
AddAJAXControls();
if ((panel = FindControl("updatePanel_OrderBlock") as UpdatePanel) != null) {
// Top Table
panel.ContentTemplateContainer.Controls.Add(GetTopTable());
// Bottom Table
panel.ContentTemplateContainer.Controls.Add(GetBottomTable());
}
// Close Div containing AJAX controls
Controls.Add(new Literal() { Text = "</div>" });
}
Este método me genera un HTML limpio y ordenado cuando el webpart es dibujado además es fácil de seguir, depurar y mantener. Ahora, todos los objetos requeridos están dentro del <DIV> y ya agregué AJAX… La única cosa que me falta es nuestra plantilla de progreso (código adjunto) que utiliza un GIF animado que viene con SharePoint.
Table retval = new Table() {
ID = "tblTopTable", CellPadding = 1,
CellSpacing = 0, Width = Unit.Percentage(100)
};
retval.Rows.AddRange(new TableRow[] {new TableRow(), new TableRow(),
new TableRow(), new TableRow(),
new TableRow(), new TableRow(),
new TableRow(), new TableRow(),
new TableRow()});
retval.Rows[ 8 ].Cells.AddRange(new TableCell[] { new TableCell() {
Width=Unit.Percentage(20)},
new TableCell() {
Width=Unit.Percentage(60)}});
// Update Progress
retval.Rows[ 8 ].Cells[0].ColumnSpan = 2;
retval.Rows[ 8 ].Cells[0].HorizontalAlign = HorizontalAlign.Left;
retval.Rows[ 8 ].Cells[0].Controls.Add(new UpdateProgress() {
ID = "workProgress",
ProgressTemplate = new UpdateProgressTemplate()
});
Bueno… hasta ahora tenemos el AJAX trabajando con nuestro webpart pero, ¿qué es lo especial de eso? Bien... no mucho en realidad pero ahora necesitamos sincronizar la selección realizada por el usuario del lado del cliente y reflejar estos cambios del lado del servidor, así que para lograr eso necesitamos escribir unos scripts (código adjunto) y un par de campos ocultos que son referenciados desde nuestro código en JavaScript y del webpart también, por lo que en aras de mantener las cosas ordenadas y simples, agregamos estos a la colección de controles del webpart una vez que ya hemos creado todo lo demás (como se muestra abajo)
protected override void CreateChildControls() {
CreateUI();
Controls.Add(new HiddenField() { ID = "selected_checkboxes",
EnableViewState = true });
Controls.Add(new HiddenField() { ID = "checkboxes_cleared",
EnableViewState = true });
ChildControlsCreated = true;
}
También necesitamos agregar JavaScript para soportar operaciones del lado del cliente por lo que sobrescribimos el método OnPreRender (El método AddJavaScriptToWebpart está adjunto a este post)
protected override void OnPreRender(EventArgs e) {
if (!Page.ClientScript.IsClientScriptBlockRegistered(JSCRIPT_NAME))
Page.ClientScript.RegisterClientScriptBlock(typeof(string),
JSCRIPT_NAME, AddJavaScriptToWebpart());
}
Hasta ahora hemos satisfecho algunos de los requerimientos solicitados por el usuario, pero ¿qué pasó con el GridView? Hablemos del GridView entonces. El GridView es creado por el siguiente método
private GridView GetSearchResultsGrid() {
GridView retval = new GridView() {
ID = "grdSearchResults", AutoGenerateColumns = false,
AllowPaging = true, AllowSorting = true, Width = Unit.Percentage(100),
PageSize = 100,
EmptyDataText="<font color='red'><b>No results found</b></font>"
};
// Add Columns to the GridView
retval.Columns.Add(new BoundField() { DataField = "sapSearch",
HeaderText = "SAP Search",
SortExpression = "sapSearch" });
retval.Columns.Add(new BoundField() { DataField = "accountNo",
HeaderText = "Account No.",
SortExpression = "accountNo" });
retval.Columns.Add(new BoundField() { DataField = "accountName",
HeaderText = "Account Name",
SortExpression = "accountName" });
retval.Columns.Add(new BoundField() { DataField = "state",
HeaderText = "State",
SortExpression = "state" });
retval.Columns.Add(new TemplateField() {
ItemTemplate = new CheckBoxTemplate(ListItemType.Item),
HeaderTemplate = new CheckBoxTemplate(ListItemType.Header)
});
// Let's align to the centre the Order Block and State Columns
retval.Columns[3].ItemStyle.HorizontalAlign = HorizontalAlign.Center;
retval.Columns[4].ItemStyle.HorizontalAlign = HorizontalAlign.Center;
// Subscribe to events
retval.Sorting += grdSearchResults_Sorting;
retval.RowCreated += grdSearchResults_RowCreated;
retval.PageIndexChanging += grdResults_PageIndexChanging;
retval.RowDataBound += grdSearchResults_RowDataBound;
return retval;
}
La selección/de-selección de las casillas de verificación es manejado por una llamada a una función en JavaScript, realizada desde CheckBoxTemplate (adjunto al post) como es mostrado abajo
private CheckBox GetTemplateContents() {
CheckBox retval = null;
switch (_type) {
case ListItemType.Header:
retval = new CheckBox() { ID = "chkHeader",
Text = "Account Block",
EnableViewState = true };
retval.Attributes["onclick"] = "BLOCKED SCRIPTcheckUncheckHeader(this);";
break;
case ListItemType.Item:
retval = new CheckBox() {ID = "chkItem_", EnableViewState = true };
retval.Attributes["onclick"] = "BLOCKED SCRIPTcheckUncheckItem(this);";
break;
}
return retval;
Como mencionamos previamente, nuestro GridVied tenía que soportar paginación y ordenamiento además de mostrar un indicador para el criterio de ordenamiento actual así que tuve que manejar el evento RowCreated event como se muestra a continuación
private void grdSearchResults_RowCreated(object sender,
GridViewRowEventArgs e) {
int rowIndex = 0;
DataView sorted = null;
string strSortedHeader = string.Empty;
// Header
if (e.Row.RowType == DataControlRowType.Header) {
foreach (TableCell tc in e.Row.Cells) {
if (tc.Controls.Count > 0 && tc.Controls[0].GetType().ToString() ==
"System.Web.UI.WebControls.DataControlLinkButton") {
strSortedHeader = ((LinkButton)tc.Controls[0]).Text;
// Sort indicator (Webdings font does the job for us)
if (((LinkButton)tc.Controls[0]).CommandArgument ==
SortExpression) {
if (GridViewSortDirection == SortDirection.Descending)
((LinkButton)tc.Controls[0]).Text =
strSortedHeader.Replace(strSortedHeader,
strSortedHeader + "<font face='Webdings'>5</font>");
else
((LinkButton)tc.Controls[0]).Text =
strSortedHeader.Replace(strSortedHeader,
strSortedHeader + "<font face='Webdings'>6</font>");
}
}
}
} else if (e.Row.RowType == DataControlRowType.DataRow) { // DataRow
if (e.Row.Cells[e.Row.Cells.Count - 1].Controls.Count > 0 &&
SearchResults != null && SearchResults.Rows.Count > 0) {
sorted = new DataView(SearchResults);
sorted.Sort = GridViewSortCondition;
rowIndex = e.Row.DataItemIndex;
((CheckBox)e.Row.Cells[e.Row.Cells.Count - 1].Controls[0]).ID +=
sorted[e.Row.DataItemIndex]["accountNo"].ToString();
((CheckBox)e.Row.Cells[e.Row.Cells.Count - 1].Controls[0]).
Checked = (bool) sorted[e.Row.DataItemIndex]["isSelected"];
// Is it checked? (Non user interaction)
if (((CheckBox)e.Row.Cells[e.Row.Cells.Count - 1].
Controls[0]).Checked)
SelectedCheckBoxes += string.Format("{0};",
((CheckBox)e.Row.Cells[e.Row.Cells.Count - 1].
Controls[0]).ClientID);
}
}
}
Por favor, nótese la diferencia cuando se está creando/dibujando las filas basadas en su tipo, es decir, el encabezado va a mostrar una flecha que indica la dirección de ordenamiento, de lo contrario, tomamos los valores recuperados de la base de datos (CRM) y cambiamos el ID de las casillas de verificación en tiempo de ejecución, al agregar el número de cuenta a éste (esto es requerido para hacer seguimiento de la selección del usuario)
En este momento se estarán preguntando, ¿en donde se toman los valores almacenados del lado del cliente y se llama a CRM? Estoy seguro que muchos saben la respuesta… El manejador del evento click del botón.
private void btnUpdate_Click(object sender, EventArgs e) {
int rowIndex = 0;
int selectedCell = 0;
DataView sorted = null;
string[] splitData = null;
string selectedControl = string.Empty;
HiddenField clientSideSelection = null;
StringBuilder userSelection = new StringBuilder();
GridView grdSearchResults = FindControl("grdSearchResults") as GridView;
HiddenField checkboxes_cleared = FindControl("checkboxes_cleared") as
HiddenField;
// Is there any data to continue?
if ((SearchResults != null && SearchResults.Rows.Count > 0) &&
(grdSearchResults != null && grdSearchResults.Rows.Count > 0)) {
// Let's create a view to deal with the data as it is displayed
sorted = new DataView(SearchResults);
sorted.Sort = GridViewSortCondition;
// Let's sync both server and client checkboxes selection
ManageDeselectedItemsOnClientSide();
// Should we combine client-side selection with data from the DB?
if ((clientSideSelection = FindControl("selected_checkboxes") as HiddenField) != null
&& !string.IsNullOrEmpty(clientSideSelection.Value)) {
splitData = clientSideSelection.Value.Split(';');
var includeQuery = from checkBoxName in splitData.ToList()
.Where(controlName => !string.IsNullOrEmpty(controlName) &&
SelectedCheckBoxes.IndexOf(controlName) == -1 &&
controlName.IndexOf("_REMOVED") == -1)
select checkBoxName;
// Is there any item we must include?
if (includeQuery.ToList().Count > 0)
includeQuery.ToList().ForEach(controlToInclude =>
userSelection.Append(string.Format("{0};",
controlToInclude.Substring(controlToInclude.IndexOf("chkItem")))));
// Let's combine it with the information coming from the DB
userSelection.Append(SelectedCheckBoxes);
} else if (checkboxes_cleared != null && // Has the user interacted with the UI?
string.IsNullOrEmpty(checkboxes_cleared.Value))
userSelection.Append(SelectedCheckBoxes);
// Accounts to update
splitData = userSelection.ToString().Split(';');
// We loop through the control names collection
// (by default, we unblock those unselected checkboxes)
foreach (string checkBoxId in splitData) {
rowIndex = 0;
foreach (GridViewRow selectedRow in grdSearchResults.Rows) {
selectedCell = selectedRow.Cells.Count - 1;
// Is it the right one?
if (selectedRow.Cells[selectedCell].Controls.Count > 0 &&
selectedRow.Cells[selectedCell].Controls[0] is CheckBox) {
selectedControl = ((CheckBox)selectedRow.Cells[selectedCell].Controls[0]).ID;
if (selectedControl.Equals(checkBoxId)) {
// Account to block
sorted[rowIndex]["isSelected"] = true;
break;
} else if (!splitData.Contains(selectedControl)) {
// Account to unblock (default behaviour)
sorted[rowIndex]["isSelected"] = false;
}
}
rowIndex++;
}
}
// Block/Unblock accounts based on the user's selection
var accountsToProcess = from currentSelection in sorted.Table
.AsEnumerable()
select new {
AccountId = currentSelection["accountId"].ToString(),
IsSelected = (bool)currentSelection["isSelected"]
};
accountsToProcess.ToList().ForEach(account =>
OrderBlockManagement.updateAccount(account.AccountId,
account.IsSelected));
// Let's clear DB selection information
SelectedCheckBoxes = string.Empty;
// Let's reflect the changes on the UI
GridBindingHelper();
}
}
El resultado final es mostrado abajo
Nuestro webpart integrando diferentes sistemas como mencioné al principio del post además de proveer una interfaz rápida al usuario.
Saludos,
Angel
Structured Exception Handling (SEH), it’s one of the top used features by developers, it’s not required any more to be dealing with On Error labels or any other less elegant mechanism to handle error conditions, however .NET Framework is an existing layer between our application and the operating system, even when the Exception class describes an error condition it doesn’t provide the error code and message associated to the operating system, that’s why it’s frustrating sometimes to interpret some “less-descriptive” exceptions and hence recovering any Windows error information can be of great help. Throughout the years Windows API has evolved and grown in size and error messages as well, many of these messages can be found in the SDK and WDK, so I had this idea about extending the Exception class by implementing an extension method. Extension methods enable us to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. They are a special kind of static method, but they are called as if they were instance methods on the extended type. The most common extension methods are the LINQ standard query operators that add query functionality to the existing IEnumerable and IEnumerable<T>.
To retrieve the description for a given error code we use the FormatMessage function, as it’s shown below
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true,
CallingConvention = CallingConvention.Winapi)]
public static extern int FormatMessage(int dwFlags, int lpSource, int dwMessageId,
int dwLanguageId, out StringBuilder lpBuffer,
int nSize, IntPtr va_list);
The extension method used is the following
public static class ExceptionExtension {
/// <summary>
/// Gets the win32 error description.
/// </summary>
/// <param name="ex">The ex.</param>
/// <returns></returns>
public static Win32Error GetWin32ErrorDescription(this Exception ex) {
Win32Error retval = Win32Error.Empty;
StringBuilder pMsgBuf = new StringBuilder();
int lastError = FormatErrorHelper.GetLastError();
FormatErrorHelper.FormatMessage(
FormatErrorHelper.FORMAT_MESSAGE_ALLOCATE_BUFFER |
FormatErrorHelper.FORMAT_MESSAGE_FROM_SYSTEM,
FormatErrorHelper.NULL, lastError,
FormatErrorHelper.MakeLangID(FormatErrorHelper.LANG_NEUTRAL,
FormatErrorHelper.SUBLANG_DEFAULT), out pMsgBuf, 0, IntPtr.Zero);
retval.ErrorCode = lastError;
retval.Description = pMsgBuf != null ? pMsgBuf.ToString() : string.Empty;
return retval;
}
}
So if we catch any exception, besides obtaining the exception object itself we get the error and message code from the operating system
Win32Error osError = Win32Error.Empty;
// Some funky exception here...
osError = ex.GetWin32ErrorDescription();
Console.WriteLine(string.Format("Code: {0} - Description: {1}",
new object[] {osError.ErrorCode, osError.Description}));
If we implement everything we’ve previously mentioned, see the difference between the exception message and the message provided by the operating system
Hope this helps,
Regards,
Angel