System.InvalidOperationException – Cross-thread operation not valid: Control ‘xxxxx’ accessed from a thread other than the thread it was created on. Normally we get this exception when we try to modify some control property from another thread. This is because when a program executes the operating system will assign a thread for the creation of UI elements and for the changes of the UI. Only this thread has got the permission to change or control UI elements created. If you creates other threads with the help of Thread class from System.Threading namespace, doesn’t have enough privileges to change or control the UI elements of the Main thread. To resolve this issue, we need write delegates and need to invoke the methods from other threads using these delegates.
This sample code is doing some long operation in a separate thread and try to update the UI from the new thread.
private void Form1_Load(object sender, EventArgs e)
{
this.threadStart = new ThreadStart(LongProcess);
this.thread = new Thread(this.threadStart);
this.thread.Start();
}
private void LongProcess()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
//This will throw an exception like this
//System.InvalidOperationException - Cross-thread operation not valid:
//Control 'textBox1' accessed from a thread other than the thread it was created on.
this.textBox1.Text = i.ToString();
}
}
And here is the source code which will fix the issue with delegates and Control.Invoke method
private ThreadStart threadStart;
private Thread thread;
private delegate void UpdateTextDelegate(string text);
private void Form1_Load(object sender, EventArgs e)
{
this.threadStart = new ThreadStart(LongProcess);
this.thread = new Thread(this.threadStart);
this.thread.Start();
}
private void LongProcess()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
//This will resolve the cross thread invalid operation exception.
this.UpdateText(i.ToString());
}
}
private void UpdateText(string text)
{
//Checks whether the called required to invoke the "Invoke" method.
if (this.textBox1.InvokeRequired)
{
UpdateTextDelegate updateTextDelegate = new UpdateTextDelegate(UpdateText);
//Calling the invoke method of the control with the parameter.
this.textBox1.Invoke(updateTextDelegate, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
Thanks to Praveen for helping me out. Happing Coding
Recently I got chance to work with security audit team for my web application, and one suggestion I got from them is to encrypt connection strings section in web.config. I thought it involves lot of coding changes, and I was not aware of ASP.Net utility which will help to encrypt and decrypt the connection strings or appsettings sections of the web application. There is no extra coding required to use this feature. You can encrypt /decrypt the connection strings / appsettings using the ASPNET_REGIIS utility. You can find this utility in your Framework folder, normally in C:\Windows\Microsoft.NET\Framework\[Version]. Or you can invoke this from Visual Studio Command Prompt.
Encrypt the connection string
aspnet_regiis -pe ConnectionString –app "/docs"
where –pe is the parameter used to encrypt the section. Connection string is the section, if you want to encrypt AppSettings, use appsettings instead of Connectionstrings. And the –app parameter is used to specify the application (it must be virtual path and need to start with “/”), if –app parameter is not specified it will encrypt the Root web.config. If the application is in File System, you need to specify –pef and Physical location as the parameter.
aspnet_regiis -pef ConnectionString –app "D:\MyWebApp"
Decrypt the connection string
It is almost same as Encryption, only difference is instead of –pe use –pd. And in the case of –pef use –pdf.
aspnet_regiis -pd ConnectionString –app "/docs"
and
aspnet_regiis -pdf ConnectionString –app "D:\MyWebApp"
You can also specify the Provider for Encryption too. Use –prov parameter for providing custom provider (You can create your own provider, for this you need to inherit from ProtectedConfigurationProvider class). By default it will be RsaProtectedConfigurationProvider.
Screenshots – Before and After encrypting the app settings.

Before Encryption

After Encryption
As I am working in a Windows Application, client asked about the Windows 7 and Windows Vista compatibility. As I was writing only managed code I was not worried about the compatibility and most of the time it was working fine. (I was using Windows Vista). Today evening one of my colleague was testing the application on his Windows 7 machine, the application was crashing
After initial diagnostics I was able to find the solution, it was because of Tracing. I was using TextWriterTraceListener,from System.Diagnostics namespace, and the File was created in the application path.Because he installed the application in C:\Program Files\AppFolder, Windows was denied access to write the File. The easily solution was, Right Click on the Application, Select RUNAS option, select Administrator. The other solution was writing the Log File in some temporary location, and use it. Then I found some nice feature in .Net called Isolated Storage. It is helpful to Run your application by less privileged users. With these stores, you can read and write data that less trusted code cannot access and prevent the exposure of sensitive information that can be saved elsewhere on the file system. Data is stored in compartments that are isolated by the current user and by the assembly in which the code exists. Additionally, data can be isolated by domain. Roaming profiles can be used in conjunction with isolated storage so isolated stores will travel with the user’s profile.
We can access the Isolated Storage related classes from System.IO.IsolatedStorage namespace.
//Getting the User scoped Store corresponding to the calling codes assembly identity.
//IsolatedStorageFile class provides basic functionality to create files or folders.
IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly();
//Checking whether Directory Exists. Directory.Exists will not work. Also do some wildcard
//search like "dotnet*" or "dotnet?"
string[] directories = isolatedStorageFile.GetDirectoryNames("dotnetthoughts");
//Creating the directory if it is not exists.
if (directories.Length == 0)
{
isolatedStorageFile.CreateDirectory("dotnetthoughts");
}
//IsolatedStorageFileStream encapsulates stream, used to create files
IsolatedStorageFileStream isolatedStorageFileStream =
new IsolatedStorageFileStream(@"dotnetthoughts\\System.log",
FileMode.OpenOrCreate, isolatedStorageFile);
//Writing the content to IsolatedStorage.
using (StreamWriter streamWriter = new StreamWriter(isolatedStorageFileStream))
{
streamWriter.WriteLine("Hello Isolated Storage");
}
//Reading the contents from Isolated storage – If you try to read like this it will throw //exception.(Stream is not Readable)
using (StreamReader streamReader = new StreamReader(isolatedStorageFileStream))
{
MessageBox.Show(streamReader.ReadToEnd());
}
isolatedStorageFileStream.Close();
isolatedStorageFile.Close();
There is some permission attributes too, which is used to grant code to access IsolatedStorage.
[IsolatedStorageFilePermission(SecurityAction.Demand)]
static class Program
{
//Code
}
The IsolatedStorage can be used in Silverlight assemblies too, which will helps to access local file system from Silverlight.
Normally when we are writing to the File Systems or I/O devices, Windows will cache the request or response to get better performance. This behavior is a good feature, but sometimes we require immediate change. By caching Windows sometimes mislead us. And I don’t think there is a way to avoid this option available in Windows. In my current project I got a chance to explore / work on this, but I need to avoid this caching.
I checked various options with File class and Stream class but there was no option available to avoid Caching. Later our VC++ developer gives me some code, which in WIN32 API, which will avoid caching. It was using “CreateFile()” method in Kernal32.dll with FILE_FLAG_NO_BUFFERING option. Then I was able to create same in C# code base on the input using PInvoke. But I have to find a managed code, with that we can write / read stream without caching. Later I found FileStream class, which supporting both synchronous and asynchronous read and write operations. But it also doesn’t have a NonCahce file option. Then I tried FileStream class with FILE_FLAG_NO_BUFFERING option. And it worked
const FileOptions FILE_FLAG_NO_BUFFERING = (FileOptions) 0x20000000;
using(FileStream fs = new FileStream("Path",FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1024, FileOptions.WriteThrough | FILE_FLAG_NO_BUFFERING))
{
fs.Write("HelloWorld");
}
This FileStream class also got a nice option, FileOptions.DeleteOnClose, if you are creating a File with this option enabled, it will delete the File after you close the FileStream. This can be used for creating real temporary files.
string TempFile = Path.GetTempFileName();
using(FileStream fs = new FileStream(TempFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1024, FileOptions.DeleteOnClose))
{
fs.Write("HelloWorld");
} //Deletes the File.
I think this FileStream class is available from .Net 2.0 Framework onwards.
One of colleague once asked a question to me, like what is the risk by distributing the windows application without obfuscating it. The only problem I found is user can use some tools like .Net Reflector and explore our assemblies. But few days before I found some nice .Net Framework tools, ildasm.exe and ilasm.exe, IL Disassembler and IL Assembler respectively. These tools are available with .Net Framework SDKs. These tools can used to generate IL code for .Net assemblies and re-create assemblies from IL code. You can achieve it in code via .Net Reflection.Emit namespace. (In Community Techdays @ Cochin, one session is on Reflection.Emit. Don’t miss it.) As it is a vast topic I am only explaining basics
Generate IL code using ILDASM.exe
- First create a HelloWorld.cs and compile it to HelloWorld.exe
using System;
public class HelloWorld
{
static int Main(string[] args)
{
Console.WriteLine("Hello World");
return(0);
}
}
- Use
csc.exeto compile the cs file to exe. – csc HelloWorld.cs
- Use
ildasm.exe HelloWorld.Exe to view the IL Code. You can find ILDASM in the Microsoft .Net SDK Path

ILDASM - Exploring HelloWorld.exe
- To generate the IL code use Select Dump option from File Menu or Press Ctrl+D. It will asks for a location to save the IL code.

IL Code Generated
- Use any Editor to modify the IL code. You can find all the string values ( “Hello World” in this example ) as it is in the IL code. Modify it.( I am modifying it as “Hello World from IL Code”).

IL Code - Notepad
So we created the IL code and modified.
Generate Assembly from IL code using ILASM.exe
- Invoke the ILASM.exe with IL file as the parameter.
ilasm helloworld_il.il
- It will show some details about assembling the IL code to assembly. And if the operation is successful you will get an exe in the location with HelloWorld_IL.exe.

Assembling the IL code to EXE
- If you invoke the exe from command prompt it will display the modified string instead of Hello World.(In this example “Hello World from IL Code”).
You can do more if you know how IL works. Happy IL Programming