Here are the examples of the csharp api System.Convert.ToByte(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
106 Examples
19
Source : SendPacket.cs
with MIT License
from 499116344
with MIT License
from 499116344
[Obsolete("请使用BinaryWriter.Write(Richtext)方法。")]
public static byte[] ConstructMessage(string message)
{
var bw = new BinaryWriter(new MemoryStream());
var r = new Regex(@"([^\[]+)*(\[face\d+\.gif\])([^\[]+)*");
if (r.IsMatch(message))
{
var faces = r.Matches(message);
for (var i = 0; i < faces.Count; i++)
{
var face = faces[i];
for (var j = 1; j < face.Groups.Count; j++)
{
var group = face.Groups[j].Value;
if (group.Contains("[face") && group.Contains(".gif]"))
{
var faceIndex =
Convert.ToByte(group.Substring(5, group.Length - group.LastIndexOf(".") - 4));
if (faceIndex > 199)
{
faceIndex = 0;
}
//表情
bw.Write(new byte[] { 0x02, 0x00, 0x14, 0x01, 0x00, 0x01 });
bw.Write(faceIndex);
bw.Write(new byte[] { 0xFF, 0x00, 0x02, 0x14 });
bw.Write((byte) (faceIndex + 65));
bw.Write(new byte[] { 0x0B, 0x00, 0x08, 0x00, 0x01, 0x00, 0x04, 0x52, 0xCC, 0x85, 0x50 });
}
else if (!string.IsNullOrEmpty(group))
{
var groupMsg = Encoding.UTF8.GetBytes(group);
//普通消息
ConstructMessage(bw, groupMsg);
}
}
}
}
return bw.BaseStream.ToBytesArray();
}
19
Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static Plant GetPlant(string name)
{
XElement plantData = null;
// load all the plants
XElement root = XElement.Load("res/data/PlantTypes.xml");
IEnumerable<XElement> plants =
from el in root.Elements("plant")
select el;
// choose the right creature
foreach (XElement p in plants)
if (ReadAttribute(p.FirstAttribute).Equals(name))
plantData = p;
if (plantData == null)
return null;
bool edible = System.Convert.ToBoolean(ReadAttribute(plantData.Element("edible").Attribute("bool")));
int growthInterval = System.Convert.ToInt32(ReadAttribute(plantData.Attribute("growth_interval")));
int seedRadius = System.Convert.ToInt32(ReadAttribute(plantData.Attribute("seed_radius")));
byte r = System.Convert.ToByte(ReadAttribute(plantData.Element("fore_color").Attribute("r"))),
g = System.Convert.ToByte(ReadAttribute(plantData.Element("fore_color").Attribute("g"))),
b = System.Convert.ToByte(ReadAttribute(plantData.Element("fore_color").Attribute("b")));
Color? foreColor = new Color(r, g, b);
IEnumerable<XElement> growthStagesTemp =
from el in plantData.Element("growth_stages").Elements("growth_stage")
select el;
List<byte> growthStages = new List<byte>();
foreach (XElement growthStage in growthStagesTemp)
growthStages.Add(System.Convert.ToByte(ReadAttribute(growthStage.Attribute("graphic"))));
string requirement;
if (ReadAttribute(plantData.Element("requirement").FirstAttribute).Equals(""))
requirement = "";
else {
requirement =
ReadAttribute(plantData.Element("requirement").FirstAttribute)
+ ';'
+ ReadAttribute(plantData.Element("requirement").Attribute("type"))
+ ';'
+ ReadAttribute(plantData.Element("requirement").Attribute("dist"));
}
return new Plant(growthStages[0], name, growthInterval, seedRadius, growthStages, requirement, edible, foreColor);
}
19
Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static Monster GetMonster(string name, Block[] map, Point position, Point worldIndex, int currentFloor)
{
XElement monsterData = null;
// load all the effects
XElement root = XElement.Load( "res/data/MonsterTypes.xml" );
IEnumerable<XElement> monsters =
from el in root.Elements( "monster" )
select el;
// choose the right effect
foreach ( XElement m in monsters )
if ( ReadAttribute( m.FirstAttribute ) == name )
monsterData = m;
if ( monsterData == null )
return null;
byte graphic = System.Convert.ToByte( ReadAttribute( monsterData.Attribute( "ascii_char" ) ) );
string faction = System.Convert.ToString( ReadAttribute( monsterData.Attribute( "faction" ) ) );
int sightDist = System.Convert.ToInt32( ReadAttribute( monsterData.Attribute( "sight_dist" ) ) );
byte r = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "r" ) ) ),
g = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "g" ) ) ),
b = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "b" ) ) );
Color? color = new Color( r, g, b );
Enum.TryParse(ReadElement(monsterData.Element("diet")), out DietType diet);
IEnumerable<XElement> majorAttData = from el in monsterData.Element( "clreplaced" ).Element( "major_attributes" ).Elements( "attribute" )
select el;
List<Attribute> majorAtt = new List<Attribute>();
foreach (XElement attE in majorAttData) {
Enum.TryParse( ReadElement( attE ), out Attribute att );
majorAtt.Add( att );
} // translate IEnumerable to List
IEnumerable<XElement> majorSkillsData = from el in monsterData.Element( "clreplaced" ).Element( "major_skills" ).Elements( "skill" )
select el;
List<Skill> majorSkills = new List<Skill>();
foreach ( XElement skillE in majorSkillsData ) {
Enum.TryParse( ReadElement( skillE ), out Skill skill );
majorSkills.Add( skill );
} // translate IEnumerable to List
IEnumerable<XElement> minorSkillsData = from el in monsterData.Element( "clreplaced" ).Element( "minor_skills" ).Elements( "skill" )
select el;
List<Skill> minorSkills = new List<Skill>();
foreach (XElement skillE in minorSkillsData) {
Enum.TryParse( ReadElement( skillE ), out Skill skill );
minorSkills.Add( skill );
} // translate IEnumerable to List
Clreplaced uClreplaced = new Clreplaced( majorAtt, majorSkills, minorSkills );
IEnumerable<XElement> baseDesiresData = from el in monsterData.Element( "base_desires" ).Elements( "desire_type" )
select el;
Dictionary<DesireType, int> baseDesires = new Dictionary<DesireType, int>();
foreach (XElement desireTypeE in baseDesiresData) {
Enum.TryParse( ReadAttribute( desireTypeE.FirstAttribute ), out DesireType desireType );
baseDesires.Add( desireType, System.Convert.ToInt32( ReadAttribute( desireTypeE.LastAttribute ) ) );
} // translate IEnumerable to List
return new Monster( map, position, worldIndex, currentFloor, color, sightDist, 3, baseDesires, uClreplaced, name, "male", diet, faction, graphic );
}
19
Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static Animal GetAnimal(string name, Block[] map, Point position, Point worldIndex, int currentFloor)
{
XElement creatureData = null;
// load all the creatures
XElement root = XElement.Load("res/data/OverworldCreatureTypes.xml");
IEnumerable<XElement> creatures =
from el in root.Elements("creature")
select el;
// choose the right creature
foreach (XElement c in creatures)
if (ReadAttribute(c.FirstAttribute).Equals(name))
creatureData = c;
if (creatureData == null)
return null;
byte graphic = System.Convert.ToByte(ReadAttribute(creatureData.Attribute("ascii_char")));
string faction = System.Convert.ToString(ReadAttribute(creatureData.Attribute("faction")));
int sightDist = System.Convert.ToInt32(ReadAttribute(creatureData.Attribute("sight_dist")));
byte r = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("r"))),
g = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("g"))),
b = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("b")));
Color? color = new Color(r, g, b);
Enum.TryParse(ReadElement(creatureData.Element("diet")), out DietType diet);
IEnumerable<XElement> majorAttData = from el in creatureData.Element("clreplaced").Element("major_attributes").Elements("attribute")
select el;
List<Attribute> majorAtt = new List<Attribute>();
foreach (XElement attE in majorAttData) {
Enum.TryParse(ReadElement(attE), out Attribute att);
majorAtt.Add(att);
}
IEnumerable<XElement> majorSkillsData = from el in creatureData.Element("clreplaced").Element("major_skills").Elements("skill")
select el;
List<Skill> majorSkills = new List<Skill>();
foreach (XElement skillE in majorSkillsData) {
Enum.TryParse(ReadElement(skillE), out Skill skill);
majorSkills.Add(skill);
}
IEnumerable<XElement> minorSkillsData = from el in creatureData.Element("clreplaced").Element("minor_skills").Elements("skill")
select el;
List<Skill> minorSkills = new List<Skill>();
foreach (XElement skillE in minorSkillsData) {
Enum.TryParse(ReadElement(skillE), out Skill skill);
minorSkills.Add(skill);
}
Clreplaced uClreplaced = new Clreplaced(majorAtt, majorSkills, minorSkills);
IEnumerable<XElement> baseDesiresData = from el in creatureData.Element("base_desires").Elements("desire_type")
select el;
Dictionary<DesireType, int> baseDesires = new Dictionary<DesireType, int>();
foreach (XElement desireTypeE in baseDesiresData) {
Enum.TryParse(ReadAttribute(desireTypeE.FirstAttribute), out DesireType desireType);
baseDesires.Add(desireType, System.Convert.ToInt32(ReadAttribute(desireTypeE.LastAttribute)));
}
return new Animal(map, position, worldIndex, currentFloor, color, sightDist, 3, baseDesires, uClreplaced, name, "male", diet, faction, graphic);
}
19
Source : Program.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private static async Task<int> RunClientAsync(ILogger logger, CancellationToken cancellationToken)
{
Console.Write("Connection Type [1] TCP, [2] RS485: ");
int cType = Convert.ToInt32(Console.ReadLine().Trim());
IModbusClient client = null;
try
{
switch (cType)
{
case 1:
{
Console.Write("Hostname: ");
string host = Console.ReadLine().Trim();
Console.Write("Port: ");
int port = Convert.ToInt32(Console.ReadLine().Trim());
client = new TcpClient(host, port, logger);
}
break;
case 2:
{
Console.Write("Interface: ");
string port = Console.ReadLine().Trim();
Console.Write("Baud: ");
int baud = Convert.ToInt32(Console.ReadLine().Trim());
Console.Write("Stop-Bits [0|1|2|3=1.5]: ");
int stopBits = Convert.ToInt32(Console.ReadLine().Trim());
Console.Write("Parity [0] None [1] Odd [2] Even [3] Mark [4] Space: ");
int parity = Convert.ToInt32(Console.ReadLine().Trim());
Console.Write("Handshake [0] None [1] X-On/Off [2] RTS [3] RTS+X-On/Off: ");
int handshake = Convert.ToInt32(Console.ReadLine().Trim());
Console.Write("Timeout (ms): ");
int timeout = Convert.ToInt32(Console.ReadLine().Trim());
Console.Write("Set Driver to RS485 [0] No [1] Yes: ");
int setDriver = Convert.ToInt32(Console.ReadLine().Trim());
client = new SerialClient(port)
{
BaudRate = (BaudRate)baud,
DataBits = 8,
StopBits = (StopBits)stopBits,
Parity = (Parity)parity,
Handshake = (Handshake)handshake,
SendTimeout = TimeSpan.FromMilliseconds(timeout),
ReceiveTimeout = TimeSpan.FromMilliseconds(timeout)
};
if (setDriver == 1)
{
((SerialClient)client).DriverEnableRS485 = true;
}
}
break;
default:
Console.Error.WriteLine($"Unknown type: {cType}");
return 1;
}
await Task.WhenAny(client.Connect(), Task.Delay(Timeout.Infinite, cancellationToken));
if (cancellationToken.IsCancellationRequested)
return 0;
while (!cancellationToken.IsCancellationRequested)
{
Console.Write("Device ID: ");
byte id = Convert.ToByte(Console.ReadLine().Trim());
Console.Write("Function [1] Read Register, [2] Device Info, [9] Write Register : ");
int fn = Convert.ToInt32(Console.ReadLine().Trim());
switch (fn)
{
case 1:
{
ushort address = 0;
ushort count = 0;
string type = "";
Console.WriteLine();
Console.Write("Address : ");
address = Convert.ToUInt16(Console.ReadLine().Trim());
Console.Write("DataType: ");
type = Console.ReadLine().Trim();
if (type == "string")
{
Console.Write("Register Count: ");
count = Convert.ToUInt16(Console.ReadLine().Trim());
}
Console.WriteLine();
Console.Write("Run as loop? [y/N]: ");
string loop = Console.ReadLine().Trim().ToLower();
int interval = 0;
if (yesList.Contains(loop))
{
Console.Write("Loop interval (milliseconds): ");
interval = Convert.ToInt32(Console.ReadLine().Trim());
}
Console.WriteLine();
do
{
try
{
Console.Write("Result : ");
List<Register> result = null;
switch (type.Trim().ToLower())
{
case "byte":
result = await client.ReadHoldingRegisters(id, address, 1);
Console.WriteLine(result?.First().GetByte());
break;
case "ushort":
result = await client.ReadHoldingRegisters(id, address, 1);
Console.WriteLine(result?.First().GetUInt16());
break;
case "uint":
result = await client.ReadHoldingRegisters(id, address, 2);
Console.WriteLine(result?.GetUInt32());
break;
case "ulong":
result = await client.ReadHoldingRegisters(id, address, 4);
Console.WriteLine(result?.GetUInt64());
break;
case "sbyte":
result = await client.ReadHoldingRegisters(id, address, 1);
Console.WriteLine(result?.First().GetSByte());
break;
case "short":
result = await client.ReadHoldingRegisters(id, address, 1);
Console.WriteLine(result?.First().GetInt16());
break;
case "int":
result = await client.ReadHoldingRegisters(id, address, 2);
Console.WriteLine(result?.GetInt32());
break;
case "long":
result = await client.ReadHoldingRegisters(id, address, 4);
Console.WriteLine(result?.GetInt64());
break;
case "float":
result = await client.ReadHoldingRegisters(id, address, 2);
Console.WriteLine(result?.GetSingle());
break;
case "double":
result = await client.ReadHoldingRegisters(id, address, 4);
Console.WriteLine(result?.GetDouble());
break;
case "string":
result = await client.ReadHoldingRegisters(id, address, count);
Console.WriteLine();
Console.WriteLine("UTF8: " + result?.GetString(count));
Console.WriteLine("Unicode: " + result?.GetString(count, 0, Encoding.Unicode));
Console.WriteLine("BigEndianUnicode: " + result?.GetString(count, 0, Encoding.BigEndianUnicode));
break;
default:
Console.Write("DataType unknown");
break;
}
}
catch
{ }
await Task.Delay(TimeSpan.FromMilliseconds(interval), cancellationToken);
}
while (interval > 0 && !cancellationToken.IsCancellationRequested);
}
break;
case 2:
{
Console.Write("[1] Basic, [2] Regular, [3] Extended: ");
int cat = Convert.ToInt32(Console.ReadLine().Trim());
Dictionary<DeviceIDObject, string> info = null;
switch (cat)
{
case 1:
info = await client.ReadDeviceInformation(id, DeviceIDCategory.Basic);
break;
case 2:
info = await client.ReadDeviceInformation(id, DeviceIDCategory.Regular);
break;
case 3:
info = await client.ReadDeviceInformation(id, DeviceIDCategory.Extended);
break;
}
if (info != null)
{
foreach (var kvp in info)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
}
}
break;
case 9:
{
Console.Write("Address: ");
ushort address = Convert.ToUInt16(Console.ReadLine().Trim());
Console.Write("Bytes (HEX): ");
string byteStr = Console.ReadLine().Trim();
byteStr = byteStr.Replace(" ", "").ToLower();
byte[] bytes = Enumerable.Range(0, byteStr.Length)
.Where(i => i % 2 == 0)
.Select(i => Convert.ToByte(byteStr.Substring(i, 2), 16))
.ToArray();
var registers = Enumerable.Range(0, bytes.Length)
.Where(i => i % 2 == 0)
.Select(i =>
{
return new Register
{
Type = ModbusObjectType.HoldingRegister,
Address = address++,
HiByte = bytes[i],
LoByte = bytes[i + 1]
};
})
.ToList();
if (!await client.WriteRegisters(id, registers))
throw new Exception($"Writing '{byteStr}' to address {address} failed");
}
break;
}
Console.Write("New Request? [y/N]: ");
string again = Console.ReadLine().Trim().ToLower();
if (!yesList.Contains(again))
return 0;
}
return 0;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return 0;
}
finally
{
Console.WriteLine("Disposing");
client?.Dispose();
Console.WriteLine("Disposed");
}
}
19
Source : AgnivoHelper.cs
with MIT License
from azist
with MIT License
from azist
private static byte[] getGDIDBytes(string str)
{
try
{
return Convert.FromBase64String(str);
}
catch (Exception)
{
}
return str.Split(new char[] {',', ' ', '"', '[', ']'}, StringSplitOptions.RemoveEmptyEntries)
.Select(e => Convert.ToByte(e))
.ToArray();
}
19
Source : 水印.cs
with Apache License 2.0
from becomequantum
with Apache License 2.0
from becomequantum
public bool 字符转基本参数(string[] s) {
try {
X百分比 = (float)Convert.ToDouble(s[0]);
Y百分比 = (float)Convert.ToDouble(s[1]);
大小百分比 = (float)Convert.ToDouble(s[2]);
string[] s颜色 = s[3].Split(',');
颜色 = Color.FromArgb(Convert.ToInt32(s颜色[0]), Convert.ToInt32(s颜色[1]), Convert.ToInt32(s颜色[2]));
透明度 = Convert.ToInt32(s[4]);
旋转角度 = Convert.ToInt32(s[5]);
横向复制个数 = Convert.ToInt32(s[6]);
纵向复制个数 = Convert.ToInt32(s[7]);
横向百分比间距 = (float)Convert.ToDouble(s[8]);
纵向百分比间距 = (float)Convert.ToDouble(s[9]);
string[] s点 = s[10].Split(',');
中心点.X = (float)Convert.ToDouble(s点[0]);
中心点.Y = (float)Convert.ToDouble(s点[1]);
string[] s大小 = s[11].Split(',');
大小.Width = (float)Convert.ToDouble(s大小[0]);
大小.Height = (float)Convert.ToDouble(s大小[1]);
透明度波动 = Convert.ToByte(s[12]);
return true;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
return false;
}
}
19
Source : CardDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private void GetBCards(string[] currentLine, CardDto card, byte max)
{
for (int i = 0; i < max; i++)
{
if (currentLine[2 + i * 6] == "-1" || currentLine[2 + i * 6] == "0")
{
continue;
}
int first = int.Parse(currentLine[i * 6 + 6]);
var bcard = new BCardDto
{
RelationType = BCardRelationType.Card,
RelationId = card.Id,
Type = (BCardType)byte.Parse(currentLine[2 + i * 6]),
SubType = (byte)((Convert.ToByte(currentLine[3 + i * 6]) + 1) * 10 + 1 + (first < 0 ? 1 : 0)),
FirstData = (first > 0 ? first : -first) / 4,
SecondData = int.Parse(currentLine[7 + i * 6]) / 4,
ThirdData = int.Parse(currentLine[5 + i * 6]),
IsLevelScaled = Convert.ToBoolean(first % 4),
IsLevelDivided = (first % 4) == 2
};
_cardBCardsCount++;
_cardBcards.Enqueue(bcard);
}
}
19
Source : CardDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private void GetBuff(string[] currentLine, CardDto card)
{
card.BuffType = (BuffType)Convert.ToByte(currentLine[3]);
}
19
Source : CardDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private void GetLevel(IReadOnlyList<string> currentLine, CardDto card)
{
card.Level = Convert.ToByte(currentLine[3]);
}
19
Source : MonsterDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private static void GetAInfo(IReadOnlyList<string> currentLine, NpcMonsterDto monster, long unknownData)
{
monster.DefenceUpgrade = Convert.ToByte(unknownData == 1 ? currentLine[2] : currentLine[3]);
}
19
Source : MonsterDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private static void GetWinfo(IReadOnlyList<string> currentLine, NpcMonsterDto monster, long unknownData)
{
monster.AttackUpgrade = Convert.ToByte(unknownData == 1 ? currentLine[2] : currentLine[4]);
}
19
Source : MonsterDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private static void GetZskill(IReadOnlyList<string> currentLine, NpcMonsterDto monster)
{
monster.AttackClreplaced = Convert.ToByte(currentLine[2]);
monster.BasicRange = Convert.ToByte(currentLine[3]);
monster.BasicArea = Convert.ToByte(currentLine[5]);
monster.BasicCooldown = Convert.ToInt16(currentLine[6]);
}
19
Source : MonsterDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private static void GetPetInfo(IReadOnlyList<string> currentLine, NpcMonsterDto monster, long unknownData)
{
if (monster.VNumRequired != 0 || unknownData != -2147481593 && unknownData != -2147481599 && unknownData != -1610610681)
{
return;
}
monster.VNumRequired = Convert.ToInt16(currentLine[2]);
monster.AmountRequired = Convert.ToByte(currentLine[3]);
}
19
Source : MonsterDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private void GetPreAtt(IReadOnlyList<string> currentLine, NpcMonsterDto monster)
{
monster.IsHostile = currentLine[2] == "1";
monster.IsHostileGroup = currentLine[3] != "0";
monster.NoticeRange = Convert.ToByte(currentLine[4]);
monster.Speed = Convert.ToByte(currentLine[5]);
monster.RespawnTime = Convert.ToInt32(currentLine[6]);
}
19
Source : MonsterDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private static void GetRace(IReadOnlyList<string> currentLine, NpcMonsterDto monster)
{
monster.Race = Convert.ToByte(currentLine[2]);
monster.RaceType = Convert.ToByte(currentLine[3]);
}
19
Source : MonsterDatConverter.cs
with GNU General Public License v3.0
from BlowaXD
with GNU General Public License v3.0
from BlowaXD
private void GetLevel(IReadOnlyList<string> currentLine, NpcMonsterDto monster)
{
monster.Level = Convert.ToByte(currentLine[2]);
}
19
Source : ValidateSubnetCalculatorSubnettingConverter.cs
with GNU General Public License v3.0
from BornToBeRoot
with GNU General Public License v3.0
from BornToBeRoot
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
// if Validation.HasError is true...
if ((bool)values[0] || (bool)values[1])
return false;
var subnet = values[2] as string;
var newSubnetmaskOrCidr = values[3] as string;
// Catch null exceptions...
if (string.IsNullOrEmpty(subnet) || string.IsNullOrEmpty(newSubnetmaskOrCidr))
return false;
// Get the cidr to compare...
var subnetData = subnet.Split('/');
var ipAddress = IPAddress.Parse(subnetData[0]);
var subnetmaskOrCidr = subnetData[1];
int cidr;
// ReSharper disable once SwitchStatementMissingSomeCases
switch (ipAddress.AddressFamily)
{
case System.Net.Sockets.AddressFamily.InterNetwork when subnetmaskOrCidr.Length < 3:
cidr = int.Parse(subnetmaskOrCidr);
break;
case System.Net.Sockets.AddressFamily.InterNetwork:
cidr = Subnetmask.ConvertSubnetmaskToCidr(IPAddress.Parse(subnetmaskOrCidr));
break;
default:
cidr = int.Parse(subnetmaskOrCidr);
break;
}
int newCidr;
// Support subnetmask like 255.255.255.0
if (Regex.IsMatch(newSubnetmaskOrCidr, RegexHelper.SubnetmaskRegex))
newCidr = System.Convert.ToByte(Subnetmask.ConvertSubnetmaskToCidr(IPAddress.Parse(newSubnetmaskOrCidr)));
else
newCidr = System.Convert.ToByte(newSubnetmaskOrCidr.TrimStart('/'));
// Compare
return newCidr > cidr;
}
19
Source : SubnetCalculatorSubnettingViewModel.cs
with GNU General Public License v3.0
from BornToBeRoot
with GNU General Public License v3.0
from BornToBeRoot
private async Task Calculate()
{
IsStatusMessageDisplayed = false;
IsCalculationRunning = true;
SubnetsResult.Clear();
var subnet = IPNetwork.Parse(Subnet);
byte newCidr = 0;
// Support subnetmask like 255.255.255.0
if (Regex.IsMatch(NewSubnetmaskOrCIDR, RegexHelper.SubnetmaskRegex))
newCidr = Convert.ToByte(Subnetmask.ConvertSubnetmaskToCidr(IPAddress.Parse(NewSubnetmaskOrCIDR)));
else
newCidr = Convert.ToByte(NewSubnetmaskOrCIDR.TrimStart('/'));
// Ask the user if there is a large calculation...
var baseCidr = subnet.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? 32 : 128;
if (65535 < Math.Pow(2, baseCidr - subnet.Cidr) / Math.Pow(2, (baseCidr - newCidr)))
{
var settings = AppearanceManager.MetroDialog;
settings.AffirmativeButtonText = Localization.Resources.Strings.Continue;
settings.NegativeButtonText = Localization.Resources.Strings.Cancel;
settings.DefaultButtonFocus = MessageDialogResult.Affirmative;
if (await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.AreYouSure, Localization.Resources.Strings.TheProcessCanTakeUpSomeTimeAndResources, MessageDialogStyle.AffirmativeAndNegative, settings) != MessageDialogResult.Affirmative)
{
IsCalculationRunning = false;
return;
}
}
// This still slows the application / freezes the ui... there are to many updates to the ui thread...
await Task.Run(() =>
{
foreach (var network in subnet.Subnet(newCidr))
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate
{
//lock (SubnetsResult)
SubnetsResult.Add(new IPNetworkInfo(network));
}));
}
});
IsResultVisible = true;
AddSubnetToHistory(Subnet);
AddNewSubnetmaskOrCIDRToHistory(NewSubnetmaskOrCIDR);
IsCalculationRunning = false;
}
19
Source : Test.cs
with Apache License 2.0
from bubibubi
with Apache License 2.0
from bubibubi
[TestMethod]
public void Convert_ToByte()
{
var e = Context.Enreplacedies;
// ReSharper disable ConditionIsAlwaysTrueOrFalse
e.Select(o => new {a = Convert.ToByte(Convert.ToByte(o.Id % 1)) >= 0})
.ToList();
e.Select(o => new {a = Convert.ToByte(Convert.ToDecimal(o.Id % 1)) >= 0})
.ToList();
e.Select(o => new {a = Convert.ToByte(Convert.ToDouble(o.Id % 1)) >= 0})
.ToList();
e.Select(o => new {a = Convert.ToByte((float) Convert.ToDouble(o.Id % 1)) >= 0})
.ToList();
e.Select(o => new {a = Convert.ToByte(Convert.ToInt16(o.Id % 1)) >= 0})
.ToList();
e.Select(o => new {a = Convert.ToByte(Convert.ToInt32(o.Id % 1)) >= 0})
.ToList();
e.Select(o => new {a = Convert.ToByte(Convert.ToInt64(o.Id % 1)) >= 0})
.ToList();
e.Select(o => new {a = Convert.ToByte(Convert.ToString(o.Id % 1)) >= 0})
.ToList();
// ReSharper restore ConditionIsAlwaysTrueOrFalse
}
19
Source : Client.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private object ConvertToValue(string value,int type)
{
var tp = (Cdy.Tag.TagType)type;
switch (tp)
{
case TagType.Bool:
return Convert.ToBoolean(value);
case TagType.Byte:
return Convert.ToByte(value);
case TagType.DateTime:
return DateTime.Parse(value);
case TagType.Double:
return double.Parse(value);
case TagType.Float:
return float.Parse(value);
case TagType.Int:
return Int32.Parse(value);
case TagType.IntPoint:
string[] ss = value.Split(new char[] { ',' });
return new IntPointData(int.Parse(ss[0]), int.Parse(ss[1]));
case TagType.IntPoint3:
ss = value.Split(new char[] { ',' });
return new IntPoint3Data(int.Parse(ss[0]), int.Parse(ss[1]), int.Parse(ss[2]));
case TagType.Long:
return long.Parse(value);
case TagType.LongPoint:
ss = value.Split(new char[] { ',' });
return new LongPointData(long.Parse(ss[0]), long.Parse(ss[1]));
case TagType.LongPoint3:
ss = value.Split(new char[] { ',' });
return new LongPoint3Data(long.Parse(ss[0]), long.Parse(ss[1]), long.Parse(ss[2]));
case TagType.Short:
return short.Parse(value);
case TagType.String:
return value;
case TagType.UInt:
return UInt32.Parse(value);
case TagType.UIntPoint:
ss = value.Split(new char[] { ',' });
return new UIntPointData(uint.Parse(ss[0]), uint.Parse(ss[1]));
case TagType.UIntPoint3:
ss = value.Split(new char[] { ',' });
return new UIntPoint3Data(uint.Parse(ss[0]), uint.Parse(ss[1]), uint.Parse(ss[2]));
case TagType.ULong:
return ulong.Parse(value);
case TagType.ULongPoint:
ss = value.Split(new char[] { ',' });
return new ULongPointData(ulong.Parse(ss[0]), ulong.Parse(ss[1]));
case TagType.ULongPoint3:
ss = value.Split(new char[] { ',' });
return new ULongPoint3Data(ulong.Parse(ss[0]), ulong.Parse(ss[1]), ulong.Parse(ss[2]));
case TagType.UShort:
return ushort.Parse(value);
}
return null;
}
19
Source : Proxy.cs
with MIT License
from citronneur
with MIT License
from citronneur
private static ProxyConfig ParseConfig()
{
if (Config == null)
{
// retrieve Proxy address
string[] proxyConfig = System.Environment.GetEnvironmentVariable("SOCKS5_PROXY").Split(':');
if (proxyConfig.Length != 2)
{
throw new Exception("Bad IP format for SOCKS5_PROXY");
}
byte[] ip = proxyConfig[0].Split('.').Select(x => Convert.ToByte(x)).ToArray();
if (ip.Length != 4)
{
throw new Exception("Bad IP format for SOCKS5_PROXY");
}
Config = new ProxyConfig()
{
proxyAddress = new Socket.in_addr()
{
s_b1 = ip[0],
s_b2 = ip[1],
s_b3 = ip[2],
s_b4 = ip[3]
},
proxyPort = Convert.ToUInt16(proxyConfig[1])
};
}
return Config;
}
19
Source : MonFilesMonsterLoader.cs
with MIT License
from CoreOpenMMO
with MIT License
from CoreOpenMMO
Dictionary<ushort, MonsterType> IMonsterLoader.LoadMonsters(string loadFromFile)
{
if (string.IsNullOrWhiteSpace(loadFromFile))
{
throw new ArgumentNullException(nameof(loadFromFile));
}
var monsFilePattern = "COMMO.Server.Data." + ServerConfiguration.MonsterFilesDirectory;
var replacedembly = replacedembly.GetExecutingreplacedembly();
var monsterDictionary = new Dictionary<ushort, MonsterType>();
var monsterFilePaths = replacedembly.GetManifestResourceNames().Where(s => s.Contains(monsFilePattern));
foreach (var monsterFilePath in monsterFilePaths)
{
using (var stream = replacedembly.GetManifestResourceStream(monsterFilePath))
{
if (stream == null)
{
throw new Exception($"Failed to load {monsterFilePath}.");
}
using (var reader = new StreamReader(stream))
{
var dataList = new List<Tuple<string, string>>();
var propName = string.Empty;
var propData = string.Empty;
foreach (var readLine in reader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
{
var inLine = readLine?.Split(new[] { ObjectsFileItemLoader.CommentSymbol }, 2).FirstOrDefault();
// ignore comments and empty lines.
if (string.IsNullOrWhiteSpace(inLine))
{
continue;
}
var data = inLine.Split(new[] { ObjectsFileItemLoader.PropertyValueSeparator }, 2);
if (data.Length > 2)
{
throw new Exception($"Malformed line [{inLine}] in objects file: [{monsterFilePath}]");
}
if (data.Length == 1)
{
// line is a continuation of the last prop.
propData += data[0].ToLower().Trim();
}
else
{
if (propName.Length > 0 && propData.Length > 0)
{
dataList.Add(new Tuple<string, string>(propName, propData));
}
propName = data[0].ToLower().Trim();
propData = data[1].Trim();
}
}
if (propName.Length > 0 && propData.Length > 0)
{
dataList.Add(new Tuple<string, string>(propName, propData));
}
var current = new MonsterType();
foreach (var tuple in dataList)
{
switch (tuple.Item1)
{
case "racenumber":
current.SetId(Convert.ToUInt16(tuple.Item2));
break;
case "name":
current.SetName(tuple.Item2.Trim('\"'));
break;
case "article":
current.SetArticle(tuple.Item2.Trim('\"'));
break;
case "outfit":
current.SetOutfit(tuple.Item2.Trim('(', ')'));
break;
case "corpse":
current.SetCorpse(Convert.ToUInt16(tuple.Item2));
break;
case "blood":
current.SetBlood(tuple.Item2);
break;
case "experience":
current.SetExperience(Convert.ToUInt32(tuple.Item2));
break;
case "summoncost":
current.SetSummonCost(Convert.ToUInt16(tuple.Item2));
break;
case "fleethreshold":
current.SetFleeTreshold(Convert.ToUInt16(tuple.Item2));
break;
case "attack":
current.SetAttack(Convert.ToUInt16(tuple.Item2));
break;
case "defend":
current.SetDefend(Convert.ToUInt16(tuple.Item2));
break;
case "armor":
current.SetArmor(Convert.ToUInt16(tuple.Item2));
break;
case "poison":
current.SetConditionInfect(Convert.ToUInt16(tuple.Item2), ConditionType.Posion);
break;
case "losetarget":
current.SetLoseTarget(Convert.ToByte(tuple.Item2));
break;
case "strategy":
current.SetStrategy(tuple.Item2.Trim('(', ')'));
break;
case "flags":
current.SetFlags(tuple.Item2.Trim('{', '}'));
break;
case "skills":
current.SetSkills(tuple.Item2.Trim('{', '}'));
break;
case "spells":
current.SetSpells(tuple.Item2.Trim('{', '}'));
break;
case "inventory":
current.SetInventory(tuple.Item2.Trim('{', '}'));
break;
case "talk":
current.SetPhrases(tuple.Item2.Trim('{', '}'));
break;
}
}
current.LockChanges();
monsterDictionary.Add(current.RaceId, current);
}
}
}
return monsterDictionary;
}
19
Source : MonsterType.cs
with MIT License
from CoreOpenMMO
with MIT License
from CoreOpenMMO
internal void SetOutfit(string outfitStr)
{
if (Locked)
{
throw new InvalidOperationException("This MonsterType is locked and cannot be altered.");
}
// comes in the form
// 68, 0-0-0-0
var splitStr = outfitStr.Split(new[] { ',' }, 2);
var outfitId = Convert.ToUInt16(splitStr[0]);
var outfitSections = splitStr[1].Split('-').Select(s => Convert.ToByte(s)).ToArray();
if (outfitId == 0)
{
Outfit = new Outfit
{
Id = outfitId,
LikeType = outfitSections[0]
};
}
else
{
Outfit = new Outfit
{
Id = outfitId,
Head = outfitSections[0],
Body = outfitSections[1],
Legs = outfitSections[2],
Feet = outfitSections[3]
};
}
}
19
Source : MonsterType.cs
with MIT License
from CoreOpenMMO
with MIT License
from CoreOpenMMO
internal void SetStrategy(string strategyStr)
{
if (Locked)
{
throw new InvalidOperationException("This MonsterType is locked and cannot be altered.");
}
// comes in the form
// 70, 30, 0, 0
var strat = strategyStr.Split(',').Select(s => Convert.ToByte(s)).ToArray();
if (strat.Length != 4)
{
throw new InvalidDataException($"Unexpected number of elements in Strategy value {strategyStr} on monster type {Name}.");
}
Strategy = new Tuple<byte, byte, byte, byte>(strat[0], strat[1], strat[2], strat[3]);
}
19
Source : GenericObjectToTypeConverter.cs
with MIT License
from craigbridges
with MIT License
from craigbridges
private T ConvertFromString(string value)
{
var convertedValue = default(object);
var convertType = typeof(T);
if (String.IsNullOrEmpty(value))
{
return default(T);
}
if (convertType.IsNullable())
{
convertType = Nullable.GetUnderlyingType(convertType);
}
if (convertType == typeof(DateTime))
{
convertedValue = System.Convert.ToDateTime(value);
}
else if (convertType == typeof(bool))
{
convertedValue = System.Convert.ToBoolean(value);
}
else if (convertType == typeof(double))
{
convertedValue = System.Convert.ToDouble(value);
}
else if (convertType == typeof(Single))
{
convertedValue = System.Convert.ToSingle(value);
}
else if (convertType == typeof(decimal))
{
convertedValue = System.Convert.ToDecimal(value);
}
else if (convertType == typeof(long))
{
convertedValue = System.Convert.ToInt64(value);
}
else if (convertType == typeof(int))
{
convertedValue = System.Convert.ToInt32(value);
}
else if (convertType == typeof(short))
{
convertedValue = System.Convert.ToInt16(value);
}
else if (convertType == typeof(char))
{
convertedValue = System.Convert.ToChar(value);
}
else if (convertType == typeof(byte))
{
convertedValue = System.Convert.ToByte(value);
}
else if (convertType.IsEnum)
{
convertedValue = Enum.Parse(convertType, value);
}
else
{
RaiseCannotConvertException(value);
}
return (T)convertedValue;
}
19
Source : GenericObjectConverter.cs
with MIT License
from craigbridges
with MIT License
from craigbridges
private T ConvertFromString(string value)
{
var convertedValue = default(object);
var convertType = typeof(T);
if (String.IsNullOrEmpty(value))
{
return default;
}
if (convertType.IsNullable())
{
convertType = Nullable.GetUnderlyingType(convertType);
}
if (convertType == typeof(DateTime))
{
convertedValue = System.Convert.ToDateTime(value);
}
else if (convertType == typeof(bool))
{
convertedValue = System.Convert.ToBoolean(value);
}
else if (convertType == typeof(double))
{
convertedValue = System.Convert.ToDouble(value);
}
else if (convertType == typeof(Single))
{
convertedValue = System.Convert.ToSingle(value);
}
else if (convertType == typeof(decimal))
{
convertedValue = System.Convert.ToDecimal(value);
}
else if (convertType == typeof(long))
{
convertedValue = System.Convert.ToInt64(value);
}
else if (convertType == typeof(int))
{
convertedValue = System.Convert.ToInt32(value);
}
else if (convertType == typeof(short))
{
convertedValue = System.Convert.ToInt16(value);
}
else if (convertType == typeof(char))
{
convertedValue = System.Convert.ToChar(value);
}
else if (convertType == typeof(byte))
{
convertedValue = System.Convert.ToByte(value);
}
else if (convertType.IsEnum)
{
convertedValue = Enum.Parse(convertType, value);
}
else
{
RaiseCannotConvertException(value);
}
return (T)convertedValue;
}
19
Source : ColourSelection.cs
with MIT License
from cwensley
with MIT License
from cwensley
protected override void OnKeyDown(KeyEventArgs e)
{
if (!e.Handled && ShowBackground)
{
switch (e.KeyData)
{
case Keys.Right:
if (attribute.Background < pal.Count - 1)
attribute.Background++;
e.Handled = true;
break;
case Keys.Left:
if (attribute.Background > 0)
attribute.Background--;
e.Handled = true;
break;
}
if (e.Handled)
backText = attribute.Background.ToString();
}
if (!e.Handled && ShowForeground)
{
switch (e.KeyData)
{
case Keys.Up:
if (attribute.Foreground < pal.Count - 1)
attribute.Foreground++;
e.Handled = true;
break;
case Keys.Down:
if (attribute.Foreground > 0)
attribute.Foreground--;
e.Handled = true;
break;
}
if (e.Handled)
foreText = attribute.Foreground.ToString();
}
if (!e.Handled)
{
if (foreSelected && ShowForeground)
{
ParseValue(ref foreText, e);
if (e.Handled && foreText.Length > 0)
attribute.Foreground = Convert.ToByte(foreText);
if (e.KeyData == Keys.Enter)
{
e.Handled = true;
if (ShowBackground)
foreSelected = false;
else
OnSelected(EventArgs.Empty);
}
}
else if (ShowBackground)
{
ParseValue(ref backText, e);
if (e.Handled && backText.Length > 0)
attribute.Background = Convert.ToByte(backText);
if (!e.Handled && e.KeyData == Keys.Backspace && backText.Length == 0)
{
foreSelected = true;
e.Handled = true;
}
if (e.KeyData == Keys.Enter)
{
e.Handled = true;
OnSelected(EventArgs.Empty);
}
}
}
if (e.Handled)
{
OnChanged(EventArgs.Empty);
Invalidate();
}
base.OnKeyDown(e);
}
19
Source : AddrParser.cs
with BSD 3-Clause "New" or "Revised" License
from dabi0ne
with BSD 3-Clause "New" or "Revised" License
from dabi0ne
public static HashSet<string> ParseRange(string target, bool cidr = false)
{
HashSet<string> result = new HashSet<string>();
int RangeCount = 0;
string[] IPStart = target.Split('.');
string[] IPEnd = new string[4];
string IPStrByte = "";
byte RStartByte = 0;
byte REndByte = 0;
string[] tmp = new string[2];
if (IPStart.Length != 4)
{
throw new Exception("IP format error : " + target);
}
for (int i = 0; i < IPStart.Length; i++)
{
IPStrByte = IPStart[i];
RangeCount = IPStrByte.Count(c => c == '-');
if (RangeCount > 1)
{
throw new Exception("Range syntax error : too many '-' on " + target);
}
else if (RangeCount == 1)
{
tmp = IPStrByte.Split('-');
RStartByte = Convert.ToByte(tmp[0]);
REndByte = Convert.ToByte(tmp[1]);
if (
(
(i != 3 && RStartByte >= 0)
||
(i == 3 && RStartByte > 0)
||
(cidr && REndByte >= 0)
)
&&
RStartByte < 255 && REndByte > 0 && REndByte < 255 && RStartByte <= REndByte
)
{
IPStart[i] = tmp[0];
IPEnd[i] = tmp[1];
}
else
{
throw new Exception("Invalid range : " + target);
}
}
else
{
REndByte = Convert.ToByte(IPStrByte);
if (
(
(i != 3 && REndByte >= 0)
||
(i == 3 && REndByte > 0)
||
(cidr && REndByte >= 0)
)
&& REndByte < 255
)
{
IPEnd[i] = IPStrByte;
}
else
{
throw new Exception("Invalid target : " + target);
}
}
}
byte[] IPStartBytes = new byte[] { Convert.ToByte(IPStart[0]), Convert.ToByte(IPStart[1]), Convert.ToByte(IPStart[2]), Convert.ToByte(IPStart[3]) };
byte[] IPEndBytes = new byte[] { Convert.ToByte(IPEnd[0]), Convert.ToByte(IPEnd[1]), Convert.ToByte(IPEnd[2]), Convert.ToByte(IPEnd[3]) };
for (byte b1 = IPStartBytes[0]; b1 <= IPEndBytes[0]; b1++)
{
for (byte b2 = IPStartBytes[1]; b2 <= IPEndBytes[1]; b2++)
{
for (byte b3 = IPStartBytes[2]; b3 <= IPEndBytes[2]; b3++)
{
for (byte b4 = IPStartBytes[3]; b4 <= IPEndBytes[3]; b4++)
{
result.Add(b1.ToString() + "." + b2.ToString() + "." + b3.ToString() + "." + b4.ToString());
}
}
}
}
return result;
}
19
Source : converter.cs
with GNU General Public License v2.0
from devmvalvm
with GNU General Public License v2.0
from devmvalvm
public string conv_byte_to_hex(string text)
{
int temp= System.Convert.ToByte(text);
if (temp < 255)
{
return temp.ToString("X2");
}
else
return "";
}
19
Source : BasicConvert.Overload.cs
with MIT License
from Dogwei
with MIT License
from Dogwei
byte IXConverter<string, byte>.Convert(string value)
=> Convert.ToByte(value);
19
Source : Server.cs
with MIT License
from Exo-poulpe
with MIT License
from Exo-poulpe
private void ReceiveFile(string data, string path)
{
string[] textValue = data.Split(SeparatorChar);
byte[] fileData = new byte[textValue.Length];
for (int i = 0; i < textValue.Length - 1; i++)
{
fileData[i] = Convert.ToByte(textValue[i]);
}
string dir = path.Substring(0, path.LastIndexOf('\\'));
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllBytes(path, fileData);
}
19
Source : MqttClientPlugin.cs
with MIT License
from fvanroie
with MIT License
from fvanroie
[DllExport]
public static IntPtr Publish(IntPtr data, int argc,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] argv)
{
Measure measure = (Measure)GCHandle.FromIntPtr(data).Target;
//If we are given two or more arguments
if (argc == 1)
{
measure.Publish(argv[0], "");
//measure.buffer = Marshal.StringToHGlobalUni("Pub");
}
else if (argc == 2)
{
measure.Publish(argv[0], argv[1]);
//measure.buffer = Marshal.StringToHGlobalUni("Pub");
}
//If we are given more arguments
else if (argc == 3 || argc == 4)
{
// try convert the string to a byte
try
{
var qos = Convert.ToByte(argv[2]);
if (argc == 3)
measure.Publish(argv[0], argv[1], qos);
else
{
bool retained = argv[3].ToLower() == "true" || argv[3] == "1";
measure.Publish(argv[0], argv[1], qos, retained);
}
}
catch
{
measure.Publish(argv[0], argv[1]);
}
}
else
{
measure.Publish("atopic", "avalue");
//measure.buffer = Marshal.StringToHGlobalUni("Arg count must be 2");
}
return Marshal.StringToHGlobalUni("");
}
19
Source : MqttClientMeasure.cs
with MIT License
from fvanroie
with MIT License
from fvanroie
internal override void ExecuteBang(String args)
{
Log(API.LogType.Notice, "Execute Bang: " + args);
if (args.ToLower().StartsWith("publish("))
{
// format: publish(a,b,c,d)
args = args.Substring(8).Trim(')');
string[] arglist = args.Split(',');
if (arglist.Length == 2)
Publish(arglist[0], arglist[1], 0, false);
if (arglist.Length == 3 || arglist.Length == 4)
{
try
{
var qos = Convert.ToByte(arglist[2]);
if (arglist.Length == 3)
{
Publish(arglist[0], arglist[1], qos);
}
else
{
bool retained = arglist[3].ToLower() == "true" || arglist[3] == "1";
Publish(arglist[0], arglist[1], qos, retained);
}
}
catch
{
Publish(arglist[0], arglist[1], 0, false);
}
}
}
}
19
Source : dns.cs
with GNU Lesser General Public License v2.1
from Gannio
with GNU Lesser General Public License v2.1
from Gannio
private void Spoof()
{
// Setup some variables.
const char character = (char)0;
var leave = false;
var ipBytes = new byte[4];
var ipAddr = IP.Split('.');
var allowedHosts = new[]
{
"conntest.nintendowifi.net", "syachi2ds.available.nintendowifi.net",
"gamestats2.gs.nintendowifi.net", "nas.nintendowifi.net", "gpcm.gs.nintendowifi.net",
"pkvldtprod.nintendo.co.jp", "syachi2ds.available.gs.nintendowifi.net"
};
// Spoofer bytes.
for (var i = 0; i < 4; i++)
ipBytes[i] = Convert.ToByte(ipAddr[i]);
// create our encoding type.
var encoding = Encoding.GetEncoding("iso-8859-1");
// var encoding = Encoding.UTF8;
// infinite loop
while (!leave)
{
try
{
// We're gonna need these to be constantly reinitialized.
var rawHost = string.Empty;
var epInitialize = new IPEndPoint(IPAddress.Any, 0);
var anyEndPoint = (EndPoint)epInitialize;
// reinitialize our request array
var clientRequest = new byte[_dnsServer.ReceiveBufferSize];
// grab the client requests
var receiveLength = _dnsServer.ReceiveFrom(clientRequest, SocketFlags.None,
ref anyEndPoint);
// reize
Array.Resize(ref clientRequest, receiveLength);
// encoding time.
var requestString = encoding.GetString(clientRequest);
var host = requestString.Substring(12, requestString.IndexOf(character, 12) - 12);
var n = 0;
while (n < host.Length)
{
rawHost += host.Substring(n + 1, clientRequest[n + 12]) + ".";
n += clientRequest[n + 12] + 1;
}
rawHost = rawHost.Trim('.').Trim();
// log quickly
// WriteLog(string.Format("Incoming data from {0}!", ((IPEndPoint) anyEndPoint).Address));
WriteLog(string.Format("{0} has requested {1}!", ((IPEndPoint)anyEndPoint).Address, rawHost));
// Check to see if this person is legitimate.
if (allowedHosts.Contains(rawHost.Trim()))
{
WriteLog("This is a valid request.");
// Okay, legitimate. Let's keep going
// Get nintendo's response.
var altServerReply = new byte[_altServer.ReceiveBufferSize];
// GANNIO: Changed, create the connection to the Alternate WFC server for verification process.
_altServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { ReceiveTimeout = 2000, SendTimeout = 2000 };
_altServer.Connect(OpenDNS, 53);
_altServer.Send(clientRequest, clientRequest.Length, SocketFlags.None);
// reply
var altServerReceiveLength = _altServer.Receive(altServerReply, SocketFlags.None);
// resize
Array.Resize(ref altServerReply, altServerReceiveLength);
// check
if (rawHost == "gamestats2.gs.nintendowifi.net")
Array.Copy(ipBytes, 0, altServerReply, 0x3c, 4);
// get the client reply ready
// var clientReply = encoding.GetString(nintendoReply);
// log
// WriteLog(string.Format("Sending reply to {0}!", ((IPEndPoint) anyEndPoint).Address));
// send it off
_dnsServer.SendTo(altServerReply, anyEndPoint);
}
else
{
WriteLog("Invalid Request! " + rawHost.Trim());
}
}
catch (ThreadAbortException)
{
// leave...
WriteLog("The DNS system has received a shutdown request.");
leave = true;
_dnsServer.Close();
_dnsServer.Dispose();
Shutdown(this, new EventArgs());
}
catch (Exception e)
{
Exception(this, new DnsExceptionDataEventArgs { ErrorMessage = "Shiny2 has run into a problem", Exception = e });
}
}
}
19
Source : ObjectExtensions.cs
with MIT License
from gordon-matt
with MIT License
from gordon-matt
public static void SetPropertyValue<T>(this T obj, PropertyInfo property, object value)
{
var propertyType = property.PropertyType;
string valuereplacedtring = value.ToString();
if (propertyType == typeof(String))
{
property.SetValue(obj, valuereplacedtring, null);
}
else if (propertyType == typeof(Int32))
{
property.SetValue(obj, Convert.ToInt32(valuereplacedtring), null);
}
else if (propertyType == typeof(Guid))
{
property.SetValue(obj, new Guid(valuereplacedtring), null);
}
else if (propertyType.GetTypeInfo().IsEnum)
{
var enumValue = Enum.Parse(propertyType, valuereplacedtring);
property.SetValue(obj, enumValue, null);
}
else if (propertyType == typeof(Boolean))
{
property.SetValue(obj, Convert.ToBoolean(valuereplacedtring), null);
}
else if (propertyType == typeof(DateTime))
{
property.SetValue(obj, Convert.ToDateTime(valuereplacedtring), null);
}
else if (propertyType == typeof(Single))
{
property.SetValue(obj, Convert.ToSingle(valuereplacedtring), null);
}
else if (propertyType == typeof(Decimal))
{
property.SetValue(obj, Convert.ToDecimal(valuereplacedtring), null);
}
else if (propertyType == typeof(Byte))
{
property.SetValue(obj, Convert.ToByte(valuereplacedtring), null);
}
else if (propertyType == typeof(Int16))
{
property.SetValue(obj, Convert.ToInt16(valuereplacedtring), null);
}
else if (propertyType == typeof(Int64))
{
property.SetValue(obj, Convert.ToInt64(valuereplacedtring), null);
}
else if (propertyType == typeof(Double))
{
property.SetValue(obj, Convert.ToDouble(valuereplacedtring), null);
}
else if (propertyType == typeof(UInt32))
{
property.SetValue(obj, Convert.ToUInt32(valuereplacedtring), null);
}
else if (propertyType == typeof(UInt16))
{
property.SetValue(obj, Convert.ToUInt16(valuereplacedtring), null);
}
else if (propertyType == typeof(UInt64))
{
property.SetValue(obj, Convert.ToUInt64(valuereplacedtring), null);
}
else if (propertyType == typeof(SByte))
{
property.SetValue(obj, Convert.ToSByte(valuereplacedtring), null);
}
else if (propertyType == typeof(Char))
{
property.SetValue(obj, Convert.ToChar(valuereplacedtring), null);
}
else if (propertyType == typeof(TimeSpan))
{
property.SetValue(obj, TimeSpan.Parse(valuereplacedtring), null);
}
else if (propertyType == typeof(Uri))
{
property.SetValue(obj, new Uri(valuereplacedtring), null);
}
else
{
property.SetValue(obj, Convert.ChangeType(value, property.PropertyType));
//property.SetValue(item, value, null);
}
}
19
Source : Form1.cs
with MIT License
from HackingThings
with MIT License
from HackingThings
private void bgw_DoSniffing()
{
try
{
port.Open();
ws = new Wireshark.WiresharkSender(tbPipeName.Text, 227);
while (true)
{
if (ws.isConnected)
{
try
{
string line = port.ReadLine();
line = line.Replace("\r", string.Empty);
string[] lines = line.Split('|');
Int32 canid = Convert.ToInt32(lines[0]);
byte[] id = new byte[4];
id = BitConverter.GetBytes(canid);
lines = lines[1].Split(' ');
byte[] data = new byte[lines.Length - 1];
for (int i = 0; i < data.Length; i++)
{
if (lines[i] != "")
{
data[i] = Convert.ToByte(lines[i]);
}
}
byte[] pcap = new byte[4 + 4 + data.Length];
pcap[0] = id[3];
pcap[1] = id[2];
pcap[2] = id[1];
pcap[3] = id[0];
pcap[4] = Convert.ToByte(data.Length);
pcap[5] = 0;
pcap[6] = 0;
pcap[7] = 0;
for (int i = 8; i < pcap.Length; i++)
{
pcap[i] = data[i - 8];
}
ws.SendToWireshark(pcap, 0, pcap.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message);
}
}
19
Source : RegionProfileServiceProxy.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
private RegionProfileData RequestSimData(Uri gridserverUrl, string gridserverSendkey, string keyField, string keyValue)
{
Hashtable requestData = new Hashtable();
requestData[keyField] = keyValue;
requestData["authkey"] = gridserverSendkey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
string methodName = "simulator_data_request";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(gridserverUrl.ToString(), methodName), 5000);
Hashtable responseData = (Hashtable) GridResp.Value;
RegionProfileData simData = null;
if (!responseData.ContainsKey("error"))
{
uint locX = Convert.ToUInt32((string)responseData["region_locx"]);
uint locY = Convert.ToUInt32((string)responseData["region_locy"]);
string externalHostName = (string)responseData["sim_ip"];
uint simPort = Convert.ToUInt32((string)responseData["sim_port"]);
uint httpPort = Convert.ToUInt32((string)responseData["http_port"]);
uint remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]);
UUID regionID = new UUID((string)responseData["region_UUID"]);
string regionName = (string)responseData["region_name"];
byte access = Convert.ToByte((string)responseData["access"]);
ProductRulesUse product = (ProductRulesUse)Convert.ToInt32(responseData["product"]);
string outsideIp = null;
if (responseData.ContainsKey("outside_ip"))
outsideIp = (string)responseData["outside_ip"];
simData = RegionProfileData.Create(regionID, regionName, locX, locY, externalHostName, simPort, httpPort, remotingPort, access, product, outsideIp);
}
return simData;
}
19
Source : UserInventoryItemSerializer.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
public static InventoryItemBase Deserialize(string serialization)
{
InventoryItemBase item = new InventoryItemBase();
StringReader sr = new StringReader(serialization);
XmlTextReader xtr = new XmlTextReader(sr);
xtr.ReadStartElement("InventoryItem");
item.Name = xtr.ReadElementString("Name");
item.ID = UUID.Parse( xtr.ReadElementString("ID"));
item.InvType = Convert.ToInt32( xtr.ReadElementString("InvType"));
item.CreatorId = xtr.ReadElementString("CreatorUUID");
item.CreationDate = Convert.ToInt32( xtr.ReadElementString("CreationDate"));
item.Owner = UUID.Parse( xtr.ReadElementString("Owner"));
item.Description = xtr.ReadElementString("Description");
item.replacedetType = Convert.ToInt32( xtr.ReadElementString("replacedetType"));
item.replacedetID = UUID.Parse( xtr.ReadElementString("replacedetID"));
item.SaleType = Convert.ToByte( xtr.ReadElementString("SaleType"));
item.SalePrice = Convert.ToInt32( xtr.ReadElementString("SalePrice"));
item.BasePermissions = Convert.ToUInt32( xtr.ReadElementString("BasePermissions"));
item.CurrentPermissions = Convert.ToUInt32( xtr.ReadElementString("CurrentPermissions"));
item.EveryOnePermissions = Convert.ToUInt32( xtr.ReadElementString("EveryOnePermissions"));
item.NextPermissions = Convert.ToUInt32( xtr.ReadElementString("NextPermissions"));
item.Flags = Convert.ToUInt32( xtr.ReadElementString("Flags"));
item.GroupID = UUID.Parse( xtr.ReadElementString("GroupID"));
item.GroupOwned = Convert.ToBoolean(xtr.ReadElementString("GroupOwned"));
xtr.ReadEndElement();
xtr.Close();
sr.Close();
return item;
}
19
Source : AvatarSearchModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
public void DirClreplacedifiedQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, uint category,
int queryStart)
{
// This is pretty straightforward here, get the input, set up the query, run it through, send back to viewer.
string query = String.Empty;
string sqlAddTerms = String.Empty;
string userText = queryText.Trim(); // newer viewers sometimes append a space
string searchStart = Convert.ToString(queryStart);
int count = MAX_RESULTS + 1; // +1 so that the viewer knows to enable the NEXT button (it seems)
string searchEnd = Convert.ToString(queryStart + count);
int i = 0;
// There is a slight issue with the parcel data not coming from land first so the
// parcel information is never displayed correctly within in the clreplacedified ad.
//stop blank queries here before they explode mysql
if (String.IsNullOrEmpty(userText))
{
remoteClient.SendDirClreplacedifiedReply(queryID, new DirClreplacedifiedReplyData[0]);
return;
}
if (queryFlags == 0)
{
sqlAddTerms = " AND (clreplacedifiedflags='2' OR clreplacedifiedflags='34') ";
}
if (category != 0)
{
sqlAddTerms = " AND category=?category ";
}
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?matureFlag", queryFlags);
parms.Add("?category", category);
parms.Add("?userText", userText);
// Ok a test cause the query pulls fine direct in MySQL, but not from here, so WTF?!
//query = "select clreplacedifieduuid, name, clreplacedifiedflags, creationdate, expirationdate, priceforlisting from clreplacedifieds " +
// "where name LIKE '" + userText + "' OR description LIKE '" + userText + "' " + sqlAddTerms;
query = "select clreplacedifieduuid, name, clreplacedifiedflags, creationdate, expirationdate, priceforlisting from clreplacedifieds " +
"where (description REGEXP ?userText OR name REGEXP ?userText) " +sqlAddTerms + " order by priceforlisting DESC limit " + searchStart + ", " + searchEnd + String.Empty;
using (ISimpleDB db = _connFactory.GetConnection())
{
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
count = results.Count;
DirClreplacedifiedReplyData[] data = new DirClreplacedifiedReplyData[count];
foreach (Dictionary<string, string> row in results)
{
data[i] = new DirClreplacedifiedReplyData();
data[i].clreplacedifiedID = new UUID(row["clreplacedifieduuid"].ToString());
data[i].name = row["name"].ToString();
data[i].clreplacedifiedFlags = Convert.ToByte(row["clreplacedifiedflags"]);
data[i].creationDate = Convert.ToUInt32(row["creationdate"]);
data[i].expirationDate = Convert.ToUInt32(row["expirationdate"]);
data[i].price = Convert.ToInt32(row["priceforlisting"]);
i++;
}
remoteClient.SendDirClreplacedifiedReply(queryID, data);
}
}
19
Source : AvatarSearchModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
public void ClreplacedifiedInfoRequest(UUID queryClreplacedifiedID, IClientAPI remoteClient)
{
// okies this is pretty simple straightforward stuff as well... pull the info from the
// db based on the Clreplacedified ID we got back from viewer from the original query above
// and send it back.
//ClreplacedifiedData data = new ClreplacedifiedData();
string query = "select * from clreplacedifieds where clreplacedifieduuid=?clreplacedifiedID";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?clreplacedifiedID", queryClreplacedifiedID);
Vector3 globalPos = new Vector3();
using (ISimpleDB db = _connFactory.GetConnection())
{
List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
foreach (Dictionary<string, string> row in results)
{
Vector3.TryParse(row["posglobal"].ToString(), out globalPos);
//remoteClient.SendClreplacedifiedInfoReply(data);
remoteClient.SendClreplacedifiedInfoReply(
new UUID(row["clreplacedifieduuid"].ToString()),
new UUID(row["creatoruuid"].ToString()),
Convert.ToUInt32(row["creationdate"]),
Convert.ToUInt32(row["expirationdate"]),
Convert.ToUInt32(row["category"]),
row["name"].ToString(),
row["description"].ToString(),
new UUID(row["parceluuid"].ToString()),
Convert.ToUInt32(row["parentestate"]),
new UUID(row["snapshotuuid"].ToString()),
row["simname"].ToString(),
globalPos,
row["parcelname"].ToString(),
Convert.ToByte(row["clreplacedifiedflags"]),
Convert.ToInt32(row["priceforlisting"]));
}
}
}
19
Source : Analyst.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
private object MagicCast(string name, string block, string field, string value)
{
Type packetClreplaced = openmvreplacedembly.GetType("OpenMetaverse.Packets." + name + "Packet");
if (packetClreplaced == null) throw new Exception("Couldn't get clreplaced " + name + "Packet");
FieldInfo blockField = packetClreplaced.GetField(block);
if (blockField == null) throw new Exception("Couldn't get " + name + "Packet." + block);
Type blockClreplaced = blockField.FieldType;
if (blockClreplaced.IsArray) blockClreplaced = blockClreplaced.GetElementType();
// Console.WriteLine("DEBUG: " + blockClreplaced.Name);
FieldInfo fieldField = blockClreplaced.GetField(field); PropertyInfo fieldProp = null;
Type fieldClreplaced = null;
if (fieldField == null)
{
fieldProp = blockClreplaced.GetProperty(field);
if (fieldProp == null) throw new Exception("Couldn't get " + name + "Packet." + block + "." + field);
fieldClreplaced = fieldProp.PropertyType;
}
else
{
fieldClreplaced = fieldField.FieldType;
}
try
{
if (fieldClreplaced == typeof(byte))
{
return Convert.ToByte(value);
}
else if (fieldClreplaced == typeof(ushort))
{
return Convert.ToUInt16(value);
}
else if (fieldClreplaced == typeof(uint))
{
return Convert.ToUInt32(value);
}
else if (fieldClreplaced == typeof(ulong))
{
return Convert.ToUInt64(value);
}
else if (fieldClreplaced == typeof(sbyte))
{
return Convert.ToSByte(value);
}
else if (fieldClreplaced == typeof(short))
{
return Convert.ToInt16(value);
}
else if (fieldClreplaced == typeof(int))
{
return Convert.ToInt32(value);
}
else if (fieldClreplaced == typeof(long))
{
return Convert.ToInt64(value);
}
else if (fieldClreplaced == typeof(float))
{
return Convert.ToSingle(value);
}
else if (fieldClreplaced == typeof(double))
{
return Convert.ToDouble(value);
}
else if (fieldClreplaced == typeof(UUID))
{
return new UUID(value);
}
else if (fieldClreplaced == typeof(bool))
{
if (value.ToLower() == "true")
return true;
else if (value.ToLower() == "false")
return false;
else
throw new Exception();
}
else if (fieldClreplaced == typeof(byte[]))
{
return Utils.StringToBytes(value);
}
else if (fieldClreplaced == typeof(Vector3))
{
Vector3 result;
if (Vector3.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClreplaced == typeof(Vector3d))
{
Vector3d result;
if (Vector3d.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClreplaced == typeof(Vector4))
{
Vector4 result;
if (Vector4.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClreplaced == typeof(Quaternion))
{
Quaternion result;
if (Quaternion.TryParse(value, out result))
return result;
else
throw new Exception();
}
else
{
throw new Exception("unsupported field type " + fieldClreplaced);
}
}
catch
{
throw new Exception("unable to interpret " + value + " as " + fieldClreplaced);
}
}
19
Source : ProxyManager.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
private object MagicCast(string name, string block, string field, string value)
{
Type packetClreplaced = openmvreplacedembly.GetType("OpenMetaverse.Packets." + name + "Packet");
if (packetClreplaced == null) throw new Exception("Couldn't get clreplaced " + name + "Packet");
FieldInfo blockField = packetClreplaced.GetField(block);
if (blockField == null) throw new Exception("Couldn't get " + name + "Packet." + block);
Type blockClreplaced = blockField.FieldType;
if (blockClreplaced.IsArray) blockClreplaced = blockClreplaced.GetElementType();
// Console.WriteLine("DEBUG: " + blockClreplaced.Name);
FieldInfo fieldField = blockClreplaced.GetField(field); PropertyInfo fieldProp = null;
Type fieldClreplaced = null;
if (fieldField == null)
{
fieldProp = blockClreplaced.GetProperty(field);
if (fieldProp == null) throw new Exception("Couldn't get " + name + "Packet." + block + "." + field);
fieldClreplaced = fieldProp.PropertyType;
}
else
{
fieldClreplaced = fieldField.FieldType;
}
try
{
if (fieldClreplaced == typeof(byte))
{
return Convert.ToByte(value);
}
else if (fieldClreplaced == typeof(ushort))
{
return Convert.ToUInt16(value);
}
else if (fieldClreplaced == typeof(uint))
{
return Convert.ToUInt32(value);
}
else if (fieldClreplaced == typeof(ulong))
{
return Convert.ToUInt64(value);
}
else if (fieldClreplaced == typeof(sbyte))
{
return Convert.ToSByte(value);
}
else if (fieldClreplaced == typeof(short))
{
return Convert.ToInt16(value);
}
else if (fieldClreplaced == typeof(int))
{
return Convert.ToInt32(value);
}
else if (fieldClreplaced == typeof(long))
{
return Convert.ToInt64(value);
}
else if (fieldClreplaced == typeof(float))
{
return Convert.ToSingle(value);
}
else if (fieldClreplaced == typeof(double))
{
return Convert.ToDouble(value);
}
else if (fieldClreplaced == typeof(UUID))
{
return new UUID(value);
}
else if (fieldClreplaced == typeof(bool))
{
if (value.ToLower() == "true")
return true;
else if (value.ToLower() == "false")
return false;
else
throw new Exception();
}
else if (fieldClreplaced == typeof(byte[]))
{
return Utils.StringToBytes(value);
}
else if (fieldClreplaced == typeof(Vector3))
{
Vector3 result;
if (Vector3.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClreplaced == typeof(Vector3d))
{
Vector3d result;
if (Vector3d.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClreplaced == typeof(Vector4))
{
Vector4 result;
if (Vector4.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClreplaced == typeof(Quaternion))
{
Quaternion result;
if (Quaternion.TryParse(value, out result))
return result;
else
throw new Exception();
}
else
{
throw new Exception("unsupported field type " + fieldClreplaced);
}
}
catch
{
throw new Exception("unable to interpret " + value + " as " + fieldClreplaced);
}
}
19
Source : KeyenceNanoByteTransform.cs
with GNU Lesser General Public License v3.0
from HslCommunication-Community
with GNU Lesser General Public License v3.0
from HslCommunication-Community
public virtual byte[] TransByte(byte[] buffer, int index, int length)
{
byte[] result = new byte[length];
for (int i = 0; i < length; i++)
{
result[i] = Convert.ToByte(BytesToStringArray(buffer)[index + i]);
}
return result;
}
19
Source : KeyenceNanoByteTransform.cs
with GNU Lesser General Public License v3.0
from HslCommunication-Community
with GNU Lesser General Public License v3.0
from HslCommunication-Community
public virtual byte TransByte(byte[] buffer, int index)
{
return Convert.ToByte(BytesToStringArray(buffer)[index]);
}
19
Source : StringParser.cs
with MIT License
from huangx916
with MIT License
from huangx916
public static byte StringToByte(string str, byte defaultValue = 0)
{
try
{
if (string.IsNullOrEmpty(str))
{
Debugger.LogError("Can not convert null or empty to byte.");
return defaultValue;
}
if (sIntRegex.IsMatch(str))
{
return Convert.ToByte(str);
}
return Convert.ToByte(Convert.ToInt32(Convert.ToDouble(str)));
}
catch (Exception e)
{
Debugger.LogError(string.Format("Can not convert {0} to int with {1}", str, e.GetType().Name));
}
return defaultValue;
}
19
Source : DataItemEntity.cs
with MIT License
from iccb1013
with MIT License
from iccb1013
private void SetLengthXml(XElement xml)
{
if (xml.Value.ToUpper() == "MAX")
{
this.Field.Length.Max = true;
}
else
{
this.Field.Length.Length = Convert.ToInt32(xml.Value);
}
this.Field.Length.DecimalDigits = Convert.ToByte(xml.Attribute("DecimalDigits").Value);
}
19
Source : New_Scenario_Page.cs
with BSD 3-Clause "New" or "Revised" License
from Ideasis
with BSD 3-Clause "New" or "Revised" License
from Ideasis
private void btnSave_Click(object sender, EventArgs e)
{
if (GlobalVariables.Is_Edit == false)
{
using (VivosEnreplacedies db = new VivosEnreplacedies())
{
List<replacedet> replacedetList = (from x in db.replacedets select x).ToList();
List<replacedetThumbnail> replacedetThumbnailList = (from x in db.replacedetThumbnails select x).ToList();
List<replacedetCommand> replacedetCommandList = (from x in db.replacedetCommands select x).ToList();
replacedet new_replacedet = new replacedet();
replacedetThumbnail new_replacedet_thumbnail = new replacedetThumbnail();
replacedetCommand[] new_replacedet_command = new replacedetCommand[commandsLayout.RowCount-1];
for (int i = 0; i < new_replacedet_command.Length; i++)
{
new_replacedet_command[i] = new replacedetCommand();
}
Guid new_replacedet_id= Guid.NewGuid();
new_replacedet.Id = new_replacedet_id;
new_replacedet.GroupId = new Guid("00000000-0000-0000-0000-000000000000");
new_replacedet.Name = txtTurkishName.Text;
new_replacedet.EnName = txtEnglishName.Text;
new_replacedet.ArabicName = txtArabicName.Text;
new_replacedet.FrName = txtFrenchName.Text;
new_replacedet.Description = txtTurkishDescription.Text;
new_replacedet.EnDescription = txtEnglishDescription.Text;
new_replacedet.ArabicDescription = txtArabicDescription.Text;
new_replacedet.FrDescription = txtFrenchDescription.Text;
if (cbAvaliable.Checked==true)
{
new_replacedet.Available = true;
}
else
{
new_replacedet.Available = false;
}
new_replacedet.Url = txtScenarioPath.Text;
new_replacedet.Exe = txtScenarioExe.Text;
new_replacedet.EntryDate = DateTime.Now;
try
{
if (pictureBox2.Image!=null)
{
Image img = pictureBox2.Image;
Bitmap bmp = new Bitmap(img);
ImageConverter converter = new ImageConverter();
new_replacedet_thumbnail.Thumbnail = (byte[])converter.ConvertTo(img, typeof(byte[]));
new_replacedet_thumbnail.replacedetId = new_replacedet_id;
}
else
{
new_replacedet_thumbnail.Thumbnail = null;
new_replacedet_thumbnail.replacedetId = new_replacedet_id;
}
}
catch (Exception)
{
}
for (int i = 0; i < commandsLayout.RowCount - 2; i++)
{
Guid new_replacedet_command_id = Guid.NewGuid();
new_replacedet_command[i].Id = new_replacedet_command_id;
new_replacedet_command[i].replacedetId = new_replacedet_id;
new_replacedet_command[i].CommandText = txtCommand[i].Text;
new_replacedet_command[i].Description = txtTurkishExplanation[i].Text;
new_replacedet_command[i].EnDescription = txtEnglishExplanation[i].Text;
new_replacedet_command[i].ArabicDescription = txtArabicExplanation[i].Text;
new_replacedet_command[i].FrDescription = txtFrenchExplanation[i].Text;
try
{
new_replacedet_command[i].Step = Convert.ToByte(txtStep[i].Text);
}
catch (Exception)
{
new_replacedet_command[i].Step = Convert.ToByte(0);
}
db.replacedetCommands.Add(new_replacedet_command[i]);
}
db.replacedets.Add(new_replacedet);
db.replacedetThumbnails.Add(new_replacedet_thumbnail);
db.SaveChanges();
DialogResult information = new DialogResult();
information = MessageBox.Show(resourceManager.GetString("msgScenarioAdded", GlobalVariables.uiLanguage));
if (information == DialogResult.OK)
{
Admin_Page admin_page = new Admin_Page();
this.Hide();
admin_page.Show();
}
}
}
else
{
using (VivosEnreplacedies db = new VivosEnreplacedies())
{
List<replacedet> replacedetList = (from x in db.replacedets select x).ToList();
List<replacedetThumbnail> replacedetThumbnailList = (from x in db.replacedetThumbnails select x).ToList();
List<replacedetCommand> replacedetCommandList = (from x in db.replacedetCommands select x).ToList();
replacedetCommand[] new_replacedet_command = new replacedetCommand[commandsLayout.RowCount - 1];
for (int i = 0; i < new_replacedet_command.Length; i++)
{
new_replacedet_command[i] = new replacedetCommand();
}
replacedet edit_replacedet= (from x in db.replacedets where x.Id == GlobalVariables.replacedet_Start_ID select x).SingleOrDefault();
if(edit_replacedet!=null)
{
edit_replacedet.Name = txtTurkishName.Text;
edit_replacedet.EnName = txtEnglishName.Text;
edit_replacedet.ArabicName = txtArabicName.Text;
edit_replacedet.FrName = txtFrenchName.Text;
edit_replacedet.Description = txtTurkishDescription.Text;
edit_replacedet.EnDescription = txtEnglishDescription.Text;
edit_replacedet.ArabicDescription = txtArabicDescription.Text;
edit_replacedet.FrDescription = txtFrenchDescription.Text;
edit_replacedet.Url = txtScenarioPath.Text;
edit_replacedet.Exe = txtScenarioExe.Text;
edit_replacedet.ModifyDate = DateTime.Now;
if (cbAvaliable.Checked==true)
{
edit_replacedet.Available = true;
}
else
{
edit_replacedet.Available = false;
}
}
replacedetThumbnail edit_replacedet_thumbnail = (from x in db.replacedetThumbnails where x.replacedetId == GlobalVariables.replacedet_Start_ID select x).SingleOrDefault();
if (edit_replacedet_thumbnail != null)
{
if (pictureBox2.Image!=null)
{
Image img = pictureBox2.Image;
Bitmap bmp = new Bitmap(img);
ImageConverter converter = new ImageConverter();
try
{
edit_replacedet_thumbnail.Thumbnail = (byte[])converter.ConvertTo(img, typeof(byte[]));
}
catch
{
}
}
}
for (int i = 0; i < commandsLayout.RowCount-2; i++)
{
int flag = 0;
for (int j = 0; j < replacedetCommandList.Count; j++)
{
if (replacedetCommandList[j].Id== Guid.Parse(txtID[i].Text))
{
replacedetCommandList[j].CommandText = txtCommand[i].Text;
replacedetCommandList[j].Description = txtTurkishExplanation[i].Text;
replacedetCommandList[j].EnDescription = txtEnglishExplanation[i].Text;
replacedetCommandList[j].ArabicDescription = txtArabicExplanation[i].Text;
replacedetCommandList[j].FrDescription = txtFrenchExplanation[i].Text;
replacedetCommandList[j].Step = Convert.ToByte(txtStep[i].Text);
flag = 1;
break;
}
}
if (flag==0)
{
Guid new_replacedet_command_id = Guid.NewGuid();
new_replacedet_command[i].Id = new_replacedet_command_id;
new_replacedet_command[i].replacedetId = GlobalVariables.replacedet_Start_ID;
new_replacedet_command[i].CommandText = txtCommand[i].Text;
new_replacedet_command[i].Description = txtTurkishExplanation[i].Text;
new_replacedet_command[i].EnDescription = txtEnglishExplanation[i].Text;
new_replacedet_command[i].ArabicDescription = txtArabicExplanation[i].Text;
new_replacedet_command[i].FrDescription = txtFrenchExplanation[i].Text;
new_replacedet_command[i].Step = Convert.ToByte(txtStep[i].Text);
db.replacedetCommands.Add(new_replacedet_command[i]);
}
}
db.SaveChanges();
DialogResult information = new DialogResult();
information = MessageBox.Show(resourceManager.GetString("msgScenarioEdited", GlobalVariables.uiLanguage));
if (information == DialogResult.OK)
{
Admin_Page admin_page = new Admin_Page();
this.Hide();
admin_page.Show();
}
}
}
}
19
Source : Login_Page.cs
with BSD 3-Clause "New" or "Revised" License
from Ideasis
with BSD 3-Clause "New" or "Revised" License
from Ideasis
public void add_scenarios(string file,Image image)
{
try
{
using (VivosEnreplacedies db = new VivosEnreplacedies())
{
string replacedet_imformation1 = null;
string[] replacedet_imformation = null;
replacedet_imformation1 = file;
replacedet_imformation = replacedet_imformation1.Split(new char[] { '\n' });
for (int i = 0; i < replacedet_imformation.Length - 1; i++)
{
replacedet_imformation[i] = replacedet_imformation[i].Remove(replacedet_imformation[i].Length - 1);
}
List<replacedet> replacedetList = (from x in db.replacedets select x).ToList();
List<replacedetThumbnail> replacedetThumbnailList = (from x in db.replacedetThumbnails select x).ToList();
List<replacedetCommand> replacedetCommandList = (from x in db.replacedetCommands select x).ToList();
int command_count = 0;
for (int i = 0; i < replacedet_imformation.Length; i++)
{
var splitted = replacedet_imformation[i].Split(new char[] { ',' });
if (splitted[0].Contains("Komutlar") == true)
{
command_count++;
}
}
replacedet new_replacedet = new replacedet();
replacedetThumbnail new_replacedet_thumbnail = new replacedetThumbnail();
replacedetCommand[] new_replacedet_command = new replacedetCommand[command_count];
for (int i = 0; i < new_replacedet_command.Length; i++)
{
new_replacedet_command[i] = new replacedetCommand();
}
Guid new_replacedet_id = Guid.NewGuid();
new_replacedet.Id = new_replacedet_id;
new_replacedet.GroupId = new Guid("00000000-0000-0000-0000-000000000000");
new_replacedet.EntryDate = DateTime.Now;
int command_add_number = 0;
for (int i = 0; i < replacedet_imformation.Length; i++)
{
var splitted = replacedet_imformation[i].Split(new char[] { ',' });
if (splitted[0].Contains("Ad") == true)
{
new_replacedet.Name = splitted[1];
new_replacedet.EnName = splitted[2];
new_replacedet.ArabicName = splitted[3];
}
else if (splitted[0].Contains("Açıklama") == true)
{
new_replacedet.Description = splitted[1];
new_replacedet.EnDescription = splitted[2];
new_replacedet.ArabicDescription = splitted[3];
}
else if (splitted[0].Contains("Aktif") == true)
{
if (splitted[1].Contains("True") == true)
{
new_replacedet.Available = true;
}
else
{
new_replacedet.Available = false;
}
}
else if (splitted[0].Contains("Senaryo Dizini") == true)
{
new_replacedet.Url = splitted[1];
}
else if (splitted[0].Contains("Senaryo Exe") == true)
{
new_replacedet.Exe = splitted[1];
}
else if (splitted[0].Contains("Komutlar") == true)
{
Guid new_replacedet_command_id = Guid.NewGuid();
new_replacedet_command[command_add_number].Id = new_replacedet_command_id;
new_replacedet_command[command_add_number].replacedetId = new_replacedet_id;
new_replacedet_command[command_add_number].Description = splitted[1];
new_replacedet_command[command_add_number].EnDescription = splitted[2];
new_replacedet_command[command_add_number].ArabicDescription = splitted[3];
new_replacedet_command[command_add_number].CommandText = splitted[4];
try
{
new_replacedet_command[command_add_number].Step = Convert.ToByte(splitted[5]);
}
catch (Exception)
{
new_replacedet_command[command_add_number].Step = Convert.ToByte(0);
}
db.replacedetCommands.Add(new_replacedet_command[command_add_number]);
command_add_number++;
}
}
try
{
Image img = image;
Bitmap bmp = new Bitmap(img);
ImageConverter converter = new ImageConverter();
new_replacedet_thumbnail.Thumbnail = (byte[])converter.ConvertTo(img, typeof(byte[]));
new_replacedet_thumbnail.replacedetId = new_replacedet_id;
}
catch (Exception)
{
}
db.replacedets.Add(new_replacedet);
db.replacedetThumbnails.Add(new_replacedet_thumbnail);
db.SaveChanges();
}
}
catch (Exception)
{
}
}
19
Source : New_Scenario_Page.cs
with BSD 3-Clause "New" or "Revised" License
from Ideasis
with BSD 3-Clause "New" or "Revised" License
from Ideasis
private void btnImport_Click(object sender, EventArgs e)
{
try
{
commandsLayout.Controls.Clear();
commandsLayout.RowCount = commandsLayout.RowCount - 1;
txtTurkishExplanation.Clear();
txtEnglishExplanation.Clear();
txtArabicExplanation.Clear();
txtFrenchExplanation.Clear();
txtCommand.Clear();
txtStep.Clear();
txtID.Clear();
string[] replacedet_imformation = null;
OpenFileDialog file1 = new OpenFileDialog();
file1.InitialDirectory = ".\\desktop";
file1.Filter = "Text|*.txt";
if (file1.ShowDialog() == DialogResult.OK)
{
replacedet_imformation = System.IO.File.ReadAllLines(file1.FileName);
}
for (int i = 0; i < replacedet_imformation.Length; i++)
{
var splitted = replacedet_imformation[i].Split(new char[] { ',' });
if (splitted[0].Contains(resourceManager.GetString("lblName", GlobalVariables.uiLanguage)) == true)
{
txtTurkishName.Text = splitted[1];
txtEnglishName.Text = splitted[2];
txtArabicName.Text = splitted[3];
txtFrenchName.Text = splitted[4];
}
else if (splitted[0].Contains(resourceManager.GetString("lblDescription", GlobalVariables.uiLanguage)) == true)
{
txtTurkishDescription.Text = splitted[1];
txtEnglishDescription.Text = splitted[2];
txtArabicDescription.Text = splitted[3];
txtFrenchDescription.Text = splitted[4];
}
else if (splitted[0].Contains(resourceManager.GetString("lblScenarioPath", GlobalVariables.uiLanguage)) == true)
{
txtScenarioPath.Text = splitted[1];
}
else if (splitted[0].Contains(resourceManager.GetString("lblScenarioExe", GlobalVariables.uiLanguage)) == true)
{
txtScenarioExe.Text = splitted[1];
}
else if (splitted[0].Contains(resourceManager.GetString("lblAvailable", GlobalVariables.uiLanguage)) == true)
{
if (splitted[1].Contains("True") == true)
{
cbAvaliable.Checked = true;
}
else
{
cbAvaliable.Checked = false;
}
}
else if (splitted[0].Contains(resourceManager.GetString("lblCommands", GlobalVariables.uiLanguage)) == true)
{
commandsLayout.RowCount = commandsLayout.RowCount + 1;
commandsLayout.Controls.Add(new TextBox() { Size = new Size(242, 20), Text = splitted[1], Name = "txtTurkishExplanations" + (commandsLayout.RowCount - 1) }, 0, commandsLayout.RowCount - 1);
commandsLayout.Controls.Add(new TextBox() { Size = new Size(242, 20), Text = splitted[2], Name = "txtEnglishExplanations" + (commandsLayout.RowCount - 1) }, 1, commandsLayout.RowCount - 1);
commandsLayout.Controls.Add(new TextBox() { Size = new Size(242, 20), Text = splitted[3], Name = "txtArabicExplanations" + (commandsLayout.RowCount - 1) }, 2, commandsLayout.RowCount - 1);
commandsLayout.Controls.Add(new TextBox() { Size = new Size(242, 20), Text = splitted[4], Name = "txtFrenchExplanations" + (commandsLayout.RowCount - 1) }, 3, commandsLayout.RowCount - 1);
commandsLayout.Controls.Add(new TextBox() { Size = new Size(242, 20), Text = splitted[5], Name = "txtCommands" + (commandsLayout.RowCount - 1) }, 4, commandsLayout.RowCount - 1);
commandsLayout.Controls.Add(new TextBox() { Text = Convert.ToByte(splitted[6]).ToString(), Name = "txtSteps" + (commandsLayout.RowCount - 1) }, 5, commandsLayout.RowCount - 1);
commandsLayout.Controls.Add(new TextBox() { Visible = false, Text = "00000000-0000-0000-0000-000000000000", Name = "txtID" + (commandsLayout.RowCount - 1) }, 6, commandsLayout.RowCount - 1);
txtTurkishExplanation.Add((commandsLayout.Controls.Find(("txtTurkishExplanations" + (commandsLayout.RowCount - 1)), true)[0]) as TextBox);
txtEnglishExplanation.Add((commandsLayout.Controls.Find(("txtEnglishExplanations" + (commandsLayout.RowCount - 1)), true)[0]) as TextBox);
txtArabicExplanation.Add((commandsLayout.Controls.Find(("txtArabicExplanations" + (commandsLayout.RowCount - 1)), true)[0]) as TextBox);
txtFrenchExplanation.Add((commandsLayout.Controls.Find(("txtFrenchExplanations" + (commandsLayout.RowCount - 1)), true)[0]) as TextBox);
txtCommand.Add((commandsLayout.Controls.Find(("txtCommands" + (commandsLayout.RowCount - 1)), true)[0]) as TextBox);
txtStep.Add((commandsLayout.Controls.Find(("txtSteps" + (commandsLayout.RowCount - 1)), true)[0]) as TextBox);
txtID.Add((commandsLayout.Controls.Find(("txtID" + (commandsLayout.RowCount - 1)), true)[0]) as TextBox);
}
else if (splitted[0].Contains(resourceManager.GetString("headerThumbnail", GlobalVariables.uiLanguage)) == true)
{
/* using (MemoryStream memoryStream = new MemoryStream(Convert.ToByte(splitted[1])))
{
Bitmap bmp = new Bitmap(memoryStream);
pictureBox2.Image = bmp;
}*/
}
}
}
catch (Exception)
{
}
}
See More Examples