I'm using Mindscape.Lightspeed and getting the following error:
Error: Invalid object name 'KeyTable'.
LightSpeedContext<LightSpeedModel1UnitOfWork> context = new LightSpeedContext<LightSpeedModel1UnitOfWork>("Development");
using (var uow = context.CreateUnitOfWork())
{
SiteUser user = new SiteUser();
user.UserName = "ABC";
user.RoleId = 1;
uow.Add(user);
}
I posted this commment on the official forum where you also posted this question :-)
This error message is being generated because you're using the KeyTable identity method. The Identity Method is how LightSpeed will generate identifiers for your entities and, by default, uses the KeyTable pattern. This requires a table called "KeyTable" (there is a script for this in the LightSpeed installation directory under the providers folder).
If you don't want to use the KeyTable identity method please configure an appropriate method on your LightSpeedContext configuration in the .config file. There is information about the various methods in the help file, in the getting started screencast and in some of the samples.
You can read the help file page online here:
http://www.mindscape.co.nz/Help/LightSpeed/Help%20Topics/LightSpeed/IdentityGeneration.html
I hope that helps,
John-Daniel
To save you a step or two, here's the SQL from the Lightspeed install folder to create the KeyTable in SQL Server 2008
(C:\Program Files (x86)\Mindscape\LightSpeed\Providers\SQLServer2008)
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name = 'KeyTable')
BEGIN
DROP TABLE KeyTable
END;
CREATE TABLE KeyTable
(
NextId INT NOT NULL
)
INSERT INTO KeyTable VALUES (1);
Related
I'm using postgres in a c# project and i'm trying to make some basic queries such as
qry.CommandText = "select * from LOGIN";
NpgsqlDataReader qryReader = qry.ExecuteReader();
But it says that the table LOGIN does not exist.
I already know that the following query works: qry.CommandText = "select * from \"myDataBase\".LOGIN"; but I would prefer not using it.
I also know from this thread that I can use SET search_path TO myschema,public; to access the table without prefix in psql command line, but I don't see how it would work for my c# projet.
Also, I have another project where I don't need the prefix but I don't know why it works for my other projet and not this one.
Any help would be very appreciated.
Thanks
While SET search_path TO myschema,public; sets the search_path for the current session only, you can make it permanent for the user running the command:
ALTER USER username SET search_path TO myschema, public;
First off, Ill say that this issue is related to my previous post.
However, I'll move everything over here for reference.
The issue I am having is I am still getting the error:
Msg 6522, Level 16, State 1, Procedure PerfInsert, Line 0 [Batch Start Line 31]
A .NET Framework error occurred during execution of user-defined routine or aggregate "PerfInsert":
System.Security.SecurityException: Request failed.
System.Security.SecurityException:
at MiddleMan.MiddleMan.CreateCommand(SqlString tblString, SqlString featureName, SqlString connectionString, SqlString perfionConnectionString, SqlString logFile)
.
Even though I believe I have followed all the steps necessary to set this up correctly. I have even gone so far as to verify that SQL Server has permissions to the directory of the files.
Anyone know what else I can check to see what the missing piece is?
Or do I need to make this an "unsafe" assembly?
C# code:
using Microsoft.SqlServer.Server;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Diagnostics;
namespace MiddleMan
{
public static class MiddleMan
{
[SqlProcedure(Name = "PerfInsert")]
public static SqlInt32 CreateCommand(SqlString tblString, SqlString featureName, SqlString connectionString, SqlString perfionConnectionString, SqlString logFile)
{
Process compiler = new Process();
compiler.StartInfo.FileName = "C:\\SQL Server C# Functions\\PerfionLoader\\PerfionLoader\\bin\\Release\\PerfionLoader.exe";
compiler.StartInfo.Arguments = tblString.Value + " " + featureName.Value + " " + connectionString.Value + " " + perfionConnectionString.Value + " " + logFile.Value;
//compiler.StartInfo.UseShellExecute = false;
//compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
return SqlInt32.Zero;
}
}
}
SQL code(s):
CREATE ASSEMBLY PerfInsert
AUTHORIZATION dbo
FROM '\\bk-int-1\c$\SQL Server C# Functions\MiddleMan\MiddleMan\bin\Release\MiddleMan.dll'
WITH PERMISSION_SET = SAFE
GO
CREATE ASYMMETRIC KEY [Brock.Retail_Brock.Retail_Brock]
AUTHORIZATION [dbo]
FROM EXECUTABLE FILE = '\\bk-int-1\c$\SQL Server C# Functions\MiddleMan\MiddleMan\bin\Release\MiddleMan.dll';
CREATE LOGIN BrokcRetail
FROM ASYMMETRIC KEY [Brock.Retail_Brock.Retail_Brock]
CREATE PROCEDURE PerfInsert
(
#tblString nvarchar(max)
, #featureName nvarchar(max)
, #connectionString nvarchar(max)
, #perfionConnectionString nvarchar(max)
, #logFiel nvarchar(max)
)
AS EXTERNAL NAME PerfInsert.[MiddleMan.MiddleMan].[CreateCommand]
GO
You are using multi-threading so yes, the Assembly 100% needs to have PERMISSION_SET = UNSAFE.
Also, since you already have the Asymmetric Key and associated Login set up (thank you for doing that and not using TRUSTWORTHY ON), you will need to do the following prior to setting the Assembly to UNSAFE:
USE [master];
GRANT UNSAFE ASSEMBLY TO [BrokcRetail];
and then:
USE [{db_containing_assembly_hopefully_not_master];
ALTER ASSEMBLY [PerfInsert] WITH PERMISSION_SET = UNSAFE;
or, if you create the Asymmetric Key-based Login and grant it the UNSAFE ASSEMBLY permission first, then you can simply use UNSAFE instead of SAFE in the CREATE ASSEMBLY statement.
Starting in SQL Server 2017, you will need to create the Asymmetric Key and associated Login before creating the Assembly. The Asymmetric Key and Login go into [master] while the Assembly can go into any DB (including [master], but usually best to not put custom code in there).
If you are already using SQL Server 2017 or newer, and if the code shown in the question is in the actual order in which you are executing it, then I would guess that you have already either set the database to TRUSTWORTHY ON or disabled "CLR strict security". Otherwise you should not have been able to create the Assembly at all without first having the signature-based login created and granted the UNSAFE ASSEMBLY permission. If I am correct about this, you can re-enable "CLR strict security" and/or turn TRUSTWORTHY OFF for that database.
Also, as I noted on your related question (the one linked to in this question), you should be using SqlString instead of SqlChars. SqlString.Value returns a .NET string while SqlChars.Value returns a char[]. Long ago people associated SqlChars with NVARCHAR(MAX), and SqlString with NVARCHAR(1-4000), but that was only due to Visual Studio / SSDT using those mappings as defaults when generating the DDL to publish the Database Project. But there never was any technical / string mapping between them. You can use either .NET type with either T-SQL datatype.
Also, please exercise caution (and lots of testing) when using multi-threading from within SQLCLR.
Please visit SQLCLR Info for more resources related to working with SQLCLR in general.
Related Posts:
System.Web in SQL Server CLR Function (on DBA.StackExchange)
CREATE PROCEDURE gets “Msg 6567, Level 16, State 2” for SQLCLR stored procedure
My problem is as follows: I need a clr udf (in C#) to query with a given ad-usr the ad-group membership
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.DirectoryServices.AccountManagement;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlInt32 check_user_is_part_of_ad_grp(SqlString ad_usr, SqlString ad_grp)
{
bool bMemberOf = false;
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, ad_grp.ToString());
UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, ad_usr.ToString());
if (group != null && usr != null)
{
bMemberOf = usr.IsMemberOf(group);
}
// Put your code here
return new SqlInt32 (bMemberOf ? 1 : 0);
}
}
If I publish the CLR to my SQL Server 2008 (.net 3.5), then I run the udf as follows:
select dbo.check_user_is_part_of_ad_grp('user', 'group')
And I get an error:
Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "check_user_is_part_of_ad_grp":
System.Security.SecurityException: Request for the permission of type 'System.DirectoryServices.DirectoryServicesPermission, System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' failed.
System.Security.SecurityException:
at UserDefinedFunctions.check_user_is_part_of_ad_grp(SqlString ad_usr, SqlString ad_grp)
I set the target framework of my project to 3.5 and the permission level to EXTERNAL_ACCESS. Also the project references (System.DirectoryServices, System.DirectoryServices.AccountManamgement, System.DirectoryServices.Protocols) to EXTERNAL
I appreciate any help
Most likely all of those Assemblies will need to be set to UNSAFE, especially the three System.DirectoryServices* .NET Framework libraries that you imported. Also, since you are importing unsupported .NET Framework libraries, you will need to set the database to TRUSTWORTHY ON in order to get them to work. Setting a Database to TRUSTWORTHY ON is typically something you want to avoid as it is a security risk, but in this case I do not believe that it can be avoided.
That said, I am not sure that you even need to create this function yourself in SQLCLR. If you are just wanting to know if a Login (Windows Logins only, obviously) belongs to a particular Active Directory group, there is a built-in function that should do that for you. The IS_MEMBER function will indicate if the current Login is a member of the specified Windows group (specified as Domain\Group). The difference in how this function works as opposed to the one that you are creating is that it only works for the current Login; you cannot pass any arbitrary Login into it. BUT, it also doesn't require any of the extra effort and security risks that are a part of this SQLCLR solution. So, something to consider :-).
Comment from O.P. on this answer:
Actually, I need to check an arbitrary Login if it's member of a particular group. I even tried to use a stored proc and `OPENQUERY' with a linked server to ADSI, but this only works as Dynamic SQL since I need to inject group and user.
In that case, just make the Dynamic SQL two layers deep instead of the usual one layer. Something along the lines of:
DECLARE #SQL NVARCHAR(MAX);
SET #SQL = N'
SELECT *
FROM OPENQUERY([LinkedServer], N''
SELECT *
FROM someResource
WHERE GroupName=N''''' + #Group + N'''''
AND ObjectName=N''''' + #Login + N''''';
'');
';
PRINT #SQL; -- DEBUG
EXEC (#SQL);
In this approach, the query executing OPENQUERY is Dynamic SQL, but the query given to OPENQUERY to execute is a string literal.
I found code here: Update linked tables in MS Access Database with C# programatically That will re-link a table, but how do you actually Link the table and change the name from what it is titled in SQL Server?
I have gotten some pretty rough code started, but am getting hung-up on the parameters...
Microsoft.Office.Interop.Access.Application docacc = new Microsoft.Office.Interop.Access.Application();
docacc.DoCmd.TransferDatabase(AcDataTransferType.acLink
EDIT -- Access 2003 - and I want to link the table from SQL server into access
EDIT # 2
I found this site: http://bytes.com/topic/visual-basic-net/answers/379904-create-linked-table
And have adapted code there, but I get an error of 'unable to establish connection' on my server?
I found a solution....
string path = "path to Access database";
DAO.Database dd;
DAO.DBEngine db = new DAO.DBEngine();
DAO.TableDef tdf - new DAO.TableDef();
dd.db.OpenDatabase(path);
tdf = dd.CreateTableDef();
tdf.Name = "Whatever you want the linked table to be named";
tdf.Connect = "ODBC;Driver=SQL Server;Server=<Server Name>;Database=<DB NAME>;Trusted_Connection=YES";
tdf.SourceTableName = "Whatever the SQL Server Table Name is";
dd.TableDefs.Append(tdf);
My issue is very similar to this issue.
However, I'm using SQL Server 2005 Service Pack 2 (SP2) (v9.0.3042) and the solution posted there does not work for me. I tried using both connection strings. One is commented out in my code.
I realize I can store all the results in a List or ArrayList in memory and return that. I've done that successfully, but that is not the goal here. The goal is to be able to stream the results as they are available.
Is this possible using my version of SQL Server?
Here's my code :
(Note that the parameters aren't actually being used currently. I did this for debugging)
public static class StoredProcs
{
[SqlFunction(
DataAccess = DataAccessKind.Read,
SystemDataAccess=SystemDataAccessKind.Read,
FillRowMethodName="FillBaseline",
TableDefinition = "[baseline_id] [int], [baseline_name] [nvarchar](256), [description] [nvarchar](max), [locked] [bit]"
)]
public static IEnumerable fnGetBaselineByID(SqlString projectName, SqlInt32 baselineID)
{
string connStr = "context connection=true";
//string connStr = "data source=.;initial catalog=DBName;integrated security=SSPI;enlist=false";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(String.Format(#"
SELECT *
FROM [DBName].[dbo].[Baseline] WITH (NOLOCK)
"), conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new Baseline(reader);
}
}
}
};
}
public static void FillBaseline(Object obj, out SqlInt32 id, out SqlString name, out SqlString description, out bool locked)
{
Baseline baseline = (Baseline)obj;
id = baseline.mID;
name = baseline.nName;
description = baseline.mDescription;
locked = baseline.mLocked;
}
}
Here's part of my SQL deploy script:
CREATE ASSEMBLY [MyService_Stored_Procs]
FROM 'C:\temp\assemblyName.dll'
WITH PERMISSION_SET = SAFE
When I use the connection string "context connection=true" I get this error:
An error occurred while getting new row from user defined Table
Valued Function :
System.InvalidOperationException: Data access is not allowed in
this context. Either the context is a function or method not marked
with DataAccessKind.Read or SystemDataAccessKind.Read, is a callback
to obtain data from FillRow method of a Table Valued Function, or is a
UDT validation method.
When I use the other connection string I get this error:
An error occurred while getting new row from user defined Table
Valued Function :
System.Security.SecurityException: Request for the permission of
type 'System.Data.SqlClient.SqlClientPermission, System.Data,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
failed.
Upon further research and trial and error I found my solution. The article that I mentioned here says
your assembly must be created with permission_set=external_access
This is much easier said than done, but was a good starting point. Simply using that line in place of permission_set=safe gives the error:
CREATE ASSEMBLY for assembly 'assemblyName' failed because assembly
'assemblyName' is not authorized for PERMISSION_SET = EXTERNAL_ACCESS.
The assembly is authorized when either of the following is true: the
database owner (DBO) has EXTERNAL ACCESS ASSEMBLY permission and the
database has the TRUSTWORTHY database property on; or the assembly is
signed with a certificate or an asymmetric key that has a
corresponding login with EXTERNAL ACCESS ASSEMBLY permission.
So the first thing I had to do was sign my dll file. To do that in Visual Studio 2010, you go to the project properties, Signing tab, and check "Sign the assembly" and give it a name. For this example, the name is MyDllKey. I chose not to protect it with a password. Then, of course, I copied the dll file to the sql server: C:\Temp
Using this page as a reference, I created a SQL login based on the above key using these 3 commands:
CREATE ASYMMETRIC KEY MyDllKey FROM EXECUTABLE FILE = 'C:\Temp\MyDll.dll'
CREATE LOGIN MyDllLogin FROM ASYMMETRIC KEY MyDllKey
GRANT EXTERNAL ACCESS ASSEMBLY TO MyDllLogin
Once the login is created as above, I can now create the assembly using this:
CREATE ASSEMBLY [MyDll]
FROM 'C:\Temp\MyDll.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS
Now the only thing left to do is use the proper connection string. Apparently using enlist=false in combination with connection=true is not possible. Here is an example of the connection string I used.
string connStr = #"data source=serverName\instanceName;initial catalog=DBName;integrated security=SSPI;enlist=false";
And it works!
The original problem is due to use of the yield keyword within your function, as explained in this question: SqlFunction fails to open context connection despite DataAccessKind.Read present.
If you avoid using yield (store results in an intermediate array, return the whole lot at the end) the problem goes away.
Alternatively you can do as you describe and avoid using the context connection, but if you do that you have to mark your assembly for external access as you describe. I think that's best described as a workaround, rather than a solution, given you lose some of the benefits available from a context connection and because of all the extra hoops you have to jump through.
In many cases the benefit of being able to use streaming behaviour (yield) does outweigh this pain, but it's still worth considering both options.
Here's the bug on Connect: http://connect.microsoft.com/SQLServer/feedback/details/442200/sql-server-2008-clr-tvf-data-access-limitations-break-existing-code
Googling for this:
Data access is not allowed in this context. Either the context is a
function or method not marked with DataAccessKind.Read or
SystemDataAccessKind.Read, is a callback to obtain data from FillRow
method of a Table Valued Function, or is a UDT validation method.
Led me to this page, but without the answer I needed.
I eventually figured out what it was.
In my CLR Function, I was calling another Method and passing in the values the Function had recieved.
Sounds innocuous, but what I had done was used the same datatypes (SqlChars, SqlBoolean, SqlInt32) for the input-parameters of the Method I added.
private static ArrayList FlatFile(SqlChars Delimeter, SqlChars TextQualifier)
Apparently using these datatypes for anything other than a CLR SqlFunction or SqlProcedure can sometimes give you this type of cryptic error.
Once I removed those datatypes on my new Method and used the C# ones (string, bool, int), the error finally went away.
private static ArrayList FlatFile(string Delimeter, string TextQualifier)
NOTE: This only errored out when I was using Impersonation to grab a file from another Domain.
When I streamed the file over the local Domain, I didn't receive this error, which is what threw me off.
I hope this helps you in your time of need. I blew way too many hours troubleshooting this.