var data = Database.Open("databasename").Query("SELECT * FROM table); visual studio - database

I know you can do this in web matrix and it works fine
var data = Database.Open("databasename").Query("SELECT * FROM table); visual studio
but how can you achieve something similar in visual studio 2010 using MVC3???
I need to be able to loop through table rows using a foreach() and implement them through an api, I originally started the project in web matrix, but was asked to use mvc in visual studios instead, i have limited knowledge with it. I am using Microsoft sql server.
Also if anyone thinks I might be going the complete wrong way about achieving this, any input to point me in the right direction would be appreciated.

I've found that the ORM which most closely resembles WebMatrix is Dapper.
https://github.com/StackExchange/dapper-dot-net
It can be used with dynamic objects in a very similar manner to WebMatrix, but can also be used with strongly typed objects if you wish. It's available as a NuGet package.
The code in your question would end up looking something like the following in Dapper:
using (var con = new SqlConnection(WebConfigurationManager.ConnectionStrings["databasename"].ConnectionString))
{
var data = con.Query("SELECT * FROM table");
foreach (var row in data)
// do stuff
}

Related

msadox28.tlb is not a valid .Net assembly file while registering it

I am developing application with vb.net (2015) and MS Access database. I can work fine with existing database. I have now situation where I need to create database programmatically, for billing purpose. It is the situation where each folder will contain database for company/firm selection.
After searching on the internet / StackOverflow I learned about ADOX. Even got the ready code for it. I applied it in my coding.
Adding reference of Microsoft ADO extend 2.8 and 6.0
Created variable Adx as new Adox.catalog
Then finally wrote Adx.create(olejet provider conn string with data source)
In this step I get an error
COM Class not registered
So I tried to register msadox.dll and msadox28.tlb with regsvr32 and regasm but at that time I get another error:
msadox.dll get registered successfully but error gives in msadox28.tlb
Fail to load -file- becuase it is not a valid .net assembly file
Now I am stuck at this point.
My system is Windows 10 64 bit. I tried to target cpu x86, and any cpu but it didn't work. I got many questions and answer here but didn't understand it.
EDIT:
I tried following connection string and it worked, but it creates old 2000-2003 mdb file. i want to use new access file .accdb
String is :
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\VBProj\Testing\test.mdb;Jet OLEDB:Engine Type=5
EDIT : on 20/9/2021 - MON
First of all Thank you very much #Jimi, your suggestion to use ACE.16 and cleaning solution worked. Thanks a lot
I use the following steps to create MS Access database using ADOX in VB.NET:
Project Menu > Add Reference > COM Section > Select Microsoft ADO Ext. 6.0 for DLL and security
Write connection string at program entry point (form load/sub main) -> Provider=Microsoft.ACE.OLEDB.16.0;Data Source=D:\VBProj\Testing\test.accdb, assign it to variable connString
Declare adox catalog globally like Public gAdxCat As New ADOX.Catalog
Use its method gAdxCat.create(connString)
That's all - DONE
Again thanks to #jimi
This is the answer to my question (helped by #jimi)
following are the steps to create msaccess database using ADOX in VB.NET and error occurs mention in original questions.
1-Project Menu > Add Reference > COM Section > Select Microsoft ADO Ext. 6.0 for DLL and security (remove ref of 2.8)
2-write connection string at program entry point (form load/sub main) -> "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=D:\VBProj\Testing\test.accdb" assign it to variable connString
3-declare adox catalog globally like Public gAdxCat As New ADOX.Catalog
4-User its method gAdxCat.create(connString)
5-Thats all DONE
again thanks to #jimi

How to properly ignore windows created by Visual Studio debugging tool for XAML

In my application I need to get a list of all windows.
var windows = Application.Current.Windows;
If I run my application in debug mode I see not only my forms in the list, but also instances of Microsoft.XamlDiagnostics.WpfTap.WpfVisualTreeService.Adorners.AdornerLayerWindow created by Visual Studio debugging tool for XAML.
What is the right way to filter list of windows to ignore windows created by debugging tool? I don't want to reference additional assembly and check if
window is AdornerLayerWindow
and I don't want to filter like
window.GetType().Name != "AdornerLayerWindow"
Any other ideas?
I just do the trick window.ActualWidth != 0. It works good for me.
Application.Current.Windows
.Cast<Window>()
.Where(w => w.ActualWidth != 0)
.ToList()
.ForEach(w => w.Close());

Is there any way to trace\log the sql using Dapper?

Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget MiniProfiler.Integrations I would like to share.
Update V2: it supports to work with other database servers, for MySQL it requires to have MiniProfiler.Integrations.MySql
Below are steps to work with SQL Server:
1.Instantiate the connection
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
2.After all works done, write all commands to a file if you want
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
(primarily) security: since dapper doesn't have a concept of a context, it would be really really easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
(secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be null in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: Debug.WriteLine etc.
You should consider using SQL profiler located in the menu of SQL Management Studio → Extras → SQL Server Profiler (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = #appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR #includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(#langCode, '','')))',N'#appId nvarchar(4000),#includeBeta bit,#langCode nvarchar(4000)',#appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',#includeBeta=0,#langCode=N'de'
Try Dapper.Logging.
You can get it from NuGet. The way it works is you pass your code that creates your actual database connection into a factory that creates wrapped connections. Whenever a wrapped connection is opened or closed or you run a query against it, it will be logged. You can configure the logging message templates and other settings like whether SQL parameters are saved. Elapsed time is also saved.
In my opinion, the only downside is that the documentation is sparse, but I think that's just because it's a new project (as of this writing). I had to dig through the repo for a bit to understand it and to get it configured to my liking, but now it's working great.
From the documentation:
The tool consists of simple decorators for the DbConnection and
DbCommand which track the execution time and write messages to the
ILogger<T>. The ILogger<T> can be handled by any logging framework
(e.g. Serilog). The result is similar to the default EF Core logging
behavior.
The lib declares a helper method for registering the
IDbConnectionFactory in the IoC container. The connection factory is
SQL Provider agnostic. That's why you have to specify the real factory
method:
services.AddDbConnectionFactory(prv => new SqlConnection(conStr));
After registration, the IDbConnectionFactory can be injected into
classes that need a SQL connection.
private readonly IDbConnectionFactory _connectionFactory;
public GetProductsHandler(IDbConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}
The IDbConnectionFactory.CreateConnection will return a decorated
version that logs the activity.
using (DbConnection db = _connectionFactory.CreateConnection())
{
//...
}
This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE #{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE #{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE #{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE #{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE #{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
You can then just use this in the immediate or watch windows to grab the SQL.
Just to add an update here since I see this question still get's quite a few hits - these days I use either Glimpse (seems it's dead now) or Stackify Prefix which both have sql command trace capabilities.
It's not exactly what I was looking for when I asked the original question but solve the same problem.

Data sources empty on ReportViewer

I'm trying to link up my report viewer to the data sources, however the dialog box is empty -
I have a file called dsReports.xsd which has data sets that work when I preview data from there.
Anyone know why this could be?
Thanks
I have got round this by programatically setting the data source -
var myDataTable = new dsReports.tsPrimaryMondayDataTable();
var myTableAdapter = new dsReportsTableAdapters.tsPrimaryMondayTableAdapter();
myTableAdapter.Fill(myDataTable, Convert.ToDateTime(dtp.Value));
var rds = new ReportDataSource("DataSet1", myDataTable as DataTable);
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(rds);
reportViewer1.RefreshReport();
This problem occur when yourfile.rdlc not have add a DATASET like "source data". Then, add a table in your report .rdlc and configure the after try add datasource in rsweb:ReportViewer dont forget of put a ScriptManager a .aspx.
The problem is that you probably save your report with newer version of Visual Studio (in my case with Visual Studio 2019). After save, the data source list will be empty in the "Choose Data Sources" section.
When I edit my original report with older version of Visual Studio the data source list shown.
(in my case a saved report cannot be restored neither with older version of VS, so I hope you have a backup :) )

How to build multilingual Crystal reports

We are developing a multilingual Winforms application using visual studio 2008. I am trying to figure out how I can create multilingual reports using crystal Reports.
Is there any thing similar to .net resource files in the Crystal reports world?
I'm sorry that I'm robbing you of your tumbleweed badge, but I don't think Crystal has the multiple language support similar to .NET. I think that your only option is to have a separate report for each language and pass the data into the report in the language that you wish to display.
Here is a link of a similar answer.
http://www.dbforums.com/crystal-reports/991737-crystal-report-multillingual-support.html
This would be a manual way of doing this:
Create a report for each language you want and put into the proper folders structure. i.e. all japanese reports will go into rpt_ja/ folder.
Use .Net Resource file to specify report resource name and full resource name for each language:
resource.resx
RPT_SAMPLE -> report01.rpt
RPT_SAMPLE_FULL -> MyCompany.NameSpace.Reports.Report01.rpt
resource.ja.resx
RPT_SAMPLE -> rpt_ja\report01.ja.rpt
RPT_SAMPLE_FULL -> MyCompany.NameSpace.Reports.Report01.ja.rpt
Then use this value in the report code file: Open the report .cs file and change:
public override string ResourceName {
get {
// Change this to HttpContext.GetGlobalResourceObject("Resource", "RPT_SAMPLE").ToString();
return "report01.rpt";
}
set {
// Do nothing
}
}
public override string FullResourceName {
get {
// Change this to HttpContext.GetGlobalResourceObject("Resource", "RPT_SAMPLE_FULL").ToString();
return "rpt_ja\report01.ja.rpt";
}
set {
// Do nothing
}
}
EDIT: HttpContext is for ASP.Net web application. In winform, you can try Properties.Resources.ResourceManager.GetString() to get the string from resources
A client ask me for a solution to this issue. I developed a solution based on Crystal Reports contentLocale keyword and Custom Functions. See my posting: http://www.cogniza.com/blog/?p=55.

Resources