I'm trying to update a SQLite database with a column "URL" with a specific value. The old url format is "http://www.blz.nl/voster/boek/9789056628512" and the new one is "http://www.blz.nl/voster/boekwinkel/zoeken/?q=9780789327505&oa=true&searchin=taal&taal=dut".
What I am trying to do is replace the url to the new format but keep the value of the 'Q' param from the old url. What is the fastest / best way to achieve this for all columns? I have no idea how to approach this using an SQL query.
You want the SQL?
Basically, you read in the table, search for your keyword, replace it, and write that data back to the database.
Assuming your database name is "mydatabase.db", your code would look something like this (untested):
using Devart.Data.SQLite;
public void Convert()
{
using (var conn = new SQLiteConnection("DataSource=mydatabase.db"))
{
var boek = "//boek//";
var boekwinkel = "//boekwinkel//";
var boek_len = boek.Length;
var table = new DataTable();
var sqlCmd = "SELECT * FROM TableName1;";
conn.Open();
// Read the data into the DataTable:
using (var cmd = new SQLiteCommand(sqlCmd, conn))
{
// The DataTable is ReadOnly!
table.Load(cmd.ExecuteReader());
}
// Use a new SQLiteCommand to write the data.
using (var cmd = new SQLiteCommand("UPDATE TableName1 SET URL=#NEW_URL WHERE URL=#URL;", conn))
{
cmd.Parameters.Add("#URL", SQLiteType.Text, 20);
cmd.Parameters.Add("#NEW_URL", SQLiteType.Text, 20);
foreach (DataRow row in table.Rows)
{
var url = String.Format("{0}", row["URL"]).Trim();
cmd.Parameters["#URL"].SQLiteValue = row["URL"];
if (!String.IsNullOrEmpty(url))
{
var index = url.IndexOf(boek);
if (-1 < index)
{
var first = url.Substring(0, index);
var middle = boekwinkel;
var last = url.Substring(index + boek_len);
var new_url = String.Format("{0}{1}{2}&oa=true&searchin=taal&taal=dut", first, middle, last);
// Place a break point after String.Format.
// Make sure the information being written is correct.
cmd.Parameters["#NEW_URL"].SQLiteValue = new_url;
cmd.ExecuteNonQuery();
}
}
}
}
conn.Close();
}
}
Related
I am making an API using ASP.netCore to fetch data from teradata. I have 2 store procedure on Teradata DB one for encryption one for description. What I want to achieve is when user call the get method to fetch data, my Store procedure should run first and then it should return all table to user(changed as SP).
I have tried a lot but didn't manage to find any way to call store procedure and Select * table together. If I run the only store procedure OR call only select * table it work. I want to call both (SP and select*) so first SP should run and change the data then return the changed data table.
My codes are following.
Codes for GetDataTable
public IEnumerable<myTable> GetData(IConfiguration _configuration)
{
try
{
myTable TableReturn = new myTable();
List<myTable> dataReturn = new List<myTable>();
var connectionString = _configuration.GetConnectionString("TeradataConnectionString");
using (var connection = new TdConnection(connectionString))
{
'Date_Of_Birth', ENCRYPTEDSTRING);";
TdCommand cmd = new TdCommand("SELECT * FROM Project.myTable;", connection) ;
TdCommand Db = (TdCommand)cmd;
Db.Connection = connection;
connection.Open();
TdDataReader reader = Db.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var newTable = new myTable();
newTable.Employee_Id = (string)reader.GetString(0);
newTable.First_name = (string)reader.GetString(1);
newTable.Last_Name = (string)reader.GetString(2);
newTable.Date_Of_Birth = (string)reader.GetString(3);
newTable.Phone = (string)reader.GetString(4);
newTable.Em_Position = (string)reader.GetString(5);
dataReturn.Add(newTable);
}
}
else
{
Console.WriteLine("no rows found");
}
}
return dataReturn;
}
catch (Exception e)
{
throw new Exception();
}
}
My codes for store procedure are following
public IEnumerable<DecryptedData> DecryptedData(IConfiguration _configuration)
{
// DecryptedData DecryptedReturn = new DecryptedData();
List<DecryptedData> dataReturn = new List<DecryptedData>();
var connectionString = _configuration.GetConnectionString("TeradataConnectionString");
using (var connection = new TdConnection(connectionString))
{
string command = "CALL Project.Decryption(STATUS,'Project' ,'myTable', 'Date_Of_Birth', ENCRYPTEDSTRING);";
TdCommand cmd = new TdCommand(command, connection);
TdCommand Db = (TdCommand)cmd;
Db.Connection = connection;
connection.Open();
TdDataReader reader = Db.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var DecryptedData = new DecryptedData();
DecryptedData.Date_Of_Birth = reader.GetString(1);
dataReturn.Add(DecryptedData);
Console.WriteLine(dataReturn);
}
}
else
{
Console.WriteLine("no rows found");
}
}
return dataReturn;
}
My ASP.NET Core MVC project has several reports. To render the reports as PDF, I'm using AspNetCore.Reporting library.
This library works fine for a single report but due to some cache issues it throws an exception while generating another report. The solution I found on the internet was to run report generation as a new process but I don't know how to implement that.
I found the suggestion to use Tmds.ExecFunction to run report generation as a seperate process. But I dont know how to pass parameters to the function.
Here is my code:
string ReportName = "invoiceDine";
DataTable dt = new DataTable();
dt = GetInvoiceItems(invoiceFromDb.Id);
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("bParam", $"{invoiceFromDb.Id}");
param.Add("gParam", $"{salesOrderFromDb.Guests}");
param.Add("tParam", $"{invoiceFromDb.Table.Table}");
param.Add("dParam", $"{invoiceFromDb.Time}");
param.Add("totalP", $"{invoiceFromDb.SubTotal}");
param.Add("t1", $"{tax1}");
param.Add("t2", $"{tax2}");
param.Add("tA1", $"{tax1Amount}");
param.Add("tA2", $"{tax2Amount}");
param.Add("AT1", $"{totalAmountWithTax1}");
param.Add("AT2", $"{totalAmountWithTax2}");
param.Add("terminalParam", $"{terminalFromDb.Name}");
param.Add("addressParam", $"{t.Address}");
param.Add("serviceParam", "Service Charges of applicable on table of " + $"{personForServiceCharges}" + " & Above");
var result = reportService.GenerateReport(ReportName, param, "dsInvoiceDine", dt);
return File(result,"application/Pdf");
This is my version of the function:
``` public byte[] GenerateReport(string ReportName, Dictionary<string,string> Parameters,string DataSetName,DataTable DataSource )
{
string guID = Guid.NewGuid().ToString().Replace("-", "");
string fileDirPath = Assembly.GetExecutingAssembly().Location.Replace("POS_Website.dll", string.Empty);
string ReportfullPath = Path.Join(fileDirPath, "\\Reports");
string JsonfullPath = Path.Join(fileDirPath,"\\JsonFiles");
string rdlcFilePath = string.Format("{0}\\{1}.rdlc", ReportfullPath, ReportName);
string generatedFilePath = string.Format("{0}\\{1}.pdf", JsonfullPath, guID);
string jsonDataFilePath = string.Format("{0}\\{1}.json", JsonfullPath, guID);
File.WriteAllText(jsonDataFilePath, JsonConvert.SerializeObject(DataSource));
FunctionExecutor.Run((string[] args) =>
{
// 0 : Data file path - jsonDataFilePath
// 1 : Filename - generatedFilePath
// 2 : RDLCPath - rdlcFilePath
ReportResult result;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding.GetEncoding("windows-1252");
LocalReport report = new LocalReport(args[2]);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(File.ReadAllText(args[0]));
report.AddDataSource(args[3], dt);
result = report.Execute(RenderType.Pdf, 1,Parameters);
using (var fs = new FileStream(args[1], FileMode.Create, FileAccess.Write))
{
fs.Write(result.MainStream);
}
}, new string[] {jsonDataFilePath, generatedFilePath, rdlcFilePath, DataSetName });
var memory = new MemoryStream();
using (var stream = new FileStream(Path.Combine("", generatedFilePath), FileMode.Open))
{
stream.CopyTo(memory);
}
File.Delete(generatedFilePath);
File.Delete(jsonDataFilePath);
memory.Position = 0;
return memory.ToArray();
}
But it throws exception "Field marshaling is not supported by ExecFunction" on line:
var result = reportService.GenerateReport(ReportName, param, "dsInvoiceDine", dt);
No Need to run report generation as a seperate process. Just Dont Pass extension as 1
in:
var result = localReport.Execute(RenderType.Pdf, 1, param);
The Solution is:
int ext = (int)(DateTime.Now.Ticks >> 10);
var result = localReport.Execute(RenderType.Pdf, ext, param);
In SQL Server I can use sql:variable:
string sql = "select * from mytable where xml_column.exist('//Tag[text()=sql:variable(\"#value\")]') = 1";
I was trying to find similar way to pass parameter into NpgsqlCommand. This one for example does not fail but also does not return any data:
string sql = "select * from mytable where xmlexists('//Tag[text()=\"#value\"]' PASSING BY REF xml_column) = true";
Is there any way of doing it?
Thanks!
Here is a code snippet:
string connstr = "PORT=5432;DATABASE=mydb;HOST=myhost;USER ID=myuser;PASSWORD=mypassword";
using (NpgsqlConnection connection = new NpgsqlConnection(connstr))
{
connection.Open();
string sql = "select xml_column from mytable where xmlexists('//Tag[text()=\"#value\"]' PASSING BY REF xml_column) = true";
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#value", "my value");
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
reader[0].Dump();
}
}
}
connection.Close();
}
Cross-posted on github, see answer there: https://github.com/npgsql/npgsql/issues/2946
I am trying to monitor multiple tables using signalR. These tables are related, but I need all columns from all tables for display purposes. I have seen SQldependcy on one table. How to implement it for multiple tables? Is this the right way to implement sqldependecy and signalr for multiple tables? In the database there are different tables with each having the ForiegnKey master--->submaster--->detail. Please suggest!
var masterpc = new List<master_Table>();
var submaster = new List<submaster_Table>();
var detail = new List<detail_Table>();
using (SqlConnection connection = new SqlConnection(regularConnectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
//var dependency = new SqlDependency(command);
//dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
// NOTE: You have to execute the command, or the notification will never fire.
var reader = command.ExecuteReader();
while (reader.Read())
{
masterpc.Add(item: new master_Table
{
MasterKeyId = (int)reader["MasterKeyId"],
Master_Name = (string)reader["Master_Name"],
Master_IP = reader["Master_IP"] != DBNull.Value ? (string)reader["Master_IP"] : "",
Master_Valid = (bool)reader["Master_Valid"],
});
count++;
}
masterViewModel.masterpc_info = masterpc;
}
}
count = 0;
using (SqlConnection connection = new SqlConnection(regularConnectionString))
{
commandText = "select * from submaster where master_Valid=1 and masterKeyId in(select masterKeyId from masterpc_table where id=24) ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
//var dependency = new SqlDependency(command);
//dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
// NOTE: You have to execute the command, or the notification will never fire.
var reader = command.ExecuteReader();
while (reader.Read())
{
submaster.Add(item: new submaster_table
{
SubmasterKeyId = (int)reader["SubmasterKeyId"],
submaster_Type = (string)reader["submaster_Type"],
submaster_SN = reader["submaster_SN"] != DBNull.Value ? (string)reader["submaster_SN"] : "",
masterPCKeyId = (int)reader["masterPCKeyId"],
});
count++;
}
masterconfigViewModel.submasterinfo = submaster;
}
}
using (SqlConnection connection = new SqlConnection(regularConnectionString))
{
commandText = "select * from detail where submasterKeyId in(select submasterkeyid from masterpc_table where id=24) ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
// NOTE: You have to execute the command, or the notification will never fire.
var reader = command.ExecuteReader();
while (reader.Read())
{
detail.Add(item: new detail_table
{
detailkeyid = (int)reader["detailkeyid"],
detail_Type = (string)reader["detail_Type"],
detail_status = reader["detail_status"] != DBNull.Value ? (string)reader["detail_status"] : "",
submasterkeyid = (int)reader["submasterkeyid"],
});
count++;
}
masterconfigViewModel.detailinfo = detail;
}
}
This might be little late to answer, but you might think the following option suitable for you.
Project known as SqlDependencyEx
https://github.com/dyatchenko/ServiceBrokerListener
How to use for multiple tables
All you need to do is to create multiple listeners with different
identities as shown below:
var listener1 = new SqlDependencyEx(connectionString, "YourDatabase", "YourTable1", identity: 1);
var listener2 = new SqlDependencyEx(connectionString, "YourDatabase", "YourTable2", identity: 2);
I have a test DX pivot grid that I'm attempting to attach a simple SQL statement against (fairly trite example I know, but I'm just "proof of concept"ing here)
#Html.DevExpress().PivotGrid(settings =>
{
settings.Name = "pivotGrid";
settings.CallbackRouteValues = new { Controller = "Home", Action = "PivotGridPartial" };
settings.OptionsView.ShowHorizontalScrollBar = true;
settings.Height = new Unit(887, UnitType.Pixel);
settings.Width = new Unit(100, UnitType.Percentage);
settings.OptionsCustomization.CustomizationFormStyle = CustomizationFormStyle.Excel2007;
var dataTable = new DataTable();
using (var con = new SqlConnection(#"Data Source=.\WHATEVER;Initial Catalog=WhatEver;integrated security=true;"))
{
con.Open();
var adapter = new SqlDataAdapter("select * from dbo.WhatEver", con);
adapter.Fill(dataTable);
}
settings.PreRender = (sender, e) =>
{
var pivot = ((MVCxPivotGrid)sender);
pivot.DataSource = dataTable;
pivot.RetrieveFields(PivotArea.FilterArea, false);
pivot.BeginUpdate();
pivot.Fields["Client"].Area = PivotArea.RowArea;
pivot.Fields["Client"].Visible = true;
pivot.Fields["Brand"].Area = PivotArea.RowArea;
pivot.Fields["Brand"].Visible = true;
pivot.Fields["Volume"].Area = PivotArea.DataArea;
pivot.Fields["Volume"].Visible = true;
pivot.EndUpdate();
};
}).GetHtml()
This works perfectly when it loads, but then if I try to expand one of the dimensions or change to another page the grid gets blanked out, i.e. like it has no data assigned against it.
Would anyone have an idea as to why? I can't find anything relating to pivot grids and DX that doesn't assume using an OLAP cube and the examples I have found (all around Access) seem to be doing what I'm attempting but obviously I'm missing something!
Thanks in advance!
It's because I'm an idiot and had the datasoruce assignment in the prerender section