How to implement lesssignificant24bytes Function - c#

Example :
Input (accountId): 63617264686F6C6465726E616D654077616C6C657470726F 76696465722E636F6D
Expected Output : 123CCB2F30BA420B17F837DF60E2FC9D6965A74476849FC D43A640F792A2B358
public String accountIdHash (String accountId)
{
String random8Bytes = 123CCB2F30BA420B
return random8Bytes + lessSignificant24bytes(strongerHash(accountId + random8Bytes))
}
public String strongerHash(String dataToHash)
{
String currentHash = dataToHash;
for (int i = 0; i < 5000; i++)
{
currentHash = sha256(currentHash);
}
return sha256(sha256(dataToHash) + currentHash);
}

Related

access returned object in another class

I'm trying to read id3 tags from a directory and I found some code online i've been trying to understand.
I understand most of it except the method GetTag(), it creates a new instance and returns an object but i can't access it from my main program.
public class Mp3Reader
{
private string _fileName;
private Stream _stream;
private byte[] data;
private const int SIZE = 128;
public Mp3Reader(string fileName)
{
_fileName = fileName;
_stream = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
}
public Mp3Tag GetTag()
{
Mp3Tag tag = new Mp3Tag();
data = new byte[SIZE];
_stream.Seek(-128, SeekOrigin.End);
_stream.Read(data, 0, SIZE);
//_stream.Close();
byte b1 = data[0];
byte b2 = data[1];
byte b3 = data[2];
if ((Convert.ToChar(b1) != 'T') || (Convert.ToChar(b2) != 'A') || (Convert.ToChar(b3) != 'G'))
{
throw new Exception("This File is NOT a MP3 file with ID3 v1");
}
for (int i = 3; i < 33; i++)
{
if (data[i] != 0)
tag.Title += Convert.ToChar(data[i]);
}
for (int i = 33; i < 63; i++)
{
if (data[i] != 0)
tag.Artist += Convert.ToChar(data[i]);
}
for (int i = 63; i < 93; i++)
{
if (data[i] != 0)
tag.Album += Convert.ToChar(data[i]);
}
for (int i = 93; i < 97; i++)
{
if (data[i] != 0)
tag.Year += Convert.ToChar(data[i]);
}
for (int i = 97; i < 127; i++)
{
if (data[i] != 0)
tag.Comment += Convert.ToChar(data[i]);
}
tag.Genere = data[127].ToString();
return tag;
}
}
main
static void Main(string[] args)
{
string folder = #"D:\\508-507-2209 (2017)";
var files = Directory.GetFiles(folder);
foreach(var val in files)
{
Mp3Reader tag2 = new Mp3Reader(val);
tag2.GetTag();
Console.WriteLine("");
}
}
mp3tag.cs
public class Mp3Tag
{
public string Title { get; set; }
public string Artist { get; set; }
public string Album { get; set; }
public string Year { get; set; }
public string Genere { get; set; }
public string Comment { get; set; }
}
If I manually Console.WriteLine(tag.xxx) right above my return it'll output to the terminal fine, what I don't understand is what to do with the "tag" variable that it created. why can't i access tag.Title in my main program?
tag.Genere = data[127].ToString();
Console.WriteLine("Title: " + tag.Title);
Console.WriteLine("Artist: " + tag.Artist);
Console.WriteLine("Album: " + tag.Album); ;
Console.WriteLine("Year: " + tag.Year);
Console.WriteLine("Comments: " + tag.Comment);
Console.WriteLine("Genere" + tag.Genere);
return tag;
shouldn't this be
static void Main(string[] args)
{
string folder = #"D:\\508-507-2209 (2017)";
var files = Directory.GetFiles(folder);
foreach(var val in files)
{
Mp3Reader tag2 = new Mp3Reader(val);
Mp3Tag mp3tag = tag2.GetTag(); // <- this here
Console.WriteLine("");
}

Creating arrays of objects of different derived classes using txt file reading. How to do better?

I have an abstract class. From which many other classes are inherited that need to be added to the file.
Then it is necessary to do the exact opposite, that is, the result will be an array of objects of different objects of derived classes.
What would be the best way to do this? Because my implementation seems to me the worst option.
In a text file, it looks like this:
Student JohnCamper
{<<FirstName>> : <<John>>,
<<LastName>> : <<Camper>>,
<<StudentID>> : <<45213>>,
<<Place Of Residence>> : <<94-932>>,
<<Sex>> : <<Male>>}
TaxiDriver ArnoldTrump
{<<FirstName>> : <<Arnold>>,
<<LastName>> : <<Trump>>}
Code:
public abstract class People
{
private Attribute<string>[] _attributes = new Attribute<string>[2];
protected People(string firstName, string lastName)
{
var firstname = new Attribute<string>(firstName, "FirstName");
var lastname = new Attribute<string>(lastName, "LastName");
_attributes[0] = firstname;
_attributes[1] = lastname;
}
public virtual void Teach()
{
Console.WriteLine("teaching someone");
}
public virtual void Study()
{
Console.WriteLine("{engaged in self-education");
}
public virtual void Drive()
{
Console.WriteLine("{is driving");
}
public string[] GetAttributesNames()
{
var result = new string[_attributes.Length];
for (var index = 0; index < result.Length; index++)
{
result[index] = _attributes[index].GetName();
}
return result;
}
public string[] GetAttributesData()
{
var result = new string[_attributes.Length];
for (int index = 0; index < result.Length; index++)
{
result[index] = _attributes[index].GetData();
}
return result;
}
private void Copy()
{
var temp = new Attribute<string>[_attributes.Length + 1];
for (var index = 0; index < _attributes.Length; index++)
{
temp[index] = _attributes[index];
}
_attributes = temp;
}
protected void AddAttribute(Attribute<string> attribute)
{
Copy();
var index = _attributes.Length - 1;
_attributes[index] = attribute;
}
}
public People[] ReadFile()
{
People[] result;
var sizePattern = new Regex(#".*\s{(.|\n)*?}");
var linePattern = new Regex(#"<<.*>>\s:\s<<(.*)>>");
var objTypePattern = new Regex(#"(.*)\s(.*){");
using (var sr = _file.OpenText())
{
var text = sr.ReadToEnd();
var matches = sizePattern.Matches(text);
result = new People[CalcSize(text)];
for (var index = 0; index < matches.Count; index++)
{
result[index] = ObjectCreate(matches[index]);
}
}
return result;
int CalcSize(string text)
{
var count = 0;
foreach (Match match in sizePattern.Matches(text))
{
count++;
}
return count;
}
People ObjectCreate(Match match)
{
People people = null;
var groups = match.Groups;
var objType = match.Value.Split(" ")[0];
var attributes = GetAttributes(match);
if (objType == "Student")
{
people = new Student(attributes[0],attributes[1],attributes[2],attributes[3],attributes[4]);
}
else if (objType == "TaxiDriver")
{
people = new TaxiDriver(attributes[0],attributes[1]);
}
return people;
}
string[] GetAttributes(Match match)
{
var text = match.Value;
var matches = linePattern.Matches(text);
var size = matches.Count;
var attributes = new string[size];
for (var index = 0; index < size; index++)
{
var group = matches[index].Groups;
var temp = group[1].Value;
attributes[index] = temp;
}
return attributes;
}
}
public class Student : People
{
public Student(string firstName, string lastName, string studentId,string stPlaceOfResidence, string studentSex) : base(firstName, lastName)
{
var id = new Attribute<string>(studentId, "StudentID");
var sex = new Attribute<string>(studentSex,"Sex");
var placeOfResidence = new Attribute<string>(stPlaceOfResidence, "Place Of Residence");
AddAttribute(id);
AddAttribute(placeOfResidence);
AddAttribute(sex);
}
public override void Study()
{
Console.WriteLine("Student is studying");
}
}

How do i get the values from leerling lower than 10?

class Leerling
{
public int Leeftijd { get; set; }
public decimal Cijfer { get; set; }
public string Naam { get; set; }
public string Achternaam { get; set; }
public List<Leerling> Studentenlijst { get; set; }
public Leerling()
{
Studentenlijst = new List<Leerling>();
}
public Leerling(int _leeftijd, int _cijfer, string _naam, string _achternaam)
{
Leeftijd = _leeftijd;
Cijfer = _cijfer;
Naam = _naam;
Achternaam = _achternaam;
}
public string ToonLeerling()
{
string output = "";
for (int i = 1; i < Studentenlijst.Count; i++)
{
if (Studentenlijst[i].Leeftijd <= 14)
{
Leerling objLeerling = (Leerling)Studentenlijst[i];
output = output + objLeerling.ToString();
}
}
return output;
}
public string ToonLeerlingouder()
{
string output = "";
for (int i = 1; i < Studentenlijst.Count; i++)
{
if (Studentenlijst[i].Leeftijd >= 15
)
{
Leerling objLeerling = (Leerling)Studentenlijst[i];
output = output + objLeerling.ToString();
}
}
return output;
}
public void addLeerling()
{
Leerling Leerling1 = new Leerling(18, 60, "Tom", "Lub");
Leerling Leerling2 = new Leerling(14, 50, "Kees", "Apenvlees");
Studentenlijst.Add((Leerling)Leerling1);
Studentenlijst.Add((Leerling)Leerling2);
}
public override string ToString()
{
return " Leeftijd " + Leeftijd + "\n Cijfer: " + Cijfer + "\n Naam: " + Naam + "\n Achternaam: " + Achternaam;
}
/*
Leerling l = new Leerling();
l.addLeerling();
Console.WriteLine(l.ToonLeerling().ToString());
Console.ReadLine();
l.addLeerling();
Console.WriteLine(l.ToonLeerlingouder().ToString());
Console.ReadLine();
*/
}
}
How do I get the values of leerling below 10?
You can try this
public List<String> ToonLeerlingJonger(){
List<String> LeerlingenJongerDan10 = new List<String>();
foreach(Leerling l in Studentenlijst){
if(l.Leeftijd < 10){
LeerlingenJongerDan10.add(l.ToString());
}
return LeerlingenJongerDan10;
}
}

Reading values from an .acf / manifest file

The file I'm trying to read is presented in the format below. How using c# can I read this file to extract property values? Are there any libraries I can leverage?
"AppState"
{
"appid" "244210"
"Universe" "1"
"name" "Assetto Corsa"
"StateFlags" "4"
"installdir" "assettocorsa"
"LastUpdated" "1469806809"
"UpdateResult" "0"
"SizeOnDisk" "23498042501"
"buildid" "1251512"
"LastOwner" "76561198018619129"
"BytesToDownload" "11541616"
"BytesDownloaded" "11541616"
"AutoUpdateBehavior" "0"
"AllowOtherDownloadsWhileRunning" "0"
"UserConfig"
{
"language" "english"
}
"MountedDepots"
{
"228983" "8124929965194586177"
"228984" "3215975441341951460"
"228985" "5758075142805954616"
"228990" "1829726630299308803"
"229002" "7260605429366465749"
"244211" "3837890045968273966"
}
"InstallScripts"
{
"0" "_CommonRedist\\vcredist\\2010\\installscript.vdf"
"1" "_CommonRedist\\vcredist\\2012\\installscript.vdf"
"2" "_CommonRedist\\vcredist\\2013\\installscript.vdf"
"3" "_CommonRedist\\DirectX\\Jun2010\\installscript.vdf"
"4" "_CommonRedist\\DotNet\\4.0\\installscript.vdf"
}
}
So I don't know if you still need it, but I wrote it myself.
Here is my code.
In my tests it worked perfectly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Steam_acf_File_Reader
{
class AcfReader
{
public string FileLocation { get; private set; }
public AcfReader(string FileLocation)
{
if (File.Exists(FileLocation))
this.FileLocation = FileLocation;
else
throw new FileNotFoundException("Error", FileLocation);
}
public bool CheckIntegrity()
{
string Content = File.ReadAllText(FileLocation);
int quote = Content.Count(x => x == '"');
int braceleft = Content.Count(x => x == '{');
int braceright = Content.Count(x => x == '}');
return ((braceleft == braceright) && (quote % 2 == 0));
}
public ACF_Struct ACFFileToStruct()
{
return ACFFileToStruct(File.ReadAllText(FileLocation));
}
private ACF_Struct ACFFileToStruct(string RegionToReadIn)
{
ACF_Struct ACF = new ACF_Struct();
int LengthOfRegion = RegionToReadIn.Length;
int CurrentPos = 0;
while (LengthOfRegion > CurrentPos)
{
int FirstItemStart = RegionToReadIn.IndexOf('"', CurrentPos);
if (FirstItemStart == -1)
break;
int FirstItemEnd = RegionToReadIn.IndexOf('"', FirstItemStart + 1);
CurrentPos = FirstItemEnd + 1;
string FirstItem = RegionToReadIn.Substring(FirstItemStart + 1, FirstItemEnd - FirstItemStart - 1);
int SecondItemStartQuote = RegionToReadIn.IndexOf('"', CurrentPos);
int SecondItemStartBraceleft = RegionToReadIn.IndexOf('{', CurrentPos);
if (SecondItemStartBraceleft == -1 || SecondItemStartQuote < SecondItemStartBraceleft)
{
int SecondItemEndQuote = RegionToReadIn.IndexOf('"', SecondItemStartQuote + 1);
string SecondItem = RegionToReadIn.Substring(SecondItemStartQuote + 1, SecondItemEndQuote - SecondItemStartQuote - 1);
CurrentPos = SecondItemEndQuote + 1;
ACF.SubItems.Add(FirstItem, SecondItem);
}
else
{
int SecondItemEndBraceright = RegionToReadIn.NextEndOf('{', '}', SecondItemStartBraceleft + 1);
ACF_Struct ACFS = ACFFileToStruct(RegionToReadIn.Substring(SecondItemStartBraceleft + 1, SecondItemEndBraceright - SecondItemStartBraceleft - 1));
CurrentPos = SecondItemEndBraceright + 1;
ACF.SubACF.Add(FirstItem, ACFS);
}
}
return ACF;
}
}
class ACF_Struct
{
public Dictionary<string, ACF_Struct> SubACF { get; private set; }
public Dictionary<string, string> SubItems { get; private set; }
public ACF_Struct()
{
SubACF = new Dictionary<string, ACF_Struct>();
SubItems = new Dictionary<string, string>();
}
public void WriteToFile(string File)
{
}
public override string ToString()
{
return ToString(0);
}
private string ToString(int Depth)
{
StringBuilder SB = new StringBuilder();
foreach (KeyValuePair<string, string> item in SubItems)
{
SB.Append('\t', Depth);
SB.AppendFormat("\"{0}\"\t\t\"{1}\"\r\n", item.Key, item.Value);
}
foreach (KeyValuePair<string, ACF_Struct> item in SubACF)
{
SB.Append('\t', Depth);
SB.AppendFormat("\"{0}\"\n", item.Key);
SB.Append('\t', Depth);
SB.AppendLine("{");
SB.Append(item.Value.ToString(Depth + 1));
SB.Append('\t', Depth);
SB.AppendLine("}");
}
return SB.ToString();
}
}
static class Extension
{
public static int NextEndOf(this string str, char Open, char Close, int startIndex)
{
if (Open == Close)
throw new Exception("\"Open\" and \"Close\" char are equivalent!");
int OpenItem = 0;
int CloseItem = 0;
for (int i = startIndex; i < str.Length; i++)
{
if (str[i] == Open)
{
OpenItem++;
}
if (str[i] == Close)
{
CloseItem++;
if (CloseItem > OpenItem)
return i;
}
}
throw new Exception("Not enough closing characters!");
}
}
}

Append path to string

I need help in appeding the string to path. The problem here is that the path that i have declare cannot be call, instead it just give normal string value. here is my code.
public static string inputhistory1 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\" + Process.GetCurrentProcess().ProcessName + DateTime.Now.ToString("yyyyMMdd")+".chf";
public static string inputhistory2 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-1).ToString("yyyyMM") + ".chf";
public static string inputhistory3 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-2).ToString("yyyyMM") + ".chf";
public static string inputhistory4 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-3).ToString("yyyyMM") + ".chf";
public static bool checkfile(string filename)
{
bool same = false;
for (i = 1; i <= 4; i++)
{
string filechf = "inputhistory" + i;
filechf = filechf;
try
{
foreach (string line in System.IO.File.ReadAllLines(filechf))
{
if (line.Contains(filename))
{
same = true;
break;
}
else
{
same = false;
}
}
}
catch (Exception)
{
// Ignore if file does not exist.
}
if (same == true)
{
break;
}
}
}
Just to show off the expressiveness of LINQ, and the power of leveraging the tools available:
List<string> inputHistories = new List<string>
{
inputhistory1, inputhistory2, inputhistory3, inputhistory4
};
public static bool checkfile(string filename)
{
return inputHistories.Any(filename =>
File.ReadLines(filename).Any(line => line.Contains(filename)));
}
That is because you assign variable filechf with string "inputhistory" + i.
Use an array or list to store input history value.
public static string inputhistory1 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\" + Process.GetCurrentProcess().ProcessName + DateTime.Now.ToString("yyyyMMdd")+".chf";
public static string inputhistory2 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-1).ToString("yyyyMM") + ".chf";
public static string inputhistory3 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-2).ToString("yyyyMM") + ".chf";
public static string inputhistory4 = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Log\\FileExtact" + DateTime.Now.AddMonths(-3).ToString("yyyyMM") + ".chf";
List<string> inputHistories = new List<string>();
inputHistories.Add(inputhistory1);
inputHistories.Add(inputhistory2);
inputHistories.Add(inputhistory3);
inputHistories.Add(inputhistory4);
Then you could access its value by index:
public static bool checkfile(string filename)
{
bool same = false;
//try
//{
for (i = 0; i < inputHistories.Count; i++)
{
string filechf = inputHistories[i];
try
{
foreach (string line in System.IO.File.ReadAllLines(filechf))
{
if (line.Contains(filename))
{
same = true;
break;
}
else
{
same = false;
}
}
}
catch (Exception)
{
//ignore if file does not exist
}
if (same == true)
{
break;
}
}
There are kinds of solutions may meet your requirements
you can store the variables in a dictionary:
var dictionary = new Dictionary<string,string>();
dictionary.Add("inputhistory1", inputhistory1);
dictionary.Add("inputhistory2", inputhistory2);
dictionary.Add("inputhistory3", inputhistory3);
dictionary.Add("inputhistory4", inputhistory4);
//use as below
Console.WriteLine(dictionary["inputhistory1"]);
or you can use reflection, for more information MSDN:
public class TestClass
{
public static string inputhistory1 = "value1";
public static string inputhistory2 = "value2";
public static string inputhistory3 = "value3";
public static string inputhistory4 = "value4";
}
var obj = new TestClass();
var field = typeof (TestClass).GetField("inputhistory1");
//use as below
Console.WriteLine(field.GetValue(obj));
even you can use switch/case to return your variable value

Categories