Objective C to C# Equivalent - c#

I've got this statement I'm trying to convert form objective c to c#:
NSData *blockData;
if(valid)
{
if(sendingLast)
{
blockData = rawFirmwareData;
}
else
{
int startingPos = (currSensor.firmwareBlockIterator *
(ourCurrentSensor.firmwareBlockSize - headerSize));
blockData = [rawFirmwareData subdataWithRange:NSMakeRange(startingPos,
rawFirmwareData.length - startingPos)]
}
}
else
{
blockData = [rawFirmwareData
subdataWithRange:NSMakeRange((currSensor.firmwareBlockIterator *
(currSensor.firmwareBlockSize - headerSize)),
(currSensor.firmwareBlockSize - headerSize))];
}
I've tried translating it to the following, but I'm not sure if I've done it properly:
byte[] blockData;
if(valid)
{
if(sendingLast)
{
blockData = rawFirmwareData;
}
else
{
blockData = new byte[(currSensor.firmwareBlockSize - headerSize)];
Array.Copy(rawFirmwaredata, (currSensor.firmwareBlockIterator *
(currSensor.firmwareBlockSize - headerSize)), blockData, 0,
(currSensor.firmwareBlockSize - headerSize));
}
}
else
{
blockData = new byte[(currSensor.firmwareBlockSize - headerSize)];
Array.Copy(rawFirmwaredata, (currSensor.firmwareBlockIterator *
(currSensor.firmwareBlockSize - headerSize)), blockData, 0,
(currSensor.firmwareBlockSize - headerSize));
}
I'm not sure if my array length is correct when I initialize it based on the starting and ending positions.

Related

Call C# function Blazor Jquery

Need some help sorting an error added a screenshot of code and the error returned by the code.
Trying to call a C# function from Jquery and pass parameters along.
_Host
function getElementSVG(e) {
var position = getPosition(e);
var circle = makeSVG('circle', { cx: position.pointx, cy: position.pointy, r: 0.02, stroke: 'black', 'stroke-width': 0.5, fill: 'black' });
document.getElementById(e.currentTarget.id).appendChild(circle);
DotNet.invokeMethodAsync('PeopleCounterWeb', 'AddPointToList', position.pointx, position.pointy).then(result => {
console.log(result);
});
return position;
}
function fnsuccesscallback(data) {
alert(data.d);
}
function fnerrorcallback(result) {
alert(result.statusText);
}
function makeSVG(tag, attrs) {
var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs)
el.setAttribute(k, attrs[k]);
return el;
}
function getPosition(e) {
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
var width = rect.width;
var height = rect.height;
var pointx = ((x / width) * 100).toFixed(2);
var pointy = ((y / height) * 100).toFixed(2);
return {
pointx,
pointy
}
};
MainMap.cshtml
[JSInvokable]
public string AddPointToList(string x, string y)
{
var alpha = x + "-" + y;
return "";
//Points.Add(obj[0], obj[1]);
}
Code
[Error]
You are trying to invoke a message on an instance without passing a reference to that instance. Without an instance you can only call static methods.
You'll need to create an instance of DotNetReference in C# and pass it to JS.
There is a section on Blazor University about calling C# from JS - https://blazor-university.com/javascript-interop/calling-dotnet-from-javascript/

How can I translate this PHP into C# code? [duplicate]

