Connecting to a Shared Data Source at Runtime - c#

I am writing a report builder program that is similar to Microsoft's Report Builder but to be hosted on an existing web application. It should be able to:
connect to a report server (SSRS2008) and a pre-configured shared data source;
let the user design RDLCs; and,
dynamically generate reports without the need for Visual Studio.
Basically, it's a stand-alone albeit proprietary report generation tool.
The users need not be report writers but do they have an understanding on how data is correlated in the database. (There are existing relationships between tables.) For some reason, they cannot or should not have access to the SSRS site to build reports from there (i.e. use Microsoft's Report Builder tool). They have to use the tool I am creating.
I'm very much done with the last two bullets. The first one is giving me the issue: I'm relatively new to this and probably it's not trivial. How can I connect to an SSRS2008 data source at runtime?
In my web.config, I added an entry to the connectionStrings like so:
<add name="ReportingSDS" connectionString="Server=http://myReportingServer;datasource=http://myReportingServer/reportserver/models/myReportModel.smdl;Integrated Security=True"/>
which is based on the prescribed format.
And I ran into a brick wall after this:
using (var conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ReportingSDS"].ConnectionString))
{
conn.Open();
// what's next?
}
The error I'm getting is:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)
My goal is to retrieve that DataSet and plug it into this snippet:
using (var memRDLC = new MemoryStream(Encoding.ASCII.GetBytes(myRdlcXml)))
{
// Bind the rdl memory stream and data set to reportviewer
rptViewer.ProcessingMode = ProcessingMode.Local;
LocalReport r = rptViewer.LocalReport;
r.LoadReportDefinition(memRDLC);
foreach (DataTable dataTable in reportEngine.DataTables)
{
r.DataSources.Add(new ReportDataSource(
dataTable.TableName + "_Table", dataTable));
}
r.Refresh();
}

Related

How to connect database with C# executable file?

I am writing code for a small company that is all about purchase and sell. I wrote C# code with using external database (SQL Server 2014), now it's time to make the exe file of that code.
I tried my best but it doesn't work.
How can I connect SQL Server 2014 database files with my application so that when someone installs it on his computer he also got SQL Server connected with that application?
Hi actually we deploy code as setup file (.msi), you can create setup project using Wix or install-shield ( maybe other too,but these two are most popular and widely used)
You can do database deployment in two ways
1.) you can provide SQL script for generating SQL server and give instruction for generating Database from Script. It is simple and easy to do.
2.) Other way is provide option to create database from setup. It need some work, but it is more good way.
Now come to your question, you can provide some UI in setup that take input from user and connect to appropriate DB. Or create a UI for Updating configurations, and save configuration (connection string ) in some file ( ex: .ini or .config file).
Below are the some URL for creating Setup and connecting to Db using Wix:
WIXDataBase
installing-databases-using-wix
Creating-an-installer-using-Wix
using-wix-to-install-sql-databases-and-execute-sql-scripts
WiX Samples
Ideally you'd have a SQL server set up somewhere. If not you'll have to install sql server. In your app it's just a matter of setting up the connection string and running sql commands against it.
string connectionString = "Data Source=server //rest of connection string"
Then in c# you can do
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT TOP 100 * FROM SomeTable", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetString(0), reader.GetString(1), reader.GetString(2));
}
}
}
GetString can be changed to GetInt or whatever the datatable will be. This should be enough information to get you started. If you know the structure of the database its simple to put the results into your classes for the application.

Change datasource in Visual Studio 2012 from SQLSRV to MySQL

I have a basic Application in Visual Studio 2012 which is connected to Sql Server 2008 R2 but now I want it to be connected only to a MySQL database (whose tables and columns are the same).
I downloaded MySQL for Visual Studio and I got a successfully connection in Data Sources to my database in MySQL.
Now I want to ask, what should I change from my app (apart of the connection string) if it only does simple CRUD with the db?
For example I've changed connection strings and when the app tried to search in db and fill a dataset I found an error in this code:
SqlDataAdapter dataAdapter = database.getPaquetes(date, _destino);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dgv_paqdisp.ReadOnly = true;
dgv_paqdisp.DataSource = ds.Tables[0];
ERROR:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).
Are those types only for SQL Server? If yes, what is an equivalent when using MySQL?
Notice I don't want you to re-make my code or anything, I only want to know if there is something I'm missing or if its not that simple to change DataSource? Thanks in advance.
As WearWolf write you need a Mysql Connector/Net. You can download it from Nuget as packages. For the code that you have written for Sql Server will need to modified too much to get it worked on MySQL.
for example
SqlConnection will be MySqlConnection
SqlCommand will be MySqlCommand
You can do this changes Be Manual Find replace for every .cs file in solution carefully. At then end you will got working your app in MySQL.
You didn't mention that your CRUD is written using Entity framework and data-source tag make confusion here.
If you use Entity framework then simply generate the entity from database, because Mysql is a different database system you need to make the table in your mysql database first.
or if you use SQl queries execution for CRUD then just use given Find and replace and it will works.
You'll neet to add a reference to MySQL Connector/NET assemblies. They should come with MySQL for Visual Studio, otherwise that link has download instructions.
Then your code would become something like
MySqlDataAdapter dataAdapter = database.getPaquetes(date, _destino);
It shouldn't change much since both implemented using ADO.net

