Create function in vertica - vertica

I checked through many sources but cudnt get result.
How to create a function in vertica to return count of all sessions in
database?
Can someone povide some idea or possible expamples in this topic.

You can create UDX in Vertica, but it does not have a session handle so you can only access data exposed via the API. Session data is not exposed.
You'll need to execute a query to do it.
SELECT COUNT(*) FROM sessions;

See this post for something similar:
SELECT
node_name
,user_name
,'SELECT CLOSE_SESSION(''' || session_id || ''');' AS CloseSession
,statement_start
,(GETDATE() - statement_start)::INTERVAL AS current_statement_duration
,REGEXP_REPLACE(current_statement,'[rnt]',' ') AS current_statement
,session_id
,transaction_id
,statement_id
,client_hostname
,client_os
,login_timestamp
,runtime_priority
,ssl_state
,authentication_method
,transaction_start
,GETDATE() AS Today
FROM v_monitor.sessions
ORDER BY current_statement_duration DESC
;
Also you can get more info from this post:
Script to List Vertica Active Sessions

create C++(count_it.cpp )
#include "Vertica.h"
#include <time.h>
#include <sstream>
#include <iostream>
using namespace Vertica;
using namespace std;
class Average : public AggregateFunction
{
virtual void initAggregate(ServerInterface &srvInterface, IntermediateAggs &aggs)
{
try {
VNumeric &sum = aggs.getNumericRef(0);
sum.setZero();
vint &cnt = aggs.getIntRef(1);
cnt = 0;
} catch(exception& e) {
vt_report_error(0, "Exception while initializing intermediate aggregates: [%s]", e.what());
}
}
void aggregate(ServerInterface &srvInterface, BlockReader &argReader, IntermediateAggs &aggs)
{
try {
VNumeric &sum = aggs.getNumericRef(0);
vint &cnt = aggs.getIntRef(1);
do {
const VNumeric &input = argReader.getNumericRef(0);
if (!input.isNull()) {
sum.accumulate(&input);
sum.setZero();
cnt++;
}
} while (argReader.next());
} catch(exception& e) {
vt_report_error(0, "Exception while processing aggregate: [%s]", e.what());
}
}
virtual void combine(ServerInterface &srvInterface,IntermediateAggs &aggs,MultipleIntermediateAggs &aggsOther)
{
try {
VNumeric &mySum = aggs.getNumericRef(0);
vint &myCount = aggs.getIntRef(1);
do {
const VNumeric &otherSum = aggsOther.getNumericRef(0);
const vint &otherCount = aggsOther.getIntRef(1);
mySum.accumulate(&otherSum);
mySum.setZero();
myCount += otherCount;
} while (aggsOther.next());
} catch(exception& e) {
vt_report_error(0, "Exception while combining intermediate aggregates: [%s]", e.what());
}
}
virtual void terminate(ServerInterface &srvInterface, BlockWriter &resWriter, IntermediateAggs &aggs)
{
try {
const VerticaType &numtype = aggs.getTypeMetaData().getColumnType(0);
const VNumeric &sum = aggs.getNumericRef(0);
sum.setZero();
uint64* tmp = (uint64*)malloc(numtype.getMaxSize() / sizeof(uint64));
VNumeric cnt(tmp, numtype.getNumericPrecision(), numtype.getNumericScale());
cnt.copy(aggs.getIntRef(1));
VNumeric &out = resWriter.getNumericRef();
if (cnt.isZero())
out.setZero();
else
out.add(&cnt,&sum);
} catch(exception& e) {
vt_report_error(0, "Exception while computing aggregate output: [%s]", e.what());
}
}
InlineAggregate()
};
class count_itFactory : public AggregateFunctionFactory
{
virtual void getPrototype(ServerInterface &srvfloaterface,ColumnTypes &argTypes,ColumnTypes &returnType)
{
argTypes.addNumeric();
returnType.addNumeric();
}
virtual void getReturnType(ServerInterface &srvfloaterface,const SizedColumnTypes &inputTypes,SizedColumnTypes &outputTypes)
{
int int_part = inputTypes.getColumnType(0).getNumericPrecision();
int frac_part = inputTypes.getColumnType(0).getNumericScale();
outputTypes.addNumeric(int_part+frac_part, frac_part);
}
virtual void getIntermediateTypes(ServerInterface &srvInterface,const SizedColumnTypes &inputTypes,SizedColumnTypes &intermediateTypeMetaData)
{
int int_part = inputTypes.getColumnType(0).getNumericIntegral();
int frac_part = inputTypes.getColumnType(0).getNumericFractional();
intermediateTypeMetaData.addNumeric(int_part+frac_part, frac_part);
intermediateTypeMetaData.addInt();
}
virtual AggregateFunction *createAggregateFunction(ServerInterface &srvfloaterface)
{ return vt_createFuncObject<Average>(srvfloaterface.allocator); }
};
RegisterFactory(count_itFactory);
compile C++
g++ -D HAVE_LONG_INT_64 -I /opt/vertica/sdk/include -Wall -shared -Wno-unused-value -fPIC -o count_it.so /home/dbadmin/libs/count_it.cpp /opt/vertica/sdk/include/Vertica.cpp
create library
CREATE LIBRARY count_it AS '/home/dbadmin/libs/count_it.so';
create function
CREATE AGGREGATE FUNCTION count_it AS LANGUAGE 'C++' NAME 'count_itFactory' LIBRARY count_it;
use function
select count_it(client_id) from sesions;

Related

PLSQL parsing using Oracle.VsDevTools.SqlAndPlsqlParser

I downloaded Oracle Developer Tools for Visual studio and explored the libraries (.dll). I need to parse the PLSQL scripts to get the SQL Statements in that and using the visitors to visit the nodes. I found Oracle.VsDevTools.SqlAndPlsqlParser library and explored further and tried to parse the PLSQL scripts. Please refer the below code.
string plSQLScript="CREATE TABLE Student(Age int);";
List<LexerToken> tokens= LexerToken.Parse(plSQLScript, false, true);
But the above code gives tokens only, I need PLSQL parser.
Is there any possible way to parser the PLSQL scripts and get the sql statements. Also I need to explicit visit the sql statements like CreateTableVisitor, CreateProcedureVisitor, etc.
I already created the parser for TSQL files by exploring Microsoft SQL library called Microsoft.SqlServer.TransactSql.ScriptDom and using the below mentioned code for parsing.
TSql100Parser parser = new TSql100Parser(true);
IList<ParseError> error;
using (TextReader tr = new StreamReader(filePath))
{
TSqlFragment fragment = parser.Parse(tr, out error);
tr.Close();
}
And using TSqlFragmentVisitor to visit the sql statements. Please refer the below mentioned code.
public override void ExplicitVisit(CreateTableStatement node)
{
//----Coding----
}
I want the same for PLSQL by using Oracle.VsDevTools.SqlAndPlsqlParser library.
Please let me know if there any possibility for this.
Thanks,Sivaprakash.
With some reflection used it's possible. The parser, nodes and grammar classes are internal. I made small example for you:
private static Assembly odacDevAssembly = Assembly.Load("Oracle.VsDevTools.14.0");
private static Type parseNodeType = odacDevAssembly.GetType("Oracle.VsDevTools.SqlAndPlsqlParser.ParseNode");
void Main()
{
var parserType = odacDevAssembly.GetType("Oracle.VsDevTools.SqlAndPlsqlParser.OracleSqlEarley");
var parser = Activator.CreateInstance(parserType);
const string sqlScriptText = "DECLARE x NUMBER; BEGIN SELECT DUMMY INTO :DUMMY FROM DUAL T1; x := 1; SELECT DUMMY INTO :DUMMY FROM DUAL T2; x := 2; INSERT INTO T3 (C) VALUES (1); x := 3; END;";
var tokens = LexerToken.Parse(sqlScriptText);
var parserGrammar = parserType.GetProperty("EarleyGrammar").GetValue(parser);
var allSymbols = (string[])parserGrammar.GetType().GetField("m_vAllSymbols", BindingFlags.Public | BindingFlags.Instance).GetValue(parserGrammar);
var sqlStatementIndex = -1;
for (var i = 0; i < allSymbols.Length; i++)
{
if (allSymbols[i] == "unlabeled_nonblock_stmt")
{
sqlStatementIndex = i;
break;
}
}
var parseTree = parserType.GetMethod("Parse").Invoke(parser, new object[] { sqlScriptText, tokens });
//parseTree.GetType().GetMethod("PrintTree", new Type[] { parserGrammar.GetType() }).Invoke(parseTree, new object[] { parserGrammar });
var commandNodes = GetDescendants(parseTree).Where(d => GetPayloadIn(d) == sqlStatementIndex);
foreach (var commandNode in commandNodes)
{
var commandText = GetCommandText(commandNode, sqlScriptText, tokens);
Console.WriteLine(commandText);
}
}
private static string GetCommandText(object parseNode, string sqlScriptText, List<LexerToken> tokens)
{
var from = (int)parseNodeType.GetProperty("From").GetValue(parseNode);
var to = (int)parseNodeType.GetProperty("To").GetValue(parseNode) - 1;
var begin = tokens[from].m_vBegin;
return sqlScriptText.Substring(begin, tokens[to].m_vEnd - begin);
}
private static IEnumerable<object> GetDescendants(object parseNode)
{
yield return parseNode;
foreach (var child in GetChildren(parseNode))
foreach (var descendant in GetDescendants(child))
yield return descendant;
}
private static int GetPayloadIn(object parseNode)
{
return (int)parseNodeType.GetProperty("PayloadIn").GetValue(parseNode);
}
private static IEnumerable<object> GetChildren(object parseNode)
{
return (IEnumerable<object>)parseNodeType.GetMethod("Children").Invoke(parseNode, null);
}
UPDATE:
I'm not exactly sure what do you want to achieve but I hope it will be at least somehow helpful:
private static Assembly odacDevAssembly = Assembly.Load("Oracle.VsDevTools.14.0");
private static Type parseNodeType = odacDevAssembly.GetType("Oracle.VsDevTools.SqlAndPlsqlParser.ParseNode");
void Main()
{
var parserType = odacDevAssembly.GetType("Oracle.VsDevTools.SqlAndPlsqlParser.OracleSqlEarley");
var parser = Activator.CreateInstance(parserType);
const string sqlScriptText = "DECLARE x NUMBER; BEGIN SELECT DUMMY INTO :DUMMY FROM DUAL T1; x := 1; SELECT DUMMY INTO :DUMMY FROM DUAL T2; x := 2; INSERT INTO T3 (C) VALUES (1); x := 3; END;";
var tokens = LexerToken.Parse(sqlScriptText);
var parserGrammar = parserType.GetProperty("EarleyGrammar").GetValue(parser);
var allSymbols = (string[])parserGrammar.GetType().GetField("m_vAllSymbols", BindingFlags.Public | BindingFlags.Instance).GetValue(parserGrammar);
const int sqlStatementIndex = 4453; // unlabeled_nonblock_stmt
var parseTree = parserType.GetMethod("Parse").Invoke(parser, new object[] { sqlScriptText, tokens });
//parseTree.GetType().GetMethod("PrintTree", new Type[] { parserGrammar.GetType() }).Invoke(parseTree, new object[] { parserGrammar });
var commandNodes = GetDescendants(parseTree)
.Select(n => ParseNodeFactory.CreateNode(n, sqlScriptText, tokens))
.Where(n => n != null);
var visitor = new GrammarNodeVisitor();
foreach (var commandNode in commandNodes)
{
commandNode.Accept(visitor);
}
}
public static class ParseNodeFactory
{
private const int queryBlockIndex = 3849; // query_block
private const int insertIndex = 3136; // insert
public static IParseNode CreateNode(object parseNode, string sqlScriptText, List<LexerToken> tokens)
{
var symbolIndex = GetPayloadIn(parseNode);
var parseData = new ParseData { ParseNode = parseNode, SqlScriptText = sqlScriptText, Tokens = tokens };
switch (symbolIndex)
{
case queryBlockIndex:
return new QueryBlock { ParseData = parseData };
case insertIndex:
return new Insert { ParseData = parseData };
default:
return null;
}
}
}
public class GrammarNodeVisitor : IParseNodeVisitor
{
public void VisitQueryBlock(QueryBlock queryBlock)
{
Console.WriteLine($"Visited query block: {GetCommandText(queryBlock.ParseData.ParseNode, queryBlock.ParseData.SqlScriptText, queryBlock.ParseData.Tokens)}");
}
public void VisitInsert(Insert insert)
{
Console.WriteLine($"Visited insert command: {GetCommandText(insert.ParseData.ParseNode, insert.ParseData.SqlScriptText, insert.ParseData.Tokens)}");
}
}
public interface IParseNodeVisitor
{
void VisitQueryBlock(QueryBlock queryBlock);
void VisitInsert(Insert insert);
}
public interface IParseNode
{
ParseData ParseData { get; }
void Accept(IParseNodeVisitor visitor);
}
public class ParseData
{
public object ParseNode { get; set; }
public string SqlScriptText { get; set; }
public List<LexerToken> Tokens { get; set; }
}
public class QueryBlock : IParseNode
{
public ParseData ParseData { get; set; }
public void Accept(IParseNodeVisitor visitor)
{
visitor.VisitQueryBlock(this);
}
}
public class Insert : IParseNode
{
public ParseData ParseData { get; set; }
public void Accept(IParseNodeVisitor visitor)
{
visitor.VisitInsert(this);
}
}
private static string GetCommandText(object parseNode, string sqlScriptText, List<LexerToken> tokens)
{
var from = (int)parseNodeType.GetProperty("From").GetValue(parseNode);
var to = (int)parseNodeType.GetProperty("To").GetValue(parseNode) - 1;
var begin = tokens[from].m_vBegin;
return sqlScriptText.Substring(begin, tokens[to].m_vEnd - begin);
}
private static IEnumerable<object> GetDescendants(object parseNode)
{
yield return parseNode;
foreach (var child in GetChildren(parseNode))
foreach (var descendant in GetDescendants(child))
yield return descendant;
}
private static int GetPayloadIn(object parseNode)
{
return (int)parseNodeType.GetProperty("PayloadIn").GetValue(parseNode);
}
private static IEnumerable<object> GetChildren(object parseNode)
{
return (IEnumerable<object>)parseNodeType.GetMethod("Children").Invoke(parseNode, null);
}

How to do OptionContext parsing on an instance?

I'm trying to get options parsing using OptionContext to work.
My code so far:
public class Options : GLib.Object {
public string option_output = "";
public Options () {
}
public void parse (string args[]) throws OptionError {
// string option_output;
const OptionEntry[] options = {
{ "output", 'o', 0, OptionArg.FILENAME,
ref option_output, "file name for encoded output (required);",
"FILE" },
{null}
};
var opt_context = new OptionContext ("- vpng2theora");
opt_context.set_help_enabled (true);
opt_context.add_main_entries (options, null);
unowned string[] temp_args = args;
foreach (var arg in temp_args) {
print ("arg: %s\n", arg);
}
opt_context.parse (ref temp_args);
print (option_output);
}
}
int main (string[] args) {
Options opts = new Options ();
opts.parse (args);
return 0;
}
As it stands this doesn't compile because:
error: Value must be constant
If I remove the const altogether:
OptionEntry[] options = {
{ "output", 'o', 0, OptionArg.FILENAME,
ref option_output, "file name for encoded output (required);",
"FILE" },
{null}
};
The error is:
error: Expected array element, got array initializer list
The only way I can get around this problem is declaring the option_output as a static class field, but that defeats the purpose of instantiation.
Is there any way to have the OptionContext parsing work on an instance instead of a static class?
The following will work:
public class Options : GLib.Object {
public string option_output = "";
public bool parse (ref unowned string[] args) {
var options = new OptionEntry[2];
options[0] = { "output", 'o', 0, OptionArg.FILENAME,
ref option_output, "file name for encoded output (required);",
"FILE" };
options[1] = {null};
var opt_context = new OptionContext ("- vpng2theora");
opt_context.set_help_enabled (true);
opt_context.add_main_entries (options, null);
foreach (var arg in args) {
print ("arg: %s\n", arg);
}
bool result= true;
try {
opt_context.parse (ref args);
print( option_output );
} catch {
result = false;
}
return result;
}
}
int main (string[] args) {
Options opts = new Options ();
if (!opts.parse (ref args)) { return -1; }
return 0;
}
The options parsing will remove the optional arguments and then you can parse the required ones, such as the filenames to process. That's why I've kept the original args passed to the parse function. So you will get a cleaned set of args back, that you can then parse again for the required arguments. I found "CLI design: Putting flags to good use" a useful read.
options is an array of structs. I don't understand well enough why setting the size of the array is necessary, but it works for me.

how to combine query results of several times function call with entity framework5?

i want to use a function to query db with linq and combine their results,i write the code as follows but cannot work , any one can help me? thanks!
the error:(The operation cannot be completed because the DbContext has been disposed)
the part code:
public static IEnumerable<UserLocation> loadedUserList;
public static IEnumerable<UserLocation> combinedUserList;
public static void loadDataInStaticClass()
{
using (var context = new SptialTestEntities())
{
var loadedUserList = from newRcords in context.UserLocations
where newRcords.ID > lastLoadedID
select newRcords;
if (loadedUserList.Any())
{
foreach (var user in loadedUserList)
{
Console.WriteLine(user.UserName);
}
if (combinedUserList != null)
{
combinedUserList = loadedUserList.Union(combinedUserList);
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n after combined:" + cc.UserName);
}
}
else
{
combinedUserList = loadedUserList;
Console.WriteLine("\nfirst run :" + combinedUserList.Count());
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n user:" + cc.UserName);
}
}
}
}
}
the problem is: the first call is ok, but the second report error: The operation cannot be completed because the DbContext has been disposed ,and how?
thanks!
i paste the whole code and some one can run and check the mistake and thank u:
userLocation a table contain userid,username,userlocation(geography type) ,and
i user database first mode in visual studio 2012 and map the userLocation to a entity of SptialTestEntities.
Program.cs
static void Main(string[] args)
{
for (int i = 1; i < 3; i++)
{
Console.WriteLine("\nrun{0}times, i);
Test.LoadUsersFromDB();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Data.Spatial;
using System.Data.Entity;
using System.Xml.Linq;
using System.IO;
using System.Configuration;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections;
using System.Globalization;
namespace SptialMatch
{
class Test
{
public static int lastedLoadedRecordID = 14;
public static IEnumerable<UserLocation> loadedUserList;
public static IEnumerable<UserLocation> combinedUserList;
public static void LoadUsersFromDB()
{
try
{
Console.WriteLine("\n------------------------load data begin----------------------------------------------------------");
//var context = new SptialTestEntities();
using (var context = new SptialTestEntities())
{
System.Diagnostics.Stopwatch loadStopwatch = new System.Diagnostics.Stopwatch();
loadStopwatch.Start();
loadedUserList = from newRcords in context.UserLocations
where newRcords.ID > lastedLoadedRecordID
select newRcords;
if (loadedUserList.Any())
{
foreach (var loadUser in loadedUserList)
{
Console.WriteLine("\n loaded element:" + loadUser.UserName);
}
if (combinedUserList != null)
{
Console.WriteLine("\nnot first run:" );
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n before union:" + cc.UserName);
}
IEnumerable<UserLocation> tmp = loadedUserList.AsEnumerable();
combinedUserList = tmp.Union<UserLocation>(combinedUserList.AsEnumerable(), new UserComparer2()).ToList();
Console.WriteLine("\nnot first run after union:" );
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n after union the user name is:" + cc.UserName);
}
}
else
{
combinedUserList = loadedUserList;
Console.WriteLine("\nfirst run the count is:" + combinedUserList.Count());
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n the combined list:" + cc.UserName);
}
}
var maxID = loadedUserList.Max(myMaxID => myMaxID.ID);
lastedLoadedRecordID = lastedLoadedRecordID + 1;
}
else
{
Console.WriteLine("\n no new data!");
Console.WriteLine("\n-----------------load end,no new data yet------------------------------------------------");
Thread.Sleep(3000);
}
loadStopwatch.Stop();
Console.WriteLine("\nload time cost{0} seconds。", loadStopwatch.Elapsed);
Console.WriteLine("\n---------------------load end ----------------------------------------------------------");
}
}
catch (Exception ex)
{
Console.WriteLine("\n exception message:" + ex.Message);
}
}
}
class UserComparer2 : IEqualityComparer<UserLocation>
{
public bool Equals(UserLocation x, UserLocation y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.ID == y.ID && x.UserName == y.UserName;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(UserLocation user)
{
//Check whether the object is null
if (Object.ReferenceEquals(user, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashUserName = user.UserName == null ? 0 : user.UserName.GetHashCode();
//Get hash code for the Code field.
int hashUserCode = user.ID.GetHashCode();
//Calculate the hash code for the product.
return hashUserName ^ hashUserCode;
}
}
}

Looking to write Bluetooth 'hcitool' equivelant in Windows

I have used Bluez Bluetooth stack in Linux which comes with a handy utility 'hcitool'. Looking to build something like that in Windows with same or equivalent functionality. Specifically, 'hcitool name < MAC >', which shows if the specified device is within range.
Any guidance will be appreciated.
I have Windows SDK v7 with Visual Studio 2010, using C/C++
thanks.
Using my 32feet.NET library something like the following.
EDIT 3rd March: I've now added code to directly lookup the device by address rather than by using device discovery; so that's a simple 'new BluetoothDeviceInfo(...)'.
See if that finds the device you want. This requires the remote device to only be in "Connectable" mode whereas the former requires it to be in "Discoverable" mode. (BTW I've left the discovery code in place.)
EDIT 8th March: Now does a connect (using the SDP API) to check that the device is in range (and in connectable mode).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using System.Diagnostics;
using System.Net.Sockets;
namespace hcitool
{
partial class Program
{
static bool infoRatherThanName;
static BluetoothAddress _searchAddress;
static int Main(string[] args)
{
if (args.Length < 1) {
Console.WriteLine("Please specify command.");
return 2;
}
var cmd = args[0];
switch (cmd) {
case "name":
infoRatherThanName = false;
break;
case "info":
infoRatherThanName = true;
break;
//-
case "dev":
return ShowRadios();
//case "auth":
// return CauseAuth(GETADDRESS());
default:
throw new NotImplementedException("Command: '" + cmd + "'");
}
if (args.Length < 2) {
Console.WriteLine("Please specify device address.");
return 2;
}
var addrS = args[1];
_searchAddress = BluetoothAddress.Parse(addrS);
//
var dev = new BluetoothDeviceInfo(_searchAddress);
bool isInRange = GetCanConnectTo(dev);
if (isInRange) {
PrintDevice(dev);
} else {
Console.WriteLine("Can't see that device.");
}
//
Console.WriteLine("simple");
return Simple();
//return Fancier();
}
//----
private static int ShowRadios()
{
BluetoothRadio[] list;
try {
list = BluetoothRadio.AllRadios;
} catch (Exception) {
return 1;
}
Debug.Assert(list.Length != 0, "Expect zero radios case to raise an error.");
foreach (var curR in list) {
Console.WriteLine("* {0} '{1}'", curR.LocalAddress, curR.Name);
Console.WriteLine("{0}", curR.SoftwareManufacturer);
Console.WriteLine("{0}", curR.Manufacturer);
Console.WriteLine("{0}", curR.Mode);
}//for
return 0;
}
private static int CauseAuth(BluetoothAddress addr)
{
BluetoothSecurity.PairRequest(addr, null);
return 0;
}
//----
static int Simple()
{
BluetoothDeviceInfo[] devices;
BluetoothDeviceInfo foundDev = null;
var cli = new BluetoothClient();
// Fast: Remembered/Authenticated
devices = cli.DiscoverDevices(255, true, true, false, false);
SimpleCheckDevice(devices, ref foundDev);
if (foundDev == null) {
// Slow: Inquiry
cli.DiscoverDevices(255, false, false, true, false);
SimpleCheckDevice(devices, ref foundDev);
}
//
if (foundDev != null) {
return 0;
} else {
return 1;
}
}
private static void SimpleCheckDevice(IEnumerable<BluetoothDeviceInfo> devices,
ref BluetoothDeviceInfo foundDev)
{
foreach (var cur in devices) {
if (cur.DeviceAddress == _searchAddress) {
foundDev = cur;
PrintDevice(cur);
}
}//for
}
private static void PrintDevice(BluetoothDeviceInfo cur)
{
Console.WriteLine("* Found device: '{0}' ", cur.DeviceName);
if (infoRatherThanName) {
try {
var vs = cur.GetVersions();
Console.WriteLine(vs.Manufacturer);
Console.WriteLine(vs.LmpVersion);
Console.WriteLine(vs.LmpSubversion);
Console.WriteLine(vs.LmpSupportedFeatures);
} catch (Exception ex) {
Console.WriteLine("Failed to get remote device versions info: "
+ ex.Message);
}
}
}
//----
private static bool GetCanConnectTo(BluetoothDeviceInfo device)
{
bool inRange;
Guid fakeUuid = new Guid("{F13F471D-47CB-41d6-9609-BAD0690BF891}");
try {
ServiceRecord[] records = device.GetServiceRecords(fakeUuid);
Debug.Assert(records.Length == 0, "Why are we getting any records?? len: " + records.Length);
inRange = true;
} catch (SocketException) {
inRange = false;
}
return inRange;
}
}
}

Table-value functions in BLToolkit

Is it possible to use SQL Server table-value functions by using the BLToolkit library?
I would like to use it within the Linq query, but I couldn't find anything regarding this on the library wiki.
Define your function in your data context class as the following:
[TableFunction(Name="GetParentByID")]
public Table<Parent> GetParentByID(int? id)
{
return GetTable<Parent>(this, (MethodInfo)MethodBase.GetCurrentMethod(), id);
}
Usage:
[Test]
public void Func2()
{
using (var db = new TestDbManager())
{
var q =
from c in db.Child
from p in db.GetParentByID(2)
select p;
q.ToList();
}
}
SQL:
SELECT
[t2].[ParentID],
[t2].[Value1]
FROM
[Child] [t1], [GetParentByID](2) [t2]
Also you can define it outside of the data context:
public class Functions
{
private readonly IDataContext _ctx;
public Functions(IDataContext ctx)
{
_ctx = ctx;
}
[TableFunction]
public Table<Parent> GetParentByID(int? id)
{
return _ctx.GetTable<Parent>(this, (MethodInfo)(MethodBase.GetCurrentMethod()), id);
}
[TableExpression("{0} {1} WITH (TABLOCK)")]
public Table<T> WithTabLock<T>()
where T : class
{
return _ctx.GetTable<T>(this, ((MethodInfo)(MethodBase.GetCurrentMethod())).MakeGenericMethod(typeof(T)));
}
}
[Test]
public void Func1()
{
using (var db = new TestDbManager())
{
var q =
from p in new Functions(db).GetParentByID(1)
select p;
q.ToList();
}
}
[Test]
public void WithTabLock()
{
using (var db = new TestDbManager())
{
var q =
from p in new Functions(db).WithTabLock<Parent>()
select p;
q.ToList();
}
}
SQL:
SELECT
[p].[ParentID],
[p].[Value1]
FROM
[GetParentByID](1) [p]
SELECT
[p].[ParentID],
[p].[Value1]
FROM
[Parent] [p] WITH (TABLOCK)

Resources