After some research I found out that in some circumstances it is necessary to add the following two statements at the beginning of the stored procedure:
SET NOCOUNT OFF; SET FMTONLY OFF;
After that everything worked as expected.
SET NOCOUNT OFF; SET FMTONLY OFF;
public bool isLocked(string s)
{
if (!File.Exists(s)) return false;
try { FileStream f = File.Open(s, FileMode.Open, FileAccess.ReadWrite); f.Close(); }
catch { return true; }
return false;
}/// <summary>
/// Checks if a file is in use or not.
/// </summary>
/// <param name="filePath">The path to the file that should be checked.</param>
/// <returns>True if the file is locked; false otherwise</returns>
public bool IsLocked(string filePath)
{
if (!File.Exists(filePath))
{
return false;
}
try
{
FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite);
fileStream.Close();
return false;
}
catch
{
return true;
}
}
public class SearchTermConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var stringValue = values[0] == null ? string.Empty : values[0].ToString();
var searchTerm = values[1] as string;
return !string.IsNullOrEmpty(searchTerm) &&
!string.IsNullOrEmpty(stringValue) &&
stringValue.ToLower().Contains(searchTerm.ToLower());
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
public static class SearchOperations
{
public static string GetSearchTerm(DependencyObject obj)
{
return (string)obj.GetValue(SearchTermProperty);
}
public static void SetSearchTerm(DependencyObject obj, string value)
{
obj.SetValue(SearchTermProperty, value);
}
public static readonly DependencyProperty SearchTermProperty =
DependencyProperty.RegisterAttached(
"SearchTerm",
typeof(string),
typeof(SearchOperations),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.Inherits));
public static bool GetIsMatch(DependencyObject obj)
{
return (bool)obj.GetValue(IsMatchProperty);
}
public static void SetIsMatch(DependencyObject obj, bool value)
{
obj.SetValue(IsMatchProperty, value);
}
/* Using a DependencyProperty as the backing store for IsMatch. This enables animation, styling, binding, etc...*/
public static readonly DependencyProperty IsMatchProperty =
DependencyProperty.RegisterAttached("IsMatch", typeof(bool), typeof(SearchOperations), new UIPropertyMetadata(false));
}
<Grid.Resources>
<local:SearchTermConverter
x:Key="SearchTermConverter" />
<SolidColorBrush
x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Blue" />
<SolidColorBrush
x:Key="HighlightColor"
Color="Yellow" />
<SolidColorBrush
x:Key="SelectedHighlightedColor"
Color="Red" />
<Style
x:Key="DefaultCell"
TargetType="{x:Type toolkit:DataGridCell}">
<Setter
Property="local:SearchOperations.IsMatch">
<Setter.Value>
<MultiBinding
Converter="{StaticResource SearchTermConverter}">
<Binding
RelativeSource="{RelativeSource Self}"
Path="Content.Text" />
<Binding
RelativeSource="{RelativeSource Self}"
Path="(local:SearchOperations.SearchTerm)" />
</MultiBinding>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger
Property="local:SearchOperations.IsMatch"
Value="True">
<Setter
Property="Background"
Value="{StaticResource HighlightColor}">
</Setter>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition
Property="IsSelected"
Value="True" />
<Condition
Property="local:SearchOperations.IsMatch"
Value="True" />
</MultiTrigger.Conditions>
<Setter
Property="Background"
Value="{StaticResource SelectedHighlightedColor}"></Setter>
</MultiTrigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<toolkit:DataGrid
AutoGenerateColumns="True"
Name="dgvDataTable"
CellStyle="{StaticResource DefaultCell}"
Margin="0,256,0,0"
Background="White" />
SearchOperations.SetSearchTerm(this.dgvObjects, this.textBox1.Text);
<Window
x:Class="SearchHighlighting.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="460.138"
Width="502"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:local="clr-namespace:SearchHighlighting">
...
<toolkit:DataGrid
AutoGenerateColumns="True"
Name="dgvDataTable"
CellStyle="{StaticResource DefaultCell}"
Margin="0,256,0,0"
Background="White"
local:SearchOperations.SearchTerm="{Binding ElementName=textBox1, Path=Text}" />

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Reflection;
using System.Data.Objects;
public static class ObjectContextExtensions
{
/*
/// <summary>
/// Searches in all string properties for the specifed search key.
/// It is also able to search for several words. If the searchKey is for example 'John Travolta' then
/// all records which contain either 'John' or 'Travolta' in some string property
/// are returned.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <param name="searchKey"></param>
/// <returns></returns>*/
public static IQueryable<T> FullTextSearch<T>(this IQueryable<T> queryable, string searchKey)
{
return FullTextSearch<T>(queryable, searchKey, false);
}
/*
/// <summary>
/// Searches in all string properties for the specifed search key.
/// It is also able to search for several words. If the searchKey is for example 'John Travolta' then
/// with exactMatch set to false all records which contain either 'John' or 'Travolta' in some string property
/// are returned.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <param name="searchKey"></param>
/// <param name="exactMatch">Specifies if only the whole word or every single word should be searched.</param>
/// <returns></returns>*/
public static IQueryable<T> FullTextSearch<T>(this IQueryable<T> queryable, string searchKey, bool exactMatch)
{
ParameterExpression parameter = Expression.Parameter(typeof(T), "c");
MethodInfo containsMethod = typeof(string).GetMethod("Contains", new Type[] { typeof(string) });
MethodInfo toStringMethod = typeof(object).GetMethod("ToString", new Type[] { });
var publicProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(p => p.PropertyType == typeof(string));
Expression orExpressions = null;
string[] searchKeyParts;
if (exactMatch)
{
searchKeyParts = new[] { searchKey };
}
else
{
searchKeyParts = searchKey.Split(' ');
}
foreach (var property in publicProperties)
{
Expression nameProperty = Expression.Property(parameter, property);
foreach (var searchKeyPart in searchKeyParts)
{
Expression searchKeyExpression = Expression.Constant(searchKeyPart);
Expression callContainsMethod = Expression.Call(nameProperty, containsMethod, searchKeyExpression);
if (orExpressions == null)
{
orExpressions = callContainsMethod;
}
else
{
orExpressions = Expression.Or(orExpressions, callContainsMethod);
}
}
}
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { queryable.ElementType },
queryable.Expression,
Expression.Lambda<Func<T, bool>>(orExpressions, new ParameterExpression[] { parameter }));
return queryable.Provider.CreateQuery<T>(whereCallExpression);
}
}
context.Customers.FullTextSearch("serachkey");
context.Customers.FullTextSearch("searchkey", true);
context.Customers.Where(c => c.FirstName.Contains("searchkey") || c.LastName.Contains("searchkey") || c.Street.Contains("searchkey") || ...);
/* /// <summary>
/// This method is the dispatcher for the different expression types.
/// NOTE: not all expression types are considered.
/// </summary>
/// <param name="expression">The expression.</param>
/// <param name="sql">The SQL string builder.</param>
/// <param name="isOnRightSide">Tells if the expression is on the right hand side. Necessary for some expression evaluations.</param> */
private object VisitExpression(Expression expression, StringBuilder sql, bool isOnRightSide)
{
LambdaExpression lambdaExpression = expression as LambdaExpression;
BinaryExpression binaryExpression = expression as BinaryExpression;
MemberExpression memberExpression = expression as MemberExpression;
ConstantExpression constantExpression = expression as ConstantExpression;
UnaryExpression unaryExpression = expression as UnaryExpression;
MethodCallExpression methodCallExpression = expression as MethodCallExpression;
ParameterExpression parameterExpression = expression as ParameterExpression;
if (lambdaExpression != null)
{
VisitExpression(lambdaExpression.Body, sql, false);
}
else if (binaryExpression != null)
{
VisitBinaryExpression(sql, binaryExpression);
}
else if (memberExpression != null)
{
return VisitMemberExpression(sql, isOnRightSide, memberExpression);
}
else if (constantExpression != null)
{
VisitConstantExpression(sql, constantExpression);
}
else if (unaryExpression != null)
{
VisitUnaryExpression(sql, unaryExpression);
}
else if (methodCallExpression != null)
{
VisitMethodCallExpression(sql, methodCallExpression);
}
else if (parameterExpression != null)
{
VisitParameterExpression(sql, parameterExpression);
}
else
{
throw new NotSupportedException(string.Format("The '{0}' is not supported!", expression.GetType().Name));
}
return null;
}
private void VisitBinaryExpression(StringBuilder sql, BinaryExpression binaryExpression)
{
sql.Append("(");
VisitExpression(binaryExpression.Left, sql, false);
sql.Append(GetOperandFromExpression(binaryExpression));
VisitExpression(binaryExpression.Right, sql, true);
sql.Append(") ");
}
/* /// <summary>
/// This method is the dispatcher for the operands.
/// NOTE: not all operands are implemented!
/// </summary>
/// <param name="expression">The expression to dispatch.</param>
/// <returns>The appropriate SQL operand.</returns>*/
private string GetOperandFromExpression(Expression expression)
{
string operand = string.Empty;
switch (expression.NodeType)
{
case ExpressionType.And:
operand = "AND";
break;
case ExpressionType.AndAlso:
operand = "AND";
break;
case ExpressionType.Equal:
operand = "=";
break;
case ExpressionType.ExclusiveOr:
operand = "OR";
break;
case ExpressionType.GreaterThan:
operand = ">";
break;
case ExpressionType.GreaterThanOrEqual:
operand = ">=";
break;
case ExpressionType.Not:
operand = "NOT";
break;
case ExpressionType.NotEqual:
operand = "<>";
break;
case ExpressionType.Or:
operand = "OR";
break;
case ExpressionType.OrElse:
operand = "OR";
break;
default:
throw new NotImplementedException();
}
return operand + " ";
}
private string FormatValue(object value)
{
if(value == null || value == DBNull.Value)
{
return "NULL";
}
string stringValue = value.ToString();
var invariantMethod = value.GetType().GetMethod("ToString", new Type[] { typeof(CultureInfo) });
if (invariantMethod != null)
{
stringValue = (string)invariantMethod.Invoke(value, new object[] { CultureInfo.InvariantCulture });
}
stringValue = stringValue.Replace("'", "''");
if (value is string || value is DateTime)
{
return string.Format("'{0}'", stringValue);
}
else
{
return stringValue;
}
}
[DBTable("cust")]
class Customer
{
[DBField("nam")]
public string Name { get; set; }
[DBField("num")]
public int Age { get; set; }
[DBField("height")]
public int Height;
[DBField("surname")]
public string Surname;
}
static void Main(string[] args)
{
ORMapper mapper = new ORMapper();
var c1 = new Customer{Name = "cus2"};
var selectQuery = mapper.Select<Customer>(c => c.Name == "hallo" && c.Age == 12 || c.Name == c1.Name && c.Name == 4.ToString() && c.Name.Contains("aaa"));
var deleteQuery = mapper.Delete<Customer>(c => c.Name == "hallo" && c.Age == 12 || c.Name == c1.Name && c.Name == 4.ToString() && c.Name.Contains("aaa"));
Console.WriteLine(selectQuery);
Console.WriteLine(deleteQuery);
Console.ReadLine();
}
SELECT * FROM cust WHERE (((nam = 'hallo') AND (num = 12)) OR ((((nam = 'cus2') AND (nam = '4')) AND (nam LIKE '%aaa%')) AND (height = 10)));
DELETE FROM cust WHERE (((nam = 'hallo') AND (num = 12)) OR (((nam = 'cus2') AND (nam = '4')) AND (nam LIKE '%aaa%')));
<?xml version="1.0" encoding="utf-8" ?>
<mapping>
<Customer table="tbl_cus">
<map property="Name" column="cus_nam"></map>
<map property="Age" column="cus_age"></map>
</Customer>
</mapping>
MessageBox.Show(this.numericUpDown1.Value.ToString());You can see an example for this in the following screenshot:



