28 November 2008

C# Textbox Auto Scroll To End ScrollToCaret Scrolling Textbox

Many of my sample C# codes,
I use textbox to write the results.

When textbox is multiline property set to true, and when I insert text into it,
I want it to auto scroll to the last line.

Here is a simple way to auto scrolling textbox.
 textbox1.SelectionStart = textbox1.Text.Length;
Textbox SelectionStart will force the textbox control to select the last part of the text,
and ScrollToCaret() function will auto scroll textbox to the end.

C# The process cannot access the file because it is being used by another process

The process cannot access the file because it is being used by another process.
This error message is mostly comes up,
when you try to access a file which is opened by another process.

You may open an image file in one of your form in a picturebox with using ImageFromFile or something.
I mostly use memorystream to open an image.
After read it in byte[] write it into a stream and close it.

You can check whether a file is being used or not with a simple function.
Try to open a file with none share.
 public bool IsFileUsedbyAnotherProcess(string filename)
File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None);
catch (System.IO.IOException exp)
return true;
return false;

This function will return true if
the file because it is being used by another process or not.

27 November 2008

C# Convert Hexadecimal to Binary String Conversion

There is no need to code tons of codes, loops, to convert hex to binary string. Convert.ToInt32 function is very useful for this purpose.
Let's convert the "A" character to binary format.
private string hex2binary(string hexvalue)
string binaryval = "";
binaryval = Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);
return binaryval;
When we call hex2binary("A"); it will return "1010" similar samples below;

hex2binary("1a"); will return "11010";
hex2bianry("1a2c"); will return "1101000101100"; and so on.

Keep in mind that this hex to binary conversion style uses 32 bit integer number.

25 November 2008

C# System Tray Minimize To Tray With NotifyIcon

Minimize application form to system tray is done
with the NotifyIcon control in Visual Studio.

NotifyIcon is in the System.Windows.Forms namespace.
Drag and drop a NotifyIcon control to your form.
To send your application form into the system tray,
we simple handle the form re-size event.
private void frmMain_Resize(object sender, EventArgs e)
if (FormWindowState.Minimized == this.WindowState)
mynotifyicon.Visible = true;
else if (FormWindowState.Normal == this.WindowState)
mynotifyicon.Visible = false;
We can also set BallonTipIcon, BallonTipText, BallonTipTitle and Icon ,
for our NotifyIcon control.
 mynotifyicon.BallonTipText = "My application still working...";
mynotifyicon.BallonTipTitle = "My Sample Application";
mynotifyicon.BallonTipIcon = ToolTipIcon.Info;

Favicon Generator How To Add Favicon to Your Website ico

favicon Favicons are the little images, icons that appears in left of the browser address bar and bookmarks menu.

size is 16x16 pixel. Favicons are very important feature, visitors may remember a website from its favicon.
is kind a symbol of a website.
How to add a favicon in your website html.
  • Create a favicon online easily visit the link below and create your favicon online.
FavIcon Generator Online
  • Upload your favicon into your hosting site.
  • Add the html tag below into your website, between head tags.
<link href="images/favicon.ico" rel="shortcut icon" />

Other favicon generator resources:


C# and ASP.NET Create Table Dynamically

In the run-time sometimes we have to create table dynamically.

From the namespace System.Data DataTable DataColumn classes we can easily create table dynamically in C# and also in ASP.NET.
using System.Data;

// Create a DataTable instance
DataTable dTbl = new DataTable("myDynamicTable");

// Create a DataColumn instances

DataColumn dValue = new DataColumn();
DataColumn dMember = new DataColumn();

dValue.ColumnName = "Id";
dValue.DataType = Type.GetType("System.Int32");

dMember.ColumnName = "Name";
dMember.DataType = Type.GetType("System.String");

// Add these DataColumns into the DataTable

After you create table dynamically, you can add rows into it.
It is a good way to create DataRow from the table we create, with the function NewRow().
// Create a DataRow Instance from the table we create above, with NewRow();

DataRow myrow = dTbl.NewRow();

myrow["Id"] = 1;
myrow["Name"] = "Tux";

// Add the row into the table

That's all for creating table dynamically in C# and also ASP.NET.

Meaning of De parvis grandis acervus erit

When you open the Google toolbar about box, you may see this text there.
De parvis grandis acervus erit.

