Silverlight can also retrieve datasets from a non-entity set from WCF.

Source: Internet
Author: User
Create a project and return the queried dataset if the database, table name, and column name are unknown. This is easy to implement in ASP. NET or C/S mode. However, it cannot be implemented in the existing SL + WCF technology. The return value is hard to determine first, and the return value type of WCF must be determined. The comparison return value is of the object type. Besides, datatable and dataset cannot be returned. If the customer fails to receive the data, the returned data type is object. Then, we can get the dataset in a common way, convert the dataset to a string in XML format, and resolve the string to the type dataset on the client side.
In fact, the work of converting a dataset into a string in XML format and parsing a string in XML format into a dataset has already completed business logic Encapsulation by Canadian counterparts, we only need to call the method in it. You can also decompile it to see what foreigners do. Code The original address of a foreigner is http://silverlightdataset.net/silverlightdataset/default.aspx. the used parts are silverlight.datasetconnector.dll (used by the server) and Silverlight. dataset. dll (used by the client)
Below is the server's Program

/// <Summary>
/// Obtain the dataset
/// </Summary>
/// <Param name = "strdatabase"> server name </param>
/// <Param name = "strdatatable"> table name </param>
/// <Param name = "data"> XML format </param>
/// <Param name = "page"> current page </param>
/// <Param name = "pagecount"> total number of pages </param>
/// <Param name = "strtablekeys"> table primary key </param>
/// <Param name = "strtableorder"> arrange fields </param>
/// <Returns> </returns>
Public String getalloriginalmetadata (string strdatabase, string strdatatable, string data, int page, out int pagecount, string strtablekeys, string strtableorder)
{
Pagecount = 0;
Try
{
Dataset dataset = connector. fromxml (data );
// Due to the uncertainty of the database and data table, you can directly access the database without using LINQ.
Using (sqlconnection = new sqlconnection (configurationmanager. connectionstrings ["metadataconnectionstring"]. connectionstring ))
{
Try
{
// Determine whether the connection is enabled
If (sqlconnection. State = connectionstate. Closed)
{
Sqlconnection. open ();
}
String strtable = strdatabase + ". DBO." + strdatatable;
// Determine whether to load data for the first time. If yes, obtain the total number of pages.
If (page =-1)
{
String strsql = "select count (*) as rowscount from" + strtable;
Sqlcommand sccount = new sqlcommand (strsql, sqlconnection );
Pagecount = convert. toint32 (sccount. executescalar ());
Page + = 2;
}

Sqlcommand SC = new sqlcommand ();
// Use the Stored Procedure
SC. commandtype = commandtype. storedprocedure;
// Name of the stored procedure
SC. commandtext = "prcpager ";
SC. Connection = sqlconnection;

// Stored procedure parameters
Sqlparameter [] parameters = {
New sqlparameter ("@ currpage", sqldbtype. Int, 4), // current page
New sqlparameter ("@ tabname", sqldbtype. nvarchar, 2000), // table name
New sqlparameter ("@ asccolumn", sqldbtype. nvarchar, 100), // sorting Field
New sqlparameter ("@ bitordertype", sqldbtype. Bit ),
New sqlparameter ("@ pkcolumn", sqldbtype. nvarchar, 100) // primary key field
};
Parameters [0]. value = page;

Parameters [1]. value = strtable;

Parameters [2]. value = strtableorder;

Parameters [3]. value = 1;

Parameters [4]. value = strtablekeys;

SC. Parameters. addrange (parameters );

Sqldataadapter = new sqldataadapter ();
Sqldataadapter. selectcommand = SC;
Sqldataadapter. Fill (dataset, "tablename ");
// Return string data in XML format
Return connector. toxml (Dataset );
}
Catch (exception E)
{
Accesslog. writelog (E. Message );
Return NULL;
}
Finally
{
Sqlconnection. Close ();
}
}
}
Catch (exception E)
{
// Accesslog. writelog (E. Message );
Return NULL;
}
}

Because the returned collection is a string in XML format, if the data volume is too large, it may take up a lot of bandwidth or time out. Therefore, use pagination. The data set returned each time is the current data set.
The following is the paging stored procedure.