if (string.IsNullOrEmpty(((Control)this.numericUpDown1).Text))
{
/* the user entered nothing */
}
else
{
/* the NUD contains a valid number */
}
[Conditional("DEBUG")]
public void LogDebugEvent(LogLevel logLevel, string message, params object[] args)
{
/* some code here*/
}int a = 3;
Get<Person>(p => p.Age == a);
public class Person
{
public int Age { get; set; }
}
public static void Get<T>(Expression<Func<T, bool>> e)
{
MemberExpression member = (MemberExpression)((BinaryExpression)e.Body).Right;
ConstantExpression constant = (ConstantExpression)member.Expression;
Console.WriteLine(constant.Value.ToString());
}
public static void Get<T>(Expression<Func<T, bool>> e)
{
MemberExpression member = (MemberExpression)((BinaryExpression)e.Body).Right;
ConstantExpression constant = (ConstantExpression)member.Expression;
FieldInfo info = (FieldInfo)member.Member;
Console.WriteLine(info.GetValue(constant.Value).ToString());
}
public static void FromMethod(int a)
{
Get<Person>(p => p.Age == a);
}
public static void UpdateAppConfig(string key, object value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var result = (from appSetting in doc.Descendants("appSettings").Descendants("add")
where appSetting.Attribute("key").Value.Equals(key)
select appSetting).FirstOrDefault();
if (result != null)
{
result.Attribute("value").SetValue(value);
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
doc = null;
}
else
{
Console.WriteLine("The application setting with key '{0}' was not found!", key);
}
}
public static void Greet(this String s)
{
Console.WriteLine("Hello " + s);
}
string name = "Tom";
name.Greet();
Customer testCustomer = new Customer() { Name = "John", Age = 35, LastName = "Smith" };testCustomer.PrintConsole();
testCustomer.PrintMessageBox();
testCustomer.PrintPropertiesConsole();
testCustomer.PrintPropertiesMessageBox();
testCustomer.ToXml();
John Smith 35
testCustomer.ToXml(myStream);
testCustomer.ToXml("c://test.xml);this.treeView1.SelectedNode.NodeFont = new Font(this.treeView1.Font, FontStyle.Bold);
this.treeView1.SelectedNode.Text += string.Empty;
Customer customer1 = new Customer();
customer1.FirstName = "John";
customer1.ID = 1;
customer1.LastName = "Smith";
Customer customer2 = new Customer();
customer2.FirstName = "Marco";
customer2.ID = 2;
customer2.LastName = "Polo";
this.cmbTest.Items.Add(customer1);
this.cmbTest.Items.Add(customer2);
this.cmbTest.DisplayMember = "FirstName";
this.cmbTest.ValueMember = "ID";
Customer customer1 = new Customer();
customer1.FirstName = "John";
customer1.ID = 1;
customer1.LastName = "Smith";
Customer customer2 = new Customer();
customer2.FirstName = "Marco";
customer2.ID = 2;
customer2.LastName = "Polo";
Customer customer3 = new Customer();
customer3.FirstName = "Tom";
customer3.ID = 3;
customer3.LastName = "Hanks";
Listcustomers = new List ();
customers.Add(customer1);
customers.Add(customer2);
customers.Add(customer3);
this.cmbTest.DataSource = objects;
this.cmbTest.DisplayMember = "FullName";
this.cmbTest.ValueMember = "ID";
this.cmbTest.RegisterType(typeof(Customer), "FirstName", "PK");
this.cmbTest.UnregisterType(typeof(Customer));
this.cmbTest.ChangeDisplayMember(typeof(Customer), "FullName");
this.cmbTest.ChangeValueMember(typeof(Customer), "LastName");
Console.WriteLine(this.cmbTest.SelectedValue.ToString());To get the selected object simply call "SelectedItem" and cast it to the correct type.
Customer selectedCustomer = this.cmbTest.SelectedItem as Customer;
if (selectedCustomer != null)
{
...
}
for (int i = 0; i <> 5)
result.Add(numbers[i]);
}
foreach (int num in numbers)
{
if (num > 5)
result.Add(num);
}
result = numbers.FindAll(new Predicate(delegate(int i) { return i > 5; }));
var res = from num in numbers
where num > 5
select num;
More lines of code contain more errors.
if (!this.backgroundWorker.IsBusy)
{
this.Enabled = false; /*lock the main application*/
ProgressDialog.Show(max);
ProgressDialog.SetTitle("this is the title");
ProgressDialog.SetMessage("I am the message for the very long task. Please be patient and wait...");
ProgressDialog.CancelEvent += new ProgressDialog.CancelEventHandler(pd_CancelEvent);
this.backgroundWorker.RunWorkerAsync();
}
this.backgroundWorker.WorkerSupportsCancellation = true;
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < max; i++)
{
/*this check is needed in order to abort the operation if the user has clicked on cancel*/
if (this.backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
ProgressDialog.SetValue(i); /*update the value*/
Console.WriteLine(i);
}
}
public static void SetTitle(string title)
{
if (instance.InvokeRequired) /*if another thread called this method*/
{
SetTitleCallback s = new SetTitleCallback(SetTitle);
instance.Invoke(s, title);
}
else
{
instance.Text = title;
}
}


