image1.Source = new BitmapImage(new Uri(@"C:\IMAGE.JPG"));Additional Reading at :
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Thursday, April 10, 2014
C# WPF Load Image from file
How to load image WPF:
C# Load Image to PictureBox
How to load image to picturebox:
Method 1 :
Method 1 :
PictureBox1.Image = Image.FromFile(@"C:\IMAGE.JPG");Method 2 :
PictureBox1.Image = New Bitmap(@"C:\IMAGE.JPG");Additional Reading at :
C# Convert Image to byte array (byte[]) or C# convert byte array (byte[]) to Image
Convert Image to byte[] method:
public byte[] imageToByteArray(Image imageIn)
{
using (var ms = new System.IO.MemoryStream())
{
System.Drawing.Imaging.ImageFormat format;
switch (imageIn.MimeType())
{
case "image/png":
format = ImageFormat.Png;
break;
case "image/gif":
format = ImageFormat.Gif;
break;
default:
format = ImageFormat.Jpeg;
break;
}
imageIn.Save(ms, format);
return ms.ToArray();
}
}
Convert byte[] to Image method:
public Image byteArrayToImage(byte[] byteArrayIn)
{
using (var ms = new System.IO.MemoryStream(byteArrayIn))
{
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
Additional Reading at :
Labels:
byte array,
byte[],
C#,
Conversion,
convert,
CSharp,
Image,
ImageFormat,
MemoryStream
Tuesday, August 20, 2013
C# Capturing Keys - KeyPress Event, KeyDown Event or KeyUp Event
Differences of the three:
Sample Code below :-
1.Create a Textbox control.
2.Adding event to your control in form1.designer.cs
get list of key code from keys enum.. link below..
Additional Reading at :
- Keydown: happens when the key is pressed.
- KeyPressed: happens when a key is pressed and then released.
- KeyUp: happens when the key is released.
Sample Code below :-
1.Create a Textbox control.
2.Adding event to your control in form1.designer.cs
this.textbox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CaptureKeyPress); this.textbox1.KeyDown += new System.Windows.Forms.KeyEventHandler(CaptureKeyDown); this.textbox1.KeyUp += new System.Windows.Forms.KeyEventHandler(CaptureKeyUp);3.Creating event handler
private void CaptureKeyPress(object sender, KeyPressEventArgs e)
{
//key press capture key char
//you can compare with keycode also
if (e.KeyChar == (char)Keys.Enter)
{
MessageBox.Show("Enter Key Press");
}
//or can compare with ascii code
if (e.KeyChar == 13) //13 in ascii code for enter
{
MessageBox.Show("Enter Key Press");
}
}
private void CaptureKeyDown(object sender, KeyEventArgs e)
{
//key down capture key code
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter Key Down");
}
}
private void CaptureKeyUp(object sender, KeyEventArgs e)
{
//key up capture key code
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter Key Up");
}
}
get list of key char from ascii table.. link below.. get list of key code from keys enum.. link below..
Additional Reading at :
Labels:
Ascii,
C#,
Capture,
Capture Enter Keys,
CSharp,
Event,
Event Handler,
Events,
Keyboard,
Keyboard Key,
KeyChar,
KeyCode,
KeyDown Event,
KeyEventArgs,
KeyPress Event,
KeyPressEventArgs,
Keys,
KeyUp Event
Thursday, May 2, 2013
C# ComboBox using DataTable
Load Combobox Using DataTable.
Make an OleDbConnection.
Create DataTable from OleDbDataReader.
Sample code:
Make an OleDbConnection.
Create DataTable from OleDbDataReader.
Sample code:
//include this
using System.Data.OleDb;
//declare
OleDbConnection OCON = null;
OleDbDataReader ODR = null;
//create connection
OCON = new OleDbConnection(@"Provider=SQLOLEDB;Data Source=192.168.0.1;Initial Catalog=TESTDATABASE;User ID=TESTUSER;Password=TESTPASS;");
try{
//open connection
OCON.Open();
//create command
OleDbCommand OCMD = null;
OCMD.CommandText = "SELECT ID, DESCRIPTION FROM TABLE";
//execute command
ODR = OCMD.ExecuteReader();
//load datareader to datatable
DataTable DT = new DataTable();
DT.Load(ODR);
//attach datatable to combobox
comboBox1.DisplayMember = "DESCRIPTION";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = DT;
//close connection
OCON.Close();
}catch(OleDbException ex){
MessageBox.Show(ex.ToString());
}
Additional Reading at :
Wednesday, May 1, 2013
C# string ToTitleCase. Capitalize the first letters of all words.
Convert string to title case. Capitalize the first letters of all words.
Sample code:
Sample code:
//include this using System.Globalization; //how to convert from uppercase string to titlecase string title = "THE TITLE STRING"; TextInfo ti = CultureInfo.CurrentCulture.TextInfo; title = ti.ToTitleCase(title.ToLower()); //result : "The Title String"Additional Reading at :
C# DateTimePicker CustomFormat Month and Year
Using DateTimePicker to select month and year only.
Additional Reading at :
//to configure datetimepicker for month and year.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MMM-yyyy";
dateTimePicker1.ShowUpDown = true;
//to get value of the datetimepicker.
dateTimePicker1.Value.ToString("yyyy-MM");
Additional Reading at :
Friday, April 26, 2013
C# Get Application Version via runtime
Setting Custom version number at project properties under application assembly information
Get application version via runtime code:
Get application version via runtime code:
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
C# Read Registry Method
To get value from registry.
Sample code:
//include this
//for registry read write
using Microsoft.Win32;
public string ReadRegistryValue(string KeyName)
{
// Opening the registry key
RegistryKey key = Registry.LocalMachine;
// Open a subKey as read-only
RegistryKey subkey = key.OpenSubKey(@"SOFTWARE\SKYPE\PHONE");
// If the RegistrySubKey doesn't exist -> (null)
if (subkey == null)
{
return null;
}
else
{
try
{
//return value
return (string)subkey.GetValue(KeyName);
}
catch (Exception e)
{
//display error
MessageBox.Show("Reading registry Exception " + e.Message.ToString());
return null;
}
}
}
//method usage
MessageBox.Show(ReadRegistryValue("SkypePath"));
Additional Reading at :
Wednesday, January 30, 2013
C# Create Delete Move Copy Rename Folder
Folder Manipulation (Create Delete Move Copy Rename Folder) in C#
Sample Code:
//include this
using System.IO;
public void CreateFolder(string FolderPath)
{
// Specify the directories you want to manipulate.
DirectoryInfo di = new DirectoryInfo(FolderPath);
try
{
//check folder already exists.
if (di.Exists)
{
MessageBox.Show("Folder already exists.");
}
else
{
//create folder
di.Create();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public void DeleteFolder(string FolderPath)
{
// Specify the directories you want to manipulate.
DirectoryInfo di = new DirectoryInfo(FolderPath);
try
{
//check folder exists.
if (di.Exists)
{
//delete all including sub folder
di.Delete(true);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (source.FullName.ToLower() == target.FullName.ToLower())
{
return;
}
// check target folder exists
if (Directory.Exists(target.FullName) == false)
{
//create target target folder
Directory.CreateDirectory(target.FullName);
}
//copy each file to target folder
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
//copy each sub folder to target folder
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
//copy all file from subfolder to target subfolder
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
public void MoveAll(DirectoryInfo source, DirectoryInfo target)
{
try
{
//check source folder exist
if(source.Exists)
//check destination not exist
if(!target.Exists)
source.MoveTo(target.ToString());
}
catch (IOException e)
{
MessageBox.Show(e.Message);
}
}
public void RenameTo(DirectoryInfo di, string NewName)
{
if (di == null)
{
MessageBox.Show("Directory info to rename cannot be null");
}
if (string.IsNullOrWhiteSpace(NewName))
{
MessageBox.Show("New name cannot be null or blank");
}
di.MoveTo(Path.Combine(di.Parent.FullName, NewName));
}
//method usage
CreateFolder(@"C:\NewFolder");
DeleteFolder(@"C:\FolderToDelete");
DirectoryInfo Source = new DirectoryInfo(@"C:\SourceFolder");
DirectoryInfo Target = new DirectoryInfo(@"C:\TargetFolder");
CopyAll(Source, Target);
MoveAll(Source, Target);
RenameTo(Source, "NewName");
Additional Reading :
C# File in Directory List
To Get List of File in directory.
Sample Code:
//include this
using System.IO;
//set directory to scan
var dirInfo = new DirectoryInfo(@"C:\FolderName");
//checking if folder exists
if (dirInfo.Exists) {
//*.* = get all file name
FileInfo[] files = dirInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);
foreach (FileInfo file in files) {
//example to list the file name using messagebox
MessageBox.Show(file.ToString());
}
}
Additional Reading at :
Tuesday, January 1, 2013
C# Debug.Writeline
Debug.WriteLine is equivalent to Debug.Print in VB.
Sample Code:
//include this using System.Diagnostics; //example String Text = "Text Something"; Debug.WriteLine(Text);
C# ODP.NET Without Oracle Client
Required File:
where to download:
Oracle Website ODP.NET
How To Use:
where to download:
Oracle Website ODP.NET
How To Use:
//add reference Oracle.DataAccess to project
//include Oracle.DataAccess
using Oracle.DataAccess.Client;
//create connection string
string OraconnectionString = "user id=" + USERID + ";password=" + USERPASSWORD + ";" +
"data source=(DESCRIPTION=(ADDRESS=" +
"(PROTOCOL=tcp)(HOST=" + IPorSERVERNAME + ")" +
"(PORT=1521))(CONNECT_DATA=" +
"(SERVICE_NAME=" + ORACLESID + ")))";
//example Connection to DB
OracleConnection OraConnection = new OracleConnection(OraconnectionString);
try
{
OraConnection.Open();
}
catch (OracleException err)
{
OraConnection.Close();
}
finally
{
OraConnection.Close();
}
//example insert/update/delete
OracleCommand OraCommand = new OracleCommand("", OraConnection);
if (OraConnection.State.ToString() == "Open")
{
try
{
//sql command
OraCommand.CommandText =
"insert into " + table + " (" + field + ") values (" + data + ")";
OraCommand.ExecuteNonQuery();
OraCommand = null;
}
catch (OracleException ex)
{
return ex.Message.ToString();
}
}
else
{
return "Oracle Connection Close";
}
//example SQL select statement
string strSQL = "select COLUMN_NAME from TABLE";
//assign connection and sql statement
OracleCommand OraCommand2 = new OracleCommand(strSQL, OraConnection);
//create data reader
OracleDataReader OraDataReader = null;
if (OraConnection.State.ToString() == "Open")
{
try
{
//execute data reader
OraDataReader = OraCommand2.ExecuteReader();
//read SQL result
while (OraDataReader.Read() == true)
{
OraDataReader["COLUMN_NAME"].ToString();
}
OraDataReader.Close();
}
catch (OracleException ex)
{
ex.Message.ToString();
}
}
else
{
return "Oracle Connection Close";
}
Wednesday, December 19, 2012
C# PadLeft and PadRight
PadLeft/PadRight is padding on the left/Right with spaces or a specified Unicode character for a specified total length.
Example as bellow:
MSDN Pad Right
string myString = ""; int myInt = 1; myString = myInt.ToString().PadLeft(8, '0'); //myString will be 00000001 myString = myInt.ToString().PadRight(8, '0'); //myString will be 10000000MSDN Pad Left
MSDN Pad Right
C# Convert Ascii string to Hex string vice versa
Convert Ascii to Hex method
public string ConvertAsciiToHex(string asciiString)
{
string hex = "";
foreach (char c in asciiString)
{
int tmp = c;
hex += String.Format("{0:X2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
return hex;
}
Convert Hex to Ascii method
public string ConvertHextoAscii(string HexString)
{
string asciiString = "";
for (int i = 0; i < HexString.Length; i += 2)
{
if (HexString.Length >= i + 2)
{
String hs = HexString.Substring(i, 2);
asciiString = asciiString + System.Convert.ToChar(System.Convert.ToUInt32(HexString.Substring(i, 2), 16)).ToString();
}
}
return asciiString;
}
Labels:
Ascii,
C#,
Conversion,
CSharp,
Hex,
String Manipulation
C# Reverse String Method
Reverse String Method as below
public static string ReverseString(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
C# Convert Decimal to Binary and Vice Versa
Decimal to Binary conversion as below:
int DecimalVal = 256; string BinaryVal = Convert.ToString(DecimalVal, 2);Binary to Decimal conversion as below:
string BinaryVal = "01001101"; string DecimalVal = Convert.ToInt32(BinaryVal, 2).ToString();
Labels:
Binary,
C#,
Conversion,
CSharp,
Decimal,
String Manipulation
C# Custom Value from DateTimePicker
Custom value from datetimepicker as below:
string date = DateTimePicker1.Value.ToString("yyyy-MM-dd");
C# Convert Hex to Decimal and vice versa
Convert Hex to Decimal as below;
int DecimalVal = Convert.ToInt32(HexVal, 16);Convert Decimal to Hex as below;
string HexVal = DecimalVal .ToString("X");
C# DateTime Custom String Method
Sample Code as bellow:
DateTime DT = DateTime.ParseExact("20121207015640","yyyyMMddHHmmss",null);
For more info
MSDN DateTime.ParseExact
Subscribe to:
Posts (Atom)