If exists (Select name from sysobjects where name = 'prcpager 'and type = 'P ')
Drop procedure prcpager
Go
Create procedure prcpager
-- Get data on a page --
@ Currpage Int = 1, -- current page number (that is, top currpage)
@ Showcolumn varchar (2000) = '*', -- the expected field (column1, column2 ,......)
@ Tabname varchar (2000), -- Name of the table to be viewed (from table_name)
@ Strcondition varchar (2000) = '', -- the query condition (where condition...) does not need to be added with the where keyword.
@ Asccolumn varchar (100) = '', -- Name of the sorted field (that is, order by column ASC/DESC)
@ Bitordertype bit = 0, --- sort type (0 is ascending, 1 is descending)
@ Pkcolumn varchar (100) = '', -- primary key name
@ Pagesize Int = 20 -- page size
As
Begin -- starts the Stored Procedure
-- Several variables required for the stored procedure
Declare @ strsql varchar (4000) -- the last statement executed by the Stored Procedure
Declare @ strordertype varchar (1000) -- sort type Statement (order by column ASC or order by column DESC)
Begin
If @ bitordertype = 1 -- bitordertype = 1: Execute descending order
Begin
Set @ strordertype = 'ORDER BY' + @ asccolumn + 'desc'
End
Else
Begin
Set @ strordertype = 'ORDER BY' + @ asccolumn + 'asc'
End
If @ currpage = 1 -- if it is the first page
Begin
If @ strcondition! =''
Set @ strsql = 'select top' + STR (@ pagesize) + ''+ @ showcolumn + 'from' + @ tabname +
'Where' + @ strcondition + @ strordertype
Else
Set @ strsql = 'select top' + STR (@ pagesize) + ''+ @ showcolumn + 'from' + @ tabname + @ strordertype
End
Else -- other pages
Begin
If @ strcondition! =''
Set @ strsql = 'select top '+ STR (@ pagesize) + ''+ @ showcolumn + 'from (select top' + STR (@ currpage * @ pagesize) + @ showcolumn + 'from'
+ @ Tabname + 'where ('+ @ strcondition +') '+ @ strordertype + ') as temp where '+ @ pkcolumn +' not in (select top '+ STR (@ currPage-1) * @ pagesize)
+ ''+ @ Pkcolumn + 'from' + @ tabname + 'where ('+ @ strcondition +') '+ @ strordertype + ')'
Else
Set @ strsql = 'select top '+ STR (@ pagesize) + ''+ @ showcolumn + 'from (select top' + STR (@ currpage * @ pagesize) + @ showcolumn + 'from' + @ tabname + @ strordertype + ') as temp'
+ 'Where' + @ pkcolumn + 'not in (select top' + STR (@ currPage-1) * @ pagesize) + ''+ @ pkcolumn + 'from' + @ tabname + @ strordertype + ')'
End
End
Exec (@ strsql)
-- Print @ strsql
End -- end of Stored Procedure
Go

The following describes the client. In fact, according to the Code of the Canadian dude, you only need to use the following code.

A) add reference to Silverlight. dataset. dll from Silverlight application project and "using" directive to your page:

using Silverlight;

B) Create Silverlight dataset and send it to server;

dataset = new dataset ();

// cretate datatables, datacolumns, and add datarows...

// use your knowledge about ADO. Net dataset for this task

// call WCF Service

proxy. processrequestasync (Dataset. toxml (true);

C) receive response from server:
void proxy_processrequestcompleted (Object sender, processrequestcompletedeventargs e)

{

// create Silverlight dataset from XML string

dataset = new dataset ();

dataset. fromxml (E. Result);

// process server response here

}

However, the SL DataGrid does not accept dataset or able data sources. Instead, it accepts the real-time collection. Therefore, we need to extend the SL DataGrid to the dataview in ASP. NET, which has the datasource attribute and the databind method. This hasSource codeYou can download it. You can expand it as needed. Is: bytes.
So the method I want to implement is to first use the same method in Canada to parse the string in XML format into its dataset, and then convert the value of this dataset to the Extended Dataset type. See the code below

Public void getallforigialmetadata (string strdatabase, string strdatatable, string strdatatablekeys, string strdatatableorder, int pageindex)
{
Dataset dataset = new dataset ();
// Client class
Metadataserviceclient MSC = new metadataserviceclient ();
MSC. endpoint. Address = utility. processserviceaddress (MSC. endpoint. Address );
MSC. getalloriginalmetadatacompleted + = new eventhandler <getalloriginalmetadatacompletedeventargs> (
(O, e) =>
{
Dataset datasets = new dataset ();
// Use the interface to resolve the data transmitted from the server to the dataset Dataset
Datasets. fromxml (E. Result );
DS = datasets;
_ Pagecount = E. pagecount;
If (oncompleted! = NULL)
{
Oncompleted ();
}
Oncompleted = NULL;
}
);
MSC. getalloriginalmetadataasync (strdatabase, strdatatable, dataset. toxml (true), pageindex, strdatatablekeys, strdatatableorder );
}

