SSRS Download All History Snapshots - reporting-services

Is it possible to download all the history snapshots of a report at once? Preferably as a CSV. Would save a lot time instead of clicking into each one individually and selecting save as CSV.
I only see the option to Delete

In PowerShell, you can loop through each snapshot and save them using this example:
<#
Description: Save SSRS Report Snapshots
#>
$sql = "
DECLARE #ReportName NVARCHAR(200) = 'Your Report Name'; --change to NULL for every snapshot
DECLARE #FileFormat NVARCHAR(50) = 'CSV'; --HTML5,PPTX,ATOM,HTML4.0,MHTML,IMAGE,EXCEL (for .xls),EXCELOPENXML (for .xlsx),WORD (for .doc),WORDOPENXML (for .docx),CSV,PDF,XML
DECLARE #FileExtn NVARCHAR(50) = 'csv';
DECLARE #ServerName NVARCHAR(100) = 'http://YourServerName';
DECLARE #DateFrom DATE = CAST(DATEADD(DAY, -1, GETDATE()) AS DATE); --change to NULL for every snapshot
DECLARE #ExportPath NVARCHAR(200) = 'C:\Temp\';
SELECT
--[ReportID] = [c].[itemid]
-- , [ReportName] = [c].[name]
-- , [ReportPath] = [c].[path]
-- , [SnaphsotDate] = FORMAT([h].[snapshotdate], 'dd-MMM-yyyy')
-- , [SnapshotDescription] = [s].[DESCRIPTION]
-- , [SnapshotEffectiveParams] = [s].[effectiveparams]
-- , [SnapshotQueryParams] = [s].[queryparams]
-- , [ScheduleName] = [sc].[name]
-- , [ScheduleNextRunTime] = CONVERT(VARCHAR(20), [sc].[nextruntime], 113)
[ExportFileName] = #ExportPath + REPLACE([c].[name], ' ', '_') + '_' + FORMAT([h].[snapshotdate], 'yyyyMMdd_HHmm') + '.' + #FileExtn
, [SnapshotUrl] =
#ServerName
+ '/ReportServer/Pages/ReportViewer.aspx?'
+ [c].[path] + '&rs:Command=Render&rs:Format='
+ #FileFormat + '&rs:Snapshot='
+ FORMAT([h].[snapshotdate], 'yyyy-MM-ddTHH:mm:ss')
FROM
[ReportServer].[dbo].[History] AS [h] WITH(NOLOCK)
INNER JOIN [ReportServer].[dbo].[SnapshotData] AS [s] WITH(NOLOCK) ON [h].[snapshotdataid] = [s].[snapshotdataid]
INNER JOIN [ReportServer].[dbo].[Catalog] AS [c] WITH(NOLOCK) ON [c].[itemid] = [h].[reportid]
INNER JOIN [ReportServer].[dbo].[ReportSchedule] AS [rs] WITH(NOLOCK) ON [rs].[reportid] = [h].[reportid]
INNER JOIN [ReportServer].[dbo].[Schedule] AS [sc] WITH(NOLOCK) ON [sc].[scheduleid] = [rs].[scheduleid]
WHERE
1=1
AND [rs].[reportaction] = 2
AND (#ReportName IS NULL OR [c].[Name] = #ReportName)
AND (#DateFrom IS NULL OR [h].[snapshotdate] >= CAST(DATEADD(DAY, -1, GETDATE()) AS DATE))
ORDER BY
[c].[name]
, [h].[snapshotdate];
;"
$server = 'YourServerName';
$dbs = 'MASTER';
$dsn = "Data Source=$server; Initial Catalog=$dbs; Integrated Security=SSPI;";
$cn = New-Object System.Data.SqlClient.SqlConnection($dsn);
#execute merge statement here with parameters
$cn = New-Object System.Data.SqlClient.SqlConnection($dsn);
$cn.Open();
$cmd = $cn.CreateCommand();
$cmd.CommandText = $sql
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $cmd
$cmd.Connection = $cn
$ds = New-Object System.Data.DataSet
$SqlAdapter.Fill($ds)
$cn.Close()
$Result = $ds.Tables[0]
Foreach ($item in $Result)
{
#Write-Host $item.name
$SnapshotUrl = $item.SnapshotUrl
$ExportFileName = $item.ExportFileName
(Invoke-WebRequest -Uri $SnapshotUrl -OutFile $ExportFileName -UseDefaultCredentials -TimeoutSec 240);
}
https://learn.microsoft.com/en-us/sql/reporting-services/url-access-parameter-reference?view=sql-server-ver15

Was having trouble with powershell, so thought I'd post simplified version of my rough Python solution inspired by the resource from #aduguid's answer.
import requests
from requests_negotiate_sspi import HttpNegotiateAuth
import os
def downloadFile(url, file_name, download_folder, session):
response = session.get(url, stream=True) # open the download link
file_path = os.path.join(download_folder, file_name)
with open(file_path, 'wb') as file: # create a new file with write binary mode
for chunk in response.iter_content(chunk_size=1024):
if chunk:
file.write(chunk)
# Can also use '/Reports()' for non-linked reports.
# Can also pass in 'path="<report_path>"' instead of using id numbers,
# e.g. '.../Reports(path="/cool%20reports/my%20report")/HistorySnapshots'
api_url = r'http://<server_name>/reports/api/v2.0/LinkedReports(<item_id>)/HistorySnapshots'
session = requests.session()
session.auth = HttpNegotiateAuth() # uses windows log in
response = session.get(api_url)
hs_snapshot_list = response.json()['value']
for item_dict in hs_snapshot_list:
download_url = (r'http://<server_name>/ReportServer/Pages/ReportViewer.aspx?<report_path>'
+ '&rs:Snapshot=' + item_dict['HistoryId']
+ '&rs:Format=CSV')
downloadFile(download_url, '<your_file_name>', '<your_download_folder>', session)
SSRS API Resource:
https://app.swaggerhub.com/apis/microsoft-rs/SSRS/2.0#/Reports/GetReportHistorySnapshots

Related

insert value txt file into mysql laravel 6

how can I insert value from my input file.txt like this to MySQL, these [example image] (https://i.stack.imgur.com/v16fi.png).
and I just need atm_id, name_atm, ip, and status agent_connection
my code is like
` $data = $request->file('file');
$filetmp = $data->getRealPath();
$filedata = file_get_contents($filetmp);
$lines = explode("\n", $filedata);
$lines=array_slice($lines,
array_keys(
array_filter($lines,
function($item){
return strpos($item,'PAR') ;
}))[0]
);
$arrays = array_map(function($array) {
$columns = ['atm_id', 'name_atm', 'ip', 'agent_connection',];
return array_combine($columns, array_map('trim', $array));
}, array_chunk($lines, 5));
dd($arrays);`
I expect I can insert just
atm_id = AT8502 atm_name = example ip = 10.51.7.50 agent_connection = complete
as much as data on txt file.

i want use placeholder to get data from user input kivy mysql

conn = mysql.connector.connect(
host="localhost",
user="root",
passwd="12123123412"
database='newdb')
cur = conn.cursor()
xx_zz = self.screen.get_screen('end').ids["rgr"].text
ee_zz = self.screen.get_screen('end').ids["gfd"].text
qur = f"SELECT * FROM (%s) WHERE bedrooms = '(%s)' "
val = (xx_zz, ee_zz)
cur.execute(qur, val)
records = cur.fetchall()
I suggest that we use a function to create the query string using match-case. This will avoid any risk of SQL injection as we are not using the string provided by the front end.
You will need to modify and complete the option values and table names and decide whether there should be a default table name or no result if the option provided is not found.
Obviously this code has not been tested.
def makeQuery( option ):
match option:
case 'option1':
return f"SELECT * FROM table_name_1 WHERE bedrooms = '(%s)' "
case 'option2':
return f"SELECT * FROM table_name_2 WHERE bedrooms = '(%s)' "
case _:
return f"SELECT * FROM default_table_name WHERE bedrooms = '(%s)' "
conn = mysql.connector.connect(
host="localhost",
user="root",
passwd="12123123412"
database='newdb')
cur = conn.cursor()
xx_zz = self.screen.get_screen('end').ids["rgr"].text
ee_zz = self.screen.get_screen('end').ids["gfd"].text
qur = makeQuery(xx_zz )
val = ( ee_zz )
cur.execute(qur, val)
records = cur.fetchall()
In textInput (field) you use hint_text to show a placeholder in a text field(input).

Generate n-gram for a specific column present in mysql db

I'm writing a code to generate n-grams for every record in the table by reading a specific column.
def extract_from_db(inp_cust_id):
sql_db = TatDBHelper()
t_sql = "select notes from raw_data where customer_id = {0}"
db_data = sql_db.execute_read(t_sql.format(inp_cust_id))
for row in db_data:
text = row.values()
bi_grams = generate_ngrams(text[0].encode("utf-8"), 2)
print bi_grams
def generate_ngrams(sentence, n):
sentence = sentence.lower()
sentence = re.sub(r'[^a-zA-Z0-9\s]', ' ', sentence)
tokens = [token for token in sentence.split(" ") if token != ""]
ngrams = zip(*[tokens[i:] for i in range(n)])
return [" ".join(ngram) for ngram in ngrams]
I'm getting the output like:
['i highly', 'highly recommend', 'recommend it']
['the penguin', 'penguin encounter', 'encounter was', 'was awesome']
I want the output to look like below, can anybody help me to get this.
['i highly',
'highly recommend',
'recommend it',
...
]
creat another list all_ngrams, and keep appending the values to it , using .extend(), and finally you will have all the ngrams in one list.
Try this :
def extract_from_db(inp_cust_id):
sql_db = TatDBHelper()
t_sql = "select notes from raw_data where customer_id = {0}"
db_data = sql_db.execute_read(t_sql.format(inp_cust_id))
all_ngrams = []
for row in db_data:
text = row.values()
bi_grams = generate_ngrams(text[0].encode("utf-8"), 2)
all_ngrams.extend(bi_grams)
print all_ngrams

Import CSV to localhost error on import

I am having some issues with an error message that keeps coming up and I cannot locate why.
I am trying to build a process that utilises the database functionalities of WAMP on my PC to store and manipulate data rather than use MS Access.
The script below contains the current powershell script that I have been working on which is creating a new database and table to contain my CSV data however when I am trying to insert the CSV data into the newly created table it is presenting me with two repetitive errors.
The property 'CommandText' cannot be found on this object. Verify that the property exists and can be set.
And
Cannot convert value ",'" to type "System.Int32". Error: "Input string was not in a correct format."
I am simply at a loss to how to correct this and why it is throwing errors, is this obvious to anyone?
$CL2Location = 'L:\Controls\BROKER CASH RECONCILIATIONS\cl2cashpositions-331-Corrected.csv'
$dbnameone = "brokerreconciliation"
[system.reflection.assembly]::LoadWithPartialName("MySql.Data")
$mysqlConn = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection
$mysqlConn.ConnectionString = "SERVER=localhost;DATABASE=brokerreconciliation;UID=root;PWD=''"
$mysqlConn.Open()
$ccmd = New-Object MySql.Data.MySqlClient.MySqlCommand
$ccmd.Connection = $mysqlConn
$ccmd.CommandText = "DROP DATABASE IF EXISTS " + $dbnameone
$ccmd.ExecuteNonQuery()
$ccmd.CommandText = 'CREATE SCHEMA `' + $dbnameone + '`'
$ccmd.ExecuteNonQuery()
$dbonetablescript = #"
CREATE TABLE brokerreconciliation.CL2 (
`ID` MEDIUMINT(8) unsigned NOT NULL auto_increment,
`CL2ACCOUNTCODE` varchar(255) default NULL,
`ACBALANCE` varchar(255) default NULL,
`PARNAME1` varchar(255) default NULL,
PRIMARY KEY (`ID`)
) AUTO_INCREMENT=1;
"#
$ccmd.CommandText = $dbonetablescript
$ccmd.ExecuteNonQuery()
$ccmd = New-Object MySql.Data.MySqlClient.MySqlCommand
$ccmd.Connection = $mysqlConn
$ccmd.CommandText = "truncate table " + $dbnameone + ".CL2;"
$ccmd.ExecuteNonQuery()
foreach ($i in Import-Csv $cl2location) {
$cmd.CommandText =
"INSERT INTO customers (id,cl2accountcode,acbalance,parname1) VALUES ("
+$i.id+",'"+$i.cl2accountcode+"','"+$i.acbalance+"','"+$i.parname+"');"
$cmd.ExecuteNonQuery()
}
Import-Csv $CL2Location ##Added to ensure that the data file was being reached it is
$mysqlConn.Close()
Link to example CSV data is here.
Trying to resolve this problem I have tried to write the data directly from the data table created via the initial sql query to reduce the amount of steps that I would require. The code below is the update, even utilising the result set directly I am still hitting the same errors when I try to upload the data to local host.
I have also edited the CREATE TABLE element to match the schema of the base database exactly to ensure there was nothing with this that was causing the issue.
I am still at a loss as to how I cannot pass the information from either CSV or script to a newly created table on localhost.
[System.Reflection.Assembly]::LoadWithPartialName("Sql.Data")
$null = [Reflection.Assembly]::LoadWithPartialName("WindowsBase")
#####################
## - CREDENTIALS - ##
#####################
$MISA = 'xx.xx.x.xx'
$userName = 'IR'
$PassWord = 'IR'
$DB = 'IR'
$timeout = 0
###### - StopWatch - ######
$timeout2 = new-timespan -Minutes 5
$sw = [diagnostics.stopwatch]::StartNew()
##### sql ####
### MIS CL2 ###
$CL2CashPositionsScript = #'
SELECT CL2ACCOUNTCODE, sum(CAST(CL2ACCOUNTBALANCE AS MONEY)) AS CBALANCE, PARNAME1
FROM T5CASHL2 CL2 LEFT OUTER JOIN T5PARTICIPANT PAR
ON PAR.PARPDRPARTICIPANTID = CL2.CL2ACCOUNTCODE
WHERE CL2CLIENTNUM not like '315'
--AND CL2ACCOUNTCODE = '331'
GROUP BY CL2ACCOUNTCODE, PARNAME1, PARNAME2
ORDER BY CL2ACCOUNTCODE ASC
'#
## CREATE MIS CREDENTIALS ##
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection("Connection Timeout=0")
$SqlConnection.ConnectionString = "Data Source=$MISA;Initial Catalog=$DB;
Initial Catalog=$DB;User ID=$userName;Password=$PassWord;"
## - Runs Script from Set Location
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandTimeout=$timeout;
$SqlCMD.CommandText = $CL2CashPositionsScript;
$SqlCmd.Connection = $SqlConnection;
## - Extract Data and build sql data object
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];
#######
$CL2Location = 'L:\Controls\BROKER CASH RECONCILIATIONS\cl2cashpositions-331-Correctedb.csv'
$dbnameone = "brokerreconciliation"
[System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$mysqlConn = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection
$mysqlConn.ConnectionString = "SERVER=localhost;DATABASE=brokerreconciliation;UID=root;PWD=''"
$mysqlConn.Open()
$ccmd = New-Object MySql.Data.MySqlClient.MySqlCommand
$ccmd.Connection = $mysqlConn
$ccmd.CommandText = "DROP DATABASE IF EXISTS " + $dbnameone
$ccmd.ExecuteNonQuery()
$ccmd.CommandText = 'CREATE SCHEMA `' + $dbnameone + '`'
$ccmd.ExecuteNonQuery()
$dbonetablescript = #"
CREATE TABLE brokerreconciliation.CL2 (
`ID` MEDIUMINT(8) unsigned NOT NULL auto_increment,
`CL2ACCOUNTCODE` char(12) default NULL,
`CBALANCE` char(20) default NULL,
`PARNAME1` varchar(30) default NULL,
PRIMARY KEY (`ID`)
) AUTO_INCREMENT=1;
"#
$ccmd.CommandText = $dbonetablescript
$ccmd.ExecuteNonQuery()
$ccmd = New-Object MySql.Data.MySqlClient.MySqlCommand
$ccmd.Connection = $mysqlConn
$ccmd.CommandText = "truncate table " + $dbnameone + ".CL2;"
$ccmd.ExecuteNonQuery()
foreach ($i in $DataSetTable) {
$ccmd.CommandText =
"INSERT INTO customers (cl2accountcode,cbalance,parname1) VALUES ("
+$i.cl2accountcode+"';'"+$i.cbalance+"';'"+$i.parname+"');"
$ccmd.ExecuteNonQuery()
}
$mysqlConn.Close()
You can't wrap strings like this:
$ccmd.CommandText =
"INSERT INTO customers (cl2accountcode,cbalance,parname1) VALUES ("
+$i.cl2accountcode+"';'"+$i.cbalance+"';'"+$i.parname+"');"
PowerShell will interpret
$ccmd.CommandText =
"INSERT INTO customers (cl2accountcode,cbalance,parname1) VALUES ("
and
+$i.cl2accountcode+"';'"+$i.cbalance+"';'"+$i.parname+"');"
as separate statements, because the first two lines are a complete statement in and by themselves. The third line then throws an error, because +$i.cl2accountcode (i.e. $null + [int]) becomes an integer, and [int] + [string] is only valid if the string can be cast to an integer (which is not the case for the string ';').
To make string concatenation work across lines you need to either escape the line break
$ccmd.CommandText =
"INSERT INTO customers (cl2accountcode,cbalance,parname1) VALUES (" `
+$i.cl2accountcode+"';'"+$i.cbalance+"';'"+$i.parname+"');"
or put the concatenation operator at the end of the line (so PowerShell knows there is more to come)
$ccmd.CommandText =
"INSERT INTO customers (cl2accountcode,cbalance,parname1) VALUES (" +
$i.cl2accountcode+"';'"+$i.cbalance+"';'"+$i.parname+"');"

Converting SQLite to MySQL script (Check if correct)

i just wrote a small script to port sqlite table to mysql but im realy not sure if i did right.
Im atleast sure, it works to the mysql-connection part, so atleast it already builds mysql connection.
from __future__ import with_statement
import sqlite3
import os
import pymysql
addonPath = "Path-To-SQLITe-Database"
addonPathOrginal = -"Path-To-Database.ini"
connection = sqlite3.connect(os.path.join(addonPath, "db.sqlite"))
#connection.row_factory = sqlite3.Row
connection.text_factory = str
cursor = connection.cursor()
sqliteexecute = cursor.execute
fetchall = cursor.fetchall
databaseinfo = os.path.join(addonPathOrginal, "database.ini")
d = {}
with open(databaseinfo, "r") as fs:
for l in fs.readlines():
l = l.strip(" ").strip("\n")
obj = l.split("=")
if len(obj) != 2: continue
if obj[1] == "": continue
d[obj[0]] = obj[1]
mysqlcon = pymysql.connect(**d)
mysqlcursor = mysqlcon.cursor()
execute = mysqlcursor.execute
execute("SET ##autocommit=1;")
execute("SET sql_notes = 1;")
execute("SET FOREIGN_KEY_CHECKS = 0;")
tablename = "jumptimes" # Convert Table 'jumptimes'
sqliteexecute("SELECT * FROM sqlite_master WHERE type='table' AND tbl_name='%s'" tablename)
#sqliteexecute("SELECT jumptimes FROM sqlite_master")
for x in fetchall():
print "Table: %s" % tablename
#if tablename == "sqlite_sequence": continue
sqliteexecute("SELECT * FROM %s" % tablename)
stuff = fetchall()
if len(stuff) == 0: continue
string = ("%s," * len(stuff[0]))[:-1]
print "Table %s, %i elements, length of string %i" % (tablename, len(stuff),len(stuff[0]))
for y in range(0, len(stuff), 5):
mysqlcursor.executemany("REPLACE INTO " + tablename + " VALUES (" + string + ")", stuff[y:y+5])
connection.close()
execute("SET FOREIGN_KEY_CHECKS = 1;")
mysqlcon.commit()
mysqlcon.close()
database.ini
host=""
user=""
passwd=""
db=""