Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

14 April 2011

C# Convert String to Integer

Converting string to int is simple in c#. There are two comman ways to convert string to int.
  • Convert.ToInt32
  • Int32.TryParse
Here is the screen shot of our string to int converter sample application:


Note that our integer number must be between −2,147,483,648 and +2,147,483,647 range.

The c# source code to convert string to integer:
private void btnConvert_Click(object sender, EventArgs e)
{
int numValue = 0;
string strValue = string.Empty;

strValue = tbInput.Text.Trim();

try
{
numValue = Convert.ToInt32(strValue);
lblResult.Text = numValue.ToString();
}
catch (Exception exc)
{
tbInput.Text = string.Empty;
lblResult.Text = string.Empty;
MessageBox.Show("Error occured:" + exc.Message);
}
}       

private void btnTryParse_Click(object sender, EventArgs e)
{
ConvertToIntTryParse();
}

private void ConvertToIntTryParse()
{
int numValue = 0;
bool result = Int32.TryParse(tbInput.Text, out numValue);
if (true == result)
lblResult.Text = numValue.ToString();
else
MessageBox.Show("Cannot parse string as int number");
}

I think IntTryParse is better to convert string to int, because it handles the parse error inside and returns bool value if the string is parsable to int.
IntTryParse return boolean value, so that if it parses the string it returns true, else returns false.

Note the parsing string with Convert.ToInt32 may cause a FormatException if the parse string value is not suitable.

25 May 2009

ASP.NET How To access Master Page Variables Class Members C#.NET

Sometimes we need to access to a variable in master page file.
For example I need to change the body onload event in html.

In the asp.net file, we simply cast our master page as its class name.

in master page aspx we add the code below.

<body onload="<%=myloadstr %>" >

in master page cs code we add the code below.
we declare it as public to access the variable.

public string myloadstr = "";


And add the code below in your asp.net cs source file.

((myMasterPage)this.Master).myloadstr = "here some javascript for load";

myMasterPage is the name of my masterpage class. We cast our asp.net page its masterpage, with "this.Master".

16 December 2008

C# MS Access Connection String OLE DB OleDbConnection

The Connection String for MS Access can be set as ;
 private constr =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdbfile.mdb;
Jet OLEDB:Database Password=yourpassword;";
And the C# code to connect to MS Access database ;
 public bool OpenConnection()
{
OleDbConnection con; con = new OleDbConnection(constr);

if (con.State != ConnectionState.Open)
{
try
{
con.Open(); return true;
}
catch (Exception) { return false; }
}
else return false;
}
C# Access Connection String OLE DB OleDbConnection password field is the password you set up in access database.

11 December 2008

C# Read Harddisk Serial Number WMI ManagementClass Win32_LogicalDisk

With the Win32_LogicalDisk Management path we can reach the local disk information.

Even you can read harddisk serial number,
size, partitions, free space and so on.

Now let's read the serial number of a harddisk in C# with ManagementClass WMI.
public static string HardDiskID()
{
ManagementClass partionsClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection partions = partionsClass.GetInstances();

string hdd = string.Empty;

foreach (ManagementObject partion in partions)
{
hdd = Convert.ToString(partion["VolumeSerialNumber"]);

if (hdd != string.Empty)
return hdd;
}

return hdd;
}
This static function will simple give us the volume serial numbers.
C# Read Harddisk Serial Number WMI ManagementClass.

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;
textbox1.ScrollToCaret();
textbox1.Refresh();
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)
{
try
{
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;
mynotifyicon.ShowBalloonTip(500);
this.Hide();
}
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;

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

dTbl.Columns.Add(dValue);
dTbl.Columns.Add(dMember);
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

dTbl.Rows.Add(myrow);
That's all for creating table dynamically in C# and also ASP.NET.

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 });
}
else
{
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;
elog.WriteEntry(message);
}

C# Event Log Write To EventLog Entry tutorial

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);

mss.Close();
fs.Close();
}
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)
    try
    {
    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
namespace.

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.

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=
@"SOFTWAREMicrosoftWindowsCurrentVersionExplorerDocFolderPaths";
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.