How can I use LinqPad's generated context in Visual Studio - linqpad

This is a follow-on from this question really:
Moving From LINQpad to a Proper Visual Studio Project?
..but I'm not able to get it to work properly.
An answer to that question suggestions dumping the context assembly out as a dll but although I have done that, when I import it as a reference, it's not exactly clear to me how I would create an instance of that context, point it at a database and actually run a query against it, something like the following:
var db = new ContextFromThatDLL(myconnectionstring);
var query = from a in db.MYTABLE where a.ID == 1 select a;
Extra information:
I am using the IQ driver in LinqPad to connect to Oracle.
I do have a license for DevArt already (which the IQ driver uses) but am aware that the IQ driver generates its own SQL from LINQ - and I prefer it. Plus, I develop queries in LinqPad which works great for my workflow but find that DevArt doesn't always generate SQL as good as IQ.

First, extract the typed data context in LINQPad as follows:
string dcPath = GetType().BaseType.Assembly.Location;
string targetFolder = #"c:\temp";
File.Copy (dcPath, Path.Combine (targetFolder, Path.GetFileName (dcPath)));
Then in Visual Studio, reference the typed data context DLL, along with the following DLLs from the driver folder:
IQDriver.dll
IQToolkit.dll
IQToolkit.Data.dll
IQToolkit.Data.(provider).dll
plus the DevArt driver.
Then, you can instantiate the typed data context as follows (this illustrates how to do it for SQLite):
var dc = new LINQPad.User.TypedDataContext (IQToolkit.Data.DbEntityProvider.From
("IQToolkit.Data.Sqlite", #"Data Source=D:\SQLite.NET\nutshell.db",
"LINQPad.User.TypedDataContext"));
var customerCount = dc.Customers.Count();
This should get you started. Bear in mind the caveats, as stated in the answer to which you linked!

Related

How do you see what SQL IronSpeed sends to the database?

