Csharp - Some Conversions
Csharp - Some Conversions
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}$";
else
{
valid = check.IsMatch(addr, 0);
}
return valid;
}
/// <summary>
/// Polje znakova u string.
/// </summary>
public static string ByteArrayToString(byte[] data)
{
string str = string.Empty;
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})";
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];
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();
}
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:
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.
2 Answers
C# - IP Adresse in ByteArray
Wandelt eine durch Punkt getrennte IP in einen ByteArray
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.
namespace Application01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
gridControl1.DataSource = deviceList;
}
// JF
// varijanta 1 -----
// SIMPLEX spremanje u fajlu
File.WriteAllBytes($"{Application.StartupPath}\\Simplex.kfg", fileContent); // zahtjeva
System.IO
}
//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);
}
}
}
// JF
// -----
byte[] empty = null;
byte[] temp = null;
uint offset = 0;
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)
{
}
}
//// 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;
// -----
// 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;
// -----
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
Here is the code to capture the screen. Change the values to the size you need.
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 :
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);
}
}
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