string connectionString = "Data Source=(local);Initial Catalog=test;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand();
dataAdapter.SelectCommand.Connection = conn;
dataAdapter.SelectCommand.CommandText = "SELECT * FROM t1";
dataAdapter.UpdateCommand = new SqlCommand();
dataAdapter.UpdateCommand.Connection = conn;
dataAdapter.UpdateCommand.CommandText = "UPDATE t1 set name = 'changed5!!!' where 2=1";
dataAdapter.Fill(ds);
ds.Tables[0].Rows[0]["name"] = "ovidiu"; // Rowsate changes from Unchanged to Modified
dataAdapter.Update(ds); // update calls the update command
// in our case, the command does not have parameters, though it typically should
Friday, August 10, 2007
Monday, February 19, 2007
Showing Class Property in debugger tooltip
When you're in debug mode and move the mouse over a variable, you cang put any property value of that class you want like this:
[System.Diagnostics.DebuggerDisplay("Name = {Name}")]
public class Option
{
private string name = string.Empty;
public string Name
{
get { return name; }
}
}
[System.Diagnostics.DebuggerDisplay("Name = {Name}")]
public class Option
{
private string name = string.Empty;
public string Name
{
get { return name; }
}
}
Wednesday, December 06, 2006
Restricting a textbox...
...using regular expressions
the following event handler is attached to a textbox that is only allowed to have digits in it
using System.Text.RegularExpressions;
private void mileageTextBox_TextChanged(object sender, EventArgs e)
{
// choose which characters are not allowed
string pattern = "[^0-9]";
// this anonymous function replaces a character from the pattern string
// (a match) with the empty string (i.e. it removes that character)
MatchEvaluator me = delegate { return string.Empty; };
// perform actual replacement of all occurences of any character
// from the pattern string with the empty string
mileageTextBox.Text = Regex.Replace(mileageTextBox.Text, pattern, me);
}
the following event handler is attached to a textbox that is only allowed to have digits in it
using System.Text.RegularExpressions;
private void mileageTextBox_TextChanged(object sender, EventArgs e)
{
// choose which characters are not allowed
string pattern = "[^0-9]";
// this anonymous function replaces a character from the pattern string
// (a match) with the empty string (i.e. it removes that character)
MatchEvaluator me = delegate { return string.Empty; };
// perform actual replacement of all occurences of any character
// from the pattern string with the empty string
mileageTextBox.Text = Regex.Replace(mileageTextBox.Text, pattern, me);
}
Saturday, November 11, 2006
Using the Controls.Remove method
Whe interating through a form's control list, simply removing a control from it doesn't work (the subsequent controls are moved one position up when you try to remove one of them?). Thus, two foreach loops shoud be used :
// clear previous turtle buttons
ArrayList forRemoval = new ArrayList();
// find buttons to remove from the control list
foreach (Control c in this.Controls)
{
Button b = c as Button;
if (b == null || !b.Name.StartsWith("turtle")) continue;
forRemoval.Add(c);
}
foreach (object o in forRemoval)
{
Button b = o as Button;
if (b == null) continue;
this.Controls.Remove(b);
}
// clear previous turtle buttons
ArrayList forRemoval = new ArrayList();
// find buttons to remove from the control list
foreach (Control c in this.Controls)
{
Button b = c as Button;
if (b == null || !b.Name.StartsWith("turtle")) continue;
forRemoval.Add(c);
}
foreach (object o in forRemoval)
{
Button b = o as Button;
if (b == null) continue;
this.Controls.Remove(b);
}
Wednesday, October 04, 2006
Delegates and Events simple examples
Some code to help me remeber how to use the two quickly:
public delegate void FSCommandEventHandler(string command, string args);
public delegate void FlashCallEventHandler(string request);
public delegate Stream LoadResourceEventHandler(string path);
public event FSCommandEventHandler MyOnFSCommand;
public event FlashCallEventHandler MyOnFlashCall;
public event LoadResourceEventHandler MyOnLoadResource;
...
this.MyOnFlashCall += new FlashCallEventHandler(FPC_MyOnFlashCall);
void FPC_MyOnFlashCall(string request)
{
XmlDocument requestXml = new XmlDocument();
///...
public delegate void FSCommandEventHandler(string command, string args);
public delegate void FlashCallEventHandler(string request);
public delegate Stream LoadResourceEventHandler(string path);
public event FSCommandEventHandler MyOnFSCommand;
public event FlashCallEventHandler MyOnFlashCall;
public event LoadResourceEventHandler MyOnLoadResource;
...
this.MyOnFlashCall += new FlashCallEventHandler(FPC_MyOnFlashCall);
void FPC_MyOnFlashCall(string request)
{
XmlDocument requestXml = new XmlDocument();
///...
Thursday, September 28, 2006
Reading and writing data (securely) in a C# 2.0 Win App
1. Add a reference to System.Configuration.dll
2. Add using System.Configuration;
3. Use the following code:
Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
c.ConnectionStrings.ConnectionStrings.Add( new ConnectionStringSettings("conn 1", "Server=local; Database=Test; Password=myPassword; User Id=myUser;"));
ConfigurationSection section = c.GetSection("connectionStrings");
if (section != null)
{
if (!section.IsReadOnly())
{
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
}
}
c.Save();
2. Add using System.Configuration;
3. Use the following code:
Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
c.ConnectionStrings.ConnectionStrings.Add( new ConnectionStringSettings("conn 1", "Server=local; Database=Test; Password=myPassword; User Id=myUser;"));
ConfigurationSection section = c.GetSection("connectionStrings");
if (section != null)
{
if (!section.IsReadOnly())
{
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
}
}
c.Save();
Monday, September 25, 2006
Call one constructor from another
Avoid duplicating code...
class C1
{
public C1() { }
public C1(string s):this() { }
}
class C1
{
public C1() { }
public C1(string s):this() { }
}
Sunday, September 24, 2006
Defining a generic method in a non-generic class
For instance:
class Class2
{
public static void GenericMethod <X>(int n)
where X:new()
{
X myXinstance = new X();
}
}
The method can be called like this:
Class2.GenericMethod <System.Collections.ArrayList>(100);
class Class2
{
public static void GenericMethod
where X:new()
{
X myXinstance = new X();
}
}
Class2.GenericMethod <System.Collections.ArrayList>
Friday, September 22, 2006
Getting the identity of an assembly
Use the following code to create an identity object for an assembly. It can be used when passing it to the GetStore method when trying to one an isolated file storage (iso) store that requires that the identity of the assembly be provided.
System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
string assemblyPath = a.FullName;
System.Security.Policy.Url url = new System.Security.Policy.Url(assemblyPath);
System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
string assemblyPath = a.FullName;
System.Security.Policy.Url url = new System.Security.Policy.Url(assemblyPath);
Monday, September 04, 2006
Using the new delegate Syste.Predicate
Here's a small case when the new C# 2.0 feature, Predicate<T> may be useful:
Consider an array of file paths retrieved from disk:
string[] s = new string[4] { @"C:\a.jpg", @"C:\b.txt", "c.bmp", "d.swf" };
We can find all the image files (i.e those that have a certain extension) by doing this:
Predicate<string> p = new Predicate<string>(CheckIfImageFile);
string[] newS = Array.FindAll<string>(s, p);
Where CheckIfImageFile is defined here:
static bool CheckIfImageFile(string fullFilePath)
{
string commonImageExtensions = "*.png;*.jpg;*.gif;*.bmp";
if (commonImageExtensions.IndexOf(Path.GetExtension(fullFilePath)) > 0) return true;
return false;
}
Consider an array of file paths retrieved from disk:
string[] s = new string[4] { @"C:\a.jpg", @"C:\b.txt", "c.bmp", "d.swf" };
We can find all the image files (i.e those that have a certain extension) by doing this:
Predicate<string> p = new Predicate<string>(CheckIfImageFile);
string[] newS = Array.FindAll<string>(s, p);
Where CheckIfImageFile is defined here:
static bool CheckIfImageFile(string fullFilePath)
{
string commonImageExtensions = "*.png;*.jpg;*.gif;*.bmp";
if (commonImageExtensions.IndexOf(Path.GetExtension(fullFilePath)) > 0) return true;
return false;
}
Saturday, September 02, 2006
Undocumented C# keywords
I found some interesting undocumented keywords (http://www.eggheadcafe.com/articles/20030114.asp):
__makeref, __refvalue, __reftype, __arglist.
Here are a few examples:
int i = 10;
TypedReference tr = __makeref(i);
Type t = __reftype(tr);
int j = __refvalue( tr,int);
protected void Page_Load(Object sender, EventArgs e)
{
int x=85;
string y = "a stringy thingy";
double d=19.45;
WriteToPage(__arglist(x,y,d));
}
public void WriteToPage(__arglist)
{
ArgIterator ai = new ArgIterator(__arglist);
while(ai.GetRemainingCount() >0)
{
TypedReference tr = ai.GetNextArg();
Response.Write(TypedReference.ToObject(tr)+"");
}
}
__makeref, __refvalue, __reftype, __arglist.
Here are a few examples:
int i = 10;
TypedReference tr = __makeref(i);
Type t = __reftype(tr);
int j = __refvalue( tr,int);
protected void Page_Load(Object sender, EventArgs e)
{
int x=85;
string y = "a stringy thingy";
double d=19.45;
WriteToPage(__arglist(x,y,d));
}
public void WriteToPage(__arglist)
{
ArgIterator ai = new ArgIterator(__arglist);
while(ai.GetRemainingCount() >0)
{
TypedReference tr = ai.GetNextArg();
Response.Write(TypedReference.ToObject(tr)+"");
}
}
Friday, September 01, 2006
Debugging Windows Services In Visual Studio 2005
To do that, change the body of the Main method of the Windows service:
#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService() };
ServiceBase.Run(ServicesToRun);
#else
MyService service = new MyService();
service.MyOnStart();
#endif
You will get two error messages at the beginning but you can continue debugging.
#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService() };
ServiceBase.Run(ServicesToRun);
#else
MyService service = new MyService();
service.MyOnStart();
#endif
You will get two error messages at the beginning but you can continue debugging.
Thursday, August 31, 2006
Transforming a List or an ArrayList collection to a C# regular array
1. From an ArrayList to, say, a string[]:
ArrayList oldList = new ArrayList();
[...]
string[] newList = (string[]) oldList.ToArray(typeof(string));
2. From a List to an array T[]. This is very simple:
List< MyClass > oldList = new List < MyClass >();
[...]
MyClass[] newList = oldList.ToArray();
ArrayList oldList = new ArrayList();
[...]
string[] newList = (string[]) oldList.ToArray(typeof(string));
2. From a List
List<
[...]
MyClass[] newList = oldList.ToArray();
Saturday, August 26, 2006
C# Classes Versus Structs
I will try to group here the differences and commonalities bewtween classes and structs.
Differences:
Classes are reference types, structs are value types.
Classes are allocated in the Heap, structs are allocated on the stack.
Class instances are passed to methods as references, a copy of the struct is passed to a method.
Classes can declare an explicit parameterless constructor, structs cannot declare an explicit parameterless constructor.
Class members can have initializers (private string s = "asd";) while struct members cannot have initializers (private string s;). They must be initialized in the constructor.
Classes cannot be instantiated without the use of the new operator, structs can be instantiated without the use of the new operator.
A struct cannot inherit from another struct or class (it inherits from object by default).
A struct cannot be the base of another class.
Commonalitites:
Both can implement interfaces.
You CAN call a parameterless constructor for both classes and structs (if the class has one defined; a struct always has it and it is implicit).
Struct usage guidelines (taken from http://www.awprofessional.com/articles/article.asp?p=423349&seqNum=2&rl=1):
Differences:
Classes are reference types, structs are value types.
Classes are allocated in the Heap, structs are allocated on the stack.
Class instances are passed to methods as references, a copy of the struct is passed to a method.
Classes can declare an explicit parameterless constructor, structs cannot declare an explicit parameterless constructor.
Class members can have initializers (private string s = "asd";) while struct members cannot have initializers (private string s;). They must be initialized in the constructor.
Classes cannot be instantiated without the use of the new operator, structs can be instantiated without the use of the new operator.
A struct cannot inherit from another struct or class (it inherits from object by default).
A struct cannot be the base of another class.
Commonalitites:
Both can implement interfaces.
You CAN call a parameterless constructor for both classes and structs (if the class has one defined; a struct always has it and it is implicit).
Struct usage guidelines (taken from http://www.awprofessional.com/articles/article.asp?p=423349&seqNum=2&rl=1):
DO NOT define a struct unless the type has all of the folloing characteristics:
- It logically represents a single value, similar to primitive types (int, double, etc.).
- It has an instance size under 16 bytes.
- It is immutable.
- It will not have to be boxed frequently.
Working with the registry
Opening a subkey:
Creating a subkey:
key = Registry.CurrentUser.CreateSubKey(subKey);
The second parameter specifies whether the key is writable or not.
Getting a value:
key.SetValue("X", 123);
Storing/Getting an array of strings:
string[] array = new string[2] { "asd", "dfg" };
k.SetValue("myArray", array, RegistryValueKind.MultiString);
object readArray = k.GetValue("myArray");
Comments:
string subKey = @"Software\Play\WindowPos";
RegistryKey key = Registry.CurrentUser.OpenSubKey(subKey, true);
RegistryKey key = Registry.CurrentUser.OpenSubKey(subKey, true);
Creating a subkey:
key = Registry.CurrentUser.CreateSubKey(subKey);
The second parameter specifies whether the key is writable or not.
Getting a value:
- either by using the static method of the Registry class (in this case, the full registry path must be specified): Registry.GetValue(Registry.CurrentUser.Name + @"\" + subKey, "X", 300)
- by using the curent key (relative path):object theValue = key.GetValue("X");
key.SetValue("X", 123);
Storing/Getting an array of strings:
string[] array = new string[2] { "asd", "dfg" };
k.SetValue("myArray", array, RegistryValueKind.MultiString);
object readArray = k.GetValue("myArray");
Comments:
- Use Flush() or Close() to commit changes of the registry key.
- Other functions of the RegistryKey class: DeleteSubkeyTree(), DeleteValue(), string[] GetSubKeyNames(), GetSubKeyValues().
The Reason Why This Blog Exists
I have been thinking for a long time to finally nail down all those .NET Framework classes that I would read about in various articles, leaving me with a feeling of uncertainty. Now, I have finally decided to have my own space where I could save all the new things I learn about C#. In parallel, I will also try to take each of the .NET assemblies and write a small example and description about each type I encounter. This way, I will have a place to come back to whenever I forget something.
Subscribe to:
Posts (Atom)