I need to know a way to implement in my system, a Driver or Dialect which, whenever I perform a SELECT in Nhibernate, the SELECT adds the with(nolock) with it.
I need that to be in C# and NHibernate, not directly in the DB !
Hope you can understand !
Thanks !
It is possible to modify the sql using an Interceptor and overriding the OnPrepareStatement method, something like this:
public class AddNoLockHintsInterceptor : EmptyInterceptor
{
public override SqlString OnPrepareStatement(SqlString sql)
{
// Modify the sql to add hints
return sql;
}
}
And here is a way to register the interceptor with NHibernate:
var session = SessionFactory.OpenSession(new AddNoLockHintsInterceptor());
Using the WITH(NOLOCK) hint is the same thing as using a READ UNCOMMITED transaction isolation level as discussed here: When should you use "with (nolock)".
You can specify the transaction isolation level when starting new transactions with NHibernate:
var session = SessionFactory.OpenSession();
session.BeginTransaction(IsolationLevel.ReadUncommitted);
I would not recommend this unless you really know what you are doing though. Here's some more information on the subject: Why use a READ UNCOMMITTED isolation level?.
Hope this would help someone,
I used this code to add no lock hints to the most of the queries, related to the answer dillenmeister
public class NoLockHintsInterceptor : EmptyInterceptor
{
public override SqlString OnPrepareStatement(SqlString sql)
{
// Modify the sql to add hints
if (sql.StartsWithCaseInsensitive("select"))
{
var parts = new List<object>((object[]) sql.Parts);
object fromItem = parts.FirstOrDefault(p => p.ToString().ToLower().Trim().Equals("from"));
int fromIndex = fromItem != null ? parts.IndexOf(fromItem) : -1;
object whereItem = parts.FirstOrDefault(p => p.ToString().ToLower().Trim().Equals("where"));
int whereIndex = whereItem != null ? parts.IndexOf(whereItem) : parts.Count;
if (fromIndex == -1)
return sql;
parts.Insert(parts.IndexOf(fromItem) + 2, " with(nolock) ");
for (int i = fromIndex; i < whereIndex; i++)
{
if (parts[i - 1].Equals(","))
{
parts.Insert(i + 2, " with(nolock) ");
i += 2;
}
if (parts[i].ToString().Trim().EndsWith(" on"))
{
parts[i] = parts[i].ToString().Replace(" on", " with(nolock) on ");
}
}
sql = new SqlString(parts.ToArray());
}
return sql;
}
}
There are two errors in this code:
For SQL script that has parameter This code won't work.
SqlString.Parts is not compile, I am using NHibernate 4.0.0.4000
Here is the Fix:
public class NoLockInterceptor : EmptyInterceptor
{
public override SqlString OnPrepareStatement(SqlString sql)
{
//var log = new StringBuilder();
//log.Append(sql.ToString());
//log.AppendLine();
// Modify the sql to add hints
if (sql.StartsWithCaseInsensitive("select"))
{
var parts = sql.ToString().Split().ToList();
var fromItem = parts.FirstOrDefault(p => p.Trim().Equals("from", StringComparison.OrdinalIgnoreCase));
int fromIndex = fromItem != null ? parts.IndexOf(fromItem) : -1;
var whereItem = parts.FirstOrDefault(p => p.Trim().Equals("where", StringComparison.OrdinalIgnoreCase));
int whereIndex = whereItem != null ? parts.IndexOf(whereItem) : parts.Count;
if (fromIndex == -1)
return sql;
parts.Insert(parts.IndexOf(fromItem) + 3, "WITH (NOLOCK)");
for (int i = fromIndex; i < whereIndex; i++)
{
if (parts[i - 1].Equals(","))
{
parts.Insert(i + 3, "WITH (NOLOCK)");
i += 3;
}
if (parts[i].Trim().Equals("on", StringComparison.OrdinalIgnoreCase))
{
parts[i] = "WITH (NOLOCK) on";
}
}
// MUST use SqlString.Parse() method instead of new SqlString()
sql = SqlString.Parse(string.Join(" ", parts));
}
//log.Append(sql);
return sql;
}
}
Related
Please help me, I'm facing a fatal problem here. If someone could fix this, I swear I will treat u to a huge drink whenever u step into my country (Vietnam). Ok here's the problem: I'm coding a webservice for multi connection simultaneously from tablet (around 100 clients). It ran well but recently whenever high traffic occurs, my webservice seems to stuck somehow and I need to copy - override the published file of webservice in order for it to run again (restart website in IIS is no use) ...
This is my w/s code for handling the data:
public string Info_Handling(string id, string name, string strDetails)
{
string checkExist = "";
string str = "";
string str2 = "";
MLL_Customer _customerClient = new MLL_Customer();
MLL_CustomerCategory _categoryClient = new MLL_CustomerCategory();
MLL_Product _productClient = new MLL_Product();
MLL_SampleProduct _sampleClient = new MLL_SampleProduct();
if (_customerClient.CheckExistCustomer(id, name.ToUpper(), 2) == 1) // SID & NAME
{
checkExist = "EXIST";
}
using (SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["Main.ConnectionString"]))
{
connection.Open();
SqlTransaction trans = connection.BeginTransaction("XXX");
try
{
// ID Example: 11 means VIP - 12 means Normal - 13 means ples... jkg
// First - Insert Customer
string strCustomerCategory = _categoryClient.SelectCategoryByID(id).ToString();
if (!checkExist.Equals("EXIST"))
{
Customer businessObject = new Customer();
businessObject.ID = sid;
businessObject.Name = name.ToUpper();
businessObject.CategoryID = strCustomerCategory;
str = "" + _customerClient.Insert(businessObject, connection, trans);
}
// Second Insert Product spliting from a string Ex: "TV&Laptop&CD"
string[] productDetails = strDetails.Split(new char[] { '&' });
object obj3;
SampleProduct objSample;
Product objProduct;
for (int j = 0; j < productDetails.Length; j++)
{
if (_productClient.CheckExist(id, productDetails[j])) == null) // Check if customer already owns this product
{
// Get the properties of sample product.
objSample = _sampleClient.SelectSampleProduct(productDetails[j]);
objProduct = new Product();
objProduct.SID = sid;
objProduct.Testcode = objSample.TestCode;
objProduct.Category = objSample.Category;
objProduct.Unit = objSample.Unit;
objProduct.Price = objSample.Price;
if (_productClient.Insert(objProduct, connection, trans) != 0)
{
str2 = str2 + "&" + objProduct.Testcode;
// return the code of product in order to see which product has been inserted successfully
}
}
}
trans.Commit();
SqlConnection.ClearAllPools();
}
catch (Exception exception)
{
str = "0";
str2 = exception.Message + exception.Source;
try
{
trans.Rollback();
}
catch (Exception)
{
}
}
}
if (!str2.Equals(""))
{
return (str + "&" + id + str2);
}
return ("0&" + sid + str);
}
I modified the code but this is basically how i roll. Could anyone plz tell me some solution. Deeply thank u.
1 more thing about ClearAllPools() method: I know how it works but I dont even know why I need it. Without this, my data will be messed up terrible. CategoryID of one customer will be assigned for another customer sometimes. ???? How could it happened ?? HELP
I finally get it. It's not just the code I use to execute the ExecuteScalar method but it is mainly the code up stream that is executing the class. It is everything calling your code. That said, can someone please see if the code executing the my SQL class has faults. I still cant pass the scans. First I will show you two examples of the code calling my code, then the calling code, and finally the executing code, which I formulated and displayed from a previous post.
Calling code with three parameters:
public bool isTamAsp(int aspKey, int fy, string accountCode)
{
MyParam myParam;
string sqlQuery = "select isTamMacom = count(macom_key) FROM hier_fy " +
"WHERE hier_key = #aspKey AND fy = #fy AND #accountCode NOT IN (3,4,7,8) AND macom_key IN (select hier_key from lkup_e581_MacomThatRequireTAM) AND is_visible = 1 AND is_active = 1";
QueryContainer Instance = new QueryContainer(sqlQuery);
myParam = new MyParam();
myParam.SqlParam = new SqlParameter("#aspKey", Instance.AddParameterType(_DbTypes.Int));
myParam.SqlParam.Value = aspKey;
Instance.parameterList.Add(myParam);
myParam = new MyParam();
myParam.SqlParam = new SqlParameter("#fy", Instance.AddParameterType(_DbTypes.Int));
myParam.SqlParam.Value = fy;
Instance.parameterList.Add(myParam);
myParam = new MyParam();
myParam.SqlParam = new SqlParameter("#accountCode", Instance.AddParameterType(_DbTypes._string));
myParam.SqlParam.Value = accountCode;
Instance.parameterList.Add(myParam);
if (Convert.ToInt32(ExecuteScaler(Instance)) < 1)
return false;
return true;
}
Calling code with no parameters:
public long GetMarinesUploadNextUploadKey()
{
string query = "SELECT MAX(upload_key) FROM temp_auth_usmc_upload";
QueryContainer Instance = new QueryContainer(query);
string result = Convert.ToString(ExecuteScaler(Instance));
if (string.IsNullOrEmpty(result))
return 1;
else
return Convert.ToInt64(result) + 1;
}
Code calling my previous code with three parameters:
public bool isTamAsp(int aspKey, int fy, string accountCode)
{
return e581provider.isTamAsp(aspKey, fy, accountCode);
}
Method calling the SQL executing my code:
DbCommand command = _provider.CreateCommand();
command.Connection = _connection;
{
command.CommandText = Instance.Query;
command.CommandType = CommandType.Text;
if (Instance.parameterList.Count > 0)
{
foreach (var p in Instance.parameterList)
{
command.Parameters.Add(p.SqlParam);
}
}
if (_useTransaction) { command.Transaction = _transaction; }
try
{
returnValue = command.ExecuteScalar();
}
My Class containing the SQL string and the cmd parameter List
public enum _DbTypes
{
Int = 1, _string = 2, _long = 3, _bool = 4, _DateTime = 5,
_decimal = 6, _float = 7, _short = 8, _bite = 9
}
public class MyParam
{
public SqlParameter SqlParam { get; set; }
}
/// <summary>
/// Summary description for QueryContainer SGH
/// </summary>
public class QueryContainer
{
string _query;
public List<MyParam> parameterList = new List<MyParam>();
public QueryContainer(string query) { _query = query; }
public SqlDbType AddParameterType(_DbTypes id)
{
switch (id)
{
case _DbTypes.Int:
return (SqlDbType)Enum.Parse(typeof(SqlDbType), "int", true);
case _DbTypes._string:
return (SqlDbType)Enum.Parse(typeof(SqlDbType), "NVarChar", true);
case _DbTypes._long:
return (SqlDbType)Enum.Parse(typeof(SqlDbType), "SqlDbType.BigInt", true);
case _DbTypes._bool:
return (SqlDbType)Enum.Parse(typeof(SqlDbType), "SqlDbType.Bit", true);
}
return SqlDbType.VarChar;
}
public string Query
{
get
{
return _query;
}
set { _query = value; }
}
}
I don't see a vulnerability in that code, but I have an idea what the scan may be asking for. The problem could be that this code makes it too easy for developers to ignore the parameterList collection in your class. If I'm a new developer in your organization who hasn't discovered Sql injection yet, I'd be tempted to ignore all that complicated query parameter stuff and just use string concatenation before setting your Query property.
Instead of wrapping this in a class, what I'm more used to seeing is a single method that has a signature like this:
IEnumerable<T> GetData<T>(string query, IEnumerable<Sqlparameter> parameters)
...or some permutation of that method signature that may use arrays or lists instead of IEnumerable. This forces downstream developers to deal with that parameters argument to the method. They can't ignore it, and so the temptation to use a quick, lazy string concatenation call to substitute some user-provided data into the query is reduced.
I don't know why the following query doesn't executed with my expected parameters !!
cmdTxt.Append("UPDATE sd32depart SET currentcredit = currentcredit + ? WHERE year = ? AND main_code = ? ");
paramList.Add("currentcredit", value.ToString().TrimEnd());
paramList.Add("year", year.ToString().TrimEnd());
paramList.Add("main_code", main_code.ToString().TrimEnd());
res = ConnectionObj.Execute_NonQueryWithTransaction(cmdTxt.ToString(), CommandType.Text, paramList);
I get
res = 1and although currentcredit = 180 as a parameter
when i check my table i found currentcredit NULL !!
public int Execute_NonQueryWithTransaction(string cmdText)
{
string return_msg = "";
int return_val = -1;
//check if connection closed then return -1;
if (connectionstate == ConnectionState.Closed)
return -1;
command.CommandText = cmdText;
command.CommandType = CommandType.Text;
command.Transaction = current_trans;
try
{
return_val = command.ExecuteNonQuery();
}
catch (IfxException ifxEx)// Handle IBM.data.informix : mostly catched
{
return_val = ifxEx.Errors[0].NativeError;
return_msg = return_val.ToString();
}
catch (Exception ex)// Handle all other exceptions.
{
return_msg = ex.Message;
}
finally
{
if (!string.IsNullOrEmpty(return_msg))//catch error
{
//rollback
current_trans.Rollback();
Close_Connection();
}
}
return return_val;
}
From the comments:
currentcredit is null before the update, what should i do
Ah, that's the problem then. In SQL, null is sticky. null + anything is: null. If this was TSQL (i.e. SQL Server), the solution would be ISNULL:
UPDATE sd32depart SET currentcredit = ISNULL(currentcredit,0) + ?
where the result of ISNULL(x, y) is x if x is non-null, otherwise y. In C# terms, it is the equivalent of x ?? y (and indeed, ISNULL(x, y) is identical to COALESCE(x, y), except that COALESCE is varadic).
So: find the informix equivalent of ISNULL or COALESCE, and use that.
From a brief search, it seems that in informix the NVL function does this, so try:
UPDATE sd32depart SET currentcredit = NVL(currentcredit,0) + ?
I want to read properties of MSI in C# in desktop application.I am using following code:
public static string GetMSIProperty( string msiFile, string msiProperty)
{
string retVal= string.Empty ;
Type classType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Object installerObj = Activator.CreateInstance(classType);
WindowsInstaller.Installer installer = installerObj as WindowsInstaller.Installer;
Database database = installer.OpenDatabase("C:\\DataP\\sqlncli.msi",0 );
string sql = String.Format("SELECT Value FROM Property WHERE Property=’{0}’", msiProperty);
View view = database.OpenView(sql);
Record record = view.Fetch();
if (record != null)
{
retVal = record.get_StringData(1);
}
else
retVal = "Property Not Found";
return retVal;
}
But I am getting error as System.Runtime.InteropServices.COMException was unhandled.
the sqlncli.msi file is physically placed at c:\DataP location. While debugging I found that database does not contain the data after installer.OpenDatabase() statement.
How can I resolve this issue and get MSI properties in C#?
Windows Installer XML's Deployment Tools Foundation (WiX DTF) is an Open Source project from Microsoft which includes the Microsoft.Deployment.WindowsInstaller MSI interop library. It's far easier and more reliable to use this to do these sorts of queries. It even has a LINQ to MSI provider that allows you to treat MSI tables as entities and write queries against them.
using System;
using System.Linq;
using Microsoft.Deployment.WindowsInstaller;
using Microsoft.Deployment.WindowsInstaller.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using(var database = new QDatabase(#"C:\tfs\iswix.msi", DatabaseOpenMode.ReadOnly))
{
var properties = from p in database.Properties
select p;
foreach (var property in properties)
{
Console.WriteLine("{0} = {1}", property.Property, property.Value);
}
}
using (var database = new Database(#"C:\tfs\iswix.msi", DatabaseOpenMode.ReadOnly))
{
using(var view = database.OpenView(database.Tables["Property"].SqlSelectString))
{
view.Execute();
foreach (var rec in view) using (rec)
{
Console.WriteLine("{0} = {1}", rec.GetString("Property"), rec.GetString("Value"));
}
}
}
Console.Read();
}
}
}
I did it in following way:
String inputFile = #"C:\\Rohan\\sqlncli.msi";
// Get the type of the Windows Installer object
Type installerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
// Create the Windows Installer object
WindowsInstaller.Installer installer = (WindowsInstaller.Installer)Activator.CreateInstance(installerType);
// Open the MSI database in the input file
Database database = installer.OpenDatabase(inputFile, 0);
// Open a view on the Property table for the version property
View view = database.OpenView("SELECT * FROM _Tables");
// Execute the view query
view.Execute(null);
// Get the record from the view
Record record = view.Fetch();
while (record != null)
{
Console.WriteLine(record.get_StringData(0) + '=' + record.get_StringData(1) + '=' + record.get_StringData(2) + '=' + record.get_StringData(3));
record = view.Fetch();
}
And its working for me.
The SQL string is incorrect. It should be:
SELECT `Value` FROM `Property` WHERE `Property`.`Property` = ’{0}’
I was trying to re-use this code, and the only change I had to make to get the code posted by Devashri to work is this line:
string sql = String.Format("SELECT `Value` FROM `Property` WHERE `Property`='{0}'", msiProperty);
Watch out for the single quotes!
as of 04/2020 it would be
Type installerType { get; set; }
WindowsInstaller.Installer installerObj { get; set; }
...
installerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
installerObj = (WindowsInstaller.Installer)Activator.CreateInstance(installerType);
var installer = installerObj as WindowsInstaller.Installer;
...
private void lnkSelectMsi_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
WindowsInstaller.Database msiDatabase = installerObj.OpenDatabase(txtMsiPath.Text, 0);
readMsiTableColumn(msiDatabase, cmbTable.Text, cmbColumn.Text);
}
private void readMsiTableColumn(WindowsInstaller.Database msiDatabase, string table)
{
WindowsInstaller.View msiView = null;
Record record = null;
string s = string.Empty;
try
{
msiView = msiDatabase.OpenView($"Select * from _Columns");
msiView.Execute();
record = msiView.Fetch();
int k = 0;
while (record != null)
{
if (record.StringData[1].Equals(table, StringComparison.OrdinalIgnoreCase))
{
k++;
s += $"{record.StringData[3],-50} ";
}
record = msiView.Fetch();
}
s += nl;
s += "".PadRight(50 * k, '-') + nl;
msiView.Close();
msiView = msiDatabase.OpenView($"Select * from {table}");
msiView.Execute();
record = msiView.Fetch();
while (record != null)
{
string recordValue = string.Empty;
for (int i = 1; i < record.FieldCount + 1; i++)
{
try { recordValue += $"{record.StringData[i],-50} "; }
catch (Exception ex) { recordValue += $"{i}. err {ex.Message}; "; }
}
s += recordValue + nl;
record = msiView.Fetch();
}
msiView.Close();
txtRes.Text = s;
}
catch (Exception ex) { txtRes.Text = ex.Message; }
}
I asked this question yesterday and got a great response/code example. The only problem is that I forgot to mention that I am forced to work with the .Net Framework 2.0 and can't use the List.Select ( I assume the linq namespace). Does anyone have a good work around for List.Select seen below:
class Program
{
struct ProcessStartTimePair
{
public Process Process { get; set; }
public DateTime StartTime { get; set; }
public DateTime ExitTime
{
get
{
return DateTime.Now; // approximate value
}
}
public ProcessStartTimePair(Process p) : this()
{
Process = p;
try
{
StartTime = p.StartTime;
}
catch (System.ComponentModel.Win32Exception)
{
StartTime = DateTime.Now; // approximate value
}
}
}
static void Main(string[] args)
{
SqlConnection cnn = new SqlConnection(#"Data Source=XXXXXX;Initial Catalog=XXXXXX;User ID=XXXX;Password=XXXX");
List<ProcessStartTimePair> knownProcesses = new List<ProcessStartTimePair>();
while (true)
{
foreach (Process p in Process.GetProcesses())
{
if (!knownProcesses.Select(x => x.Process.Id).Contains(p.Id))
{
knownProcesses.Add(new ProcessStartTimePair(p));
//Console.WriteLine("Detected new process: " + p.ProcessName);
}
}
for (int i = 0; i < knownProcesses.Count; i++)
{
ProcessStartTimePair pair = knownProcesses[i];
try
{
if (pair.Process.HasExited)
{
Console.WriteLine(pair.Process.ProcessName + " has exited (alive from {0} to {1}).", pair.StartTime.ToString(), pair.ExitTime.ToString());
knownProcesses.Remove(pair);
i--; // List was modified, 1 item less
// TODO: Store in the info in the database
String sql = "insert into procs (machine,login,process,start_time,end_time) ";
sql += "values ('" + Environment.MachineName + "','" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString().Split('\\')[1] + "','" + pair.Process.ProcessName + "','" + pair.StartTime.ToString() + "','" + pair.ExitTime.ToString() + "');";
SqlCommand cmd = new SqlCommand(sql, cnn);
try
{
cnn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
finally
{
cnn.Close();
}
}
}
catch (System.ComponentModel.Win32Exception)
{
// Would have to check whether the process still exists in Process.GetProcesses().
// The process probably is a system process.
}
}
//Console.WriteLine();
System.Threading.Thread.Sleep(5000);
}
}
}
I'm not sure the datatype of Id. I'll assume an int, you get the idea:
List<int> idList = new List<int>();
foreach(ProcessStartTimePair proc in knownProcesses)
{
idList.Add(proc.Process.Id);
}
if(idList.Contains(p.Id))
{
// ...
}
You just have to do the work of getting the list of IDs yourself.
Also, it's generally a better idea to edit your original question, and leave comments on the answers of others.
Try this:
if(!knownProcesses.Exists(x => x.Process.Id == p.Id))
Or, if you are using Visual Studio 2005 (not 2008),
if(!knownProcesses.Exists(delegate(ProcessStartTimePair x) { return x.Process.Id == p.Id; }))