Android pairing to custom USB bluetooth adapter - bluetooth

Is it possible to force a legacy fixed pin entry when pairing an android to a custom USB adapter, such as the DKBT111. Looking at SSP and the "Just works" pairing, this doesn't seem to satisfy the security requirement I am working with.
I would like to guarantee no one can attempt to pair with the USB device while it is discoverable without a fixed, preset PIN. I am having trouble configuring the controller using bluetoothctl and Bluez. The best I can get is the 6 digit passkey comparison, but I won't have a display for the code on the box the usb will be connected to.
What settings do I have to change to be able to set a PIN for the server, and any phone needs to type it in to pair?
I am using Bluez on tinycore.

To achieve such scenario you may need to implement custom agent. As you don't have Display, you have to choose one of the capability of your device from the options.
Bluez always expects minimum 6 digit PIN key, if you want to restrict yourself to 4 digit PIN, then you should pad using "0"'s as specified here.
For your custom agent, you need to implement either "DisplayPinCode" or "DisplayPasskey" method returning fixed PIN and registering it using "RegisterAgent".
For restricting only your Android device, you can compare your device MAC address in DisplayPinCode/DisplayPasskey, which gets the MAC address of the device which is requesting pairing as "First Argument object device".
Note that the "object device" is MAC address as object path i.e /org/bluez/hciX/dev_AA_BB_CC_XX_YY_ZZ format.
#include <glib.h>
#include <gio/gio.h>
#include "agent.h"
#define AGENT_PATH "/org/bluez/AutoPinAgent"
static void bluez_agent_method_call(GDBusConnection *conn,
const gchar *sender,
const gchar *path,
const gchar *interface,
const gchar *method,
GVariant *params,
GDBusMethodInvocation *invocation,
void *userdata)
{
g_print("Agent method call: %s.%s()", interface, method);
}
static const GDBusInterfaceVTable agent_method_table = {
.method_call = bluez_agent_method_call,
};
int bluez_register_agent(GDBusConnection *con)
{
GError *error = NULL;
guint id = 0;
GDBusNodeInfo *info = NULL;
static const gchar bluez_agent_introspection_xml[] =
"<node name='/org/bluez/SampleAgent'>"
" <interface name='org.bluez.Agent1'>"
" <method name='Release'>"
" </method>"
" <method name='RequestPinCode'>"
" <arg type='o' name='device' direction='in' />"
" <arg type='s' name='pincode' direction='out' />"
" </method>"
" <method name='DisplayPinCode'>"
" <arg type='o' name='device' direction='in' />"
" <arg type='s' name='pincode' direction='in' />"
" </method>"
" <method name='RequestPasskey'>"
" <arg type='o' name='device' direction='in' />"
" <arg type='u' name='passkey' direction='out' />"
" </method>"
" <method name='DisplayPasskey'>"
" <arg type='o' name='device' direction='in' />"
" <arg type='u' name='passkey' direction='in' />"
" <arg type='q' name='entered' direction='in' />"
" </method>"
" <method name='RequestConfirmation'>"
" <arg type='o' name='device' direction='in' />"
" <arg type='u' name='passkey' direction='in' />"
" </method>"
" <method name='RequestAuthorization'>"
" <arg type='o' name='device' direction='in' />"
" </method>"
" <method name='AuthorizeService'>"
" <arg type='o' name='device' direction='in' />"
" <arg type='s' name='uuid' direction='in' />"
" </method>"
" <method name='Cancel'>"
" </method>"
" </interface>"
"</node>";
info = g_dbus_node_info_new_for_xml(bluez_agent_introspection_xml, &error);
if(error) {
g_printerr("Unable to create node: %s\n", error->message);
g_clear_error(&error);
return 0;
}
id = g_dbus_connection_register_object(con,
AGENT_PATH,
info->interfaces[0],
&agent_method_table,
NULL, NULL, &error);
g_dbus_node_info_unref(info);
//g_dbus_connection_unregister_object(con, id);
return id;
}
The above example is incomplete template without any specific methods. You need to implement "DisplayPinCode/DisplayPasskey" inside "bluez_agent_method_call" based on "method" name, which comes as argument.
EDIT: Same example for Fixed PIN with more details answered in this question. Adding it for future reference and completeness.