Unable to connect to SQL Server database using C#

I'm currently working on a wpf application where I tried to create a database.
I used data sources > add new datasource > dataset and copied the query string for its properties, but it is giving me the following exception:
What might be the problem? This is a local database... and when I click on the test connection button it writes "test connection succeeded"
Thanks
You are connecting to an SDF file. This means that you are using Sql Server Compact, not the full fledged Sql Server.
The classes to be used are named
SqlCeConnection
SqlCeCommand
The one you are using (SqlConnection) cannot understand the connection string used for a Sql Server Compact
Of course you need to add the reference to the assembly and the appropriate using directives
Assembly: System.Data.SqlServerCe.dll
using System.Data.SqlServerCe;
....
You are using a SqlConnection rather than the SqlCeConnection that you require. SqlConnection is for connecting directly to a "real" sql server.
Take a look at the MSDN for more information.

Object Reference not set to an instance of an object - Server Only

I have recently placed a web application on a remote server for testing. This application uses a range of SQL Server (Express) databases to hold card and user information, of which all are linked into my master database. The database is referred to in my web.config file.
I have made .bak files from my databases and restored them on my server, with the connection string now showing:
<add key="ConnectionString" value="server=localhost; database=DatabaseMaster; uid=...; pwd=..."/>
On my local computer the application is fine and throws no exceptions. However, upon connecting to my application via the web server, and trying to retrieve data from my cards table a NullReferenceException error is thrown. I have checked my code via breakpoints on the following code:
private void FillGrid()
{
DataSet ds = new DataSet();
//get data from session
ds = (DataSet)SessionNavigator.GetDataFromCurrentPage
(PageParams.Customer.DataCards);
if (ds != null)
{
DataView dv = ds.Tables["Cards"].DefaultView;
gridCtrl.RowsCount = dv.Count;
gridCtrl.BindGrid(dv);
}
}
My checks have found that the DataSet ds is indeed not null, and in fact it seems that the application is not recognising the table "Cards", there being no reference to an instance of the object in the table.
Confusingly enough, other tables (such as for users) have no problems whatsoever on the server. Also, manipulating data related to the card objects (such as making transactions and changing points values) are reflected in the SQL Server Management Studio.
I am inexperienced with SQL Server so I may be wrong but I don't think it has anything to do with the database itself.
So SO, are there any glaringly obvious steps that I may have missed when setting up the application that are causing these issues? If so, are there any reference materials that you can recommend?
Edit: After Searching through the PageParams Enumerable and looking closely at the ds Dataset, I have found that ds is not null but has a value of {System.Data.DataSet} containing System.Data.DataTableCollection with a list of size 0.
Found the Answer! Searching through my output when debugging the FillGrid method I found this little line:
System.Data.SqlClient.SqlException: SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', see "Surface Area Configuration" in SQL Server Books Online
After that it was just a simple case of allowing Ad Hoc Distributed Queries via sp_configure in the SQL Server Management Studio, resolving the issue completely. This explains why my local copy of the application was working fine but the server was having issues retrieving the relevant DataCards.
It might just be that the name of the table isn't read from the source, and that it's just called "Table1" in your DataSet.
Have you tried to look at the actual content of the dataset?

How do I used a database I created in MS SQL Server 2008 R2 with a VS C# Project?

I created a new database using SQL Server 2008 R2 by using the Management Studio. The connection says (local) and I am using Windows Authentication (though I installed with mixed mode).
My questions are:
How do I connect to the DB via my C# application -
The only time I ever have done this before I just used VS Menu > Tools > Connect to DB and the drop down saw my database and connected, then right clicked on it and grabbed the connection string for use in connecting. However I'm thinking because its (local) I don't have that option.
As per Q#1 I am assuming the database file is being stored somewhere locally - I am wondering how to find that location and how I can include it with my application
Edit** Per comment: VSMenu-> View-> Server Explorer and then use add connection to connect to your local SQL Server instance and then use the database you created from the databases dropdown, and from advance settings copy the connection string created by the connection dialog
This is what I am looking for but I am missing the step during "add connection" where do I find my SQL Server I created locally? As mentioned before I have no idea where it is stored or how to find it
MSDN has an example in the SQLConnection documentation
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(queryString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
You can then optionally use a SqlDataAdapter.
You need to use ADO.NET, which is comprised of a connection object (SqlConnection), command object (SqlCommand), parameters objects (SqlParameter) and data sets (DataSet) or data readers (SqlDataReader).
Read A Beginner's Tutorial for Understanding ADO.NET.

Categories