How can you run a report from the ReportServer database without building subscriptions? - sql-server

I'd like to build a back end system that allows me to run each report every night and then query the execution log to see if anything failed. I know you can build out subscriptions for these reports and define parameters etc but is there a way to execute each report from the ReportServer database using TSQL without building out each subscription?

I understand that your overall goal is that you want to automate this and not have to write a subscription for every report. You say you want to do it in T-SQL, but is that required to meet your overall goal?
If you can accept, say .Net, then you can use the System.Data.SqlClient.SqlConnection and related classes to query your report server catalog and fetch a listing of all your reports.
Then you can use System.Net.WebClient or similar tool to attempt to download a pdf of your report. From there you can either read your execution log, or catch the error in the .Net Code.
EDIT
Well, since you accepted the answer, and it seems you may go this route, I'll mention that if you're not familiar with .net, it may be a long path for you. Here's a few things to get you started.
Below is a c# function utilizing .Net that will query the report catalog. If safeImmediate is set to true, it will only capture reports that can be run immediately, as in there are no parameters or the defaults cover the parameters.
IEnumerable<string> GetReportPaths(
string conStr,
bool safeImmediate // as in, you can exexute the report right away without paramters
) {
using (var con = new SqlConnection(conStr))
using (var cmd = new SqlCommand()) {
cmd.Connection = con;
cmd.CommandText = #"select path from catalog where type=2";
con.Open();
if (safeImmediate)
cmd.CommandText = #"
select path
from catalog
cross apply (select
params = convert(xml, Parameter).value('count(Parameters/Parameter)', 'int'),
defaults = convert(xml, Parameter).value('count(Parameters/Parameter/DefaultValues/Value)', 'int')
) counts
where type = 2
and params = defaults
and path not like '%subreport%' -- this is not standard. Just works for my conventions
";
using (var rdr = cmd.ExecuteReader())
while (rdr.Read())
yield return rdr["path"].ToString();
}
}
The next function will download a report given proper paths passed to it:
byte[] DownloadReport (
WebClient wc,
string coreUrl,
string fullReportPath,
string parameters = "" // you won't use this but may come in handy for other uses
) {
var pathToViewer = "ReportServer/Pages/ReportViewer.aspx"; // for typical ssrs installs
var renderOptions = "&rs:Format=pdf&rs:Command=Render"; // return as pdf
var url = $#"{coreUrl}/{pathToViewer}?{fullReportPath}{parameters}{renderOptions}";
url = Uri.EscapeUriString(url); // url's don't like certain characters, fix it
return wc.DownloadData(url);
}
And this utilizes the functions above to find what's succeeding and whats not:
var sqlCon = "Server=yourReportServer; Database=ReportServer; Integrated Security=yes"; // or whatever
var ssrsSite = "http://www.yourSite.org";
using (var wc = new WebClient()) {
wc.UseDefaultCredentials = true; // or whatever
int loops = 3; // get rid of this when you're ready for prime-time
foreach(var path in GetReportPaths(sqlCon, true)) {
try {
DownloadReport(wc, ssrsSite, path);
Debug.WriteLine($"Success with: {path}");
}
catch(Exception ex) { // you might want to get more specific
Debug.WriteLine($"Failed with: {path}");
}
if (loops-- == 0)
break;
}
}
Lots to learn, but it can be very beneficial. Good luck.

Related

Updating Database Value in windows forms

