Showing posts with label execute. Show all posts
Showing posts with label execute. Show all posts

Monday, March 19, 2012

Calculate % qry

Hi,

I am trying to execute a query which calculate % on group by. here is the query

SELECT C.USR_HIGHEST_DEGREE,COUNT(DISTINCT C.MASTER_CUSTOMER_ID) AS [# MEM],(convert(numeric(5,2),COUNT(DISTINCT C.MASTER_CUSTOMER_ID))

/ (


SELECT convert(numeric(5,2),COUNT(CC.MASTER_CUSTOMER_ID))

FROM MBR_PRODUCT AS MPP WITH (NOLOCK) INNER JOIN
PRODUCT AS PP WITH (NOLOCK) ON MPP.PRODUCT_ID = PP.PRODUCT_ID INNER JOIN
ORDER_MASTER AS AA WITH (NOLOCK) INNER JOIN
CUSTOMER AS CC WITH (NOLOCK) ON AA.SHIP_MASTER_CUSTOMER_ID = CC.MASTER_CUSTOMER_ID INNER JOIN
ORDER_DETAIL AS BB WITH (NOLOCK) ON AA.ORDER_NO = BB.ORDER_NO ON MPP.PRODUCT_ID = BB.PRODUCT_ID
WHERE (CC.CUSTOMER_STATUS_CODE = 'ACTIVE') AND (BB.CYCLE_END_DATE >= GETDATE()) AND (AA.ORDER_STATUS_CODE = 'A') AND
(BB.LINE_STATUS_CODE = 'A') AND (BB.FULFILL_STATUS_CODE IN ('A', 'G')) AND (MPP.LEVEL1 IN ('NATIONAL'))

)*100 AS [%]

FROM MBR_PRODUCT AS MP WITH (NOLOCK) INNER JOIN
PRODUCT AS P WITH (NOLOCK) ON MP.PRODUCT_ID = P.PRODUCT_ID INNER JOIN
ORDER_MASTER AS A WITH (NOLOCK) INNER JOIN
CUSTOMER AS C WITH (NOLOCK) ON A.SHIP_MASTER_CUSTOMER_ID = C.MASTER_CUSTOMER_ID INNER JOIN
ORDER_DETAIL AS B WITH (NOLOCK) ON A.ORDER_NO = B.ORDER_NO ON MP.PRODUCT_ID = B.PRODUCT_ID
WHERE (C.CUSTOMER_STATUS_CODE = 'ACTIVE') AND (B.CYCLE_END_DATE >= GETDATE()) AND (A.ORDER_STATUS_CODE = 'A') AND
(B.LINE_STATUS_CODE = 'A') AND (B.FULFILL_STATUS_CODE IN ('A', 'G')) AND (MP.LEVEL1 IN ('NATIONAL'))
GROUP BY C.USR_HIGHEST_DEGREE

My problem here it , query gives error. I would appreciate if someone can give me any idea how to go about this. I tried calculating % outside sql but still doesn't work.

Any help would be appreciate.

learnasp:

My problem here it , query gives error

Please tell us the exact error.

|||

Hi,

Thanks for your reply. The error i get is

"Incorrect snytax near the keyword 'AS'.

But both queries run without any eroor separately. I run the nested select and main without nest select. Both give answers. Now I don't know what is problem.

Thanks

|||

I did not get any parsing error if I put a bracket after the multiply by 100 as shown below in red.

---

SELECT C.USR_HIGHEST_DEGREE,COUNT(DISTINCT C.MASTER_CUSTOMER_ID) AS [# MEM],(convert(numeric(5,2),COUNT(DISTINCT C.MASTER_CUSTOMER_ID))

/ (

SELECT convert(numeric(5,2),COUNT(CC.MASTER_CUSTOMER_ID))

FROM MBR_PRODUCT AS MPP WITH (NOLOCK) INNER JOIN
PRODUCT AS PP WITH (NOLOCK) ON MPP.PRODUCT_ID = PP.PRODUCT_ID INNER JOIN
ORDER_MASTER AS AA WITH (NOLOCK) INNER JOIN
CUSTOMER AS CC WITH (NOLOCK) ON AA.SHIP_MASTER_CUSTOMER_ID = CC.MASTER_CUSTOMER_ID INNER JOIN
ORDER_DETAIL AS BB WITH (NOLOCK) ON AA.ORDER_NO = BB.ORDER_NO ON MPP.PRODUCT_ID = BB.PRODUCT_ID
WHERE (CC.CUSTOMER_STATUS_CODE = 'ACTIVE') AND (BB.CYCLE_END_DATE >= GETDATE()) AND (AA.ORDER_STATUS_CODE = 'A') AND
(BB.LINE_STATUS_CODE = 'A') AND (BB.FULFILL_STATUS_CODE IN ('A', 'G')) AND (MPP.LEVEL1 IN ('NATIONAL'))

)*100)AS [%]

FROM MBR_PRODUCT AS MP WITH (NOLOCK) INNER JOIN
PRODUCT AS P WITH (NOLOCK) ON MP.PRODUCT_ID = P.PRODUCT_ID INNER JOIN
ORDER_MASTER AS A WITH (NOLOCK) INNER JOIN
CUSTOMER AS C WITH (NOLOCK) ON A.SHIP_MASTER_CUSTOMER_ID = C.MASTER_CUSTOMER_ID INNER JOIN
ORDER_DETAIL AS B WITH (NOLOCK) ON A.ORDER_NO = B.ORDER_NO ON MP.PRODUCT_ID = B.PRODUCT_ID
WHERE (C.CUSTOMER_STATUS_CODE = 'ACTIVE') AND (B.CYCLE_END_DATE >= GETDATE()) AND (A.ORDER_STATUS_CODE = 'A') AND
(B.LINE_STATUS_CODE = 'A') AND (B.FULFILL_STATUS_CODE IN ('A', 'G')) AND (MP.LEVEL1 IN ('NATIONAL'))
GROUP BY C.USR_HIGHEST_DEGREE

Wednesday, March 7, 2012

Cache: rsInvalidDataSourceCredentialSetting

Error-Message:
"The current action cannot be completed because the user data source
credentials that are required to execute this report are not stored in the
report server database. (rsInvalidDataSource-CredentialSetting) (Report
Services SOAP Proxy Source)".
Our previous action:
In SQL-Server Management Studio, Connect to Reporting Services, Home,
myReports, someReportName.
Right-Click on this report, Properties.
Here on the left side: Execution
Right Side: Cache the Report, OK
Now happens the Error cited above.
Logged on as Local Adminsitrator, as usual, no Domain configured, standalone
Server in Workgroup.
The whole ReportServer was installed and configured from scratch with all
possible patience:
All the following programs in english:
Win Enterprise 2003 R2, SQL Server 2005 completely, SQL-Server SP1, Post SP1
hotfixes and ALL recommended Security Updates/Fixes by Windows Update.Hi Henry,
Thank you for using MSDN Managed Newsgroup Support.
From your description, my understanding of this issue is: You can not
configure the Report Cache and you get the following error message:
"The current action cannot be completed because the user data source
credentials that are required to execute this report are not stored in the
report server database. (rsInvalidDataSource-CredentialSetting) (Report
Services SOAP Proxy Source)".
If I misunderstood your concern, please feel free to let me know.
Since the report cache need a credential to connect to the datasource to
render the report, it will need the credential stored in the report server
database.
To store the credential, please do the following:
1. Open the Management Studio, connect to Reporting Services, go to the
report you want to configure.
2. Expand the left panel, and click the Data Sources, right-click your data
source name and click Properties.
3. Check the Credentials stored securely on the report server and specify a
Login Name and password.
4. Click Ok and try to configure the report cache.
Hope this will be helpful, thank you!
Sincerely,
Wei Lu
Microsoft Online Community Support
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================This posting is provided "AS IS" with no warranties, and confers no rights|||Hi Wei,
thanks to your advice we finally achieved to configure caching.
It follows here:
- our initial security-config
- the way we solved the problem by temporarily changing this config
- ONE Question
All Reports use a shared datasource.
This shared datasource is configured to connect using Windows integrated
security.
Our security-config is as following:
- SQL-Server is configured for "SQL Server and Windows Authentication mode"
- The reportserver machine is in a workgroup, not in a Domain
- Anonymous access to the ReportServer website is allowed via the
IUSR_machine User
- we created a local Server windows-group "Report-Reader" in Computer
Management
- we added the IUSR_machine Account to this group
- we added this windows-group as a "System User" (not System Administrator)
to Report Services
- we gave this windows-group the Browser-Role
- we gave this windows-group the datareader role with explicit rights to
select and execute on the target databases
We achieved enabling caching only after configuring this shared datasource
temporarily with:
- Connection: Credentials stored securely on the report server
- sa, password
standard config before and after: Windows integrated security (= the
IUSR_machine account) did not work
Question:
Me, the SQL Server Admin, with all possible rights, I want to configure the
caching behaviour.
Why does there need to be configured differently any shared datasource
rights to do this?
What has the config of the datasource to do with ME wanting to change a
behaviour?
Muchas Gracias, yours Henry|||Hello Henry,
Thank you for your update and glad to hear the information is helpful.
I would liket to explain that why we need to store the Credential.
Since the Report Cache is an automatical process to render the report, it
will need the credential to connect to the datasource to get the data. If
you use the Windows integrated security, it will be fine if an user try to
access the report. But the Cache can not connect to the datasource because
it does not know which credential it should use to connect to the
datasource. Thus, you need to store the credential in the database.
Don't worry about the security because the database use a symetic key to
encrypt the credential.
Here is an article for your reference:
Specifying Credential and Connection Information
http://msdn2.microsoft.com/en-us/library/ms160330(d=ide).aspx
Sincerely,
Wei Lu
Microsoft Online Community Support
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================This posting is provided "AS IS" with no warranties, and confers no rights.|||Hi Henry,
How is everything going? Please feel free to let me know if you need any
assistance.
Sincerely,
Wei Lu
Microsoft Online Community Support
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================This posting is provided "AS IS" with no warranties, and confers no rights.|||Hi Wei,
OK, resolved.
But one big question:
If I give e.g. the sa-credentials to be stored securely in the data-source,
and if any one user achieves to send some "= 1; drop someDB; --" Code to our
Stored Procedures that sometimes use dynamic SQL, then we're fried.
Seems to be necessary to configure a SQL-Server account with less privileges.
Or let caching out.
Saludos, Henry|||Hi Henry,
Thank you for the update.
The SQL injection is really a big problem. I recommend you to configure a
SQL account which only have select permission on the database since the
reporting service only need to get the data from datasource.
Hope this will be helpful!
Sincerely,
Wei Lu
Microsoft Online Community Support
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================This posting is provided "AS IS" with no warranties, and confers no rights.|||Hello Henry,
How are you doing on this thread? As Wei has been OOF due to some urgent
issues, I'm helping him contact you to see whether you still have any
problems on this. For the security threaten you mentioned earlier, Wei and
I have discussed this with our product team's engineers and their
suggestion is that we recommend the reporting service datasource always use
a readonly permission identity to access database server since reporting
service report only need readonly access. As always, if you have any
further issues, please feel free to post here.
Sincerely,
Steven Cheng
Microsoft MSDN Online Support Lead
This posting is provided "AS IS" with no warranties, and confers no rights.|||Hi Steven,
thank you very much for your invested time.
We are happy, that SSRS-caching could finally be switched on in our
dev-/test-environment.
We'll investigate it further, when our product is live and running and we
need to optimize it.
Have a nice day, greetings from Peru
Yours Henry

Cache Miss event in SQL Server 2005

Hello!
Every time I execute stored procedure I see SP:CacheMiss and
SP:CacheHist events in Profiler. Stored procedure is owner qualified. I am
using SQL Serve 2005 and understand that caching algorithm is probably
different from SQL 2000. I am not sure why there is always CacheMiss event.
Is this something I should be concerned about? I know that in SQL 2000 this
might be caused by not fully qualifying stored procedure, but this is not
the case with my stored procedure. Can anybody forward me to the place
explaining difference in caching between SQL Server 2000 and 2005?
Any help is greatly appreciated.
Thanks,
IgorI think I found the answer:
http://blogs.sqlservercentral.com/blogs/michael_coles/archive/2006/08/09/695.aspx
"imarchenko" <igormarchenko@.hotmail.com> wrote in message
news:%23dKVMRjrHHA.1296@.TK2MSFTNGP06.phx.gbl...
> Hello!
> Every time I execute stored procedure I see SP:CacheMiss and
> SP:CacheHist events in Profiler. Stored procedure is owner qualified. I am
> using SQL Serve 2005 and understand that caching algorithm is probably
> different from SQL 2000. I am not sure why there is always CacheMiss
> event. Is this something I should be concerned about? I know that in SQL
> 2000 this might be caused by not fully qualifying stored procedure, but
> this is not the case with my stored procedure. Can anybody forward me to
> the place explaining difference in caching between SQL Server 2000 and
> 2005?
> Any help is greatly appreciated.
> Thanks,
> Igor
>

Saturday, February 25, 2012

c++ ole DB stack overflow during sql server compilation

hi,
when i execute :
CCommand<CManualAccessor, CBulkRowset, CNoMultipleResults> rs;
rs.SetRows(100);
HRESULT code_resultat = rs.Open(session, requete, &propset, NULL,
DBGUID_DBSQL, FALSE);

with a requete with length = 13000, it works perfectly
but when my requete length is 200000 (example : SELECT * FROM myTABLE
WHERE id_table IN("lot of number : more then 30000 number"))
i have code_resultat = DB_E_ERRORSINCOMMAND (= 0x80040e14)
and when i explore the IErrorInfo message, i have :
minor = 565 and the message is
source :Microsoft OLE DB Provider for SQL Server
serveur has made a stack overflow during compilation...

Is there a solution to extract to data ?
in a fast way ...

thanks in advance ...
Mike[posted and mailed, please reply in news]

michael (mmike74@.caramail.com) writes:
> when i execute :
> CCommand<CManualAccessor, CBulkRowset, CNoMultipleResults> rs;
> rs.SetRows(100);
> HRESULT code_resultat = rs.Open(session, requete, &propset, NULL,
> DBGUID_DBSQL, FALSE);
> with a requete with length = 13000, it works perfectly
> but when my requete length is 200000 (example : SELECT * FROM myTABLE
> WHERE id_table IN("lot of number : more then 30000 number"))
> i have code_resultat = DB_E_ERRORSINCOMMAND (= 0x80040e14)
> and when i explore the IErrorInfo message, i have :
> minor = 565 and the message is
> source :Microsoft OLE DB Provider for SQL Server
> serveur has made a stack overflow during compilation...

That sounds like there is a bug or limitation somewhere.

Anyway, SQL Server does not perform well with very long IN clauses.
It could take over 15 seconds just to compile that query.

Take a look at http://www.sommarskog.se/arrays-in-sql.html for alternative
methods to pose the query.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Friday, February 24, 2012

c# UI Escape character problem to execute command line

Hi!

Thanks For your reply!

but this is very urgent please help!!!!!!!

I need one more help in this issue. what if i do not need any \ "

for e.g: i am trying to set conn string and varaible value

jobCommand = new SqlCommand("xp_cmdshell 'dtexec /f \"" + path + "\" /Conn \"" + Packconn + "\" \"" + connect + "\" '",cconn);

i am getting some value like this :

CommandText "xp_cmdshell 'dtexec /f \"D:\\SSISProject\\Integration Services Project1\\ArchiveMainMultiTables.dtsx\" /Conn \"SE413695\\AASQL2005.TestDB;\" \"Provider=SQLNCLI.1;Data Source=SE413695\\AASQL2005;Initial Catalog=TestDB;Provider=SQLNCLI.1;Integrated Security=SSPI;\" '" string

I do not need the highlighted escape characters in it. what should i do?

i need some thing like this :

xp_cmdshell 'dtexec /f "D:\SSISProject\Integration Services Project1\ArchiveMainMultiTables.dtsx" /Conn SE413695\AASQL2005.TestDB;"Provider=SQLNCLI.1;Data Source=SE413695\AASQL2005;Initial Catalog=TestDB;Provider=SQLNCLI.1;Integrated Security=SSPI;"'

Thanks,

Jas

C# has support for unescaped strings. Anything you put in them will appear as is. The only thing to escape is the " and you do that by using two ("")

You must append an @. to the front of the string to tell the compiler that is is unescaped.

So your code would look like this:

jobCommand = new SqlCommand(@."xp_cmdshell 'dtexec /f """ + path + """ /Conn """ + Packconn + """ """ + connect + """ '",cconn);
|||

hi!

Need some urgent help

I am not using @. symbol cos i need to use \ character.

path = @."D:\SSISProject\Integration Services Project1\ArchiveMainMultiTables.dtsx";

string conn = @."Data Source=SE413695\AASQL2005;Initial Catalog=TestDB;Provider=SQLNCLI.1;Integrated Security=SSPI;";

jobCommand = new SqlCommand("xp_cmdshell 'dtexec /f \"" + path + "\" /Set \\package.Variables[User::connectst].Properties[Value]; \"" + conn + "\"'", cconn);

Path works correctly with ur previous answer but the conn as some thing liek this

Which is not working correclty i am getting this value

xp_cmdshell 'dtexec /f \"D:\\SSISProject\\Integration Services Project1\\ArchiveMainMultiTables.dtsx\"/Set \package.Variables[User::connectst].Properties[Value];\"Data Source=SE413695\\AASQL2005;Initial Catalog=TestDB;Provider=SQLNCLI.1;Integrated Security=SSPI;\"'

error near spaces when i execute SQL

Argument "\package.Variables[User::connectst].Properties[Value];"Data "Source=SE413695\\AASQL2005;Initial" "Catalog=TestDB;Provider=SQLNCLI.1;Integrated" Security=SSPI;"" for option "set" is not valid.

I need to get some thing like this through c#

xp_cmdshell 'dtexec /f \"D:\\SSISProject\\Integration Services Project1\\ArchiveMainMultiTables.dtsx\"/Set \package.Variables[User::connectst].Properties[Value];\""Data Source=SE413695\\AASQL2005;Initial Catalog=TestDB;Provider=SQLNCLI.1;Integrated Security=SSPI;"\"'

Please help me with this

thanks,

Jasmine

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

C# : failed due to the following error: 80040154

When i execute the following code provided by msdn, it shows error on the line Application app = newApplication().

But i got some comments that it works fine in 64-bit machine. Could you please help me out. Thanks in advance.

Executed Code

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SqlServer.Dts.Runtime;

namespace Connections_Collection

{

classProgram

{

staticvoid Main(string[] args)

{

// The package is one of the SSIS Samples.

string mySample = @."C:\Program Files\Microsoft SQL Server\90\Samples\Integration Services\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";

// Create an application and load the sample.

Application app = newApplication();

Package pkg = app.LoadPackage(mySample, null);

Connections myConns = pkg.Connections;

int connCount = myConns.Count;

Console.WriteLine("The number of connections in the package is: {0}", connCount);

// Enumerate over the collection, printing out

// the values for various properties.

foreach (ConnectionManager connMgr in myConns)

{

Console.WriteLine("ConnectionString: {0}", connMgr.ConnectionString);

Console.WriteLine("CreationName: {0}", connMgr.CreationName);

Console.WriteLine("DelayValidation: {0}", connMgr.DelayValidation);

Console.WriteLine("Description: {0}", connMgr.Description);

Console.WriteLine("HostType: {0}", connMgr.HostType);

Console.WriteLine("ID: {0}", connMgr.ID);

Console.WriteLine("InnerObject: {0}", connMgr.InnerObject);

Console.WriteLine("Name: {0}", connMgr.Name);

Console.WriteLine("ProtectionLevel: {0}", connMgr.ProtectionLevel);

Console.WriteLine("SupportsDTCTransactions: {0}", connMgr.SupportsDTCTransactions);

}

Console.WriteLine("");

}

}

}

Error message

Retrieving the COM class factory for component with CLSID {E44847F1-FD8C-4251-B5DA-B04BB22E236E} failed due to the following error: 80040154.

Thanks,
Kalam

I am also facing the same problem. Can anybody help on this?

the Code works fine in a 32 bit machine but shows this on a 64 bit machine.

Any idea?

Thanks in advance

|||Try to upload the DTS from a 32 bit machine onto the 64 bit and probably it should work...|||Could you elaborate on this solution please ("upload the DTS")? What is involved with uploading DTS onto Windows Vista Business 64-bit? I also get the same error message for a program running in 64-bit mode that is trying to call a 32-bit DLL. Thanks.

C# : failed due to the following error: 80040154

When i execute the following code provided by msdn, it shows error on the line Application app = new Application().

But i got some comments that it works fine in 64-bit machine. Could you please help me out. Thanks in advance.

Executed Code

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SqlServer.Dts.Runtime;

namespace Connections_Collection

{

class Program

{

static void Main(string[] args)

{

// The package is one of the SSIS Samples.

string mySample = @."C:\Program Files\Microsoft SQL Server\90\Samples\Integration Services\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";

// Create an application and load the sample.

Application app = new Application();

Package pkg = app.LoadPackage(mySample, null);

Connections myConns = pkg.Connections;

int connCount = myConns.Count;

Console.WriteLine("The number of connections in the package is: {0}", connCount);

// Enumerate over the collection, printing out

// the values for various properties.

foreach (ConnectionManager connMgr in myConns)

{

Console.WriteLine("ConnectionString: {0}", connMgr.ConnectionString);

Console.WriteLine("CreationName: {0}", connMgr.CreationName);

Console.WriteLine("DelayValidation: {0}", connMgr.DelayValidation);

Console.WriteLine("Description: {0}", connMgr.Description);

Console.WriteLine("HostType: {0}", connMgr.HostType);

Console.WriteLine("ID: {0}", connMgr.ID);

Console.WriteLine("InnerObject: {0}", connMgr.InnerObject);

Console.WriteLine("Name: {0}", connMgr.Name);

Console.WriteLine("ProtectionLevel: {0}", connMgr.ProtectionLevel);

Console.WriteLine("SupportsDTCTransactions: {0}", connMgr.SupportsDTCTransactions);

}

Console.WriteLine("");

}

}

}

Error message

Retrieving the COM class factory for component with CLSID {E44847F1-FD8C-4251-B5DA-B04BB22E236E} failed due to the following error: 80040154.

Thanks,
Kalam

I am also facing the same problem. Can anybody help on this?

the Code works fine in a 32 bit machine but shows this on a 64 bit machine.

Any idea?

Thanks in advance

|||Try to upload the DTS from a 32 bit machine onto the 64 bit and probably it should work...|||Could you elaborate on this solution please ("upload the DTS")? What is involved with uploading DTS onto Windows Vista Business 64-bit? I also get the same error message for a program running in 64-bit mode that is trying to call a 32-bit DLL. Thanks.

C# : failed due to the following error: 80040154

When i execute the following code provided by msdn, it shows error on the line Application app = new Application().

But i got some comments that it works fine in 64-bit machine. Could you please help me out. Thanks in advance.

Executed Code

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SqlServer.Dts.Runtime;

namespace Connections_Collection

{

class Program

{

static void Main(string[] args)

{

// The package is one of the SSIS Samples.

string mySample = @."C:\Program Files\Microsoft SQL Server\90\Samples\Integration Services\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";

// Create an application and load the sample.

Application app = new Application();

Package pkg = app.LoadPackage(mySample, null);

Connections myConns = pkg.Connections;

int connCount = myConns.Count;

Console.WriteLine("The number of connections in the package is: {0}", connCount);

// Enumerate over the collection, printing out

// the values for various properties.

foreach (ConnectionManager connMgr in myConns)

{

Console.WriteLine("ConnectionString: {0}", connMgr.ConnectionString);

Console.WriteLine("CreationName: {0}", connMgr.CreationName);

Console.WriteLine("DelayValidation: {0}", connMgr.DelayValidation);

Console.WriteLine("Description: {0}", connMgr.Description);

Console.WriteLine("HostType: {0}", connMgr.HostType);

Console.WriteLine("ID: {0}", connMgr.ID);

Console.WriteLine("InnerObject: {0}", connMgr.InnerObject);

Console.WriteLine("Name: {0}", connMgr.Name);

Console.WriteLine("ProtectionLevel: {0}", connMgr.ProtectionLevel);

Console.WriteLine("SupportsDTCTransactions: {0}", connMgr.SupportsDTCTransactions);

}

Console.WriteLine("");

}

}

}

Error message

Retrieving the COM class factory for component with CLSID {E44847F1-FD8C-4251-B5DA-B04BB22E236E} failed due to the following error: 80040154.

Thanks,
Kalam

I am also facing the same problem. Can anybody help on this?

the Code works fine in a 32 bit machine but shows this on a 64 bit machine.

Any idea?

Thanks in advance

|||Try to upload the DTS from a 32 bit machine onto the 64 bit and probably it should work...

C

Hi,

I have a bit of code written in class ASP that connects to a database with Command.Execute. It works fine with SQL 2000 but after an upgrade to SQL 2005 causes the asp page to hang while w3wp runs at at 100%

I'm running SQL 2005 SP1 on the same machine as IIS. I can't see anything in the event log or the SQL logs that would explain this (no errors in either). SQL profiler shows the stored procedure is called.

The code is below. Does anyone know of anything that might be causing this. I've spent two days so far trying to find a cause. The ODBC connection SDB1 is using SQL Native Client.

MyConn.Open "DSN=SDB1;Initial Catalog=database","username","password"

Set MyCommand.ActiveConnection=MyConn
MyCommand.CommandType = adCmdStoredProc
MyCommand.CommandText = "[owner].[procname]"
Set MyParam=MyCommand.CreateParameter("in_ip",adVarChar,adParamInput,10)
MyCommand.Parameters.Append MyParam
Set MyResult=MyCommand.CreateParameter("ip_country",adVarChar,adParamOutput,50)
MyCommand.Parameters.Append MyResult

MyCommand.Execute

Can anyone shed any light on this?

For anybody elses reference, I have found the cause of this.

The database user had connect permission but nothing else. This meant the user could connect to the database but not select/update or delete. Giving it the necessary rights solved the problem.

However, why this was causing IIS to run at 100% is still a mystery.

Regards,

Mark.

Tuesday, February 14, 2012

Button That Execute Stored Procedure

I have a button in a form that I want to execute a simple stored procedure to insert a single value into a database table.
The Stored Procedure is:
=================
CREATE PROCEDURE bplog_insert_invoice_detail (@.invo_Id Int) AS
INSERT INTO Invoice_Detail
(Invo_Id)
VALUES(@.Invo_Id)
GO
=================
How do i pass the value from and text field (@.invo_id) and execute the stored procedure when a button is clicked.
Regards.

This is untested, but it should work:

SqlConnection cn = new SqlConnection(connectionString);
SqlComment cmd = cn.CreateCommand();

cmd.CommandText = "bplog_insert_invoice_detail";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm = new SqlParameter("@.invo_Id", SqlDbType.Int)
parm.Value = parameterValue;
cmd.Parameters.Add(parm);
cmd.ExecuteNonQuery();

Hope that helps.