C# CommandTimeout Using statement issue - command-timeout

I have a method which has served me well, but now the queries have changed and I need to add a CommandTimeout to allow for the fact that some of the client machines on which this is executed are a little under-powered. The issue I'm having is the using lines as adding a CommandTimeout doesn't work.
The program itself pulls queries down from an SFTP server each night and then executes the queries against the client DB, writes the results to file then sends the results back to the SFTP server.
I can't improve the efficiency of the query (read only access) on the client machines, so I'm stuck with this method.
public void DumpTableToFile(string connection, string destinationFile, string QueryToExec)
{
string logDirectory = VariableStorage.logDirectory;
string Practice = VariableStorage.Practice;
try
{
SqlConnection conn = new SqlConnection(connection);
conn.Open();
using (var command = new SqlCommand(QueryToExec, conn))
using (var reader = command.ExecuteReader())
using (var outFile = File.CreateText(destinationFile))
{
string[] columnNames = GetColumnNames(reader).ToArray();
int numFields = columnNames.Length;
outFile.WriteLine(string.Join("\t", columnNames));
if (reader.HasRows)
{
while (reader.Read())
{
string[] columnValues =
Enumerable.Range(0, numFields)
.Select(i => reader.GetValue(i).ToString())
.Select(field => string.Concat("", field.Replace("\"", "\"\""), ""))
.ToArray();
outFile.WriteLine(string.Join("\t", columnValues));
}
}
}
}
catch (Exception e)
{
Program log = new Program();
log.WriteToLog(" Error: " + e);
SendEmailReport(Practice + " - Data Collection Error", " Error: " + e);
}
}

OK, found the answer. I had to remove the Using statements.
var command = new SqlCommand(QueryToExec, conn);
command.CommandTimeout = 300;
var reader = command.ExecuteReader();
var outFile = File.CreateText(destinationFile);

Related

How to get Logic App Metrics?

I'm trying to get Logic Apps metrics like BillableExecutions, Latency etc in my console application.
Currently I'm able to list the logic apps runs, triggers, versions using the .Net Client Microsoft.Azure.Management. But it doesn't seem to have the API to access the monitoring API's.
Code excerpt
private static void Main(string[] args)
{
var token = GetTokenCredentials();
var client = new LogicManagementClient(token, new HttpClientHandler())
{
SubscriptionId = new AzureSubscription().SubscriptionId
};
var dataQuery = new ODataQuery<WorkflowFilter>
{
Top = 50
};
using (client)
{
var logicAppsWorkFlows = client.Workflows.ListBySubscription(dataQuery);
foreach (var logicAppsWorkFlow in logicAppsWorkFlows)
{
var runs = GetWorkflowRuns(client, logicAppsWorkFlow.Id.Split('/')[4], logicAppsWorkFlow.Name);
Console.WriteLine(runs.Count);
}
Console.WriteLine(logicAppsWorkFlows.Count());
}
}
Can someone tell me how to access Logic Apps Metrics? Is there a client similar to Microsoft.Azure.Management for access metrics data?
Update 2
I have found a client dll which was in pre release mode which is used to get metrics. Below is my current code
var token = GetTokenCredentials();
var insightsClient = new InsightsClient(token, new HttpClientHandler())
{
SubscriptionId = new AzureSubscription().SubscriptionId
};
var logicManagementClient = new LogicManagementClient(token, new HttpClientHandler())
{
SubscriptionId = new AzureSubscription().SubscriptionId
};
var dataQuery = new ODataQuery<WorkflowFilter>
{
Top = 50
};
using (logicManagementClient)
{
var logicAppsWorkFlows = logicManagementClient.Workflows.ListBySubscription(dataQuery);
foreach (var logicAppsWorkFlow in logicAppsWorkFlows)
{
using (insightsClient)
{
var metricsDataQuery = new ODataQuery<Metric>
{
Filter = "name.value eq 'ActionLatency' and startTime ge '2014-07-16'"
};
IEnumerable<Metric> metricsList = null;
try
{
metricsList = insightsClient.Metrics.List(logicAppsWorkFlow.Id, metricsDataQuery);
}
catch (Exception e)
{
Console.WriteLine(e);
}
if (metricsList == null) continue;
foreach (var metric in metricsList)
{
foreach (var metricValue in metric.Data)
{
Console.WriteLine(metric.Name.Value + " = " + metricValue.Total);
}
}
}
}
}
I'm getting an exception saying the filter string is not valid. Im referring the filter string structure provided here
https://learn.microsoft.com/en-us/rest/api/monitor/filter-syntax
Can someone tell what im doing wrong here?
Thanks
It looks like ge is not allowed for Logic Apps StartTime field for some reason. I had to change the code to below to make it work
using (logicManagementClient)
{
var logicAppsWorkFlows = logicManagementClient.Workflows.ListBySubscription(dataQuery);
foreach (var logicAppsWorkFlow in logicAppsWorkFlows)
{
using (insightsClient)
{
var metricsDataQuery = new ODataQuery<Metric>
{
Filter = "startTime eq " + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " and name.value eq 'BillableTriggerExecutions' and endTime eq " + DateTime.Now.ToString("yyyy-MM-dd")
};
var query = metricsDataQuery.GetQueryString();
Console.WriteLine(query);
IEnumerable<Metric> metricsList = null;
try
{
//throws exception if there is no metrics data
//TODO: Check whether the logic app ran atleast one time
metricsList = insightsClient.Metrics.List(logicAppsWorkFlow.Id, metricsDataQuery);
}
catch (Exception e)
{
Console.WriteLine(e);
}
if (metricsList == null) continue;
foreach (var metric in metricsList)
{
foreach (var metricValue in metric.Data)
{
Console.WriteLine(metric.Name.Value + " = " + metricValue.Total);
}
}
}
}
}