This question already has answers here:
What is the meaning of [] [closed]
(4 answers)
Closed 3 years ago.
I am trying to create a tournament bracket system in my C# asp.net core application. I found this Tournament bracket placement algorithm post and RWC's answer is what I need because it also includes byes.
The problem I'm having is translating this piece of code to c#:
<?php
define('NUMBER_OF_PARTICIPANTS', 16);
$participants = range(1,NUMBER_OF_PARTICIPANTS);
$bracket = getBracket($participants);
var_dump($bracket);
function getBracket($participants)
{
$participantsCount = count($participants);
$rounds = ceil(log($participantsCount)/log(2));
$bracketSize = pow(2, $rounds);
$requiredByes = $bracketSize - $participantsCount;
echo sprintf('Number of participants: %d<br/>%s', $participantsCount, PHP_EOL);
echo sprintf('Number of rounds: %d<br/>%s', $rounds, PHP_EOL);
echo sprintf('Bracket size: %d<br/>%s', $bracketSize, PHP_EOL);
echo sprintf('Required number of byes: %d<br/>%s', $requiredByes, PHP_EOL);
if($participantsCount < 2)
{
return array();
}
$matches = array(array(1,2));
for($round=1; $round < $rounds; $round++)
{
$roundMatches = array();
$sum = pow(2, $round + 1) + 1;
foreach($matches as $match)
{
$home = changeIntoBye($match[0], $participantsCount);
$away = changeIntoBye($sum - $match[0], $participantsCount);
$roundMatches[] = array($home, $away);
$home = changeIntoBye($sum - $match[1], $participantsCount);
$away = changeIntoBye($match[1], $participantsCount);
$roundMatches[] = array($home, $away);
}
$matches = $roundMatches;
}
return $matches;
}
function changeIntoBye($seed, $participantsCount)
{
//return $seed <= $participantsCount ? $seed : sprintf('%d (= bye)', $seed);
return $seed <= $participantsCount ? $seed : null;
}
?>
I have tried translating each piece of PHP line to C# equivalent. However, this snippet is what stopped me at my tracks:
for($round=1; $round < $rounds; $round++)
{
$roundMatches = array();
$sum = pow(2, $round + 1) + 1;
foreach($matches as $match)
{
$home = changeIntoBye($match[0], $participantsCount);
$away = changeIntoBye($sum - $match[0], $participantsCount);
$roundMatches[] = array($home, $away);
$home = changeIntoBye($sum - $match[1], $participantsCount);
$away = changeIntoBye($match[1], $participantsCount);
$roundMatches[] = array($home, $away);
}
$matches = $roundMatches;
}
I don't understand what $roundMatches[] is trying to accomplish. Is it recreating the array? Is it setting a pointer? No idea. The C# version I wrote gives me wrong seeding number fo each match.
public Dictionary<int, string> getBracket(Dictionary<int, string> participants)
{
Dictionary<int, string> orderedParticipants = new Dictionary<int, string>();
var count = participants.Count;
var rounds = Math.Ceiling(Math.Log(count) / Math.Log(2));
var bracketSize = Math.Pow(2, rounds);
var requiredByes = bracketSize - count;
string p = $"Number of participants: {count}";
string r = $"Number of rounds: {rounds}";
string b = $"Bracket size: {bracketSize}";
string byes = $"Required number of byes: {requiredByes}";
List<List<int>> matches = new List<List<int>>();
matches.Add(new List<int>() {1, 2});
for (int round = 1; round < rounds; round++)
{
List<int> roundMatches = new List<int>();
var sum = (int)Math.Pow(2, round + 1) + 1;
foreach (var match in matches)
{
var home = changeIntoBye(match[0], count);
var away = changeIntoBye(sum - match[0], count);
roundMatches = new List<int> {home.Value, away.Value};
//roundMatches
home = changeIntoBye(sum - match[1], count);
away = changeIntoBye(match[1], count);
}
matches.Add(roundMatches);
}
return orderedParticipants;
}
it is basically the same as array_push
example
$var[] = "element 1";
$var[] = "element 2";
print_r($var);
will output
Array ( [0] => element 1 [1] => element 2 )
if you want to do the same in c# i think you have to use myList.add("element")

IComparer compare value of enum

