0% found this document useful (0 votes)
39 views

Csharp - Some Conversions

This C# code defines a class called ClassCommon that contains various utility methods for working with IP addresses, MAC addresses, and byte arrays. It includes methods to validate IP and MAC address strings, convert between addresses and byte arrays, concatenate bytes into strings, and format addresses for display. The code is intended to be used for network configuration in a product called UST_1_Konfigurator.

Uploaded by

karo
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Csharp - Some Conversions

This C# code defines a class called ClassCommon that contains various utility methods for working with IP addresses, MAC addresses, and byte arrays. It includes methods to validate IP and MAC address strings, convert between addresses and byte arrays, concatenate bytes into strings, and format addresses for display. The code is intended to be used for network configuration in a product called UST_1_Konfigurator.

Uploaded by

karo
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

using System;

using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Globalization;

namespace UST_1_Konfigurator
{
public static class ClassCommon
{
/// <summary>
/// Provjeri ispravnost IP adrese.
/// </summary>
/// <param name="addr"></param>
/// <returns></returns>
public static bool IsValidIP(string addr)
{
string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|
1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";

Regex check = new Regex(pattern);


bool valid = false;
if (addr == "")
{
valid = false;
}

else
{
valid = check.IsMatch(addr, 0);
}

return valid;
}

/// <summary>
/// Polje znakova u string.
/// </summary>
public static string ByteArrayToString(byte[] data)
{
string str = string.Empty;

byte[] temp = Encoding.Convert(Encoding.GetEncoding("iso-8859-2"), Encoding.GetEncoding("iso-


8859-2"), data);
string tempString = Encoding.UTF8.GetString(temp, 0, temp.Length);

for (int i = 0; i < tempString.Length; ++i)


{
if (tempString[i] != '\0')
{
str += tempString[i];
}
else
{
break;
}
}

return str;
}
/// <summary>
/// Provjeri ispravnost MAC adrese.
/// </summary>
/// <param name="addr"></param>
/// <returns></returns>
public static bool IsValidMAC(string addr)
{
string pattern = @"(([0-9A-Fa-f]{2}[-:]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]
{4})";

Regex check = new Regex(pattern);


bool valid = false;
if (addr == "")
{
valid = false;
}

else
{
valid = check.IsMatch(addr, 0);
}
return valid;
}

/// <summary>
/// Konvertiraj string IP adrese u polje okteta.
/// </summary>
/// <param name="IPAddr"></param>
/// <returns></returns>
public static byte[] IPAddressToArray(string IPAddr)
{
System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddr);
byte[] byteIP = oIP.GetAddressBytes();

return byteIP;
}

/// <summary>
/// Konvertiraj string MAC adrese u polje okteta.
/// </summary>
/// <param name="IPAddr"></param>
/// <returns></returns>
public static byte[] MACToArray(string MAC)
{
byte[] bytes = new byte[6] { 0, 0, 0, 0, 0, 0 };
byte[] macAddress = new byte[6];

string[] text = MAC.Split(':');

for (int i = 0; i < 6; i++)


{
bytes[i] = byte.Parse(text[i].ToString(), System.Globalization.NumberStyles.HexNumber);
}

return bytes;
}

/// <summary>
/// Iz polja okteta napravi string.
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static string ArrayToString(byte[] array)
{
string ret = string.Empty;
for (int i = 0; i < array.Length; ++i)
{
ret += System.Convert.ToChar(array[i]);
}

return ret;
}

/// <summary>
/// Prikaz IP adrese
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static string ArrayToIP(byte[] array)
{
return array[0].ToString() + "." + array[1].ToString() + "." + array[2].ToString() + '.' +
array[3].ToString();

/// <summary>
/// Prikaz MAC adrese
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static string ArrayToMac(byte[] array)
{
return array[0].ToString("X2") + ":" + array[1].ToString("X2") + ":" +
array[2].ToString("X2") + ":" + array[3].ToString("X2") + ":" + array[4].ToString("X2") + ":" +
array[5].ToString("X2");
}
}
public FormSystemParameters(byte[] mac, UInt32 serial, UInt32 firmware)
{
InitializeComponent();

num_serial.Value = serial;
tb_mac.Text = string.Format("{0:x2}:{1:x2}:{2:x2}:{3:x2}:{4:x2}:{5:x2}", mac[0], mac[1],
mac[2], mac[3], mac[4], mac[5]);
tb_firmware.Text = string.Format("{0}.{1}.{2}", (firmware >> 24) & 0xFF, (firmware >> 16) &
0xFF, (firmware >> 8) & 0xFF);
}

/// <summary>
///
/// </summary>
private void button_ok_Click(object sender, EventArgs e)
{
if (ClassCommon.IsValidMAC(tb_mac.Text) == false)
{
MessageBox.Show("Neispravna MAC adresa.\rParametri ne mogu biti prihvaćeni.", "Upis
tvorničkih parametara", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

try
{
serial_number = System.Convert.ToUInt32(num_serial.Value);
mac = ClassCommon.MACToArray(tb_mac.Text);
}
catch
{
MessageBox.Show("Neispravna MAC adresa.\rParametri ne mogu biti prihvaćeni.", "Upis
tvorničkih parametara", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

this.DialogResult = DialogResult.OK;
}
converting IP to byte/convert back to string
I'm storing an IPV4 address on a SQLSERVER 2008 database as Binary(4). So, I'm converting the values before
data input (and due to company restrictions I CANNOT create functions inside the db, well thats not up for
discussion).
public static byte[] IpToBin(string ip)
{
return IPAddress.Parse(ip).GetAddressBytes();
}

public static string HexToIp(string ip)


{
return new IPAddress(long.Parse(ip, NumberStyles.HexNumber)).ToString();
}

After IpToBin is called, the data generated is (for example 0x59FC09F3). When I call HexToIp the ip came
reversed probably due little/big endian conversion.

Could anyone please come up with a decent solution without 50 billion lines of code?

How do you store an IPv6 address in 4 bytes? – dtb Jan 24 '13 at 10:50
Thats only for IPV4 – Alexandre Jan 24 '13 at 10:51
You're writing new code in 2013 that doesn't support IPv6? That's like writing new code in 1999 that supports
1
only 2-digit years in dates. Y2K – dtb Jan 24 '13 at 10:54
Its funny how people like to jump in without knowing whats the code for. I wouldn't need IPV6 on that
3
application at all. – Alexandre Jan 24 '13 at 10:59

2 Answers

I think the real issue here is that you are treating the raw form as a string; especially since it is binary(4), you
should never have to do that: just fetch it back from the db as a byte[]. IpToBin is fine, but HexToIp should
probably be:
public static IPAddress BinToIp(byte[] bin)
{
return new IPAddress(bin);
}

then: job done. But with your existing HexToIp code, you want:

return new IPAddress(new byte[] {


Convert.ToByte(ip.Substring(0,2), 16), Convert.ToByte(ip.Substring(2,2), 16),
Convert.ToByte(ip.Substring(4,2), 16), Convert.ToByte(ip.Substring(6,2), 16)}
).ToString();

Actually if i return the byte array from the database i deffinitly should follow your guideline to dont use the
raw hex itself but the byte[]. Thanks! – Alexandre Jan 24 '13 at 11:11
Convert byte[] to string and back again
I have an application that is storing the IP Addresses of requests in the database as a varbinary(16) in a manner
described here: Byte Array Size for a IPv6 IP Address.

I need to pass the IP Address from one server to another. For that reason, I cannot just rely on the Request object.
My question is, if I have the IP Address as a byte[], how do I encode it as a string and then decode it as a byte[]
again? I always get confused with the ASCII, UTF8, Unicode, etc. encodings.

Thank you so much!

2 Answers

var ipString = (new IPAddress(myBytes)).ToString()

then at the other end

var addressBytes = IPAddress.Parse(ipString).GetAddressBytes();

C# - IP Adresse in ByteArray
Wandelt eine durch Punkt getrennte IP in einen ByteArray

//z.B. Value = "192.168.1.1";


private byte[] IpToByteArray(string Value)
{
string[] Temp = Value.Split('.');
int Length = Temp.Length;
byte[] Rueckgabe = new byte[Length];
for (int i = 0; i < Length; i++)
{
Rueckgabe[i] = Convert.ToByte(Convert.ToInt32(Temp[i]));
}
return Rueckgabe;
}

2 Kommentare zum Snippet

Rueckgabe[i] = Convert.ToByte(Temp[i]);

Wäre nicht ausreichend gewesen das Hexadezimal eine String 1 ander ist als eine Integer 1.
Aus einer String eins wird eine 31 gemacht und aus eine Integer 1 wirkliche eine 1.

Oha, wie wäre es denn mit


String IP = "127.0.0.1";
IPAddress _IP;
IPAddress.TryParse(IP, out _IP);
byte[] AdrBuffer = _IP.GetAddressBytes();

das würde ich etwas "eleganter" finden...


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
// JF
// SIMPLEX spremanje u fajlu
using System.IO;
using System.Net; // ReSharper dodao za objekt IPAddress
using System.Text; // ReSharper dodao za "Encoding"

namespace Application01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

var deviceList = new List<Device>();

deviceList.Add(new Mt10Sq("192.168.1.1", 11915000));


deviceList.Add(new Mt10Sq("192.168.1.2", 11915001));

deviceList.Add(new Mt40("192.168.1.100", 28115000));


deviceList.Add(new Mt40("192.168.1.101", 28115001));

foreach (var device in deviceList)


{
device.ReadSerialNumber();

// programska logika koja je isključivo za tip uređaja MT-10SQ


if (device is Mt10Sq)
{
var mt10Sq = device as Mt10Sq;

// programska logika koja je isključivo za tip uređaja MT-40


if (device is Mt40)
{
var mt40 = device as Mt40;
}
}

gridControl1.DataSource = deviceList;
}

private void btnSaveToFile_Click(object sender, System.EventArgs e)


{
// JF
// ubačeno try-catch radi eventualnih grešaka kod spremanja
try
{
// JF komentar
// podaci se prikazuju na formi unutar gridControl1
// na toj formi se mogu i mijenjati
// i zato ih ponovo izvlačimo iz DataSource-a gridControl1
var deviceList = gridControl1.DataSource as List<Device>;

// nema podataka u listi


if ((deviceList == null) || (deviceList.Count <= 0))
return;
// polje s konfiguracijom uređaja
var fileContent = new byte[deviceList.Count * Device.FileSizePerDevice];

for (var i = 0; i < deviceList.Count; ++i)


{
Array.Copy(deviceList[i].GetBytes(), 0, fileContent, i * Device.FileSizePerDevice,
Device.FileSizePerDevice);
}

// JF
// varijanta 1 -----
// SIMPLEX spremanje u fajlu
File.WriteAllBytes($"{Application.StartupPath}\\Simplex.kfg", fileContent); // zahtjeva
System.IO

MessageBox.Show("Konfiguracija upisana u datoteku", "Informacija", MessageBoxButtons.OK,


MessageBoxIcon.Information);

}
//catch (Exception exception)
//{
// MessageBox.Show(exception.ToString()); // ReSharper ponudio -
Console.WriteLine(exception);
// // ako se ostavi throw kojeg je ponudio ReSharper
// // ovdje se javlja greška "Unhandled Null Exception"
// // izbačeno
// //throw;
//}
catch (Exception)
{
MessageBox.Show("Konfiguracija NIJE upisana u datoteku", "Greška", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}

}
}

public abstract class Device


{
// JF komentar
// broj byte-a po svakom uređaju, npr
// na početku je zajednički dio za svaki Device
// -----
// 4 byte-a TypeInteger |
// 4 byte-a IpAddress | 12 byte-a
// 4 byte-a SerialNumber |
// -----
// a iza toga slijedi specifični dio
// za svaki uređaj (MT-10SQ, MT-40,...)
// -----
// MT-10SQ:
// 52 byte-a bez podataka
// -----
// MT-40:
// 26 byte-a FtpUserName | 52
// 26 byte-a FtpPassword | byte-a
// -----
public const int FileSizePerDevice = 64;

private string _ipAddress;

public int TypeInteger { get; set; }

public string Type { get; set; }


public string IpAddress { get; set; }

public uint SerialNumber { get; set; }

public virtual string TypePretty => $"Mjerni terminal {Type}";

public abstract uint ReadSerialNumber();

public abstract byte[] GetBytes();

protected Device(int typeInteger, string type, string ipAddress, uint serialNumber)


{
Type = type;
TypeInteger = typeInteger;
IpAddress = ipAddress;
SerialNumber = serialNumber;
}

protected Device(int typeInteger, string type, byte[] data)


{
TypeInteger = typeInteger;
Type = type;
}
}

public class Mt10Sq : Device


{
public override uint ReadSerialNumber()
{
return 0;
}

public override byte[] GetBytes()


{
var bytes = new byte[FileSizePerDevice];

// JF
// -----
byte[] empty = null;
byte[] temp = null;
uint offset = 0;

temp = BitConverter.GetBytes(TypeInteger); // izgleda ok


for (var i = 0; i < 4; i++)
{
bytes[offset + i] = temp[i];
}
offset += 4;

//// varijanta 1 -----


//// nije ok - upisuje string a ne vrijednost
//// i to samo prva 4 ASCII znaka, npr. za 192.168.1.1
//// upisuje <1><9><2><.>
//IPAddress address = IPAddress.Parse(IpAddress);
//temp = address.GetAddressBytes();
//for (var i = 0; i < 4; i++)
//{
// bytes[offset + i] = temp[i];
//}
//offset += 4;
// varijanta 2 -----
string[] sTemp = IpAddress.Split('.');
int length = sTemp.Length;
//MessageBox.Show(length.ToString());
if (length == 4)
{
for (int i = 0; i < 4; i++)
{
bytes[offset + i] = Convert.ToByte(sTemp[i]);
}
}
else
{
MessageBox.Show("Neispravna IP adresa (format X.X.X.X)");
// ovo nije ok jer u slučaju greske vraća prazno polje
// nakon čega Array.Copy u btnSaveToFile_Click
// ne zna što bi s tim
return empty;
}
offset += 4;

temp = BitConverter.GetBytes(SerialNumber); // izgleda ok


for (var i = 0; i < 4; i++)
{
bytes[offset + i] = temp[i];
}
offset += 4;
// -----

return bytes;
}

// JF
// konstruktor uređaja Mt10Sq iz polja podataka
// uz pozivanje konstruktora "bazne klase" Device
public Mt10Sq(byte[] data)
:base(1, "MT-10SQ", data)
{

// JF
// konstruktor uređaja Mt10Sq s određenom IP adresom i serijskim brojem
// uz pozivanje konstruktora "bazne klase" Device
public Mt10Sq(string ipAdress, uint serialNumber)
:base(1, "MT-10SQ", ipAdress, serialNumber)
{

}
}

public class Mt40 : Device


{
public string FtpUserName { get; set; } = "administrator";

public string FtpPassword { get; set; } = "iel_mt_40";

public override string TypePretty => "Monitor kvalitete " + Type;

public override uint ReadSerialNumber()


{
// ovdje može doci kod koji izvlaci npr. cita preko Modbus protokola serijski broj uredaja
return 0;
}

public override byte[] GetBytes()


{
var bytes = new byte[FileSizePerDevice];
// JF
// -----
byte[] empty = null;
uint offset = 0;

// "join variable end assignment"


//byte[] temp;
//temp = BitConverter.GetBytes(TypeInteger); // izgleda ok
var temp = BitConverter.GetBytes(TypeInteger);

for (var i = 0; i < 4; i++)


{
bytes[offset + i] = temp[i];
}
offset += 4;

//// varijanta 1
//// nije ok - upisuje string a ne vrijednost
//// i to samo prva 4 ASCII znaka, npr. za 192.168.1.1
//// upisuje <1><9><2><.>
//IPAddress address = IPAddress.Parse(IpAddress);
//temp = address.GetAddressBytes();
//for (var i = 0; i < 4; i++)
//{
// bytes[offset + i] = temp[i];
//}
//offset += 4;
// varijanta 2
string[] sTemp = IpAddress.Split('.');
int length = sTemp.Length;
//MessageBox.Show(length.ToString());
if (length == 4)
{
for (int i = 0; i < 4; i++)
{
bytes[offset + i] = Convert.ToByte(sTemp[i]);
}
}
else
{
MessageBox.Show("Neispravna IP adresa (format X.X.X.X)");
return empty;
}
offset += 4;

temp = BitConverter.GetBytes(SerialNumber); // izgleda ok


for (var i = 0; i < 4; i++)
{
bytes[offset + i] = temp[i];
}
offset += 4;

// -----
// dodatni podaci za MT-40:
// 26 byte-a FtpUserName | 52
// 26 byte-a FtpPassword | byte-a
// -----
byte[] bName = Encoding.ASCII.GetBytes(FtpUserName);
for (var i = 0; i < FtpUserName.Length; i++)
{
if (bName[i] != 0)
{
bytes[offset + i] = bName[i];
}
else
{
break;
}
}
offset += 26;

byte[] bPswd = Encoding.ASCII.GetBytes(FtpPassword);


for (var i = 0; i < FtpPassword.Length; i++)
{
if (bPswd[i] != 0)
{
bytes[offset + i] = bPswd[i];
}
else
{
break;
}
}
// nije potrebno jer smo došli do kraja fajle
//offset += 26;

// -----

return bytes;
}

// JF
// konstruktor uređaja Mt40 iz polja podataka
// uz pozivanje konstruktora "bazne klase" Device
public Mt40(byte[] data)
:base(2, "MT-40", data)
{

// JF
// konstruktor uređaja Mt40 s određenom IP adresom i serijskim brojem
// uz pozivanje konstruktora "bazne klase" Device
public Mt40(string ipAdress, uint serialNumber)
: base(2, "MT-40", ipAdress, serialNumber)
{

}
}
}
C#: how to take a screenshot of a portion of screen
like
TakeScreenshot(new Rectangle(0,0,100,100), "output.jpg");

2 You need to specify is it WinForms, WPF or Silverlight. – alxx Jul 22 '10 at 7:22
I'm trying to create this method in a class library – Louis Rhys Jul 22 '10 at 7:28

4 Answers

Use the following:


Rectangle rect = new Rectangle(0, 0, 100, 100);
Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size,
CopyPixelOperation.SourceCopy);
bmp.Save(fileName, ImageFormat.Jpeg);

what is "PixelFormat.Format32bppArgb" for? – Louis Rhys Jul 22 '10 at 7:35


PixelFormat.Format32bppArgb specifies that the format is 32 bits per pixel; 8 bits each are used for the alpha,
1
red, green, and blue components. – Marcel Gheorghita Jul 22 '10 at 7:53
thanks! this is the closes to what I need so I'm accepting this answer :) – Louis Rhys Jul 22 '10 at 8:06

Here is the code to capture the screen. Change the values to the size you need.

Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width,


Screen.PrimaryScreen.Bounds.Height);

Graphics graphics = Graphics.FromImage(printscreen as Image);

graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);

printscreen.Save(@"C:\printscreen.jpg", ImageFormat.Jpeg);

Or make method which will return you captured image like this :

Image CaptureScreen(int sourceX, int sourceY, int destX, int destY,


Size regionSize)
{
Bitmap bmp = new Bitmap(regionSize.Width, regionSize.Height);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(sourceX, sourceY, destX, destY, regionSize);
return bmp;
}
......
// call
Image image = CaptureScreen(sourceX, sourceY, destX, destY, regionSize);
image.Save(@"C:\Somewhere\screen.jpg);
Use the Graphics.CopyFromScreen method. Google turns up this tutorial.
Have you checked the Graphics.CopyFromScreen method?

Saving Panel as JPEG, only saving visible areas c#


I'm trying to save, and then print a panel in c#. My only problem is that it only saves the visible areas and when I
scroll down it prints that.
Bitmap bmp = new Bitmap(this.panel.Width, this.panel.Height);

this.panel.DrawToBitmap(bmp, new Rectangle(0, 0, this.panel.Width, this.panel.Height));

bmp.Save("c:\\panel.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

2 Answers

Try following
public void DrawControl(Control control,Bitmap bitmap)
{
control.DrawToBitmap(bitmap,control.Bounds);
foreach (Control childControl in control.Controls)
{
DrawControl(childControl,bitmap);
}
}

public void SaveBitmap()


{
Bitmap bmp = new Bitmap(this.panel.Width, this.panel.Height);

this.panel.DrawToBitmap(bmp, new Rectangle(0, 0, this.panel.Width,


this.panel.Height));
foreach (Control control in panel.Controls)
{
DrawControl(control, bmp);
}

bmp.Save("d:\\panel.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}

Here is my result:

Form ScreenShot :
Saved bitmap :

As you can see there is TextBox wich is not visible on form but is present in saved bitmap
Thankyou alot :) – Karl May 14 '11 at 12:04
This is also the solution if (like me) you are attempting to save the Panel before the form has actually been
drawn on the screen. – Chris Rae Dec 6 '11 at 21:35
Your solution worked for me BUT controls in panels where drawn twice! So I fixed it with a IF( control is not
a panel) before caling the child controls. – Christian Gold Feb 10 at 14:48
Panel1.Dock = DockStyle.None // If Panel Dockstyle is in Fill mode
Panel1.Width = 5000 // Original Size without scrollbar
Panel1.Height = 5000 // Original Size without scrollbar
Dim bmp As New Bitmap(Me.Panel1.Width, Me.Panel1.Height)
Me.Panel1.DrawToBitmap(bmp, New Rectangle(0, 0, Me.Panel1.Width, Me.Panel1.Height))
bmp.Save("C:\panel.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
Panel1.Dock = DockStyle.Fill
Note: Its working fine

You might also like