Error in ExecuteNonQuery command in C#, can't update database

here is the code that i have written for change password in my website in C#, but it shows the error in "ExecuteNonQuery()" command..and i cant update the database with new password... i have tried many solution for that like i have check permission in windows authentication for modify the "Database" file..
-> Code in Change.aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb";
conn = new OleDbConnection(connectionString);
conn.Open();
string str1 = "select * from Student_Login where Password ='" + TextBox1.Text + "'";
OleDbCommand cmd = new OleDbCommand(str1, conn);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
OleDbConnection con1 = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb");
con1.Open();
string str = "UPDATE Student_Login SET Password=" + TextBox3.Text + "where Password= " + TextBox1.Text;
using (OleDbCommand cmd1 = new OleDbCommand(str, con1))
{
cmd1.ExecuteNonQuery();
}
Label1.Visible = true;
con1.Close();
}
else
{
Label3.Visible = true;
}
conn.Close();
}
...................
error image
It seems that there are a few syntax issues within your existing code, such as missing quotes around your parameter values when building your queries and concatenating your strings like the following line :
string str = "UPDATE Student_Login SET Password='" + TextBox3.Text + "' where Password= " + TextBox1.Text + "'";
A bigger issue here is that you aren't using SQL Parameterization, which can cause issues like this to occur (and lead to SQL Injection vulnerabilities). Consider the following code, which should resolve all of your previous issues and keep you protected against any injection-based nastiness:
// Create your connection
using (var conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb"))
{
// Build your first query
var query = "SELECT * FROM Student_Login WHERE Password = #password";
// Create a command to execute your query
using (var cmd = new OleDbCommand(query, conn))
{
// Open your connection
conn.Open();
// Add your parameter (prevents SQL Injection and syntax issues)
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
// Execute your query into a reader
using (var dr = cmd.ExecuteReader())
{
// Go through each row
while(dr.Read())
{
// Build an update query
var updateQuery = "UPDATE Student_LogIn SET Password = #password WHERE Password = #oldPassword";
// Build a new command to execute
using (var updateCmd = new OleDbCommand(updateQuery, conn))
{
// Set a parameter and execute
updateCmd.Parameters.AddWithValue("#password", TextBox3.Text);
updateCmd.Parameters.AddWithValue("#oldPassword", TextBox1.Text);
// Execute your query
updateCmd.ExecuteNonQuery();
Label1.Visible = true;
}
}
}
}
}
You can also try this version which doesn't rely on named parameters :
// Create your connection
using (var conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb"))
{
// Build your first query
var query = "SELECT * FROM Student_Login WHERE Password = ?";
// Create a command to execute your query
using (var cmd = new OleDbCommand(query, conn))
{
// Open your connection
conn.Open();
// Add your parameter (prevents SQL Injection and syntax issues)
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
// Execute your query into a reader
using (var dr = cmd.ExecuteReader())
{
// Go through each row
while(dr.Read())
{
// Build an update query
var updateQuery = "UPDATE Student_LogIn SET Password = ? WHERE Password = ?";
// Build a new command to execute
using (var updateCmd = new OleDbCommand(updateQuery, conn))
{
// Set a parameter and execute
updateCmd.Parameters.AddWithValue("#password", TextBox3.Text);
updateCmd.Parameters.AddWithValue("#oldPassword", TextBox1.Text);
// Execute your query
updateCmd.ExecuteNonQuery();
Label1.Visible = true;
}
}
}
}
}
Can you try once this...
updateCmd.Parameters.Add("#password", SqlDbType.VarChar);
updateCmd.Parameters["#password"].Value = TextBox3.Text;
updateCmd.Parameters.Add("#oldPassword", SqlDbType.VarChar);
updateCmd.Parameters["#oldPassword"].Value = TextBox1.Text;

running stored procedures into own model with servicestack ormlite

Is there any examples to be found for running a stored procedure on serviceStack MVC using ormlite? mythz ? seen this block of code:
var results = new List<EnergyCompare>
{dbFactory.Exec(dbCmd =>
{
dbCmd.CommandType = CommandType.StoredProcedure;
dbCmd.Parameters.Add(new SqlParameter("#id", 1));
dbCmd.CommandText = "GetAuthorById";
return dbCmd.ExecuteReader().ConvertTo<EnergyCompare>();
}
)};
but came with the text of never worked on the google groups!
i can also write this:
using(var db = new SwitchWizardDb())
{
var results2 = db.dbCmd.ExecuteProcedure()
}
but not sure how to complete this with parameters, and in the source code I looked at, it said obsolete?
thanks
Looks like ServiceStack.ORMLite has been updated to make this easier:
List<Poco> results = db.SqlList<Poco>("EXEC GetAnalyticsForWeek 1");
List<Poco> results = db.SqlList<Poco>("EXEC GetAnalyticsForWeek #weekNo", new { weekNo = 1 });
List<int> results = db.SqlList<int>("EXEC GetTotalsForWeek 1");
List<int> results = db.SqlList<int>("EXEC GetTotalsForWeek #weekNo", new { weekNo = 1 });
This example is on the front page of the github repo.
Well I figured it was best to roll my own handler so have created this, any thoughts would be most welcome, especially with how I could pass over params in some kind of func or something:
I have a main class to deal with easy access to my connection object:
public class DatabaseNameSp : IDisposable
{
private readonly SqlConnection _spConn = new SqlConnection(DatabaseNameSp .dbConString);
public readonly SqlCommand SpCmd;
public DatabaseNameSp (string procedureName)
{
_spConn.Open();
SpCmd = new SqlCommand
{
Connection = _spConn,
CommandType = CommandType.StoredProcedure,
CommandText = procedureName
};
}
public void Dispose()
{
_spConn.Close();
SpCmd.Dispose();
}
}
usage:
using (var db = new DatabaseNameSp ("procedurenname"))
{
db.SpCmd.Parameters.Add(new SqlParameter("#Id", 1));
var rdr = db.SpCmd.ExecuteReader(CommandBehavior.CloseConnection);
var results = new List<CustomDTO>();
while (rdr.Read())
{
results.Add(new CustomDTO { Name = rdr["name"].ToString(), Id = rdr["id"].ToString() });
}
return new CustomDTOResponse { Results = results };
}
Any thoughts !
thanks
Here is an example of running a stored procedure with ormLite that may help you:
IList<MyDTO> myList = DbFactory.Run(dbCnx =>
{
using (var dbCmd = dbCnx.CreateCommand())
{
dbCmd.CommandType = CommandType.StoredProcedure;
dbCmd.CommandText = "mySchema.myStoredProc";
dbCmd.Parameters.Add(new SqlParameter("#param1", val1));
dbCmd.Parameters.Add(new SqlParameter("#param2", val2));
var r = dbCmd.ExecuteReader();
return r.ConvertToList<MyDTO>();
}
});
To just simply run a stored procedure with no data returned:
public class ComsManager : Dbase
{
private IDbConnection dbConn;
public ComsManager()
{
dbConn = Dbase.GetConnection();
}
public void Housekeeping()
{
using(var dbCmd = dbConn.CreateCommand())
dbConn.Exec(res => { dbCmd.CommandType = CommandType.StoredProcedure; dbCmd.CommandText = "SP_housekeeping"; dbCmd.ExecuteNonQuery(); });
}

missing semicolon at end of sql statement

I have a problem when i m rum my code then error is occured "missing semicolon at end of sql statement."
My code is :
Code
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Geeta/Desktop/mssl2.accdb;Persist Security Info=False";);
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string sql = "INSERT INTO digital(Product_Name, Product_Code, Product_Price, Product_Image, Product_Description) VALUES(#pnm, #pcod, #ppr, #pimg, #pdes) SELECT ##IDENTITY;";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#pnm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#pcod", txt_productcode.Text.Trim());
cmd.Parameters.AddWithValue("#ppr", txt_productprice.Text.Trim());
cmd.Parameters.AddWithValue("#pdes", txt_productdescri.Text.Trim());
cmd.Parameters.AddWithValue("#pimg", imgByte);
int Id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", Id);
conn.Close();
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
}
}
}
add semicolon before select ##identity. then try to excute. which means for insert statement one semicolon and for select on semi colon.
Before "SELECT ##IDENTITY", you need a semi-colon.
Technically you're creating two SQL statements.
One for insert, and one for SELECT ##IDENTITY. That's why you need a semi-colon between those two queries.