/// <Summary>
/// Initialize data
/// </Summary>
/// <Param name = "pageindex"> current page number. If the value is-1, the data is loaded for the first time. </param>
Private void initdata (INT pageindex)
{
Windows Ws = new windows (this. findname ("Waiting") as waiting );
Windows. showwaitingofchild ();
// Convert parameters into Arrays
String [] arr = convert. tostring (TAG). Split ('| ');
Forigialmetadata fomd = new forigialmetadata ();
Fomd. oncompleted + = new forigialmetadata. oncomplete (
() =>
{
String strcaption = string. empty;
// Initialize the extended datatable
Data. datatable dt = new data. datatable ("mydatatable ");
Fomd. oncompletedcols + = new forigialmetadata. oncomplete (
() =>
{
// Column data set
_ List = fomd. List;
String STR = "varchar ";
// Initialize the DT variable Column Based on the original data column
Foreach (Silverlight. datacolumn DC in fomd. forigialmetadataset. Tables [0]. columns)
{
List <tbdatacolumns> TDC = NULL;
// If the column set exists
If (_ list. Count> 0)
{
TDC = _ list. Where (t => T. cnvccolumnename = Dc. columnname). tolist <tbdatacolumns> ();
// If the queried column does not exist, continue
If (TDC. Count = 0)
Continue;
// Assign a value to the Chinese column name and type
Strcaption = TDC. elementat (0). cnvccolumnname;
STR = TDC. elementat (0). cnvcdatatype;
}
Else // a set of non-existing columns
{
Strcaption = Dc. columnname;
}
Data. datacolumn dcchild = new hieg2.portal. Data. datacolumn (DC. columnname, strcaption, true, STR );
DT. Columns. Add (dcchild );
}
// Copy the data of each row
Foreach (Silverlight. datarow DR in fomd. forigialmetadataset. Tables [0]. Rows)
{
Data. datarow drchild = new hieg2.portal. Data. datarow ();
Foreach (data. datacolumn DC in DT. columns)
{
// When the data type is datetime, it needs to be formatted as yyyy-mm-dd hh: mm: SS
If (DC. strdatatype. tolower () = "datetime ")
{
If (convert. tostring (Dr [DC. columnname])! = "")
Drchild [DC. columnname] = convert. todatetime (Dr [DC. columnname]). tostring ("yyyy-mm-dd hh: mm: SS ");
Else
Drchild [DC. columnname] = "";
Continue;
}
Drchild [DC. columnname] = Dr [DC. columnname];
}
DT. Rows. Add (drchild );
}
Data. dataset DS = new data. dataset ("mydataset ");
DS. Tables. Add (DT );
// Assign the data source to the table set
Radgridview. datasource = Ds;
Radgridview. datamember = "mydatatable ";
// Bind data
Radgridview. databind ();
// When loading for the first time, you need to set pagination
If (pageindex =-1)
{
Raddatapager. bindsource (fomd. pagecount, pagesize );
Raddatapager. pageindexchanged-= new eventhandler <eventargs> (dpemployee_pageindexchanged );
Raddatapager. pageindexchanged + = new eventhandler <eventargs> (dpemployee_pageindexchanged );
}
Windows. hidewaitingofchild ();
}
);
Fomd. getallorigialmetadatacols (ARR [0]);

}
);
// Obtain the raw data of the current page
Fomd. getallforigialmetadata (ARR [1], arr [2], arr [3], arr [4], pageindex );
}
Void dpemployee_pageindexchanged (Object sender, eventargs E)
{
Initdata (raddatapager. pageindex + 1 );
}
}

In fact, the above method can be used to obtain a dataset from WCF on the SL end without being sure about the database and data table. However, there is another area to be extended, that is, datapager. For specific implementation, see commit.

Public static class datapageextension
{
Public static void bindsource (this datapager, int totalcount, int pagesize)
{
List <int> List = new list <int> (totalcount );
For (INT I = 0; I <totalcount; I ++) List. Add (I );
Pagedcollectionview PCV = new pagedcollectionview (list );
PCV. pagesize = pagesize;
Datapager. Source = PCV;
}
}

Well, I wrote this article today. If you have any questions, let's talk about it. If you have any shortcomings, please point out.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.