After I googling, I found several possible meanings;
  • Out of small things a great heap will be formed.
  • Little by little there's so much done.
  • Tall oaks from little acorns grow.
  • Small things will make a large pile.
I really love this quote, I think it summarize the Google great services clearly, their passion and simplicity beyond the great work and service. Please let me know if this translations are incorrect or any other suggestions.

C# Process Process.GetProcessesByName, Kill Process and Exit Event

A process instance can be created by call Process.GetProcessesByName with the name of the process.
Let's say we want to reach, notepad.exe.
  • Get the process by its name
using System.Diagnostics;

private Process GetaProcess(string processname)
Process[] aProc = Process.GetProcessesByName(processname);

if (aProc.Length > 0)
return aProc[0];

else return null;
Call GetaProcess("notepad.exe"); will return notepad process, if it is already launched.
  • To Kill the process
Process myprc = Call GetaProcess("notepad.exe"); myprc.Kill();
Will kill the process notepad.exe.
  • Handle the Exit Event of the Process
 Process myprc = Call GetaProcess("notepad.exe");
myprc.Exited += new EventHandler(myprc_Exited);

void myprc_Exited(object sender, EventArgs e)
MessageBox.Show (((Process)sender).ProcessName + " process has exited!");
Now we will noticed when the notepad process exited.

C# Illegal Cross Thread Operation Problem Solution

In Visual Studio, using .NET Framework,
if you are trying to access a user interface control, in multi thread operation, you may get this error Illegal Cross Thread Operation .

That is the thread other than the thread it was created on has no access to change the control interface properties.
To avoid the Illegal Cross Thread Operation error here is the solution;
  • Make a delegate for the control which you want update in multi threading.
  • Check if needs InvokeRequired.
  • Invoke the control, then it will invoke ones again, by its creator object.
  • Second time the control invokes, set its properties as you wish.
The Following C# sample code shows all these steps.
public delegate void UpdateMeLabel(string _str, Color _fontcolor);
public void FormTxtUpdate(string str, Color fontcolor)
if (this.label1.InvokeRequired)
UpdateMeLabel updaterdelegate = new UpdateMeLabel(FormTxtUpdate);
this.Invoke(updaterdelegate , new object[] { str, fontcolor });
label1.Text = str;
label1.ForeColor = fontcolor;

By this way, we update the control label1, its text and color values. For example call FormTxtUpdate("Hello World", Color.Red) in multi thread operation, Then label1 text will set to "Hello World" and its color set to Red.

C# Event Log Write To EventLog Entry

Write to event log in C#
  • Add reference using System.Diagnostics to your project
  • Check whether the source exits or not.
  • If not create event source.
  • Create an EventLog object.
  • Set its event source.
  • Write the entry into event source.
C# sample source code is below;

using System.Diagnostics;

private void WriteToEventLog(string message)
string cs = "Your Source Name";
EventLog elog = new EventLog();

if (!EventLog.SourceExists(cs))
EventLog.CreateEventSource(cs, cs);

elog.Source = cs;
elog.EnableRaisingEvents = true;

C# Event Log Write To EventLog Entry tutorial


Fan-out is the number of loads that the output of a gate can drive without decreasing the performance of the logic gate.
Fan-out depends on the logic family of related gate.


Fan-in is the number of inputs available on a logic gate.

Fan-in and gate

Fan in is 2 in the and gate diagram above.
There are 2 inputs on this gate.

Boolean Algebra

Basic identities used in boolean algebra digital logic.

Note that X' means not X, the complement of X
  1. X+0 = X
  2. X.1 = X
  3. X+1= 1
  4. X.0 = X
  5. X+X = X
  6. X.X=X
  7. X+X'=1
  8. X.X'=0
  9. X''=X

Other boolean algebra properties.

  • Commutative: X+Y = Y+X
  • Associative: X+(Y+Z) = (X+Y)+Z
  • Distributive: X(Y+Z) = XY + XZ
  • DeMorgan's: (X+Y)' = X'+Y'