I'm using IronSpeed Designer 12.2 and trying to write custom SQL in a WhereClause override. The custom SQL I wrote and submitted in the WhereClause is throwing an SQL exception, but I can't see the SQL IronSpeed is sending to the database. Without the SQL, I cannot troubleshoot.
I can't find where the SQL is submitted to the database, such as by an ExecuteReader method call.
I'm using a statement like this:
if (MiscUtils.IsValueSelected(this.MyFilter)) {
String sql = "(EXISTS (SELECT TOP 1 CompanyId FROM Collateral as c WHERE CODE = '{0}' AND c.CompanyId = Company.CompanyId))";
wc.iAND(String.Format(sql, this.MyFilter.SelectedValue));
}
I know my WhereClause SQL is correct when used outside of IronSpeed because I copy-pasted it from a query working directly in MSSQL. However I can't see how IronSpeed combines it with its internally-generated SQL after it becomes a WhereClause.
I'm hoping someone has experience with this issue and can point me in the right direction. Thanks for the help!
If you look for answer long enough, you can find it yourself. Here's how I found you can examine the SQL sent to the database:
Go to C:\Program Files\Iron Speed\Designer v12.2.0.
Copy the BaseClasses folder to the root of my IronSpeed solution folder.
Add the existing BaseClasses project to the IronSpeed solution.
Delete the existing references to baseclasses.dll from the projects in the IronSpeed solution (I'm using a web app rather than web site project).
Add references to the BaseClasses project now included in the solution.
Open the file MicrosoftDynamicSQLAdapter.vb.
In method GetRecordValuesEx(...), go to line 1514 statement "reader = SqlTransaction.ExecuteReader(myCommand, cmdBehavior)" and set a breakpoint on this line.
Run the project. When the breakpoint is hit, examine the command of myCommand object.

Easy way to get and modify a .vb file like a text file

I'm creating a vb.net application for converting a Data Access Layer classes from Oracle DB oriented to SQL Server DB oriented ,
And i must convert every Oracle oriented class like :
OracleCommand , OracleDataAdapter , OracleDataReader ...
to it's SQL Server equivalent .
Is there any way to get methods list from .vb file and to get the body of each method from vb application to change it dynamically and create new version of each file ???
If you compile in debug mode, one of the output files is PROGRAMNAME.xml, which contains all the method signatures for the EXE. (Where PROGRAMNAME is the name of your EXE).
You can write a program to edit the .vb files just like any other text file, because they are text files.
Download trial version of Resharper and it will help you to do it with no pain. One month trial should be enough.
VS also has some tools - "Find all references" and "Find and Replace in Files". So, you can Find and replace Oracle... To Sql...
On the other note, why not writing wrappers that will provide DB-agnostic providers for command, transaction, etc. For example, instead of
Dim reader As OracleDataReader = OracleCommand.ExecuteReader...
Do this
Dim reader As IDataReader = MyAgnosticCommand.ExecuteReader...
So, if the new boss is coming tomorrow and says, "Oh we need oracle" - you don't have to do it all over again.

How to convert certain C# code to VB.NET

I've been googling around around and read this article
C# How to get SQL Server installation path programatically?
and this is exactly what i need in VB.NET , however i'm not good in translating this code into VB.NET Code. So, any help would greatly appreciated. Thank you.
Note : I'm using SQL Server 2005 and Visual Basic 2008
While the question was originally titled about retrieving SQL Server's installation path, I felt it was more about a code translation problem (the solution already existed, just not in the right language).
But then I thought that the method in the original code was fairly blunt.
Evan provided you with what I assume is a workable translation of the existing solution. But probably a much easier way to perform this specific task - assuming you just need to find the installation path for an instance you're already connected to, and assuming that a user who can read the registry will also have VIEW SERVER STATE permissions - is to issue this simple query against the DMV sys.dm_os_loaded_modules from your program:
SELECT name
FROM sys.dm_os_loaded_modules
WHERE name LIKE '%sqlservr.exe';
This will give you something like this:
C:\Program Files\Microsoft SQL Server\MSSQL11.SQL2012\MSSQL\Binn\sqlservr.exe
You have some parsing to do, depending on exactly what you're after (e.g. do you want to stop at MSSQL, or Binn?), but this is much easier than reading the registry or other methods that are out there IMHO.
I just used a code converter ... There are only basic things that need to be changed ..
Using sqlServerKey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Microsoft SQL Server")
For Each subKeyName As String In sqlServerKey.GetSubKeyNames()
If subKeyName.StartsWith("MSSQL.") Then
Using instanceKey As RegistryKey = sqlServerKey.OpenSubKey(subKeyName)
Dim instanceName As String = instanceKey.GetValue("").ToString()
If instanceName = "MSSQLSERVER" Then
'say
Dim path__1 As String = instanceKey.OpenSubKey("Setup").GetValue("SQLBinRoot").ToString()
path__1 = Path.Combine(path__1, "sqlserver.exe")
Return path__1
End If
End Using
End If
Next
End Using
If you were to just read a quick article on C#, you would notice that strings are declared differently, and minor syntax discrepancies exist such as foreach vs for each
You can read here for some more common differences.
I use a very good (offline) tool, called Convert .NET Free
It's from www.fishcodelib.com
Here's a direct link to the latest release (as of 19/04/14) Size: 2.06MB, File: Zip :
[Direct Link]
Hope this is of some use ;)
P.S. This software requires .NET Framework 4.5.
This almost never fails! :) Good Luck
http://www.developerfusion.com/tools/convert/csharp-to-vb/

DB Query no longer recognizes SQL parameters in existing application when debugging in VS2010