net send command program debugging in C#

I write a program to execute and send msg using windows net send command.Its working fine for single receptor.But the problem happen when i want to send message in many receptors. i use a for loop to take receptor name from a list box. Here all message go to the first receptor.The problem happen on process execution.So far i guess the process is not clear or dead on the time.
Can any body guide me how i can send the msg to multiple users at a time?
my code below:
string sendingMessage = messageRichTextBox.Text;
string[] recepentAddressArray = new string[recepentAddressListBox.Items.Count];
for (int j = 0; j < recepentAddressListBox.Items.Count; j++) // Getting address from list box
{
recepentAddressArray[j] = recepentAddressListBox.Items[j].ToString();
string recepantAddress = recepentAddressArray[j];
try
{
string strLine = "net send " + recepantAddress + " " + sendingMessage + " >C:netsend.log";
FileStream fs = new FileStream("c:netsend.bat", FileMode.Create, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.BaseStream.Seek(0, SeekOrigin.End);
streamWriter.Write(strLine);
streamWriter.Flush();
streamWriter.Close();
fs.Close();
Process p = new Process();
p.StartInfo.FileName = "C:netsend.bat";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
p.WaitForExit();
p.Close();
FileStream fsOutput = new FileStream("C:netsend.log", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fsOutput);
reader.BaseStream.Seek(0, SeekOrigin.Begin);
string strOut = reader.ReadLine();
reader.Close();
fsOutput.Close();
}
catch (Exception)
{
MessageBox.Show("ERROR");
}
}

Resources