Showing posts with label management. Show all posts
Showing posts with label management. Show all posts

Friday, February 24, 2012

C# Stored procedure

When I execute the stored procedure (a C# dll) from Management Studio, I get
the following error:
================================================== ===
Msg 6522, Level 16, State 1, Procedure LoadImageToDB, Line 0
A .NET Framework error occurred during execution of user defined routine or
aggregate 'LoadImageToDB':
System.Security.SecurityException: Request for the permission of type
'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
System.Security.SecurityException:
at
System.Security.CodeAccessSecurityEngine.CheckNRet urnSO(PermissionToken
permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32
unrestrictedOverride, Int32 create)
at System.Security.CodeAccessSecurityEngine.Assert(Co deAccessPermission
cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Assert()
at StoredProcedures.LoadImageToDB()
..
================================================== ==
Can anyone point me into the right direction? Thanks.
Hi,
Error 6522 is the wrapped .NET error code. you are calling a function
or assembly which isn=B4t *secure* for SQL Server, so step through your
code and try to see what is happening.
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
|||This is the message I get when I debug the code. Any ideas?
================================================== ==
A first chance exception of type 'System.Security.SecurityException'
occurred in mscorlib.dll
================================================== ==
"Jens" wrote:

> Hi,
> Error 6522 is the wrapped .NET error code. you are calling a function
> or assembly which isn′t *secure* for SQL Server, so step through your
> code and try to see what is happening.
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
>
|||How did you register the code as SAFE, UNSAFE or EXTERNAL_ACCESS ?
Depending on your settings the code isn=B4t allowed to execute several
things. There are only a few classes which are allowed to execute with
*only* safe permissions.
HTH; Jens Suessmeyer.
http://www.sqlserver2005.de
|||It is registered as SAFE. What do I need to change to make it work? Any help
is appreciated. Thanks.
"Jens" wrote:

> How did you register the code as SAFE, UNSAFE or EXTERNAL_ACCESS ?
> Depending on your settings the code isn′t allowed to execute several
> things. There are only a few classes which are allowed to execute with
> *only* safe permissions.
> HTH; Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
>
|||Guessing from the name LoadImagetoDB you'll need EXTERNAL_ACCESS in order to
access the image (file?) you want to load into the database.
HTH,
Jasper Smith (SQL Server MVP)
http://www.sqldbatips.com
"KMP" <KMP@.discussions.microsoft.com> wrote in message
news:0BC394CB-2E61-40F1-BC01-0439622CE994@.microsoft.com...[vbcol=seagreen]
> It is registered as SAFE. What do I need to change to make it work? Any
> help
> is appreciated. Thanks.
> "Jens" wrote:
|||When I do that, I get an error message saying "LoadImage failed because
assembly is not authorized for PERMISSION_SET = EXTERNAL_ACCESS". This is
just part of the error message.
"Jasper Smith" wrote:

> Guessing from the name LoadImagetoDB you'll need EXTERNAL_ACCESS in order to
> access the image (file?) you want to load into the database.
> --
> HTH,
> Jasper Smith (SQL Server MVP)
> http://www.sqldbatips.com
>
> "KMP" <KMP@.discussions.microsoft.com> wrote in message
> news:0BC394CB-2E61-40F1-BC01-0439622CE994@.microsoft.com...
>
>
|||Hello KMP,
http://www.sqljunkies.com/WebLog/kte...ssemblies.aspx
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/
|||Thanks for the link/solution. Is this the only way to do, is there no other
"simpler "option? Thanks.
"Kent Tegels" wrote:

> Hello KMP,
> http://www.sqljunkies.com/WebLog/kte...ssemblies.aspx
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>
|||Hello KMP,
ALTER DATABASE name SET TRUSTWORTHY ON
But then anything gets to run. Ick.
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/

C# Stored procedure

When I execute the stored procedure (a C# dll) from Management Studio, I get
the following error:
===================================================== Msg 6522, Level 16, State 1, Procedure LoadImageToDB, Line 0
A .NET Framework error occurred during execution of user defined routine or
aggregate 'LoadImageToDB':
System.Security.SecurityException: Request for the permission of type
'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
System.Security.SecurityException:
at
System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken
permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32
unrestrictedOverride, Int32 create)
at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission
cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Assert()
at StoredProcedures.LoadImageToDB()
.
====================================================
Can anyone point me into the right direction? Thanks.Hi,
Error 6522 is the wrapped .NET error code. you are calling a function
or assembly which isn=B4t *secure* for SQL Server, so step through your
code and try to see what is happening.
HTH, Jens Suessmeyer.
--
http://www.sqlserver2005.de
--|||This is the message I get when I debug the code. Any ideas?
====================================================
A first chance exception of type 'System.Security.SecurityException'
occurred in mscorlib.dll
====================================================
"Jens" wrote:
> Hi,
> Error 6522 is the wrapped .NET error code. you are calling a function
> or assembly which isn´t *secure* for SQL Server, so step through your
> code and try to see what is happening.
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
>|||How did you register the code as SAFE, UNSAFE or EXTERNAL_ACCESS ?
Depending on your settings the code isn=B4t allowed to execute several
things. There are only a few classes which are allowed to execute with
*only* safe permissions.
HTH; Jens Suessmeyer.
--
http://www.sqlserver2005.de
--|||It is registered as SAFE. What do I need to change to make it work? Any help
is appreciated. Thanks.
"Jens" wrote:
> How did you register the code as SAFE, UNSAFE or EXTERNAL_ACCESS ?
> Depending on your settings the code isn´t allowed to execute several
> things. There are only a few classes which are allowed to execute with
> *only* safe permissions.
> HTH; Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
>|||Guessing from the name LoadImagetoDB you'll need EXTERNAL_ACCESS in order to
access the image (file?) you want to load into the database.
--
HTH,
Jasper Smith (SQL Server MVP)
http://www.sqldbatips.com
"KMP" <KMP@.discussions.microsoft.com> wrote in message
news:0BC394CB-2E61-40F1-BC01-0439622CE994@.microsoft.com...
> It is registered as SAFE. What do I need to change to make it work? Any
> help
> is appreciated. Thanks.
> "Jens" wrote:
>> How did you register the code as SAFE, UNSAFE or EXTERNAL_ACCESS ?
>> Depending on your settings the code isn´t allowed to execute several
>> things. There are only a few classes which are allowed to execute with
>> *only* safe permissions.
>> HTH; Jens Suessmeyer.
>> --
>> http://www.sqlserver2005.de
>> --
>>|||When I do that, I get an error message saying "LoadImage failed because
assembly is not authorized for PERMISSION_SET = EXTERNAL_ACCESS". This is
just part of the error message.
"Jasper Smith" wrote:
> Guessing from the name LoadImagetoDB you'll need EXTERNAL_ACCESS in order to
> access the image (file?) you want to load into the database.
> --
> HTH,
> Jasper Smith (SQL Server MVP)
> http://www.sqldbatips.com
>
> "KMP" <KMP@.discussions.microsoft.com> wrote in message
> news:0BC394CB-2E61-40F1-BC01-0439622CE994@.microsoft.com...
> >
> > It is registered as SAFE. What do I need to change to make it work? Any
> > help
> > is appreciated. Thanks.
> >
> > "Jens" wrote:
> >
> >> How did you register the code as SAFE, UNSAFE or EXTERNAL_ACCESS ?
> >> Depending on your settings the code isn´t allowed to execute several
> >> things. There are only a few classes which are allowed to execute with
> >> *only* safe permissions.
> >>
> >> HTH; Jens Suessmeyer.
> >>
> >> --
> >> http://www.sqlserver2005.de
> >> --
> >>
> >>
>
>|||Thanks for the link/solution. Is this the only way to do, is there no other
"simpler "option? Thanks.
"Kent Tegels" wrote:
> Hello KMP,
> http://www.sqljunkies.com/WebLog/ktegels/articles/SigningSQLCLRAssemblies.aspx
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>|||I still can't get it work by turning on that option. I get the same error
message that I had listed in my very first posting. Any ideas?
"Kent Tegels" wrote:
> Hello KMP,
> ALTER DATABASE name SET TRUSTWORTHY ON
> But then anything gets to run. Ick.
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>|||Hello KMP,
Oh, that's ugly. Can you post the code throwing the error? I wonder what
you're doing...
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels|||Ok, here is my C# stored procedure. I am trying to read/write an image file
to the the database from the local hard drive. Please let me know what is
wrong. Thanks.
=====================================================using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Globalization;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void LoadImageToDB()
{
// Put your code here
SqlConnection con = new SqlConnection("server=localhost;integrated
security=true;database=RegPerfectDb");
//con.ConnectionString = "Context Connection=true";
SqlClientPermission perm = new
SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
perm.Assert();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM DAHS", con);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataSet ds = new DataSet("DAHS");
SqlCommand SqlCmd = new SqlCommand("SELECT * FROM DAHS", con);
int DAHS_ID = 0;
SqlDataReader SqlImgReader;
SqlCmd.CommandType = CommandType.Text;
FileStream fs;
byte[] MyData = null;
con.Open();
SqlImgReader = SqlCmd.ExecuteReader();
if (File.Exists(@."D:\RegPerfect\Bin\Reports\ReportsLogo.bmp"))
{
FileIOPermission filePerm = new
FileIOPermission(FileIOPermissionAccess.Read,
@."D:\RegPerfect\Bin\Reports\ReportsLogo.bmp");
filePerm.Assert();
fs = new
FileStream(@."D:\RegPerfect\Bin\Reports\ReportsLogo.bmp", FileMode.Open,
FileAccess.Read);
MyData = new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
da.UpdateCommand = new SqlCommand("UPDATE DAHS SET Logo = @.iLOGO
", con);
// Add the Parameters for the UPDATE Command
da.UpdateCommand.Parameters.Add("@.iLOGO", SqlDbType.Image,
(int)fs.Length, "Logo");
fs.Close();
}
else if (File.Exists(@."C:\RegPerfect\Bin\Reports\ReportsLogo.bmp"))
{
fs = new
FileStream(@."C:\RegPerfect\Bin\Reports\ReportsLogo.bmp", FileMode.Open,
FileAccess.Read);
MyData = new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
da.UpdateCommand = new SqlCommand("UPDATE DAHS SET Logo = @.iLOGO
", con);
// Add the Parameters for the UPDATE Command
da.UpdateCommand.Parameters.Add("@.iLOGO", SqlDbType.Image,
(int)fs.Length, "Logo");
fs.Close();
}
int DAHSIDOrd = SqlImgReader.GetOrdinal("DAHS_Id");
while (SqlImgReader.Read())
{
DAHS_ID = (int)SqlImgReader.GetValue(DAHSIDOrd);
}
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.FillSchema(ds, SchemaType.Source, "DAHS");
da.Fill(ds, "DAHS");
DataTable DAHSTable = ds.Tables["DAHS"];
DataRow myRow;
myRow = DAHSTable.Rows.Find(DAHS_ID);
myRow.BeginEdit();
myRow["Logo"] = MyData;
myRow.EndEdit();
da.Update(ds, "DAHS");
SqlImgReader.Close();
con.Close();
}
};
=====================================================
"Kent Tegels" wrote:
> Hello KMP,
> Oh, that's ugly. Can you post the code throwing the error? I wonder what
> you're doing...
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>|||Thanks a lot Kent. I guess I was trying to do something that was achievable
through a single UPDATE statment. I really really appreciate you help.
"Kent Tegels" wrote:
> Hello KMP,
> I'm not a CAS expert by any stretch of the imagination, but when I reduce
> your code to this:
> [Microsoft.SqlServer.Server.SqlProcedure]
> public static void LoadImageToDB()
> {
> SqlConnection con = new SqlConnection("server=localhost;integrated
> security=true;database=RegPerfectDb");
> //con.ConnectionString = "Context Connection=true";
> SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
> perm.Assert();
> FileStream fs;
> byte[] MyData = null;
> if (File.Exists(@."c:\ssa.dll"))
> {
> FileIOPermission filePerm = new
> FileIOPermission(FileIOPermissionAccess.Read,@."c:\ssa.dll");
> filePerm.Assert();
> fs = new FileStream(@."c:\ssa.dll", FileMode.Open,FileAccess.Read);
> MyData = new byte[fs.Length];
> fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
> }
> }
> I get this exception on the filePerm.Asset():
> System.Security.SecurityException: Stack walk modifier must be reverted before
> another modification of the same type can be performed.
> System.Security.SecurityException:
> at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission
> cap, StackCrawlMark& stackMark)
> at System.Security.CodeAccessPermission.Assert()
> at StoredProcedures.LoadImageToDB()
> Is there a particular reason that you are asserting these permissions?
> Also, if you're simply trying to load a image into a database, this might
> be easier:
> create table dbo.images
> (
> img varbinary(max)
> )
> go
> insert into dbo.images
> select * from
> openrowset(bulk 'C:\etc\ktegels\My Pictures\1px.gif'
> ,single_blob) as p
> go
> select * from dbo.images
> go
>
> Any help?
> Thanks,
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>|||Hi Kent,
I was using the UPDATE statement to update the database with the image
stored on the hard drive. I wrote a small sql script that checks for the
existence of a certain drive, for example (pseudocode)-
IF Exists 'D:\'
UPDATE <table> SET <colname> = (SELECT * FROM OPENROWSET(BULK
'D:\test.bmp', SINGLE_BLOB) AS P)
ELSE
UPDATE <table> SET <colname> = (SELECT * FROM OPENROWSET(BULK
'C:\test.bmp', SINGLE_BLOB) AS P)
After the first IF is executed, the else part also gets executed. I am not
sure why this is happening. Can you please help me?
Thanks.
"Kent Tegels" wrote:
> Hello KMP,
> I'm not a CAS expert by any stretch of the imagination, but when I reduce
> your code to this:
> [Microsoft.SqlServer.Server.SqlProcedure]
> public static void LoadImageToDB()
> {
> SqlConnection con = new SqlConnection("server=localhost;integrated
> security=true;database=RegPerfectDb");
> //con.ConnectionString = "Context Connection=true";
> SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
> perm.Assert();
> FileStream fs;
> byte[] MyData = null;
> if (File.Exists(@."c:\ssa.dll"))
> {
> FileIOPermission filePerm = new
> FileIOPermission(FileIOPermissionAccess.Read,@."c:\ssa.dll");
> filePerm.Assert();
> fs = new FileStream(@."c:\ssa.dll", FileMode.Open,FileAccess.Read);
> MyData = new byte[fs.Length];
> fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
> }
> }
> I get this exception on the filePerm.Asset():
> System.Security.SecurityException: Stack walk modifier must be reverted before
> another modification of the same type can be performed.
> System.Security.SecurityException:
> at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission
> cap, StackCrawlMark& stackMark)
> at System.Security.CodeAccessPermission.Assert()
> at StoredProcedures.LoadImageToDB()
> Is there a particular reason that you are asserting these permissions?
> Also, if you're simply trying to load a image into a database, this might
> be easier:
> create table dbo.images
> (
> img varbinary(max)
> )
> go
> insert into dbo.images
> select * from
> openrowset(bulk 'C:\etc\ktegels\My Pictures\1px.gif'
> ,single_blob) as p
> go
> select * from dbo.images
> go
>
> Any help?
> Thanks,
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>|||Here you go. It is pretty straight forward piece of code, but both IF and
ELSE parts get executed. Thanks for all the help Kent.
=====================================================
DECLARE
@.OutputPath VARCHAR(100),
@.Result INT
SET NOCOUNT ON
SELECT @.OutputPath = '\Test\Logo.bmp'
SELECT @.OutputPath = '"' + 'dir ' + 'D:' + @.OutputPath + '"'
EXEC @.Result = master..xp_cmdshell @.OutputPath , NO_OUTPUT
--Check the available drives
IF @.Result = 0
UPDATE Test SET Logo = (SELECT * FROM OPENROWSET(BULK 'D:\Test\Logo.bmp',
SINGLE_BLOB) AS P)
ELSE
UPDATE Test SET Logo = (SELECT * FROM OPENROWSET(BULK 'C:\Test\Logo.bmp',
SINGLE_BLOB) AS P)
=====================================================
"Kent Tegels" wrote:
> Hello KMP,
> > IF Exists 'D:\'
> > UPDATE <table> SET <colname> = (SELECT * FROM OPENROWSET(BULK
> > 'D:\test.bmp', SINGLE_BLOB) AS P)
> > ELSE
> > UPDATE <table> SET <colname> = (SELECT * FROM OPENROWSET(BULK
> > 'C:\test.bmp', SINGLE_BLOB) AS P)
> > After the first IF is executed, the else part also gets executed. I am
> > not sure why this is happening. Can you please help me?
> Well, it depends how many times you're executing as part of some other query
> and how the "if exists" works. If nothing else, try wrapping the if body
> and else body in begin end (even though they should be just single statements,
> I know...)
> Could you post the actual code too?
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>|||I put PRINT statements and that is how I know that both IF and ELSE parts are
getting executed. Also in the results pane in Management Studio, I get an
error message saying 'C:\Test\Logo.bmp' path not found (which is correct,
because I expect the IF part to be executed ONLY and not ELSE). Thnx.
"Kent Tegels" wrote:
> Hello KMP,
> Okay, take a look at the estimated execution plan and you'll see that fully
> evaluates if the bulk load is likely to succeed in either cause. I don't
> believe it actually executes both statements, but it does seem to be trying
> to figure out if it can or not, so that's why it looks like it is.
> You can probably see which one is actually getting executed by adding 'print
> true' and 'print false' in begin-end pairs for each condition.
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>|||Sorry, but I don't understand. I ran the same query and my table does not
get updated. So what is the suggested solution to the problem? Thanks.
"Kent Tegels" wrote:
> Hello KMP,
> Right, you're getting the not found not because the bulk read is executing,
> but because the Query Optimizer seems to be heck-bent on determining ahead
> of time if it can be.
> I just ran the query and only the true or false part were actually being
> executed on my laptop...
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>|||Please help, I can't get it to work.
"KMP" wrote:
> Sorry, but I don't understand. I ran the same query and my table does not
> get updated. So what is the suggested solution to the problem? Thanks.
> "Kent Tegels" wrote:
> > Hello KMP,
> >
> > Right, you're getting the not found not because the bulk read is executing,
> > but because the Query Optimizer seems to be heck-bent on determining ahead
> > of time if it can be.
> >
> > I just ran the query and only the true or false part were actually being
> > executed on my laptop...
> >
> > Thank you,
> > Kent Tegels
> > DevelopMentor
> > http://staff.develop.com/ktegels/
> >
> >
> >|||Thanks for all your help, Kent.
"Kent Tegels" wrote:
> Hello KMP,
> > Sorry, but I don't understand. I ran the same query and my table does
> > not get updated. So what is the suggested solution to the problem?
> > Thanks.
> Okay, here's some code that seems to work for me. Note that I'm very paranoid
> about XP_CMDSHELL, so I re-did the test-for-file-existance as a CLRUDF.
> using System;
> using System.Data;
> using System.Data.SqlClient;
> using System.Data.SqlTypes;
> using System.IO;
> public partial class FileFunctions
> {
> public static SqlBoolean FileExists(SqlString FilePath) {
> try { if (File.Exists(FilePath.Value))
> return SqlBoolean.True;
> else
> return SqlBoolean.False;
> } catch (Exception ex) {
> return(SqlBoolean.Null);
> }
> }
> };
> Here's the updated script. One row in the table. :)
> drop table dbo.images
> go
> drop function dbo.FileExists
> go
> drop assembly fileFunctions
> go
> create assembly FileFunctions from 'c:\etc\ktegels\examples\FileExist\FileExist\bin\Debug\FileExist.dll'
> with permission_set=external_access
> go
> create function dbo.FileExists(@.FilePath nvarchar(4000)) returns bit with
> execute as caller as external name FileFunctions.FileFunctions.FileExists
> go
> create table dbo.images(pkid tinyint identity(1,1) primary key,[name] varchar(8),blob
> varbinary(max))
> go
> sp_configure 'clr enabled','1'
> go
> reconfigure
> go
> if dbo.FileExists('c:\one.txt')=1
> begin
> insert into images([name],blob)
> select 'one.txt',BulkColumn from openrowset(bulk 'c:\one.txt',single_blob) p
> end
> else
> begin
> insert into images([name],blob)
> select '2.txt',bulkcolumn from openrowset(bulk 'c:\2.txt',single_blob) p
> end
> go
> select cast(blob as varchar(max)) from dbo.images
> go
> sp_configure 'clr enabled','0'
> go
> reconfigure
> go
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>
>

C# Stored procedure

When I execute the stored procedure (a C# dll) from Management Studio, I get
the following error:
========================================
=============
Msg 6522, Level 16, State 1, Procedure LoadImageToDB, Line 0
A .NET Framework error occurred during execution of user defined routine or
aggregate 'LoadImageToDB':
System.Security.SecurityException: Request for the permission of type
'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
System.Security.SecurityException:
at
System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken
permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32
unrestrictedOverride, Int32 create)
at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission
cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Assert()
at StoredProcedures.LoadImageToDB()
.
========================================
============
Can anyone point me into the right direction? Thanks.Hi,
Error 6522 is the wrapped .NET error code. you are calling a function
or assembly which isn=B4t *secure* for SQL Server, so step through your
code and try to see what is happening.
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--|||This is the message I get when I debug the code. Any ideas?
========================================
============
A first chance exception of type 'System.Security.SecurityException'
occurred in mscorlib.dll
========================================
============
"Jens" wrote:

> Hi,
> Error 6522 is the wrapped .NET error code. you are calling a function
> or assembly which isn′t *secure* for SQL Server, so step through your
> code and try to see what is happening.
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
>|||How did you register the code as SAFE, UNSAFE or EXTERNAL_ACCESS ?
Depending on your settings the code isn=B4t allowed to execute several
things. There are only a few classes which are allowed to execute with
*only* safe permissions.
HTH; Jens Suessmeyer.
http://www.sqlserver2005.de
--|||It is registered as SAFE. What do I need to change to make it work? Any help
is appreciated. Thanks.
"Jens" wrote:

> How did you register the code as SAFE, UNSAFE or EXTERNAL_ACCESS ?
> Depending on your settings the code isn′t allowed to execute several
> things. There are only a few classes which are allowed to execute with
> *only* safe permissions.
> HTH; Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
>|||Guessing from the name LoadImagetoDB you'll need EXTERNAL_ACCESS in order to
access the image (file?) you want to load into the database.
HTH,
Jasper Smith (SQL Server MVP)
http://www.sqldbatips.com
"KMP" <KMP@.discussions.microsoft.com> wrote in message
news:0BC394CB-2E61-40F1-BC01-0439622CE994@.microsoft.com...[vbcol=seagreen]
> It is registered as SAFE. What do I need to change to make it work? Any
> help
> is appreciated. Thanks.
> "Jens" wrote:
>|||When I do that, I get an error message saying "LoadImage failed because
assembly is not authorized for PERMISSION_SET = EXTERNAL_ACCESS". This is
just part of the error message.
"Jasper Smith" wrote:

> Guessing from the name LoadImagetoDB you'll need EXTERNAL_ACCESS in order
to
> access the image (file?) you want to load into the database.
> --
> HTH,
> Jasper Smith (SQL Server MVP)
> http://www.sqldbatips.com
>
> "KMP" <KMP@.discussions.microsoft.com> wrote in message
> news:0BC394CB-2E61-40F1-BC01-0439622CE994@.microsoft.com...
>
>|||Hello KMP,
http://www.sqljunkies.com/WebLog/kt...op.com/ktegels/|||Thanks for the link/solution. Is this the only way to do, is there no other
"simpler "option? Thanks.
"Kent Tegels" wrote:

> Hello KMP,
> http://www.sqljunkies.com/WebLog/kt...op.com/ktegels/
>
>|||Hello KMP,
ALTER DATABASE name SET TRUSTWORTHY ON
But then anything gets to run. Ick.
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/

Sunday, February 19, 2012

C# and SQL Server 2005, Same Query Different Results (More Rows)

Hi,

I execute this query in SQL Server 2005 Management Studio:

SELECT c.id, c.clientname
FROM NFClients AS c INNER JOIN
NFExportGroups AS eg ON eg.cid = c.id INNER JOIN
NFExportGroupInfo AS ei ON ei.exportid = eg.exportid
WHERE (ei.meterid = 4938) AND (NOT (eg.emailgroup IS NULL))

I get one row returned and it is correct.

Then I go to Visual Studio 2005, to my C-Sharp application, and I use the same query to populate two indexes of 'rowvalues', my trusty two-dimensional string array:

Code Snippet

SqlCommand sqlcmdExx = new SqlCommand("SELECT c.id, c.clientname from NFClients AS c INNER JOIN " +

"NFExportGroups AS eg ON eg.cid = c.id INNER JOIN NFExportGroupInfo AS ei ON ei.exportid = eg.exportid " +

"WHERE (ei.meterid = " + comparedgroupids[i, 2].ToString() + ") AND (NOT (eg.emailgroup IS NULL))", sqlconnBuildDataGridViewSet);

SqlDataReader sqldrExx = sqlcmdExx.ExecuteReader();

while (sqldrExx.Read())

{

rowvalues[i, 2] = sqldrExx.GetValue(1).ToString();

rowvalues[i, 3] = sqldrExx.GetValue(0).ToString();

}

sqldrExx.Close();

This time, the SqlDataReader picks up two rows, and the second one, with a different c.id and c.clientname does have a NULL value for eg.emailgroup. I have verified that the value of comparedgroupids[i, 2] is 4938, and I have also confirmed that sqlcmdExx.CommandText is exactly the same as the query I run in the SQL Server Management Studio. Why do I get different results with same query on the same database?

Thanks.

Dale

I'm not sure as to the cause of the difference but try using "(eg.mailgroup IS NOT NULL)" instead of (NOT (eg.emailgroup IS NULL))|||

Hi,

Found out this morning it was my mistake, I was looking at the wrong copy of the database. Sorry about that.

Dale

Thursday, February 16, 2012

Bye-Bye Web Synchronization

I'm using the Microsoft Sample Code to create the subscription. First on the Publisher I delete any subscription manually using SQL Server Management Studio. Then on the client using SQL Express Management studio, I delete the subscription on the subscribing PC.

So my code starts off presumably with database engines on subscriber and publisher having no subscriptions. It then tries to create the subscription on the client PC and then synchronize it.

Again this is Web Synchronization, and the websync siagnostic information on the publisher/distributor/iis machine all looks good, "success" in all the right places.

I get the error below, indicating the subscription already exists when I go to create the subscription.

I look in SQL Express subscriber and sure enough the subscription is back. But I right click on it in the Management Studio and select "Properties" and I get an error saying the subscription doesn't exist (even though I see it in Management Studio) or I don't have access to it. I'm logged in with Administrator credentials.

On the publishing server, the subscription is not created. The publication is set for anonymous synching.

Here is the exception trapped by my code

System.ApplicationException: The subscription could not be synchronized. Verify that the subscription has been defined correctly. > System.ApplicationException: The subscription could not be created. Verify that the subscription has been defined correctly. > Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. > System.Data.SqlClient.SqlException: Cannot create the subscription because the subscription already exists in the subscription database. Only one subscription to the same publication is allowed in each subscription database. Drop the subscription and add it again if necessary. If the problem persists, replication metadata might be incorrect; see Books Online for troubleshooting information.
The subscription properties table 'MSsubscription_properties' does not exist in the current database.

So apparently the subscription gets partially created, and then fails and is inaccessible, but holding space.

I'll follow this post with the code in the next reply.

Thanks for any help, I need help figuring out:

1) How to create the subscription correctly?, and

2) How to detect that it is already there so I won't try to create it again?, and

3) How to synch it correctly?

I am using the sample codes and books online.

SQLExpress subscribing client and SQL Server publisher are on SP2.

David

'Here is the code
Dim publicationName As String = "CALM"
Dim publisherName As String = "DEV2K3"
Dim subscriberName As String = "(local)\SQLEXPRESS"
Dim subscriptionDbName As String = "dbName_on_subscriber"
Dim publicationDbName As String = "dbName_on_publisher"
'Dim hostname As String = My.Computer.Name
Dim webSyncUrl As String = "https://myserver.mydomain.com/replication/replisapi.dll"

'Create the Subscriber connection.
Dim conn As ServerConnection = New ServerConnection(subscriberName)

' Create the objects that we need.
Dim subscription As MergePullSubscription

Try
' Connect to the Subscriber.
conn.Connect()
' Define the pull subscription.
subscription = New MergePullSubscription()
subscription.ConnectionContext = conn
subscription.PublisherName = publisherName
subscription.PublicationName = publicationName
subscription.PublicationDBName = publicationDbName
subscription.DatabaseName = subscriptionDbName
subscription.SubscriberType = MergeSubscriberType.Anonymous
subscription.UseWebSynchronization = True
subscription.InternetUrl = webSyncUrl
subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication
subscription.InternetLogin = "mylogin"
subscription.InternetPassword = "mypassword"
subscription.CreateSyncAgentByDefault = True
Try
subscription.Create()
Catch ex As Exception
Throw New ApplicationException("The subscription could not be " + _
"created. Verify that the subscription has " + _
"been defined correctly.", ex)
End Try
Dim agent As MergeSynchronizationAgent
If subscription.LoadProperties() Then
agent = subscription.SynchronizationAgent
If agent.PublisherSecurityMode = Nothing Then
agent.PublisherSecurityMode = SecurityMode.Integrated
agent.Distributor = "myserver.mydomain.com"
agent.DistributorSecurityMode = SecurityMode.Integrated
agent.UseWebSynchronization = True
agent.InternetUrl = webSyncUrl
agent.InternetSecurityMode = SecurityMode.Standard
agent.InternetLogin = "mydomain\mylogin"
agent.InternetPassword = "mypassword"
End If
agent.OutputVerboseLevel = 1
agent.Output = ""
agent.Synchronize()
Else
Throw New ApplicationException(String.Format( _
"A subscription to '{0}' does not exist on {1}", _
publicationName, subscriberName))
End If
Catch ex As Exception
Throw New ApplicationException("The subscription could not be " + _
"synchronized. Verify that the subscription has " + _
"been defined correctly.", ex)
Finally
conn.Disconnect()
End Try|||Hope everybody had a good weekend!
Pray for rain in Texas, we're dry.

Well on this issue I have proceeded to determine that the web synch is not configured correctly somehow, and I'm trying to get through that issue. I may end up spend the $$ with Microsoft support.

Using the Microsoft Synchronization Manager I can not get the subscription to work with ftp snapshot.

I get all the way to the point that the https://mywebserver.com/replication/replisapi.dll?diag is showing all success.

I have a client PC on the same segment, no firewalls between, domain names in hosts file to insure they resolve exactly as on the certificate, and so that's all resulting in a successful diagnostics page.

But from that same client PC with SQL Server Express on it I am attempting to get the subscription correct even with the Synch Manager and with the SQL Server Management Studio Express, the dropmergesub used to clean up, and cleanining up on the Publisher also, then attempting the subscription again, same failures.

So in SQL Manager express I go to Replication, Local Subscriptions, nothing is there. I right click, and select New Subscription. I get the Wizard. I try the web address and SQL authentication and get SQL Server error 53, Named Pipes provider error 40, could not open connection. That's expected at this point. But since I'm on the same segment, domain and logged in as a Domain Admin. I connect to the server from the new subscription Wizard and see the publication. I select it and select the database it is going into on the SQL Express client, setting it as a pull subscription. I mark it for Web Synchronization, snapshot to transfer at first, on demand only. It starts off showing progress then fails, saying "The subscription already exists. (New Subscription Wizard)"

So either something is going wrong in the subscription process, or something is wrong in the clean up of my previous attempts.

Keep in mind, however, that ultimately I do not want to subscribe on the domain, I want to subscribe from clients that are never on the domain, web only.

Do you have any insights into what I'm screwing up here?

Thanks,

David|||

Okay, I ran this again after deleting the subscription in SQL Management Studio Express on the client PC
sp_dropmergepullsubscription @.publication=N'mypub',@.publisher=N'myserver', @.publisher_db = N'mydb'

But I found this among the stored procedures and ran it on the publishing server, though I haven't seen it mentioned anywhere:
sp_cleanupdbreplication, and it totally nuked the publication. So I totally recreated the publication from scratch, getting all success along the way.

From a client PC browser I browse to https://myserver/replication/replisapi.dll?diag and I get prompted as expected for my ID and password, I use a domain admin credentials, and I get the SQL Websync Diagnostic Information page, and it shows all success. As the app user ID, I get access denied. I understand this is proper and what I should expect.

Then I set up the subscription on SQL Server Express on the client laptop. It says all success too.

So I open the Microsoft Synchronization Manager and try to synch the subscription and it says it can't connect to https://.... but doesn't show me the rest of the message, because I get a popup error reporting screen that sends the following error to Microsoft, and nukes out my app so I can't read anything.

This is the report getting sent to Microsoft.

Event Type: Error
Event Source: Application Error
Event Category: (100)
Event ID: 1000
Date: 3/26/2007
Time: 11:12:41 AM
User: N/A
Computer: DELL4150
Description:
Faulting application mobsync.exe, version 5.1.2600.2180, faulting module comctl32.dll, version 6.0.2900.2982, fault address 0x0006d0cc.

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
Data:
0000: 41 70 70 6c 69 63 61 74 Applicat
0008: 69 6f 6e 20 46 61 69 6c ion Fail
0010: 75 72 65 20 20 6d 6f 62 ure mob
0018: 73 79 6e 63 2e 65 78 65 sync.exe
0020: 20 35 2e 31 2e 32 36 30 5.1.260
0028: 30 2e 32 31 38 30 20 69 0.2180 i
0030: 6e 20 63 6f 6d 63 74 6c n comctl
0038: 33 32 2e 64 6c 6c 20 36 32.dll 6
0040: 2e 30 2e 32 39 30 30 2e .0.2900.
0048: 32 39 38 32 20 61 74 20 2982 at
0050: 6f 66 66 73 65 74 20 30 offset 0
0058: 30 30 36 64 30 63 63 006d0cc

David

|||

I ran it again and got that the Synch failed, and it says "The parameter is incorrect:" then has a funny character on the end of the string.

David

|||

I finally discovered the websync log in IIS in the replication folder and it has this very interesting clue:

CReplicationListenerWorker , 2007/03/26 19:59:50.828, 1952, 174, S2, INFO: =============== START PROCESSING REQUEST ==============
CReplicationListenerWorker , 2007/03/26 19:59:50.828, 1952, 298, S2, INFO: Processed request type: MESSAGE_TYPE_SyncContentsUpload.
replrec!FillErrorInfo , 2007/03/26 19:59:50.937, 1952, 19823, S1, ERROR: ErrNo = 0x80045901, ErrSrc = <null>, ErrType = 9, ErrStr = The process could not connect to Distributor 'dev01.ensourcebsi.com'.
DatabaseReconciler , 2007/03/26 19:59:50.937, 1952, 19935, S2, :T:,110,0,10,,,,,,,
DatabaseReconciler , 2007/03/26 19:59:50.937, 1952, 19942, S2, INFO: Session Highlights: FAIL, WEBSYNC_SERVER,
ReconcilerHost , 2007/03/26 19:59:50.937, 1952, 189, S1, ERROR: ReconcilerHost::Initialize failed, hr = 0x80045901.
CReplicationListenerWorker , 2007/03/26 19:59:50.937, 1952, 315, S1, ERROR: Failure initializing ReconcilerHost, hr = 0x80045901.
CReplicationListenerWorker , 2007/03/26 19:59:50.937, 1952, 396, S2, INFO: =============== DONE PROCESSING REQUEST ===============

Do you know what this is telling me?

David

|||My final solution: I will not use Web Synchronization nor SQL server Replication for my software product, it is not suitable in this case.

Instead I'm using Visual Studio and writing my own web service and my own business logic to synchronize my data.

David