The identities below are useful for simpling the logic equations.

  • X(X+Y)=X
  • (X+Y)(X+Y')=X
  • X(X'+Y)=XY
Boolean algebra digital logic tutorial.

BCD Binary Decimal Codes

Binary decimal codes contains 0 to 9 numbers, that is human readable, unlike computer systems use binary number systems 0 and 1s.

Decimal NumberBCD Digit

BCD example

(215)10 = (0010 0001 0101)BCD

BCD Binary Decimal Codes tutorial

Octal Number System

Octal number system is base-8 system with 8 digits 0 to 7.

Example of a octal number: 147.2

Expanding numbers as a power series with base of 8.

Example of octal number:

(147.2)8 = 1x82 + 4x81 + 7x80 + 2x8-1 = 64 + 32 + 7 + 0.25 = (103.25)10

Octal number system tutorial.

Binary Number System

Binary number system is base-2 system with 2 digits 0 and 1.

Example of a binary number: 1101.1

Binary number can be expanding numbers as a power series with base of 2.


(1101.1)2 = 1x23 + 1x2 + 0x210 + 1x2-1 = (13.5)10

Binary number 1101.1 is equal to 13.5 in base-10 number system.

Also 1K (kilo) = 210
Also 1M (mega) = 220

Binary number system tutorial

HTML Redirect Tag Page Redirection

Html redirect page tag is inserted between head tags in html page file.

Copy paste HTML redirect tag code below between head tag.

<meta equiv="refresh" content="3;http://alperguc.blogspot.com/">

3 is the duration that html page will wait and after 3 seconds page will redirect to the url.

First parameter of HTML redirect tag is seconds: 3
Second parameter of HTML redirect tag is url: http://alperguc.blogspot.com/

How to redirect html page with refresh tag.

C# WMI Startup Programs, List Startup Applications with ManagementClass

It is possible to list Startup Programs of operating system in C#.

With the use of ManagementClass, a few lines of code will give us this list.
The WMI classes are easy to use such these operations.
  • Add reference System.Management to your project.
  • Add the following code to your code file.
  • using System.Management;
    using System.Management.Instrumentation;
  • Add the code below to list the startup application assigned in os.
  •  ManagementClass mangnmt =
    new ManagementClass("Win32_StartupCommand");

    ManagementObjectCollection mcol = mangnmt.GetInstances();

    foreach (ManagementObject strt in mcol)
    Console.WriteLine("Application Name: "
    + strt["Name"].ToString());

    Console.WriteLine("Application Location: "
    + strt["Location"].ToString());

    Console.WriteLine("Application Command: "
    + strt["Command"].ToString());

    Console.WriteLine("User: " + strt["User"].ToString());

List Autorun programs in C#

C# a generic error occurred in GDI+ Solution

A generic error occurred in GDI+
I encountered this error while I was working with images,
when I try to save image file with EncoderParameter and ImageCodecInfo classes in C#.

This problem is mostly occurred for the security reasons,
you may not enough permission to write file and so on.
Here is solution.
  • Create a System.IO.MemoryStream object.
  • Create a System.IO.FileStream object
  • Save image into MemoryStream
  • Read bytes[] from the MemoryStream
  • Save the image file with FileStream
And Here is the C# sample code;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;

public static void SaveJpeg
(string path, Image img, int quality)
EncoderParameter qualityParam
= new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

ImageCodecInfo jpegCodec
= GetEncoderInfo(@"image/jpeg");

EncoderParameters encoderParams
= new EncoderParameters(1);

encoderParams.Param[0] = qualityParam;

System.IO.MemoryStream mss = new System.IO.MemoryStream();

System.IO.FileStream fs
= new System.IO.FileStream(path, System.IO.FileMode.Create
, System.IO.FileAccess.ReadWrite);

img.Save(mss, jpegCodec, encoderParams);
byte[] matriz = mss.ToArray();
fs.Write(matriz, 0, matriz.Length);

Do not forget to close streams, other wise you will get a out of memory error.

C# ASP.NET MySQL Connection Tutorial with MySQL Connector

In order to connect to MySQL Server with .NET in C# or ASP.NET does not matter actually,
  • You need to download MySQL Connector/Net .
  • After you add a reference to your project, it is probably in C:\Program Files\MySQL\MySQL Connector Net 5.0.7\Binaries\.NET 2.0 folder, add the MySql.Data.dll file as a reference.
  • Make your connection string, the following code will shows a standard MySQL connection string.

using MySql.Data.MySqlClient;
public static string GetConnectionString()
string connStr =
String.Format("server={0};user id={1}; password={2};
database=yourdb; pooling=false", "yourserver",
"youruser", "yourpass");

return connStr;
  • Then create an instance from MySql.Data.MySqlClient.MySqlConnection as shown below.
  •  MySql.Data.MySqlClient.MySqlConnection mycon
    = new MySqlConnection( GetConnectionString());
  • Then Try to open the MySQL connection.
  • if(mycon .State != ConnectionState.Open)
    mycon .Open();
    catch (MySqlException ex)
    throw (ex);
So simple as you see, It is always better to do this in data access layer also called DAL.
Connect Mysql in C# and ASP.NET.

C# How To Get Computer IP Address IPHostEntry

To get the IP address of the local machine in C#,
using system.net

From IPHostEntry class, we get the list in a string array.
 using System.Net;

Private string GetIP()
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();

IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

IPAddress[] addr = ipEntry.AddressList;

return addr[addr.Length-1].ToString();

Read IP address of the local computer.

You can check your IP address on myip.help.

C# Regex Time Validation With Regular Expression

In order to check whether an input is a valid time format or not,
regular expressions
can be used to validate the input value.

The sample function below show how to check if the input
is valid time in XX:XX, code is in C#.

This regular expression checks the input for 00:00 to 23:59 is a valid time format.

using System.Text.RegularExpressions;

public bool IsValidTime(string thetime)
Regex checktime =
new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$");

return checktime.IsMatch(thetime);
Time regular expression used to control time is ^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$

Is valid time validation with regular expression in C#.

C# Regex Number Validation With Regular Expression

In order to check whether an input is a valid number or not,
regular expressions
are very easy to use to validate the input value.

The sample function below show how to check if the input is number or not, code is in C#.

using System.Text.RegularExpressions;

public static bool IsItNumber(string inputvalue)
Regex isnumber = new Regex("[^0-9]");
return !isnumber.IsMatch(inputvalue);
IsItNumber("2"); will return true;
IsItNumber("A"); will return false;

Is number validation with regular expression in C#.

C# Read Windows Logon User Name in WMI

Using the namespace System.Management,
we can easily read the Windows Logon User name.

The WMI (Windows Media Instrumentation)
queries are very similar with the SQL queries.

The sample code below written in C# reads the logon user name.
using System.Management;

public static string logonUser()
string _user = string.Empty;
ConnectionOptions co = new ConnectionOptions();
System.Management.ManagementScope ms
= new System.Management.ManagementScope("\" + "localhost" + "rootcimv2", co);

System.Management.ObjectQuery oq =
new System.Management.ObjectQuery("SELECT * FROM Win32_ComputerSystem");
ManagementObjectSearcher query =
new ManagementObjectSearcher(ms, oq);

ManagementObjectCollection queryCollection;
queryCollection = query.Get();

foreach (ManagementObject mo in queryCollection)
_userl = mo["UserName"].ToString();

char[] charSeparators = new char[] { '' };

int deger = _user.Split(charSeparators, StringSplitOptions.None).Length;
_user= _user.Split(charSeparators, StringSplitOptions.None)[deger - 1];

return _user;
Will return the Windows Logon User name. Many other WMI queries are available.

How To Add HTML Meta Description Tag in Wordpress Theme

Many search engine spiders read the description meta tag, instead of keywords meta tags.

In many wordpress themes does not have description meta tag in html headers.
There are several plugins for adding meta tags, but I will show you an easy way to add it without plugin install.

Open your header.php file in your templates folder, and add the code below and save it.
 <meta name="Description" content=" <?php if(is_home())
{ echo get_bloginfo('name'); }

if(is_single() or is_page())
{single_post_title('', true);}
else if(is_category())
else if(is_archive())
else if(is_search())
else {wp_title('');} ?> " />
This code will add description html meta tag with the title of your post or category,
this will positively improve your seo (search engine optimization),
your content and the meta tag relevancy will increase.

C# WMI Howto List Windows OS User List With Login Names

It is not easy to reach windows login users list in C#.

There are several ways to get this list, like WMI (windows media instrumentation).
But here I will use a different way, let's read the registry and list the win user list.
string users_reg_key=
With using this registry key, we can have all users who login into that os. Let's write a simple function to read this registry key in C#.
 public string[] ListWinUsersList()
//The registry key for reading user list.

RegistryKey key =
Registry.LocalMachine.OpenSubKey(users_reg_key, true);

string[] winusers;

if (key != null && key.ValueCount > 0)
winusers = key.GetValueNames();
return winusers[];
And now we get a string array filled with windows users list.