Related

.netcore on linux odbc connection to hive

I'm trying to connect to Hive from .netcore (v. 1.0.1) app on linux (Red Hat 7.3 64-bit).
Program.cs code:
using System;
using System.Data.Odbc;
using System.Collections;
using System.Collections.Generic;
namespace app
{
class Program
{
static void Main(string[] args)
{
var connectionString = "DSN=Hadoop Hive";
var createTableCommandText = "CREATE TABLE Searches(searchTerm STRING, userid BIGINT,userIp STRING) " +
"COMMENT 'Stores all searches for data' " +
"PARTITIONED BY(searchTime DATE) " +
"STORED AS SEQUENCEFILE;";
using (var connection = new OdbcConnection(connectionString))
{
using (var command = new OdbcCommand(createTableCommandText, connection))
{
try
{
connection.Open();
// Create a table.
command.ExecuteNonQuery();
// Insert row of data.
command.CommandText = "INSERT INTO TABLE Searches PARTITION (searchTime = '2015-02-08') " +
"VALUES ('search term', 1, '127.0.0.1')";
command.ExecuteNonQuery();
// Reading data from Hadoop.
command.CommandText = "SELECT * FROM Searches";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
for (var i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader[i]);
}
}
}
}
catch (OdbcException ex)
{
Console.WriteLine(ex.Message);
throw;
}
finally
{
Drop table
command.CommandText = "DROP TABLE Searches";
command.ExecuteNonQuery();
}
}
}
My project settings file:
app.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
<PackageId>HadoopLibrary</PackageId>
<NetStandardImplicitPackageVersion>1.6.0</NetStandardImplicitPackageVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Data.Common" Version="4.3.0" />
<PackageReference Include="System.Threading.Thread" Version="4.3.0" />
<PackageReference Include="System.Collections.NonGeneric" Version="4.0.1" />
<PackageReference Include="MSA.NetCore.ODBC" Version="1.0.3" />
</ItemGroup>
When running "dotnet run" I receive the following error:
Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'odbc32.dll': The specified module could not be found.
(Exception from HRESULT: 0x8007007E)
at System.Data.Odbc.libodbc.SQLAllocHandle(OdbcHandleType HandleType, IntPtr InputHandle, IntPtr& OutputHandlePtr)
at System.Data.Odbc.OdbcConnection.Open()
at hwapp.Program.Main(String[] args)
Can anyone help how to fix that? The driver (Hortonworks ODBC for Hive) works on this server. There is an issue with the library for ODBC connection here.
it looks like you are trying to build and load it as a 32-bit application and that's what Hortonworks ODBC for Hive may not support. Need to check the documentation of Hortonworks for that.

Telerik grid updates not working in batch editing