I am implementing a compare method (IComparer) for the game Manille and I need to compare certain cards (enum values) with each other.
I want to order them in a certain way so that Number 10 is the biggest card and Ace the second biggest.
There is also a certain symbol that is always higher then other cards (for example Hearts)
The problem:
I don't know how to tell that Nummer.Tien is bigger then B, D, H
Also Ace has to be the second highest card, but the algorithm is putting him on the first place.
public class ManilleComparer : IComparer<Kaart>
{
private Kleur symbol; // the symbol that is higher
public ManilleComparer(Kleur symbol)
{
this.symbol = symbol;
}
public int Compare(Kaart x, Kaart y)
{
int compareTo = x.Kleur.CompareTo(y.Kleur); //check symbols against each other
if (compareTo == 0) // if value is 0 they have the same symbol
{
compareTo = x.Nummer.CompareTo(y.Nummer); // order them
return compareTo;
}
return x.Nummer.CompareTo(y.Nummer); // else compare values
}
}
public enum Nummer { Aas, Twee, Drie, Vier, Vijf, Zes, Zeven, Acht, Negen, Tien, Boer, Dame, Heer } // Ace, Two, Three, Four, Five, Six, Zeven, Eight, Nine, Ten, 11, 12, 13
public enum Kleur { Schoppen, Harten, Klaveren, Ruiten }
I have a Sort methot that sorts all the cards in the correct orde, which words fine:
public int CompareTo(object obj)
{
Kaart dezeKaart = this;
Kaart andereKaart = obj as Kaart;
int compareTo = dezeKaart.Kleur.CompareTo(andereKaart.Kleur);
if(compareTo == 0)
{
compareTo = dezeKaart.Nummer.CompareTo(andereKaart.Nummer);
return compareTo;
}
return compareTo;
}
The outcome of this sort method is:
// ♠A - ♠2 - ♠3 - ♠4 - ♠5 - ♠6 - ♠7 - ♠8 - ♠9 - ♠10 - ♠B - ♠D - ♠H
// ♥A - ♥2 - ♥3 - ♥4 - ♥5 - ♥6 - ♥7 - ♥8 - ♥9 - ♥10 - ♥B - ♥D - ♥H
// ♣A - ♣2 - ♣3 - ♣4 - ♣5 - ♣6 - ♣7 - ♣8 - ♣9 - ♣10 - ♣B - ♣D - ♣H
// ♦A - ♦2 - ♦3 - ♦4 - ♦5 - ♦6 - ♦7 - ♦8 - ♦9 - ♦10 - ♦B - ♦D - ♦H
I now want to implement Icompare
to have this as an outcome:
// ♦7 - ♦8 - ♦9 - ♦B - ♦D - ♦H - ♦A - ♦10
// ♣7 - ♣8 - ♣9 - ♣B - ♣D - ♣H - ♣A - ♣10
// ♠7 - ♠8 - ♠9 - ♠B - ♠D - ♠H - ♠A - ♠10
// ♥7 - ♥8 - ♥9 - ♥B - ♥D - ♥H - ♥A - ♥10
You can do the following:
public class ManilleComparer : IComparer<Kaart>
{
public ManilleComparer(){}
public ManilleComparer(List<Kleur> PrefKleurRank)
{
KleurRank = PrefKleurRank;
}
public ManilleComparer(Kleur LastColor)
{
KleurRank.Remove(LastColor);
KleurRank.Add(LastColor);
}
private List<Kleur> KleurRank = new List<Kleur>() { Kleur.Ruiten , Kleur.Klaveren, Kleur.Schoppen, Kleur.Harten };
private List<Nummer> NummerRank = new List<Nummer>() { Nummer.Twee, Nummer.Drie, Nummer.Vier, Nummer.Vier, Nummer.Zes, Nummer.Zeven, Nummer.Acht, Nummer.Negen, Nummer.Boer, Nummer.Dame, Nummer.Heer, Nummer.Aas, Nummer.Tien };
public int Compare(Kaart x, Kaart y)
{
int compareTo = KleurRank.IndexOf(x.Kleur).CompareTo(KleurRank.IndexOf(y.Kleur)); //check symbols against each other
if (compareTo == 0) // if value is 0 they have the same symbol
{
compareTo = NummerRank.IndexOf(x.Nummer).CompareTo(NummerRank.IndexOf(y.Nummer));
}
return compareTo;
}
}
you can also pass the order to the contructor to be more flexible
This is how to use it:
Kaart k1 = new Kaart() { Kleur = Kleur.Ruiten, Nummer = Nummer.Drie };
Kaart k2 = new Kaart() { Kleur = Kleur.Harten, Nummer = Nummer.Heer };
Kaart k3 = new Kaart() { Kleur = Kleur.Ruiten, Nummer = Nummer.Aas };
Kaart.ManilleComparer m = new Kaart.ManilleComparer();
List<Kaart> mylist = new List<Kaart>();
mylist.Add(k1);
mylist.Add(k2);
mylist.Add(k3);
mylist.Sort(m);
private List<Kleur> MyKleurRank = new List<Kleur>() { Kleur.Ruiten , Kleur.Klaveren, Kleur.Harten , Kleur.Schoppen};
Kaart.ManilleComparer m2 = new Kaart.ManilleComparer(MyKleurRank);
mylist.Sort(m2);

