CREATE ASSEMBLY uploads an assembly that was previously compiled as a .dll file from managed code for use inside an instance of SQL Server.
What I want to do here is enable/create a "MODIFY" option on CLR-based objects in Object Explorer.
Option is only supported for assemblies who's source code has been previously loaded into DB via ALTER ASSEMBLY
Upon electing the option, source code gets displayed in editor.
Users alters managed source
User clicks the "Execute" button in the editor
onClick of "Execute" performs following
Alters managed source (not sure if this can be done in the system tables, may have to save .cs/.vb files out to file system first then reupload)
Builds updated source/.dll is built
Executes an ALTER ASSEMBLY statement to "refresh" the dll and it's associated source code file(s)
Using the Microsoft Patterns and Practices "Object Builder" (Dependency Injection/Builder library), I wrote an SQL CLR Stored Procedure (using VS 2005 Professional).
All compiles and deploys ok (to SQL Server 2005 Express).
However, at run-time, I get the following error upon a "BuilderContext" object's instantiation: {"Attempted to perform an operation that was forbidden by the CLR host."}
Thoughts on how to get ObjectBuilder working in the SQLCLR?
Thanks!
Andy
(posted below is the sample code...with the run-time exception occuring on the ...BuilderContext cxt = new ... call)
Microsoft.Practices.ObjectBuilder.BuilderStrategyChain chain = new Microsoft.Practices.ObjectBuilder.BuilderStrategyChain();
Microsoft.Practices.ObjectBuilder.Locator locator1 = new Microsoft.Practices.ObjectBuilder.Locator(null);
// Get error when new'ing BuilderContext: "Attempted to perform an operation that was forbidden by the CLR host." Microsoft.Practices.ObjectBuilder.BuilderContext cxt = new Microsoft.Practices.ObjectBuilder.BuilderContext(chain, locator1, null);
I am using Sql server 2005, i am trying to find out all the tables that modified recently. i cant find any last modified date!!.
My situation is; i have altered so many tables, usually when i do alter i save the sql file for doing the same alteration in the production database. but somehow i lost the scripts and i am not sure what are the tables that i have modified and what is new.
Hi,I'm a newbie to sql server and this may be a really dumb question forsome you. I'm trying to find some examples of sql server triggers thatwill set columns (e.g. the created and modified date columns) if the rowis being inserted and set a column (e.g. just the modified date column)if the row is being updated.I know how to do this in oracle plsql. I would define it as a beforeinsert or update trigger and reference old and new instances of therecord. Does sql server have an equivalent? Is there a better way to dothis in sql server?Thanksericthis is what i do in oracle that i'm trying to do in sqlserver...CREATE OR REPLACE TRIGGER tr_temp_biubefore insert or updateon tempreferencing old as old new as newfor each rowbeginif inserting then:new.created_date := sysdate;end if;:new.modified_date := sysdate;end tr_temp_biu;
In my office computer network system (LAN), my Windows XP Pro PC has SQL Server Express and VB 2005 Express installed and I was granted to have the Administrator priviledge to access SQL Server Express. I tried to create a SQLCLR project in my terminal PC. 1) I tried to set up a remote connection to SQL Server Express in the following way: SQL Server EXpress => SQL Server Surface Area Configuration. In the Surface Area Configuration for Service and Connection - local, I clicked on Remote Connection of Database Engine, SQLEXPRESS and I had a "dot" on "Local and remote connections" and "Using TCP/IP only". Then I clicked on "Apply" and "OK" buttons. Then I went to restart my database engine in SQL Server Management. When I went to check SQL Server 2005 Surface Area Configuration, I saw the arrow is pointing to "Service", not to "Remote Connections"!!!??? Is it right/normal? Please comment on this matter and tell me how I can have "Remote Connecton" on after I selected it.
2) After I restarted the database engine (I guess!!), I executed the following project code (copied from a book) in my VB 2005 Express:
//////////////--Form9.vb---/////////////////
mports System.Data.SqlClient
Imports System.Data
Public Class Form9
Dim cnn1 As New SqlConnection
Private Sub Form5_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Compute top-level project folder and use it as a prefix for
'the primary data file
Dim int1 As Integer = InStr(My.Application.Info.DirectoryPath, "bin")
Dim strPath As String = Microsoft.VisualBasic.Left(My.Application.Info.DirectoryPath, int1 - 1)
Dim pdbfph As String = strPath & "northwnd.mdf"
Dim cst As String = "Data Source=.sqlexpress;" & _
"Integrated Security=SSPI;" & _
"AttachDBFileName=" & pdbfph
cnn1.ConnectionString = cst
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
Loop
'Invoke the WriteToServer method fo the sqc1 SqlBulkCopy
'object to populate FromExcel table in the database with
'the FromExcel DataTable in the project
Try
cnn1.Open()
Using sqc1 As SqlBulkCopy = New SqlBulkCopy(cnn1)
sqc1.DestinationTableName = "dbo.FromExcel"
sqc1.WriteToServer(FromExcel)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cnn1.Close()
End Try
'Read the FromExcel table and display results in
'a message box
Dim strQuery As String = "SELECT * " & _
"FROM dbo.FromExcel "
Dim str1 As String = ""
Dim cmd1 As New SqlCommand(strQuery, cnn1)
cnn1.Open()
Dim rdr1 As SqlDataReader
rdr1 = cmd1.ExecuteReader()
Try
While rdr1.Read()
str1 += rdr1.GetString(0) & ", " & _
rdr1.GetString(1) & ", " & _
rdr1.GetSqlInt32(2).ToString & ControlChars.CrLf
End While
Finally
rdr1.Close()
cnn1.Close()
End Try
MessageBox.Show(str1, "FromExcel")
End Sub
End Class ////////////////////////////////////////////////////////////////////////////// I got the following error messages: SecurityException was unhandled Request for the permission of type 'System. Security. Permissions.FileIOPermission,mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'failed that is pointing to the code statement "Dim int1 As Integer = InStr (My.Application.Info.DirectoryPath, "bin")." Troubleshooting tips: Store application data in isolated storage. When deploying an Office solution, check to make sure you have fulfilled all necessary requirments. Use a certificate to obtain the required permission(s). If an assembly implementing the custom security references other assemblies, add the referenced assemblies to the full trust assembly list. Get general help for the exception.
I am a new Microsoft VS.NET Express user to do the SQL Server 2005 Express and VB 2005 Express programming by using the example of a tutorial book. Please help and tell me what is wrong in my SQLCLR sep-up and project coding and how to correct the problems.
How to create object type in sql server, i.e in Oracle we can directly create an object TYPE and we can use it in other applications. What's the equivalent of this object Type in SQL Server
I opened SSMSexpress and attached to my sql 2005 database and automatically created the scripts for creating all the object in a SQL 2000 DB. The objects seem to be created but I did get script messages. Are these messages harmless?thanksMilton Msg 208, Level 16, State 1, Procedure Requestview, Line 3 Invalid object name 'dbo.requests'. Msg 15135, Level 16, State 1, Procedure sp_validatepropertyinputs, Line 147 Object is invalid. Extended properties are not permitted on 'dbo.Requestview', or the object does not exist. Msg 15135, Level 16, State 1, Procedure sp_validatepropertyinputs, Line 147 Object is invalid. Extended properties are not permitted on 'dbo.Requestview', or the object does not exist.
I would like to populate an array with an object. In other words, I would like for each element in the array to consist of an object that has several elements. Below is some code so you can see what I'm talking about: Function buildObj() Dim countLimit As Integer = 5 Dim mArray() As myObject While reader.Read() For counter = 0 To countLimit - 1 mArray(counter).objVal1 = reader.GetValue(0) 'Error is here mArray(counter).objVal2 = reader.GetValue(1) mArray(counter).objVal3 = reader.GetValue(2) counter += 1 Next End While Return mArray End Function Dim showValArr As Array = buildObj()Response.Write(showValArr(0).objVal1.ToString) When I build my site, I get the following error:Object reference not set to an instance of an object. It's pointing to the line that says "Error is here". Any ideas would be very helpful.Thank you!
I just completed creating a replication job between a server at my location, where I have SA privileges, to a subscription server at a location where I have db_owner rights (no SA). When replication runs, the objects get created on the subscriber as userid.object rather then dbo.object. The subscriber permissions were set by clicking on "Replication", right clicking on "Publication", clicking on "Configure Publishing, Subscribers and Distribution...", clicking on Subscribers tab, choosing the subscriber and selecting "Use SQL Server Authentication". How do I cause replication to create the objects as dbo.object if I connect to the subscriber using an id defined as db_owner?
I need to create RDF files dynamically. As one example, I need to output a report that contains an OLAP table from an MDX query and will need to generate the RDL that represents the table on the fly. (Binding to a data source with any built-in control will not even come close to solving the problem. The actual requirements are extremely complex.)
In short... Rather than outputting the RDL XML the hard way is there an object model I can use to construct an RDL document with? Even if it's a bindhind-the-scenese, not-supported library?
I try to implement mirroring using certificate authentication. When I do this query :
create certificate Principal_cert with subject = 'Principal certificate', start_date = '2007/11/01', expiry_date = '2020/11/01'; GO
Create endpoint endpoint_Princ state = started
as tcp(listener_port = 7024, listener_ip = all)
for database_mirroring (authentication=certificate Principal_cert, encryption = disabled, role = all);
GO
I have this error :
Msg 1088, Level 15, State 1, Line 1
Cannot find the object "Principal_cert" because it does not exist or you do not have permissions.
I have also noticed that the error does not occured when I try this in the master database.
So, I have two questions:
1. Why SQL server does not find a certificate that just been created ? 2. Should the certificate be in the master database or in the database being mirrored ?
Hello all, What is an easy way of scripting all the database tables and sprocs automatically to a separate file each one? I can't find this option in SQL Server Management Studio. Or is any other way of uploading all objects to a Visual Source Safe project that does not require to copy and paste each script into a VSS sql script? Thanks! David
I am trying to create an assembly object when a report is initialized and I am getting the error:
[rsCompilerErrorInExpression] The BackgroundColor expression for the textbox 'textbox2' contains an error: [BC30390] 'ReportExprHostImpl.CustomCodeProxy.X' is not accessible in this context because it is 'Private'
In the Code tab, I have: Dim X As namespace.classname Protected Overrides Sub OnInit() X = new namespace.classname() End Sub
In my color field, I have "=code.X.color" If I replace the color field with "=namespace.classname.color" and have color be a shared property, then it works. However, I ultimately need the color to be based on individual user settings, so I cannot use the shared property approach.
Any ideas on how to get around this "because it is private" error?
FYI, I am trying to replicate the concept of themes using report formatting information pulled from a database.
I had a SSIS Package which was developed on Beta Version Of SSIS, Now We have Standard Edition Of SSIS(Sql2k5) Installed.
In the Package we have One Flat file Source, One Script Component and A Sql Server as Target, We are programaticaly creating the package, Now When we open this Package in the Designer and Try to Run We get this error
"The script component is configured to pre-compile the script, but binary code is not found. Please visit the IDE in Script Component Editor by clicking Design Script button to cause binary code to be generated. "
Now when we just open the Script Designer and close it, The package runs.
I found the Error description at this link http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.dts.runtime.hresults.dts_e_binarycodenotfound.aspx
but could not find any help on this.
Same thing use to work on Beta version now it is now working. From my understanding the problem is that in beta version, the script use to run at runtime, Now what they have done is that they generate a compiled code out of script and run.
My problem is that since i am using C# code to generate the package, How Will I Create a Binary Code out of Script.
I'm having a problem executing a SQLCLR function: this function calls a web services that processes a query to a data base and returns a table to be used in a stored procedure. In a low concurrency scenario (not to many clients connected), the function returns correctly, however when the concurrency level is increased we have a SQLCLR command execution problem (all the SQLCLR processes hangs), making the server unavailable to all web services processes.
At first we thought the problem could be the SQLCLR, since the web services is 100% available, all the time. We monitored to come to this conclusion. Do you know of some SQLCLR bug?
Could someone help me with this? I'm in a difficult situation with my client, considering that we defended the MS SQLServer technology and now it's not working properly.
I'll keep trying new threads here... sooner or later, I'm sure an expert Microsoft CLR employee will gladly lend a helping hand!
The pieces:
1. SQL 2005, MS Windows Server 2003, Standard Edition, SP 1
2. .NET 2005/C#
3. Instance of SQL 2005 running locally.
Trigger on local SQL2005 DB table INSERT calls 2 CLR Functions:
1. Retrieve data from SQL2005 DB table and populate local DBF through OLEDB
2. Call external 16-bit application (written in Clipper) that iterates through local DBF records (added from step 1 above) and populates DBF on domain resource.
Step 2 detail:
External 16-bit application is called by CreateProcessAsUser after impersonating token.
THIS IS SUCCESSFUL - IF: I populate SQL2005 DB table using TSQL insert statement. The trigger executes, Step 1 and Step 2 execute perfectly!
THIS IS UNSUCCESSFUL - IF: The SQL2005 DB table is populated by synchronizing SQL Mobile Server database from a SQL Mobile Edition 2005 PDA emulation. The trigger executes. Step 1 executes perfectly. Step 2 executes without exceptions. HOWEVER, the 16-bit application does not execute! Remember, no exceptions. In fact, the result variable returns true from function below:
result = ProcessUtility.CreateProcessAsUser(
hDupedToken,
null,
@"C:MobileDBMobile.exe",
ref sa, ref sa,
false, 0, IntPtr.Zero,
@"C:MobileDB", ref si, ref pi
);
Also, if I Right-click on the Step 2 function in the Server Explorer and click "Execute", it works perfectly. Domain DBF is updated successfully.
So, in short CLR "CreateProcessAsUser" is not doing it's job when the trigger is fired after SQL 2005 DB is populated via replication/sychronization. I would appreciate a response... Thx!
My .NET SQL UDF needs do very complex computation on every call regardless on user input. I would be very happy if I could cache this computed data somewhere in SQL Server memory. And then I should not need to recompute this complex information on every UDF call. Is it possible to cache something inside SQL Server from CLR ?
I'm personally in favor of using the SQL CLR where appropriate, although I'm wondering what the negative consequences of enabling SQL CLR might be? Its disabled by default within SQL Server 2005 and most likely 2008, so what was the reason behind this ... beyond the fear of the DBA enabling something he might not himself fully understand.
By using impersonation I am able to push data to network path / old fashioned DBF's. Of course, I must use unsafe. I am unable, however to successfully run a "cmd.exe" process(), even if I populate the Username, Domain and password (with securestring). It authenticates correctly (checked by giving wrong password or bad username). But when it runs (even just a "cmd.exe"), I get an access is denied error...
System.Security.SecureString password = new System.Security.SecureString();
foreach (char c in "secret")
password.AppendChar(c);
Process p = new Process();
ProcessStartInfo si = new ProcessStartInfo("cmd.exe");
si.UserName = "MyName";
si.Password = password;
si.Domain = "MySecretDomain";
si.UseShellExecute = false;
try
{
p.StartInfo = si;
p.Start();
}
catch (Exception ex)
{
//handle the exception here (This exception handler will not handle the exception, but I get a
//Window popup (While executing my CLR!!!)
}
finally
{
sw.Close();
}
The message popup says: The application failed to initialize poperly (0xc0000142). Click on OK to terminate the application. I'm kind of at a loss...
I'm using a Windows 2003 server box with the latest SQL Server 2005, .NET 2.0/2005. Let me know if you need anything else.
Oh, just FYI - I am moving replicated data from SQL2005 server to a legacy app using DBF (FoxPro driver). I really need an external DOS app to process some data for the DOS application (Clipper).
I am searching for a way of using SQLCLR to do Bulk Insert/Copy within SQL Server 2005. I am not permit to use SQL command BULK INSERT with any of text based file csv, or xml etc. I did tried to use SqlBulkCopy within SQLCLR but failed, the context connection was not allowed, I did also use normal connection string with sa & pwd but no luck.
I understand that I can move bulk insert to a service such as windows, web or WCF but it is not on the card at present. Is there a way of doing this within CLR, size of bulk is fair about 2000+ rows.
If you have solution, sample or link would be appriciated.
I have an SQLCLR assembly which is required to connect to a remote WCF service. In order to do this in a host such as IIS you would need to store all your WCF configuration data (endpoints, types etc) in the Web.config or App.config (in a windows forms app). This begs the question: Where do you store configuration data for SQLCLR assemblies?
The System.Configuration assembly is available in the SQLCLR, but this assumes a Web or App config files exists? Does SQL have its own config file that you can keep your settings in which is called when the assembly is running from within the SQL process?
If this is not possible, should I rather be storing configuration data in the database itself?
This particular example relates to WCF configuration but is relevant for assemblies using Enterprise Library which is also config driven.
Just wondering which scenarios is suitable to use SQLCLR. Any kind of data access is not recommended I guess. Only things that cannot be easily done in TSQL should be done in SQLCLR but why? Can't those things be done in app layer itself? Scenarios recommended for SQL CLR: - External data access like filesystem, registry etc - Complex calculation - Recursion without data access (this can be implemented with CTE for data access)
If data access with SQL CLR is not recommended why should CLR should be even used and logic reside in database layer.. it makes no sense to me. Any thoughts??
I have just begun to delve into the SQLCLR objects in SQL Server 2005. I have created a simple VB function as a SQLFunction. Here's the code:
Imports System
Imports Microsoft.SqlServer.Server
Partial Public Class UserDefinedFunctions
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function FileDate(ByVal FilePath As String) As Date
Return FileDateTime(FilePath)
End Function
End Class
The function is run with this T-SQL:
declare @FileDate datetime
select @FileDate = dbo.FileDate('C:setup.bat)
select @FileDate
This works fine, but I had to set the Permission Level of the Visual Studio project to "Unsafe" rather than "External" in order to avoid the following error message:
A .NET Framework error occurred during execution of user defined routine or aggregate 'FileDate':
System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Is there any way to avoid having to set the permission level to "Unsafe"? If not, what does "unsafe" mean in terms of overall system security? Is it acceptable to use on an internal LAN?
I had DTS the Northwind sample database from SqlServer 2000 to 2005. It's went ok and no errors. Then, I created a SP named upGetCustomer, bascially it queries the Customers table and list some of it's fields and order by CustomerId,CustomerName, Country decrementally. SP is so simple and has no errors.
Then, I created a SqlServer project in VS2005 using C#. Add store procedure class as below, using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void Customers(string customerid) { using (SqlConnection sqlConn = new SqlConnection("context connection=true")) { sqlConn.Open(); SqlPipe sqlPipe = SqlContext.Pipe; SqlParameter param = new SqlParameter("@custId", SqlDbType.VarChar, 5); param.Value = customerid; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.CommandText = "upGetCustomer"; sqlCmd.Parameters.Add(param); SqlDataReader rdr = sqlCmd.ExecuteReader(); SqlContext.Pipe.Send(rdr); } }
I had taken method of created SQLCLR from source in Microsoft website, but coding is mine, and hopes it is correct. I used SqlConnection string as 'context connection=true' which I still not quite sure what does it means, hopes it mean current connection I am using on my Windows authentication.
The project did compiled & deployed OK on the VS2005 side.
The problem is that when I tried to locate the assembly on the Sql Server 2005, but can't find it anywhere on Sql Server.
I did try complied and deloyed again, it keeps saying there is an error in deployment as customers assembly is already exist on the database. I then, tried to remove this assembly on the database using SQL script, drop assembly customers in the Northwind database but got error saying it does not exist. So where is it???
I keep getting different answers from different people on regarding if you can or cannot kill the hosting sql server process with an unsafe assembly. Can you do this? If so could you please attach a sample demonstrating this?
Throughout the course of this book and even before it I have come across conflicting information regarding how SQLCLR attempts to resolve system/CLR assembly references. For example, prior to my latest read thourgh April BOL 2005, I thought SQLCLR attempted to resolve these references implicity for you via the local machine's GAC. Yet here is what I found while trying to help another person in this forum yesterday in BOL... Assembly Validation SQL Server performs checks on the assembly binaries uploaded by the CREATE ASSEMBLY statement to guarantee the following:
The assembly binary is well formed with valid metadata and code segments, and the code segments have valid Microsoft Intermediate language (MSIL) instructions.
The set of system assemblies it references is one of the following supported assemblies in SQL Server: Microsoft.Visualbasic.dll, Mscorlib.dll, System.Data.dll, System.dll, System.Xml.dll, Microsoft.Visualc.dll, Custommarshallers.dll, System.Security.dll, System.Web.Services.dll, and System.Data.SqlXml.dll. Other system assemblies can be referenced, but they must be explicitly registered in the database.
For assemblies created by using SAFE or EXTERNAL ACCESS permission sets:
The assembly code should be type-safe. Type safety is established by running the common language runtime verifier against the assembly.
The assembly should not contain any static data members in its classes unless they are marked as read-only.
The classes in the assembly cannot contain finalizer methods.
The classes or methods of the assembly should be annotated only with allowed code attributes. For more information, see Custom Attributes for CLR Routines.
Besides the previous checks that are performed when CREATE ASSEMBLY executes, there are additional checks that are performed at execution time of the code in the assembly:
Calling certain Microsoft .NET Framework APIs that require a specific Code Access Permission may fail if the permission set of the assembly does not include that permission.
For SAFE and EXTERNAL_ACCESS assemblies, any attempt to call .NET Framework APIs that are annotated with certain HostProtectionAttributes will fail.
COULD SOMEONE PLEASE GIVE ME THE DEFENITE ANSWER ON HOW THIS WORKS!
Hi, I've got a requirement for a procedure to write a text file and want to do it without using command line utilities.
I wrote a sqlclr which queries a db and writes the file that I need. After setting the external_access and database to trustworthy, It only works on my own machine, not on network shares.
Some threads I've found have been related to the "1 network hop" of Windows credentials, which most of us are probably familiar with.
It doesn't make sense to me that this is the problem, since I'm on my workstation, connecting to a local db instance and hopping one time to the shared server. Anyone know what the cause might be?
Code Block System.UnauthorizedAccessException: Access to the path '\isrc02Users3sgreene estwrite.txt' is denied. System.UnauthorizedAccessException: at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamWriter.CreateFile(String path, Boolean append) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize) at System.IO.StreamWriter..ctor(String path) at StoredProcedures.Inovah_JV(String& greeting)
I am trying to generate a SQL CLR stored procedure and i have done it too. Now the next step is to convert that *.dll file in to assembly. I am getting erro that. My server Database is on the LAN, not on my PC.
Here is the code which i have tried to register an assembly...
/* CREATE ASSEMBLY MyAssembly FROM 'C:Documents and SettingsAdministrator.ORC80My DocumentsVisual Studio 2005ProjectsMyDB1MyDB1inDebugMyDB1.dll'
WITH PERMISSION_SET=SAFE
GO */
and here is the error that i am getting...
/* Msg 6585, Level 16, State 1, Line 1
Could not impersonate the client during assembly file operation. */