public class MyButton : Button
{
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
g.FillRectangle(Brushes.White, pevent.ClipRectangle);
g.DrawRectangle(new Pen(Brushes.Black), pevent.ClipRectangle);
if (Enabled)
{
if(Image != null)g.DrawImage(Image, 0, 0);
g.DrawString(Text, Font, Brushes.Black, new PointF(100, 0));
}
else
{
if(Image != null)ControlPaint.DrawImageDisabled(g, Image, 0, 0, Color.Transparent);
ControlPaint.DrawStringDisabled(g, Text, Font, Color.Transparent, new RectangleF(100, 0, 100, 20), StringFormat.GenericDefault);
}
}
}
/* This method is responsible to convert the datatypes into their corresponding */
/* sql representation. Change it if you encounter problems or if a data type */
/* needs special treatmend. */
private static string ToSQL(object obj)
{
if (obj is string || obj is Boolean)
return "'" + obj.ToString() + "'";
else if (obj is DateTime)
return "'" + ((DateTime)obj).ToString(DATE_TIME_FORMAT) + "'";
else if (obj is decimal)
return obj.ToString().Replace(',', '.');
else
return obj.ToString();
}
/* This method is responsible to obtain all public, not inherited properties of an object. */
private static PropertyInfo[] GetProperties(object obj)
{
return obj.GetType().GetProperties(
BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
}
[Table("myTable")]
public class TestObject
{
private int table_pk;
private string text;
private DateTime datetime;
private int number;
private bool boolean;
private decimal decimalNum;
[Column("mytable_pk", true)]
public int Table_PK
{
get { return table_pk; }
set { table_pk = value; }
}
[Column("datetime")]
public DateTime Datetime
{
get { return datetime; }
set { datetime = value; }
}
[Column("number")]
public int Number
{
get { return number; }
set { number = value; }
}
[Column("text")]
public string Text
{
get { return text; }
set { text = value; }
}
[Column("boolean")]
public bool Boolean
{
get { return boolean; }
set { boolean = value; }
}
[Column("decimalnum")]
public decimal DecimalNum
{
get { return decimalNum; }
set { decimalNum = value; }
}
public TestObject()
{
this.table_pk = 999;
this.number = 5;
this.text = "this is a test string";
this.datetime = DateTime.Now;
this.boolean = true;
this.decimalNum = new decimal(1.5);
}
public override string ToString()
{
return "pk = " + this.Table_PK + ", datetime = " + this.Datetime.ToLongDateString() + ", number = " + this.Number.ToString() + ", text = " + this.Text + ", boolean = " + this.Boolean.ToString() + ", decimal = " + this.DecimalNum.ToString() ";";
}
}
TestObject a = new TestObject();
string sql = ObjectToSqlConverter.CreateInsertStatement(a);
sql = ObjectToSqlConverter.CreateUpdateStatement(a);
sql = ObjectToSqlConverter.CreateDeleteStatement(a);