I'm using RadGrid in ASPX, .net 4.5. The data comes up and displays in my grid fine, but I cannot update, insert, or delete records. I have followed the sample version as closely as I can:
http://demos.telerik.com/aspnet-ajax/grid/examples/data-editing/batch-editing/defaultcs.aspx
When I try to modify data in the grid, then hit Save, the grid reloads and the data is unchanged. No errors, just no updates.
Originally I had the grid wrapped in ajax panel, but when these problems occurred, I removed it. That made not much difference; though when I was using ajax panel, often times clicking the Save icon did absolutely nothing. Or appeared to do nothing. So with that gone, the page/grid does normal postbacks EXCEPT that none of my event handlers are being called. Page_Load gets called, but nothing else (for example RadGrid1_BatchEditCommand, RadGrid1_ItemUpdated). It seems these should be getting called.
ASPX code:
<telerik:RadScriptManager runat="server" ID="RadScriptManager1" />
<telerik:RadListBox runat="server" ID="SavedChangesList" Width="600px" Height="200px" Visible="false"></telerik:RadListBox>
<telerik:RadGrid ID="RadGrid1" GridLines="None" runat="server" AllowAutomaticDeletes="True"
AllowAutomaticInserts="True" PageSize="10" Skin="Default" OnItemDeleted="RadGrid1_ItemDeleted" OnItemInserted="RadGrid1_ItemInserted"
OnItemUpdated="RadGrid1_ItemUpdated" OnPreRender="RadGrid1_PreRender" AllowAutomaticUpdates="True" AllowPaging="True"
AutoGenerateColumns="False" Width="1000px" OnBatchEditCommand="RadGrid1_BatchEditCommand" DataSourceID="sqlContractMatrix">
<MasterTableView CommandItemDisplay="TopAndBottom" DataKeyNames="ID" DataSourceID="sqlContractMatrix" HorizontalAlign="NotSet" EditMode="Batch" AutoGenerateColumns="False">
<BatchEditingSettings EditType="Cell" />
<SortExpressions>
<telerik:GridSortExpression FieldName="SiteID,ProductID" SortOrder="Descending" />
</SortExpressions>
<Columns>
<telerik:GridTemplateColumn HeaderText="Site" HeaderStyle-Width="150px" UniqueName="SiteID" DataField="SiteID">
<ItemTemplate>
<%# Eval("SiteName") %>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadDropDownList runat="server" ID="ddlSites" AppendDataBoundItems="true" DataValueField="SiteID" DataTextField="SiteName" DataSourceID="sqlSites">
</telerik:RadDropDownList>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Product" HeaderStyle-Width="150px" UniqueName="ProductID" DataField="ProductID">
<ItemTemplate>
<%# Eval("ProductName") %>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadDropDownList runat="server" ID="ddlProducts" DropDownWidth="250" DropDownHeight="400" DefaultMessage="Product" AppendDataBoundItems="true" DataValueField="ProductID" DataTextField="ProductName" DataSourceID="sqlProducts">
</telerik:RadDropDownList>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridAttachmentColumn DataSourceID="sqlContractMatrix" MaxFileSize="1048576" HeaderStyle-Width="250px"
EditFormHeaderTextFormat="Upload File:" HeaderText="HTML Template" AttachmentDataField="BinaryData"
AttachmentKeyFields="ID" FileNameTextField="TemplateFileBinary" DataTextField="TemplateFileBinary"
UniqueName="TemplateFileBinary">
</telerik:GridAttachmentColumn>
<%--
<telerik:GridBoundColumn DataField="TemplateFile" HeaderStyle-Width="200px" HeaderText="Template"
SortExpression="TemplateFile" UniqueName="TemplateFile">
</telerik:GridBoundColumn>
--%>
<telerik:GridBoundColumn DataField="PDFName" HeaderStyle-Width="200px" HeaderText="PDF Name"
SortExpression="PDFName" UniqueName="PDFName">
</telerik:GridBoundColumn>
<telerik:GridButtonColumn ConfirmText="Delete this record?" ConfirmDialogType="RadWindow"
ConfirmTitle="Delete" HeaderText="Delete" HeaderStyle-Width="50px" ButtonType="ImageButton"
CommandName="Delete" Text="Delete" UniqueName="DeleteColumn">
</telerik:GridButtonColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:SqlDataSource ID="sqlContractMatrix" runat="server" ConnectionString="<%$ ConnectionStrings:FitTrack %>"
DeleteCommand="DELETE FROM ContractMatrix WHERE ID = #ID"
InsertCommand="INSERT INTO ContractMatrix (SiteID, ProductID, TemplateFile, PDFName, LastModifiedDate, LastModifiedByID) VALUES (#SiteID, #ProductID, #TemplateFile, #PDFName, #LastModifiedDate, #LastModifiedByID)"
UpdateCommand="UPDATE ContractMatrix SET SiteID = #SiteID, ProductID = #ProductID, TemplateFile = #TemplateFile, PDFName = #PDFName, LastModifiedDate = GETDATE(), LastModifiedByID = #LastModifiedByID WHERE ID = #ID">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32"></asp:Parameter>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="SiteID" Type="Int32"></asp:Parameter>
<asp:Parameter Name="ProductID" Type="Int32"></asp:Parameter>
<asp:Parameter Name="TemplateFile" Type="String"></asp:Parameter>
<asp:Parameter Name="PDFName" Type="String"></asp:Parameter>
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="SiteID" Type="Int32"></asp:Parameter>
<asp:Parameter Name="ProductID" Type="Int32"></asp:Parameter>
<asp:Parameter Name="TemplateFile" Type="String"></asp:Parameter>
<asp:Parameter Name="PDFName" Type="String"></asp:Parameter>
<asp:Parameter Name="ID" Type="Int32"></asp:Parameter>
</UpdateParameters>
</asp:SqlDataSource>
<!-- SQL data sources for various lookup tables -->
<asp:SqlDataSource ID="sqlSites" runat="server" ConnectionString="<%$ ConnectionStrings:FitTrack %>" ProviderName="System.Data.SqlClient" SelectCommand="SELECT SiteID, SiteName FROM gym.Site ORDER BY SiteID"></asp:SqlDataSource>
<asp:SqlDataSource ID="sqlProducts" runat="server" ConnectionString="<%$ ConnectionStrings:FitTrack %>" ProviderName="System.Data.SqlClient"></asp:SqlDataSource>
C# code:
protected void RadGrid1_BatchEditCommand(object sender, Telerik.Web.UI.GridBatchEditingEventArgs e)
{
SavedChangesList.Visible = true;
}
protected void RadGrid1_ItemUpdated(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
{
GridEditableItem item = (GridEditableItem)e.Item;
string id = item.GetDataKeyValue("ID").ToString();
if (e.Exception != null)
{
e.KeepInEditMode = true;
e.ExceptionHandled = true;
NotifyUser("Record with ID " + id + " cannot be updated. Reason: " + e.Exception.Message);
}
else
{
NotifyUser("Record with ID " + id + " is updated!");
}
}
protected void RadGrid1_ItemInserted(object source, GridInsertedEventArgs e)
{
if (e.Exception != null)
{
e.ExceptionHandled = true;
NotifyUser("Product cannot be inserted. Reason: " + e.Exception.Message);
}
else
{
NotifyUser("New product is inserted!");
}
}
protected void RadGrid1_ItemDeleted(object source, GridDeletedEventArgs e)
{
GridDataItem dataItem = (GridDataItem)e.Item;
string id = dataItem.GetDataKeyValue("ID").ToString();
if (e.Exception != null)
{
e.ExceptionHandled = true;
NotifyUser("Product with ID " + id + " cannot be deleted. Reason: " + e.Exception.Message);
}
else
{
NotifyUser("Product with ID " + id + " is deleted!");
}
}
Please help. Why are the data updates not occurring? Why are none of the telerik events/methods in the codebehind being called? Only Page_Load() is executing, none of the others.
For me this was down to trying to use OnItemUpdated instead of OnUpdateCommand.
The ItemDeleted, ItemUpdated and ItemInserted events of RadGrid only work in combination with a directly bound ADO type DataSource. I'm using my own DAL so these 3 events weren't firing.
So the fix was to hook up the events OnUpdateCommand and OnDeleteCommand instead. The event handler looks something like this.
protected void radGrid_UpdateCommand(object sender, GridCommandEventArgs e)
{
var gridDataItem = ((GridDataItem)e.Item);
var table = gridDataItem.OwnerTableView;
var keyValues = table.DataKeyValues[gridDataItem.ItemIndex];
// Get key value.
var id = keyValues["id"];
// Get other values
var foo = ((TextBox)gridDataItem["foo"].Controls[0]).Text;
var bar = ((TextBox)gridDataItem["bar"].Controls[0]).Text;
myDAL.Update(id, foo, bar);
}

Getting related entity count through FetchXML

I have the following fetchXML code for returning the total number of related entities. Main entity name is new_transaction and related entity name is new_transactionproduct.
The code below is placed in a web resource javascript but when this function is called it never gets to success or error portions, it simply hangs.
function countLineItems()
{
var ID = Xrm.Page.data.entity.getId();
var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' aggregate='true'>";
fetchXml += "<entity name='new_transactionproduct'>";
fetchXml += "<attribute name='new_name' alias='recordcount' aggregate='countcolumn' />";
fetchXml += "<filter type='and'>";
fetchXml += "<condition attribute='new_transactionid' operator='eq' value='" + ID + "' />";
fetchXml += "</filter>";
fetchXml += "</entity>";
fetchXml += "</fetch>";
alert(fetchXml);
XrmSvcToolkit.fetch({
fetchXml: fetchXml,
async: false,
successCallback: function (result) {
var countValue = result.entities[0].recordcount;
alert(countValue);
//Xrm.Page.getAttribute(new_totalqty).setValue(countValue);
},
errorCallback: function (error) {
throw error;
}
});
}
Just a quick side note you could always setup your fetchXML like below to minimise the amound of times you append to the string.
string fetchXml = #"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' aggregate='true'>
<entity name='new_transactionproduct'>
<attribute name='new_name' alias='recordcount' aggregate='countcolumn' />
<filter type='and'>
<condition attribute='new_transactionid' operator='eq' value='" + ID + #"' />
</filter>
</entity>
</fetch>";
XrmSvcToolkit needed to be added as a web resource and referenced on the page.

PreparedStatement Logging

I use log4j for the logging.
I could see the SQLs through Log4j like below.
Here's my java source which access data base with jdbcTemplate.
public QnaDTO selectBoard(int articleID) {
String SQL =
"SELECT " +
" QA.ARTICLE_ID, " +
" QA.EMAIL, " +
" QA.TEL, " +
" QA.CATEGORY_ID, " +
" CG.CATEGORY_NAME, " +
" QA.SUBJECT, " +
" QA.CONTESTS, " +
" QA.WRITER_NAME, " +
" QA.WRITER_ID, " +
" QA.READCOUNT, " +
" QA.ANSWER, " +
" QA.FILE_NAME, " +
" QA.OPEN_FLG, " +
" QA.KTOPEN_FLG, " +
" TO_CHAR(QA.WRITE_DAY, 'YYYY.MM.DD') WRITE_DAY, " +
" QA.DISPOSAL_FLG " +
"FROM QNA QA JOIN QNA_CATEGORY_GROUP CG " +
"ON QA.CATEGORY_ID = CG.CATEGORY_ID " +
"WHERE QA.ARTICLE_ID = ? ";
QnaDTO qnaDTO = (QnaDTO) jdbcTemplate.queryForObject(
SQL,
new Object[]{articleID},
new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
QnaDTO qnaDTO = new QnaDTO();
qnaDTO.setArticleID(rs.getInt("ARTICLE_ID"));
qnaDTO.setCategoryID(rs.getInt("CATEGORY_ID"));
qnaDTO.setCategoryName(rs.getString("CATEGORY_NAME"));
qnaDTO.setEmail1(rs.getString("EMAIL"));
qnaDTO.setTel1(rs.getString("TEL"));
qnaDTO.setSubject(rs.getString("SUBJECT"));
qnaDTO.setContests(rs.getString("CONTESTS"));
qnaDTO.setName(rs.getString("WRITER_NAME"));
qnaDTO.setUserID(rs.getString("WRITER_ID"));
//
qnaDTO.setReadcount(rs.getString("READCOUNT"));
qnaDTO.setAnswer(rs.getString("ANSWER"));
qnaDTO.setFileName(rs.getString("FILE_NAME"));
qnaDTO.setOpenFlg(rs.getString("OPEN_FLG"));
qnaDTO.setKtOpenFlg(rs.getString("KTOPEN_FLG"));
//
qnaDTO.setWriteDay(rs.getString("WRITE_DAY"));
qnaDTO.setDisposalFlg(rs.getString("DISPOSAL_FLG"));
return qnaDTO;
}
}
);
return qnaDTO;
}
As you can see above.
jdbcTemplate.queryForObject(...) is the method which really send Query And Get some result.
Inside of jdbcTemplate.queryForObject, finally logger used
public Object query(final String sql, final ResultSetExtractor rse)
throws DataAccessException
{
Assert.notNull(sql, "SQL must not be null");
Assert.notNull(rse, "ResultSetExtractor must not be null");
if(logger.isDebugEnabled())
logger.debug("Executing SQL query [" + sql + "]");
class _cls1QueryStatementCallback
implements StatementCallback, SqlProvider
{
public Object doInStatement(Statement stmt)
throws SQLException
{
ResultSet rs = null;
Object obj;
try
{
rs = stmt.executeQuery(sql);
ResultSet rsToUse = rs;
if(nativeJdbcExtractor != null)
rsToUse = nativeJdbcExtractor.getNativeResultSet(rs);
obj = rse.extractData(rsToUse);
}
finally
{
JdbcUtils.closeResultSet(rs);
}
return obj;
}
public String getSql()
{
return sql;
}
_cls1QueryStatementCallback()
{
super();
}
}
return execute(new _cls1QueryStatementCallback());
}
But with above sources, I could only get the SQL with ?.
What I want is that my result doesn't have question mark ?
It means filling ? with real data.
Is there any way to do this?
thanks
Jeon, sorry, was occupied with work. :-) Anyway, I have looked into your code and replicate here using spring 2.5. I've also google and I think you want to read this and this further to understand.
From the official documentation,
Finally, all of the SQL issued by this class is logged at the 'DEBUG'
level under the category corresponding to the fully qualified class
name of the template instance (typically JdbcTemplate, but it may be
different if a custom subclass of the JdbcTemplate class is being
used).
So you need to figure out how to enable logging with debug level.
Not sure exactly how you trace, but with my trace, I end up to below. So if you enable debug level, you should be able to see the output, maybe not exactly like QA.ARTICLE_ID = 123; but you should probably get the value printed in the next line something like in that example. Anyway, I don't have the exact setup like in your environment but this I think should you give a clue.
public Object execute(PreparedStatementCreator psc, PreparedStatementCallback action)
throws DataAccessException {
Assert.notNull(psc, "PreparedStatementCreator must not be null");
Assert.notNull(action, "Callback object must not be null");
if (logger.isDebugEnabled()) {
String sql = getSql(psc);
logger.debug("Executing prepared SQL statement" + (sql != null ? " [" + sql + "]" : ""));
}

SPListItemCollection.GetDataTable() doesn't return all columns?

I ran into an issue when using the GetDataTable() method. I'm trying to return the default SharePoint column "FileRef" in my results to use. I include it in my SPQuery.ViewFields
Query:
<Where><IsNotNull><FieldRef Name='FileRef'/></IsNotNull></Where>
ViewFields:
<FieldRef Name='Title' /><FieldRef Name='Category' /><FieldRef Name='FileRef' /><FieldRef Name='ID' /><FieldRef Name='Created' />
I can even see it returned in the items.XML but when I call GetDataTable() it is not put in the datatable.
SPListItemCollection items = list.GetItems(spq);
dtItems = items.GetDataTable();
Why isn't GetDataTable working correctly? Am I going to have to write my own conversion method?
You can use this code:Improving SharePoint's SPListItemCollection GetDataTable(), let's get all the fields I need
I'd recommend you a better solution
As SPListItemCollection has Xml proeprty that stores all item data, you can use this XSLT to get data in normal XML format and then create DataSet from XML.
This Idea can be converted to handy extension function:
using System.Data;
using System.Xml;
using System.Xml.Xsl;
using Microsoft.SharePoint;
namespace Balticovo.SharePoint
{
public static partial class Extensions
{
static string sFromRowsetToRegularXmlXslt =
"<xsl:stylesheet version=\"1.0\" " +
"xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" " +
"xmlns:s=\"uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882\" " +
"xmlns:z=\"#RowsetSchema\">" +
"<s:Schema id=\"RowsetSchema\"/>" +
"<xsl:output method=\"xml\" omit-xml-declaration=\"yes\" />" +
"<xsl:template match=\"/\">" +
"<xsl:text disable-output-escaping=\"yes\"><rows></xsl:text>" +
"<xsl:apply-templates select=\"//z:row\"/>" +
"<xsl:text disable-output-escaping=\"yes\"></rows></xsl:text>" +
"</xsl:template>" +
"<xsl:template match=\"z:row\">" +
"<xsl:text disable-output-escaping=\"yes\"><row></xsl:text>" +
"<xsl:apply-templates select=\"#*\"/>" +
"<xsl:text disable-output-escaping=\"yes\"></row></xsl:text>" +
"</xsl:template>" +
"<xsl:template match=\"#*\">" +
"<xsl:text disable-output-escaping=\"yes\"><</xsl:text>" +
"<xsl:value-of select=\"substring-after(name(), 'ows_')\"/>" +
"<xsl:text disable-output-escaping=\"yes\">></xsl:text>" +
"<xsl:value-of select=\".\"/>" +
"<xsl:text disable-output-escaping=\"yes\"></</xsl:text>" +
"<xsl:value-of select=\"substring-after(name(), 'ows_')\"/>" +
"<xsl:text disable-output-escaping=\"yes\">></xsl:text>" +
"</xsl:template>" +
"</xsl:stylesheet>";
public static DataTable GetFullDataTable(this SPListItemCollection itemCollection)
{
DataSet ds = new DataSet();
string xmlData = ConvertZRowToRegularXml(itemCollection.Xml);
if (string.IsNullOrEmpty(xmlData))
return null;
using (System.IO.StringReader sr = new System.IO.StringReader(xmlData))
{
ds.ReadXml(sr, XmlReadMode.Auto);
if (ds.Tables.Count == 0)
return null;
return ds.Tables[0];
}
}
static string ConvertZRowToRegularXml(string zRowData)
{
XslCompiledTransform transform = new XslCompiledTransform();
XmlDocument tidyXsl = new XmlDocument();
try
{
//Transformer
tidyXsl.LoadXml(Extensions.sFromRowsetToRegularXmlXslt);
transform.Load(tidyXsl);
//output (result) writers
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
using (XmlTextWriter tw = new XmlTextWriter(sw))
{
//Source (input) readers
using (System.IO.StringReader srZRow = new System.IO.StringReader(zRowData))
{
using (XmlTextReader xtrZRow = new XmlTextReader(srZRow))
{
//Transform
transform.Transform(xtrZRow, null, tw);
return sw.ToString();
}
}
}
}
}
catch
{
return null;
}
}
}
}
By the way, using this method, you will get, if needed, file attachment URL's (SPQuery.IncludeAttachmentUrls = true) not just TRUE/FALSE values as you would get it by using previously mentioned method.
Regarding Janis' answer - I'd remove the bits that do a substring on the ows_ and attempt to remove it, just use:-
"<xsl:value-of select=\"name()\"/>" +
because SP2010 now includes fields such as ETag which don't being with "ows_" and the solution fails. Very good solution otherwise.

Resources