Parsing Through Wave File with BinaryReader

In .NET Assembly mscorlib System.IO namespace, I am using ReadInt16() method to loop through audio data bytes and dumping signed integer values into a text file. How does one interpret the two values associated with one sample rate? That is if I have one second of mono data there will be 88200 bytes, hence using ReadInt16() returns 88200 discrete integers. This is too much information, I should only have 44100 integers. So do I need to use a different method or perhaps advance the loop by 1 per each iteration.
Many thanks..........Mickey
using System;
using System.IO;
public struct WaveFormat
{
private short m_FormatTag; // most often PCM = 1
private short m_nChannels; // number of channels
private int m_SamplesPerSecond; // samples per second eg 44100
private int m_AvgBytesPerSecond; // bytes per second eg 176000
private short m_BlockAlign; // blockalign (byte per sample) eg 4 bytes
private short m_BitsPerSample; // bits per sample, 8, 16, 24
public WaveFormat(byte BPS, int SPS, byte nChn)
{
m_FormatTag = 1; //PCM
m_nChannels = nChn;
m_SamplesPerSecond = SPS;
m_BitsPerSample = BPS;
m_BlockAlign = (short)(m_nChannels * m_BitsPerSample / 8);
m_AvgBytesPerSecond = (int)(m_BlockAlign * m_SamplesPerSecond);
}
public short FormatTag
{
get { return m_FormatTag; }
set { m_FormatTag = value; }
}
public short Channels
{
get { return m_nChannels; }
}
public int SamplesPerSecond
{
get { return m_SamplesPerSecond; }
}
public int AvgBytesPerSecond
{
get { return m_AvgBytesPerSecond; }
}
public short BlockAlign
{
get { return m_BlockAlign; }
}
public short BitsPerSample
{
get { return m_BitsPerSample; }
}
public void Read(BinaryReader br)
{
m_FormatTag = br.ReadInt16();
m_nChannels = br.ReadInt16();
m_SamplesPerSecond = br.ReadInt32();
m_AvgBytesPerSecond = br.ReadInt32();
m_BlockAlign = br.ReadInt16();
m_BitsPerSample = br.ReadInt16();
}
public void Write(BinaryWriter bw)
{
bw.Write(m_FormatTag);
bw.Write(m_nChannels);
bw.Write(m_SamplesPerSecond);
bw.Write(m_AvgBytesPerSecond);
bw.Write(m_BlockAlign);
bw.Write(m_BitsPerSample);
}
public override string ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine("FormatTag: " + m_FormatTag.ToString());
sb.AppendLine("nChannels: " + m_nChannels.ToString());
sb.AppendLine("SamplesPerSecond: " + m_SamplesPerSecond.ToString());
sb.AppendLine("AvgBytesPerSecond: " + m_AvgBytesPerSecond.ToString());
sb.AppendLine("BlockAlign: " + m_BlockAlign.ToString());
sb.AppendLine("BitsPerSample: " + m_BitsPerSample.ToString());
return sb.ToString();
}
}
Generally when you read arrays of data your code should look like:
for(int i = 0; i < totalNumberOfEntries; i++)
{
// read all data for this entry
var component1 = reader.ReadXXX();
var component2 = reader.ReadXXX();
// deal with data for this entry
someEntryStroage.Add(new Entry(component1, component2);
}
Most likely (I don't know Wave file format) in your case you either need to read pairs of Int16 values (if samples are together) or read channels separately if data for one channel is after another.
you must read the chunkinfos. The data-chunk tells you how much bytes you have to read. the WaveFormat tells you ho much Averagebytespersecond you have, and much more. I have some VB-code...
have converted the VB-code with sharpdevelop to C# maybe it helps a little bit...
using System;
using System.IO;
public class ChunkInfo
{
private byte[] m_Header;
private long m_Length;
private long m_OffSet;
public ChunkInfo(string Header)
{
m_Header = new byte[Header.Length];
for (int i = 0; i <= m_Header.GetUpperBound(0); i++)
{
m_Header[i] = (byte)Header[i];
}
}
public ChunkInfo(byte[] Header)
{
m_Header = Header;
}
public void Read(BinaryReader br)
{
m_OffSet = SearchOffset(br);
if (m_OffSet >= 0)
{
br.BaseStream.Position = m_OffSet + m_Header.Length;
m_Length = br.ReadInt32();
}
}
public void Write(BinaryWriter bw)
{
bw.Write(m_Header);
bw.Write(m_Length);
}
public long Length
{
get { return m_Length; }
}
public long OffSet
{
get { return m_OffSet; }
}
private long SearchOffset(BinaryReader br)
{
byte[] haystack = null;
bool found = false;
long offset = 0;
long basepos = 0;
int hlength = 260;
long basepos_grow = hlength - m_Header.Length;
while (!(found || (basepos >= br.BaseStream.Length)))
{
br.BaseStream.Position = basepos;
haystack = br.ReadBytes(hlength);
offset = BoyerMooreHorspool.find(haystack, m_Header);
found = offset >= 0;
if (found)
{
offset += basepos;
break;
}
else
{
basepos += basepos_grow;
}
}
return offset;
}
}
public static class BoyerMooreHorspool
{
//detects a needle in the haystack
const int UBYTE_MAX = 255;
static int[] bad_char_skip4 = new int[UBYTE_MAX + 3];
static int[] bad_char_skip8 = new int[UBYTE_MAX + 3];
static bool IsInitialized = false;
public static void init()
{
//little optimization for needles with length 4 or 8
for (int i = 0; i <= UBYTE_MAX + 2; i++)
{
bad_char_skip4[i] = 4;
bad_char_skip8[i] = 8;
}
IsInitialized = true;
}
public static int find(byte[] haystack, byte[] needle, int start = 0)
{
if (!IsInitialized) init();
int i_n = 0;
//needle index
int n_n = needle.Length;
int[] bad_char_skip = null;
switch (n_n)
{
case 4:
bad_char_skip = bad_char_skip4;
break;
case 8:
bad_char_skip = bad_char_skip8;
break;
default:
bad_char_skip = new int[UBYTE_MAX + 3];
for (i_n = 0; i_n <= UBYTE_MAX + 2; i_n++)
{
bad_char_skip[i_n] = n_n;
}
break;
}
int ifind = -1;
//if not found then return - 1
int i_h = start;
//haystack index
int n_h = haystack.Length;
if (n_n > n_h)
throw new ArgumentOutOfRangeException("needle", "needle is to long");
int last = n_n - 1;
for (i_n = 0; i_n <= last - 1; i_n++)
{
bad_char_skip[needle[i_n]] = last - i_n;
}
byte bcs = 0;
int bhs = 0;
while ((n_h - start) >= n_n)
{
i_n = last;
while (haystack[i_h + i_n] == needle[i_n])
{
i_n -= 1;
if (i_n == 0)
{
ifind = i_h;
break;
}
}
bhs = haystack[i_h + last];
bcs = (byte)(bad_char_skip[bhs]);
n_h -= bcs;
i_h += bcs;
}
return ifind;
}
}

how to pass an id number string to this class

I'm very much a vb person, but have had to use this id number class in c#. I got it from http://www.codingsanity.com/idnumber.htm :
namespace Utilities
{
[Serializable]
public class IdentityNumber
{
public enum PersonGender
{
Female = 0,
Male = 5
}
public enum PersonCitizenship
{
SouthAfrican = 0,
Foreign = 1
}
static Regex _expression;
Match _match;
const string _IDExpression = #"(?<Year>[0-9][0-9])(?<Month>([0][1-9])|([1][0-2]))(?<Day>([0-2][0-9])|([3][0-1]))(?<Gender>[0-9])(?<Series>[0-9]{3})(?<Citizenship>[0-9])(?<Uniform>[0-9])(?<Control>[0-9])";
static IdentityNumber()
{
_expression = new Regex(_IDExpression, RegexOptions.Compiled | RegexOptions.Singleline);
}
public IdentityNumber(string IDNumber)
{
_match = _expression.Match(IDNumber.Trim());
}
public DateTime DateOfBirth
{
get
{
if(IsUsable == false)
{
throw new ArgumentException("ID Number is unusable!", "IDNumber");
}
int year = int.Parse(_match.Groups["Year"].Value);
// NOTE: Do not optimize by moving these to static, otherwise the calculation may be incorrect
// over year changes, especially century changes.
int currentCentury = int.Parse(DateTime.Now.Year.ToString().Substring(0, 2) + "00");
int lastCentury = currentCentury - 100;
int currentYear = int.Parse(DateTime.Now.Year.ToString().Substring(2, 2));
// If the year is after or at the current YY, then add last century to it, otherwise add
// this century.
// TODO: YY -> YYYY logic needs thinking about
if(year > currentYear)
{
year += lastCentury;
}
else
{
year += currentCentury;
}
return new DateTime(year, int.Parse(_match.Groups["Month"].Value), int.Parse(_match.Groups["Day"].Value));
}
}
public PersonGender Gender
{
get
{
if(IsUsable == false)
{
throw new ArgumentException("ID Number is unusable!", "IDNumber");
}
int gender = int.Parse(_match.Groups["Gender"].Value);
if(gender < (int) PersonGender.Male)
{
return PersonGender.Female;
}
else
{
return PersonGender.Male;
}
}
}
public PersonCitizenship Citizenship
{
get
{
if(IsUsable == false)
{
throw new ArgumentException("ID Number is unusable!", "IDNumber");
}
return (PersonCitizenship) Enum.Parse(typeof(PersonCitizenship), _match.Groups["Citizenship"].Value);
}
}
/// <summary>
/// Indicates if the IDNumber is usable or not.
/// </summary>
public bool IsUsable
{
get
{
return _match.Success;
}
}
/// <summary>
/// Indicates if the IDNumber is valid or not.
/// </summary>
public bool IsValid
{
get
{
if(IsUsable == true)
{
// Calculate total A by adding the figures in the odd positions i.e. the first, third, fifth,
// seventh, ninth and eleventh digits.
int a = int.Parse(_match.Value.Substring(0, 1)) + int.Parse(_match.Value.Substring(2, 1)) + int.Parse(_match.Value.Substring(4, 1)) + int.Parse(_match.Value.Substring(6, 1)) + int.Parse(_match.Value.Substring(8, 1)) + int.Parse(_match.Value.Substring(10, 1));
// Calculate total B by taking the even figures of the number as a whole number, and then
// multiplying that number by 2, and then add the individual figures together.
int b = int.Parse(_match.Value.Substring(1, 1) + _match.Value.Substring(3, 1) + _match.Value.Substring(5, 1) + _match.Value.Substring(7, 1) + _match.Value.Substring(9, 1) + _match.Value.Substring(11, 1));
b *= 2;
string bString = b.ToString();
b = 0;
for(int index = 0; index < bString.Length; index++)
{
b += int.Parse(bString.Substring(index, 1));
}
// Calculate total C by adding total A to total B.
int c = a + b;
// The control-figure can now be determined by subtracting the ones in figure C from 10.
string cString = c.ToString() ;
cString = cString.Substring(cString.Length - 1, 1) ;
int control = 0;
// Where the total C is a multiple of 10, the control figure will be 0.
if(cString != "0")
{
control = 10 - int.Parse(cString.Substring(cString.Length - 1, 1));
}
if(_match.Groups["Control"].Value == control.ToString())
{
return true;
}
}
return false;
}
}
}
}
Can someone please tell the syntax for how I pass an id number to the class?
You'll have to use the constructor.
var someNumber = new IdentityNumber("123456");
Then, you can use the properties of that class to find out the specifics of that Id number.
Console.WriteLine (someNumber.DateOfBirth);
Console.WriteLine (someNumber.Gender);
Console.WriteLine (someNumber.Citizenship);
Console.WriteLine (someNumber.IsValid);
Console.WriteLine (someNumber.IsUsable);
IdentityNumber number = new IdentityNumber("123456");
All you need is to use provided Constructor like
IdentityNumber someNumber = new IdentityNumber("006834");

Categories

Resources