I am trying to do a function to update a value in a SQL database, this is my table
This is the function
private void UpdateGanToDB(float entrada, string Id)
{
string string_entrada = entrada.ToString();
string conString = Properties.Settings.Default.LocalDataBaseConnectionString;
string command_string = "UPDATE Gan SET Ganan = #GetGan WHERE Id = #GetId";
SqlConnection connection = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(command_string, connection);
cmd.Parameters.AddWithValue("#GetGan", string_entrada);
cmd.Parameters.AddWithValue("#GetId", Id);
try
{
connection.Open();
int row = cmd.ExecuteNonQuery();
if (row > 0) {
MessageBox.Show("Upgrade successful");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
I am getting the message "upgrade successful" but when I check the database I can't see the changes. When I run the text in the command_string with known values I can see the changes but not with my function
Edit:
I added this code to the code above
int row = cmd.ExecuteNonQuery();
if (row > 0) {
SqlCommand command = new SqlCommand("SELECT * FROM Gan ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
System.Data.DataTable dataTable = new System.Data.DataTable();
adapter.Fill(dataTable);
MessageBox.Show(dataTable.Rows[0]["Ganan"].ToString());
}
To see if it is updating the value and I get the excepted 200 (Original value was 0) But When I close the application and see the values in the local database I see the original value 0 I don't know why the update is not saving
EDIT2:
I found another post with a work around for this problem: Can I commit changes to actual database while debugging C# in Visual Studio?
I think your code is correct and there is no problem
If you created database via Add\NewItem\Service-Base Database
I'm not sure, but I think After running your project, one copy of your original database will be included in the debug folder in your project and the update operation and also other operations run on that, not your original database
so, if you want to see a result, you should connect to that via View\ServerExplorer
meantime, after Change your Code and rebuild your Project, your debug database will be deleted and again one copy of your original database will be included in the debug folder

Switching or Selecting Database Server's Connection String Best Practices

I'm developing a software that will be used in different locations with different Servers. It differs in Server Name, Database name, etc.
Example:
Location 1 : Server Name: ChinaServer; Database Name: ChinaDB
Location 2 : Server Name: USServer; Database Name: USDB
Currently, I am using .ini file, I store the server name, database name and other configurations to it. I read it and use it runtime for my connection string. The problem here is that every time we switch locations, I need to change/edit the .ini file.
I'm asking everyone that has more experience that mine to give me other options or best approach on this matter.
Client's Environment : Windows 7
Developers : Windows 7, Visual Studio 2015, MS SQL, VB.NET
Thanks IA.
There's a couple of ways, each with their own advantages and disadvantages, the configuration file would work, could also store it in the registry of the server and read it that way. Or you could even use a My.Setting variable that can be updated in a settings page (probably not the most suitable for your situation)
You can get the basic idea from the The Twelve-Factor App "manifesto":
The twelve-factor app stores config in environment variables...
So what you need is to establish a machine-wide (setx /M NAME VALUE) environment variable which you'll later use like this:
var connectionString = Environment.GetEnvironmentVariable("MY_APP_CONNECTION_STRING");
var dbContext = new DbContext(connectionString);
You can use the SQL Server enumerator in System.Data.Sql, and run a query to get the database names. From there bind those lists to combo boxes, and use a SqlConnectionStringBuilder to keep track of your connection settings. You can save them to disk, or just ask the user to choose the server and database. Note that the enumerator is not guaranteed to always find all servers, so make sure you have a way to enter it manually if necessary.
private SqlConnectionStringBuilder _connString = new SqlConnectionStringBuilder();
private void RefreshConnectionString()
{
_connString.ApplicationName = AppDomain.CurrentDomain.ApplicationIdentity.FullName;
_connString.ApplicationIntent = ApplicationIntent.ReadWrite;
_connString.DataSource = GetSqlDatasources().FirstOrDefault();
_connString.InitialCatalog = GetSqlDatabases().FirstOrDefault();
_connString.AsynchronousProcessing = true;
_connString.ConnectTimeout = 5;
_connString.IntegratedSecurity = true;
_connString.Pooling = true;
}
private IEnumerable<string> GetSqlDatabases()
{
using (var conn = new SqlConnection(_connString.ConnectionString))
{
using (var cmd = new SqlCommand(#"SELECT [name] FROM sys.databases WHERE [name] NOT IN ('master', 'model', 'msdb', 'tempdb')", conn))
{
var dbnames = new List<string>();
try
{
conn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read()) dbnames.Add(reader.GetString(0));
}
catch {}
return dbnames;
}
}
}
private IEnumerable<string> GetSqlDatasources()
{
var sqlEnum = SqlDataSourceEnumerator.Instance;
return sqlEnum.GetDataSources().Rows.OfType<DataRow>().Select(row => row[0].ToString());
}

Check MySql Connection is Opened Or Not in Visual C++

Sorry, If u filling bored. I have searched on several search engines but could not got any result. Anyway I am working in an App which database is mysql. Now I have created a database wrapper class and want to check if the connection is already opened. Could u help me?
String^ constring = L"datasource=localhost;port=3306;username=root;password=pass;database=eps;";
String^ my_query = L"select id from eps_users where usr = '" + this->user_name->Text + "' and psw = md5('" + this->pass_word->Text + "');";
MySqlConnection^ conDatabase = gcnew MySqlConnection(constring);
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
MySqlDataReader^ myreader;
try
{
conDatabase->Open();
myreader = cmd->ExecuteReader();
int count = 0;
while (myreader->Read())
{
count = count + 1;
}
if (count == 1){
MessageBox::Show("Username And Password is correct.", "Success", MessageBoxButtons::OK,
MessageBoxIcon::Information);
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
}
else{
MessageBox::Show("Username And Password is not correct.", "Error", MessageBoxButtons::OK,
MessageBoxIcon::Error);
// <del>
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
// </del>
}
}
catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}
conDatabase->Close();
I need to check if( conDatabase->HasBeenOpened()) { conDatabase->Open();}
The MySqlConnection type implements a feature called connection pooling that relies on the garbage collector to help recycle connections to your database, such that the best practice with regards to connection objects is to create a brand new object for most calls to the database, so that the garbage collector can correctly recycle the old ones. The process goes like this:
Create a new connection
Open the connection
Use the connection for one query/transaction
Dispose the connection
Where all four steps live within a single try/catch/finally block. (Also, the dispose step needs to happen inside the finally block!) Because you generally start with a brand new connection object, there's not typically a need to check if it's open first: you know it's closed. You also don't need to check the state after calling Open(): the method will block until it's finished, and throw an exception if it fails.
However, if you really are in one of the (rare!) situations where it's a good idea to preserve the connection for an extended period, you can check the state like this:
if( conDatabase->State == ConnectionState::Open)
Now, there is one other issue in that code I'd like to talk about. The issue comes down to this: what do you think will happen if I put the following into your username text box:
';DROP Table eps_users;--
If you think that it will try to execute that DROP statement in your database, you're right: it will! More subtle and damaging queries are possible, as well. This is a huge issue: there are bots that run full time crawling web sites looking for ways to abuse this, and even an corporate internal desktop apps will get caught from time to time. To fix this, you need to use Parameterized Queries for every instance where include user-provided data as part of your sql statement.
A quick example might look like this:
String^ my_query = L"select id from eps_users where usr = #userID;";
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
cmd->Parameters->AddWithValue(L"#userID", this->user_name->Text);

Setup Database before run ui coded tests on Visual Studio 2010

I'm automating UI tests to my Silverlight App and I'm using Visual Studio 2010 for it. Some tests required a setup to my Oracle Database.
Things i've done:
1 - A setup.sql file where I connect to my Database and perform actions on it. I had this file as an existing item to my project and I add as a Deployment on TestSettings.
Code:
CONNECT USERNAME#DATABASE,
CREATE TABLE TABLE_NAME,
EXIT
2 - A set.bat file where I call the setup.sql file. I had the path of this file on Setup and Cleanup tab on TestSetings.
Code:
sqlcmd -S MARIALISBOA -i setup.sql
3 - I wrote a TestInitilize method on my TestClass.
Code:
[TestInitialize()]
public void Initialize()
{
System.Diagnostics.Process.Start("setup.bat");
}
4 - I connected do my Database throw Visual Studio (Data -> Add New Data Source).
I run a test on Visual Studio but the class isn't created on my database.
Could anyone help me? I'm trying to solve this problem since Monday and I starting to lose my mind
While it does not solve your initial problem, a solution would be to use something similiar to this;
Do not create the table within your tests. this should be created on install of the Test Environment
Clear down the table for each test you want to do using a Helper Method within the test.
For example (Please note that this is SQL Server, use OLE DB connection or similiar);
internal static object FireSqlStatement(string sqlStatement)
{
object result = null;
using (var cn = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionString].ConnectionString))
{
cn.Open();
var cmd = new SqlCommand
{
CommandText = sqlStatement,
CommandType = CommandType.Text,
Connection = cn
};
result = cmd.ExecuteScalar();
cmd.Dispose();
cn.Close();
}
return result;
}
An example of how I use this within my test;
[Test]
public void GetUserTriggers()
{
//Insert Test Record
Helper.FireSqlStatement("INSERT INTO [Users].[Triggers] (Id) VALUES (1)");
var request = new GetTriggersRequest()
{
TriggerType = TriggerType.UserTrigger
};
var response = ServiceInvoker.Invoke<IReports,
GetTriggersRequest, GetTriggersResponse>(
"Reports",
request,
(proxy, req) => proxy.GetTriggers(req));
foreach (var t in response.Triggers)
{
Console.WriteLine(t.Id.ToString());
}
Assert.NotNull(response);
Assert.NotNull(response.Triggers);
Assert.Greater(response.Triggers.Count, 0);
}
In your case, you could call;
Helper.FireSqlStatement("TRUNCATE TABLE tableName");
Any good?

The file 'C:\....\.....\.....\bin\debug\128849991926295643' already exists

I'm using Visual C#2008 Express Edition and an Express SQL database. Every time I build my solution, I get an error like the one above. Obviously the file name changes. A new file is also created every time I hit a debug point.
I have a stored proc that gets every row from a database table, it gets these rows every time the main form initialises and Adds them to a Generics list. Without inserting or deleting from the table, it gets a different number of rows each time I start my windows application. The error started happening at the same time as the weird data retrieval issue. Any ideas at all about what can cause this?
Thanks
Jose,
Sure, here's my c# method, it retrieves every row in my table, each row has an int and and Image ....
private List<ImageNumber> GetListOfKnownImagesAndNumbers()
{
//ImageNumber imNum = new ImageNumber();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = _conn;
try
{
MemoryStream ms = new MemoryStream();
sqlCommand.CommandText = "usp_GetKnownImagesAndValues";
_conn.Open();
using (IDataReader dr = sqlCommand.ExecuteReader())
{
while (dr.Read())
{
ImageNumber imNum = new ImageNumber();
imNum.Value = dr.IsDBNull(dr.GetOrdinal("ImageValue")) ? 0 : Convert.ToInt32(dr["ImageValue"]);
//Turn the bitmap into a byte array
byte[] barrImg = (byte[])dr["ImageCaptured"];
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(strfn,
FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg, 0, barrImg.Length);
fs.Flush();
fs.Close();
imNum.Image = (Bitmap)Image.FromFile(strfn);
_listOfNumbers.Add(imNum);
}
dr.Close();
_conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
_conn.Close();
}
return _listOfNumbers;
}
And here's my stored proc....
ALTER PROCEDURE dbo.usp_GetKnownImagesAndValues
AS
BEGIN
select ImageCaptured, ImageValue
from CapturedImages
END
Thanks for looking at this. The answer in the end was to put a Thread.Sleep inside the while loop and it started working perfectly. There may be something else I could do, I am obviously waiting for something to complete which is why allowing more time has helped here. If I knew what needed to complete and how to detect when it had completed then I could check for that instead of simply waiting for a short time.

Resources