I just started working with an application that I inherited from someone else and I'm having some issues. The application is written in C# and runs in VS2010 against the 3.5 framework. I can't run the application on my machine to debug because it will not recognize the way they referenced their parameters when writing their DB queries.
For instance wherever they have a SQL or DB2 query it is written like this:
using (SqlCommand command = new SqlCommand(
"SELECT Field1 FROM Table1 WHERE FieldID=#FieldID", SQLconnection))
{
command.Parameters.AddWithValue("FieldID", 10000);
SqlDataReader reader = command.ExecuteReader();
...
If you will notice the "parameters.AddWithValue("FieldID", 10000);" statement does not include the "#" symbol from the original command text. When I run it on my machine I get an error message stating that the parameter "FieldID" could not be found.
I change this line:
command.Parameters.AddWithValue("FieldID", 10000);
To this:
command.Parameters.AddWithValue("#FieldID", 10000);
And all is well... until it hits the next SQL call and bombs out with the same error. Obviously this must be a setting within visual studio, but I can't find anything about it on the internet. Half the examples for SQL parameter addition are written including the "#" and the other half do not include it. Most likely I just don't know what to search for.
Last choice is to change every query over to use the "#" at the front of the parameter name, but this is the transportation and operations application used to manage the corporation's shipments and literally has thousands of parameters. Hard to explain the ROI on your project when the answer to the director's question "How's progress?" happens to be "I've been hard at it for a week and I've almost started."
Has anyone run into this problem, or do you know how to turn this setting off so it can resolve the parameter names without the "#"?
Success! System.Data is automatically imported whenever you create a .NET solution. I removed this reference and added it back to make sure that I had the latest version of this library and that fixed the issue. I must have had an old version of this library that was originally pulled in... only thing I can figure.
Its handled by the .NET Framework data providers not Visual Studio.
It depends on the data source. Look here:Working with Parameter Placeholders
You can try working with System.Data.Odbc provider and using the question mark (?) place holder. In thios case dont forget to add the parameters in the same order they are in the query.

I would like to extract the SQL queries from Crystal Report .rpt files, is there a way to do this?

I would like to extract the SQL queries from Crystal Report .rpt files, is there a way to do this?
I don't have any of the Crystal Reports products, just the .rpt files.
Here's a .Net example of code that grabs the Command Sql from all Crystal Reports in a given directory. It requires the Crystal 2008 .Net SDK to be installed (you can download a trial from SAP):
foreach (string file in Directory.GetFiles("c:\\projects\\Reports", "*.rpt"))
{
Console.WriteLine(String.Format("Processing {0}...", file));
var doc = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
doc.Load(file);
foreach (dynamic table in doc.ReportClientDocument.DatabaseController.Database.Tables)
{
if (table.ClassName == "CrystalReports.CommandTable")
{
string commandSql = table.CommandText;
//TODO: do something with commandSql
}
}
}
To get the SQL as Crystal would build it when running a report, see this link: SAP Note 1280515 - How to extract SQL query from Crystal reports using RAS sdk.
I believe to do this, you need to supply the report parameter values so that Crystal can connect to the database in order to build the SQL. In the example, since a Report Viewer control is used, Crystal can prompt the user for the parameters.
In "Crystal Reports ActiveX Designer Design and Runtime Library" (craxddrt.dll), the Report.SQLQueryString property will do what you want.
I can't seem to find an equivalent property in the .Net SDK, and believe me, I've been looking.
** edit **
It appears that one can make use of the In-Process RAS Server to get this information:
CrystalDecisions.ReportAppServer.DataDefModel.CommandTableClass.CommandText
The other way around this is if you can run the reports, you can hook up SQL Profiler to your DB and capture the incoming SQL on the database side.
JoshL's answer worked for several of my reports, but not all of them. The following method, using ReportClientDocument.RowsetController.GetSQLStatement, was able to extract some of the queries that the other method missed.
foreach (string file in Directory.GetFiles("c:\\projects\\Reports", "*.rpt"))
{
Console.WriteLine(String.Format("Processing {0}...", file));
var doc = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
doc.Load(file);
var controller = doc.ReportClientDocument.RowsetController;
var groupPath = new CrystalDecisions.ReportAppServer.DataDefModel.GroupPath();
string temp = String.Empty;
string commandSql = controller.GetSQLStatement(groupPath, out temp);
//TODO: do something with commandSql
}
My experience is with older versions of Crystal (8,9) - I've no idea what the file formats look like for more recent versions. However, it's worth opening the files up in a text editor just in case, but for the file formats I've seen, the query text is not accessible this way.
If I remember correctly, some versions of Visual Studio 2003 came with tools for manipulating Crystal .rpt files (but I guess this isn't of much use to you, since if you had this already, you wouldn't be asking!).
It's not a very imaginative suggestion, but perhaps your quickest route would be to download the 30-day trial version of the current Crystal Reports, and see if that will open the files for you.
In the Visual studio, select the .rpt file and Go to field explorer, right click on DatabaseFields. Click on SQL query option to view the query.