Is there any way to log all requests ongoing to a database or can you only log snapshots to a database?
The following example relies upon OLEDB 4.0 which is not available for 64bit processes. You can either select another data provider (e.g. SQLServer) or you can force Fiddler to run in 32bit mode.
Add the following to the Rules file to create a new menu item.
// Log the currently selected sessions in the list to a database.
// Note: The DB must already exist and you must have permissions to write to it.
public static ToolsAction("Log Selected Sessions")
function DoLogSessions(oSessions: Fiddler.Session[]){
if (null == oSessions || oSessions.Length < 1){
MessageBox.Show("Please select some sessions first!");
return;
}
var strMDB = "C:\\log.mdb";
var cnn = null;
var sdr = null;
var cmd = null;
try
{
cnn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strMDB);
cnn.Open();
cmd = new OleDbCommand();
cmd.Connection = cnn;
for (var x = 0; x < oSessions.Length; x++){
var strSQL = "INSERT into tblSessions ([ResponseCode],[URL]) Values (" +
oSessions[x].responseCode + ", '" + oSessions[x].url + "')";
cmd.CommandText = strSQL;
cmd.ExecuteNonQuery();
}
}
catch (ex){
MessageBox.Show(ex);
}
finally
{
if (cnn != null ){
cnn.Close();
}
}
}
Note: To use the Database Objects in Fiddler 2.3.9 and below, you'll need to add system.data to the References list inside Tools | Fiddler Options | Extensions | Scripting. In 2.3.9.1 and later, this reference will occur automatically.
Then, list the new import at the top of your rules script:
import System.Data.OleDb;
see FiddlerScript CookBook
Related
I need to know the correct way to handle SQL Injection when using the FromSQL command.
At runtime, I need to dynamically create a where statement. So I am using FromSql to create the SQL command. Now I know that using use string interpolation is the way to go. However, I need to step through a list of "Where Parameters" to generate the command. Simple enough to do;
foreach (var x in wp)
{
if (!string.IsNullOrEmpty(results))
results = $"{results} and {x.Field} = {x.Value}";
if (string.IsNullOrEmpty(results))
results = $"where {x.Field} = {x.Value}";
}
Problem is that this return a simple string and would not be string interpolation. How can I do this correctly?
Entityframework will parameterize your queries if you put it in the following format:
db.something.FromSql("SELECT * FROM yourTable WHERE AuthorId = {0}", id)
Is x.Field a form field that has a fixed number of possibilities? i.e. title, firstname etc. If so then something like the following:
var sqlstring = new StringBuilder();
var sqlp = new List<SqlParameter>();
var i = 0;
foreach (var x in wp)
{
var param = "#param" + i.ToString();
if (i!=0)
{
sqlstring.Append($" AND {x.Field} = " + param);
sqlp.Add(new SqlParameter(param, x.Value));
}
if (i==0)
{
sqlstring.Append($"WHERE {x.Field} = " + " #param" + i.ToString());
sqlp.Add(new SqlParameter(param, x.Value));
}
i++;
}
You'd then need to do something like this:
db.something.FromSql(sqlstring.ToString(), sqlp.ToArray())
Might be a better/cleaner way but that should work.
My solution to this problem is a VS extension, QueryFirst. QueryFirst generates a C# wrapper for sql that lives in a .sql file. As such, parameters are the only way to get data into your query and SQL injection is near impossible. There are numerous other advantages: you edit your sql in a real environment, it's constantly validated against your db, and using your query in your code is very simple.
I'm trying to save a "history" I'm building after you sent a command from a line, so every time you press Enter the commands goes to the jTextPane with a line separator... However when I save the file it doesn't seem to get the line separator. Example, my jTextPane has something like:
Create database user
use database user
show tables from database
Instead of saving the workspace just like that, it gives me this:
Create database useruse database usershow tables from database
What should I do? Here's my code
String ar;
String TEXTO = jTextPane1.getText() + System.lineSeparator();
FileFilter ft = new FileNameExtensionFilter("Text Files", ".txt");
FC.setFileFilter(ft);
int returnVal = FC.showSaveDialog(this);
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
java.io.File saved_file = FC.getSelectedFile();
String file_name = saved_file.toString();
File archivo;
ar = "" + file_name + ".txt";
archivo = new File(ar);
try {
if (saved_file != null) {
try (FileWriter GUARDADO = new FileWriter(ar)) {
GUARDADO.write(TEXTO);
}
}
} catch (IOException exp) {
System.out.println(exp);
}
}
You need to use :
jTextPane1.getDocument().getText(0,jTextPane1.getDocument().getLength());
The issue is that you need to use /n instead of System.lineSeparator. The JTextPane behavior doesn't depends on the System.
We've got a little console app that creates scripts based on to>from migrations ... we're using to do our rollback scripts as well.
With rollback we stick in null and the migration to rollback to.
We've just moved the Console app to a new solution, but I cannot get it to make the first rollback script when the is only one migration in _MigrationHistory.
Any ideas?
public static string CreateScriptBetween(string from, string to, string name)
{
var dbMigrator = new DbMigrator(new EmptyConfiguration());
var scriptor = new MigratorScriptingDecorator(dbMigrator);
var script = "USE MYCOOLSKILLZDB" + Environment.NewLine + Environment.NewLine + "GO" + Environment.NewLine
+ Environment.NewLine;
script += scriptor.ScriptUpdate(from, to);
var filename = FileGenerator.NewNamedFilename(name, "sql");
using (var writer = new StreamWriter(filename, false))
{
writer.Write(script);
}
return filename;
}
I have an issue implementing CCR with SQL. It seems that when I step through my code the updates and inserts I am trying to execute work great. But when I run through my interface without any breakpoints, it seems to be working and it shows the inserts, updates, but at the end of the run, nothing got updated to the database.
I proceeded to add a pause to my code every time I pull anew thread from my pool and it works... but that defeats the purpose of async coding right? I want my interface to be faster, not slow it down...
Any suggestions... here is part of my code:
I use two helper classes to set my ports and get a response back...
/// <summary>
/// Gets the Reader, requires connection to be managed
/// </summary>
public static PortSet<Int32, Exception> GetReader(SqlCommand sqlCommand)
{
Port<Int32> portResponse = null;
Port<Exception> portException = null;
GetReaderResponse(sqlCommand, ref portResponse, ref portException);
return new PortSet<Int32, Exception>(portResponse, portException);
}
// Wrapper for SqlCommand's GetResponse
public static void GetReaderResponse(SqlCommand sqlCom,
ref Port<Int32> portResponse, ref Port<Exception> portException)
{
EnsurePortsExist(ref portResponse, ref portException);
sqlCom.BeginExecuteNonQuery(ApmResultToCcrResultFactory.Create(
portResponse, portException,
delegate(IAsyncResult ar) { return sqlCom.EndExecuteNonQuery(ar); }), null);
}
then I do something like this to queue up my calls...
DispatcherQueue queue = CreateDispatcher();
String[] commands = new String[2];
Int32 result = 0;
commands[0] = "exec someupdateStoredProcedure";
commands[1] = "exec someInsertStoredProcedure '" + Settings.Default.RunDate.ToString() + "'";
for (Int32 i = 0; i < commands.Length; i++)
{
using (SqlConnection connSP = new SqlConnection(Settings.Default.nbfConn + ";MultipleActiveResultSets=true;Async=true"))
using (SqlCommand cmdSP = new SqlCommand())
{
connSP.Open();
cmdSP.Connection = connSP;
cmdSP.CommandTimeout = 150;
cmdSP.CommandText = "set arithabort on; " + commands[i];
Arbiter.Activate(queue, Arbiter.Choice(ApmToCcrAdapters.GetReader(cmdSP),
delegate(Int32 reader) { result = reader; },
delegate(Exception e) { result = 0; throw new Exception(e.Message); }));
}
}
where ApmToCcrAdapters is the class name where my helper methods are...
The problem is when I pause my code right after the call to Arbiter.Activate and I check my database, everything looks fine... if I get rid of the pause ad run my code through, nothing happens to the database, and no exceptions are thrown either...
The problem here is that you are calling Arbiter.Activate in the scope of your two using blocks. Don't forget that the CCR task you create is queued and the current thread continues... right past the scope of the using blocks. You've created a race condition, because the Choice must execute before connSP and cmdSP are disposed and that's only going to happen when you're interfering with the thread timings, as you have observed when debugging.
If instead you were to deal with disposal manually in the handler delegates for the Choice, this problem would no longer occur, however this makes for brittle code where it's easy to overlook disposal.
I'd recommend implementing the CCR iterator pattern and collecting results with a MulitpleItemReceive so that you can keep your using statements. It makes for cleaner code. Off the top of my head it would look something like this:
private IEnumerator<ITask> QueryIterator(
string command,
PortSet<Int32,Exception> resultPort)
{
using (SqlConnection connSP =
new SqlConnection(Settings.Default.nbfConn
+ ";MultipleActiveResultSets=true;Async=true"))
using (SqlCommand cmdSP = new SqlCommand())
{
Int32 result = 0;
connSP.Open();
cmdSP.Connection = connSP;
cmdSP.CommandTimeout = 150;
cmdSP.CommandText = "set arithabort on; " + commands[i];
yield return Arbiter.Choice(ApmToCcrAdapters.GetReader(cmdSP),
delegate(Int32 reader) { resultPort.Post(reader); },
delegate(Exception e) { resultPort.Post(e); });
}
}
and you could use it something like this:
var resultPort=new PortSet<Int32,Exception>();
foreach(var command in commands)
{
Arbiter.Activate(queue,
Arbiter.FromIteratorHandler(()=>QueryIterator(command,resultPort))
);
}
Arbiter.Activate(queue,
Arbiter.MultipleItemReceive(
resultPort,
commands.Count(),
(results,exceptions)=>{
//everything is done and you've got 2
//collections here, results and exceptions
//to process as you want
}
)
);
Is it possible to implement batching of multiple stored procedure calls (doing updates/deletes) in ADO.NET without resorting to DataAdapters?
You could try using System.Data.SqlClient.SqlCommandSet. It's actually internal, but Ayende made a wrapper to make it public.
Code is currently hosted in sourceforge.
You're SQL text can contain multiple commands. If you return multiple result sets, then you can use a DataReader and use the NextResult function. What I often do is store the SQL to execute as an Embedded Resource, then load that text. If it contains parameters, then set the parameters just like you would normally.
For example, I have a file:
UPDATE dbo.QuotePricedLineItem
SET fkQuoteVendorLineSet = NULL
FROM dbo.QuotePricedLineItem qpli
INNER JOIN dbo.QuoteLineItem qli ON qpli.Id = qli.Id
WHERE qli.fkQuote = #quoteId AND qpli.fkQuoteVendorLineSet = #ciscoConfigId
DELETE CiscoQuoteLineItem
FROM CiscoQuoteLineItem cqli
INNER JOIN QuoteLineItem qli ON cqli.Id = qli.Id
WHERE qli.fkQuote = #quoteId AND cqli.fkCiscoQuoteVendorLineSet = #ciscoConfigId
that I execute as such:
using (SqlConnection conn = DbUtils.CreateConnection() as SqlConnection)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = MvcApplication.GetResource("SQL.DemoteCiscoQuoteLineItems.sql");
cmd.Parameters.AddWithValue("#quoteId", q.Id);
cmd.Parameters.AddWithValue("#ciscoConfigId", configSetId);
cmd.ExecuteNonQuery();
}
Note that MvcApplication.GetResource is not a built in function - it's one you have to write... here's mine:
public static string GetResource(string p)
{
Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("CortexQuoting.Res." + p);
if (s == null) return null;
StreamReader sw = new StreamReader(s);
string ss = sw.ReadToEnd();
sw.Close();
return ss;
}