public void BaseNCompareToBase64() { string s = "aaa"; var converter = new BaseN(Base64.DefaultAlphabet); string encoded = converter.EncodeString(s); string base64standart = Convert.ToBase64String(Encoding.UTF8.GetBytes(s)); Assert.AreEqual(base64standart, encoded); }
public void ReverseOrder() { var converter = new BaseN(StringGenerator.GetAlphabet(54), 32, null, true); var original = "sdfrewwekjthkjh"; var encoded = converter.EncodeString(original); var decoded = converter.DecodeToString(encoded); Assert.AreEqual(original, decoded); }
private string Encrypt(string JSON, string seed) { m_output += "Encrypting data: " + JSON + '\n'; string hash = MD5Hash.GetHash(seed); //Getting the hash of the randomized string RC4 packetKey = new RC4(m_encryptionKey); //Setting the key for the RC4 StringBuilder combinedHash = new StringBuilder(); combinedHash.Append(hash); combinedHash.Append(packetKey.Convert(JSON)); //Gets the proper RC4 string then Combine the MD5 and the RC4. return(BaseN.ProduceString(combinedHash.ToString())); }
internal VehicleConfig(XmlDocument doc) { m_nVersion = (byte)BaseN.S64ToInt(doc.DocumentElement.GetAttribute("V", string.Empty)); string strUTMZone = doc.DocumentElement.GetAttribute("U", string.Empty); m_nUTMZoneNo = int.Parse(strUTMZone.Substring(0, strUTMZone.Length - 1)); m_chUTMZoneLetter = strUTMZone[strUTMZone.Length - 1]; StringReader sr = new StringReader(doc.DocumentElement.FirstChild.Value); string str = sr.ReadLine(); int nRow = -1; while (str != null) { switch (++nRow) { case 0: if (str.Length > 0) { m_strHeadSignDefault = str; } break; case 1: byte.TryParse(str, out m_nRouteNoFmt); break; case 2: m_strNSAPrefix = str.Split('~')[0]; break; case 3: m_strConnPrefix = str.Split('~')[0]; break; case 4: { string[] stra = str.Split('~'); m_strNSDStopping = stra[0]; m_strNSDStoppingConcat = stra[1]; break; } case 5: m_strSAPrefixFmt = str.Split('~')[0]; break; } str = sr.ReadLine(); } sr.Close(); }
internal ServiceAlertConfig(XmlDocument doc) { m_Doc = doc; m_nVersion = (byte)BaseN.S64ToInt(m_Doc.DocumentElement.GetAttribute("V", string.Empty)); byte n = 0; string str = m_Doc.DocumentElement.GetAttribute("E", string.Empty); if (str.Length == 0 || !byte.TryParse(str, out n)) { m_SAMode = AVMode.None; } else { m_SAMode = (AVMode)n; } }
public void GetOptimalBitsCount() { Assert.AreEqual(5, BaseN.GetOptimalBitsCount2(32, out var charsCountInBits)); Assert.AreEqual(6, BaseN.GetOptimalBitsCount2(64, out charsCountInBits)); Assert.AreEqual(32, BaseN.GetOptimalBitsCount2(85, out charsCountInBits)); Assert.AreEqual(13, BaseN.GetOptimalBitsCount2(91, out charsCountInBits)); StringBuilder builder = new StringBuilder(); for (int i = 2; i <= 256; i++) { var bits = BaseBigN.GetOptimalBitsCount2((uint)i, out charsCountInBits, 512); double ratio = (double)bits / charsCountInBits; builder.AppendLine(bits + " " + charsCountInBits + " "+ ratio.ToString("0.0000000")); } string str = builder.ToString(); }
public void EncodeDecodeBaseN() { byte testByte = 157; List<byte> bytes = new List<byte>(); for (uint radix = 2; radix < 1000; radix++) { var baseN = new BaseN(StringGenerator.GetAlphabet((int)radix), 64); int testBytesCount = Math.Max((baseN.BlockBitsCount + 7) / 8, (int)baseN.BlockCharsCount); bytes.Clear(); for (int i = 0; i <= testBytesCount + 1; i++) { var array = bytes.ToArray(); var encoded = baseN.Encode(array); var decoded = baseN.Decode(encoded); CollectionAssert.AreEqual(array, decoded); bytes.Add(testByte); } } }
internal RoutePatternConfig(XmlDocument doc) { m_Doc = doc; m_nVersion = (byte)BaseN.S64ToInt(m_Doc.DocumentElement.GetAttribute("V", string.Empty)); { byte n = 0; string str = m_Doc.DocumentElement.GetAttribute("F", string.Empty); if (str.Length == 0 || !byte.TryParse(str, out n)) { m_FareboxFields = FareboxFields.None; } else { m_FareboxFields = (FareboxFields)n; } } { byte n = 0; string str = m_Doc.DocumentElement.GetAttribute("C", string.Empty); if (str.Length == 0 || !byte.TryParse(str, out n)) { m_ConnMode = AVMode.None; } else { m_ConnMode = (AVMode)n; } } { string str = m_Doc.DocumentElement.GetAttribute("R", string.Empty); if (str.Length == 0) { m_nNSAReminderSec = 0; } else { m_nNSAReminderSec = (ushort)(60 * BaseN.S64ToInt(str)); } } }
public void EncodeDecodeBaseN() { byte testByte = 157; List <byte> bytes = new List <byte>(); for (uint radix = 2; radix < 1000; radix++) { var baseN = new BaseN(StringGenerator.GetAlphabet((int)radix), 64); int testBytesCount = Math.Max((baseN.BlockBitsCount + 7) / 8, (int)baseN.BlockCharsCount); bytes.Clear(); for (int i = 0; i <= testBytesCount + 1; i++) { var array = bytes.ToArray(); var encoded = baseN.Encode(array); var decoded = baseN.Decode(encoded); CollectionAssert.AreEqual(array, decoded); bytes.Add(testByte); } } }
internal bool GetContent(string strRouteTag64, out string strProjectTag, out string strRouteNo, out double nRouteLength, out string strRPcsv) { bool bOK = false; strProjectTag = strRouteNo = strRPcsv = null; nRouteLength = 0.0; XPathNodeIterator it = (XPathNodeIterator)m_Doc.CreateNavigator().Evaluate("//P[@T='" + strRouteTag64 + "']"); if (it.MoveNext()) { bOK = true; strProjectTag = it.Current.GetAttribute("p", string.Empty); if (strProjectTag.Length == 0) { strProjectTag = "1"; } strRouteNo = it.Current.GetAttribute("N", string.Empty); nRouteLength = BaseN.S64ToInt(it.Current.GetAttribute("L", string.Empty)); strRPcsv = it.Current.Value; } return(bOK); }
public void EncodeDecodeParallel() { var randomString = StringGenerator.GetRandom(10000000, true); var baseN = new BaseN(StringGenerator.GetAlphabet(85)); var stopwatch = new Stopwatch(); stopwatch.Start(); var baseNEncoded = baseN.EncodeString(randomString); stopwatch.Stop(); var baseNTime = stopwatch.Elapsed; stopwatch.Restart(); baseN.Parallel = true; var baseNEncodedParallel = baseN.EncodeString(randomString); stopwatch.Stop(); var baseNParallelTime = stopwatch.Elapsed; CollectionAssert.AreEqual(baseNEncoded, baseNEncodedParallel); Assert.Less(baseNParallelTime, baseNTime); }
public static Trip Create(Vehicle vehicle, short nRouteTag, int nRP, int?nTripNo, ushort?nServiceStart, Vehicle.RoutePatternConfig configRP, Vehicle.ServiceAlertConfig configSA, Vehicle.VehicleConfig configV, bool fFerry) { Trip trip = null; try { double nRouteLength; string strProjectTag, strRouteNo, strRPcsv; if (!configRP.GetContent(BaseN.IntToS64(nRouteTag), out strProjectTag, out strRouteNo, out nRouteLength, out strRPcsv)) { return(null); } StringReader sr = new StringReader(strRPcsv); Queue <Platform> queue = new Queue <Platform>(0x80); Collection <string> colNextStop = new Collection <string>(); double nLastEasting = 0.0, nLastNorthing = 0.0, nLastRadius = 0.0; int nLastRP = 0, nNextStopIndex = 0; string str = sr.ReadLine(), strLastDestination = null, strLastHeadSign = null; byte? nLastFareSet = null; byte nServiceDay = 0; ushort nScheduledMin = 0; if (nServiceStart.HasValue) { nServiceDay = (byte)(nServiceStart.Value & 0x07); nScheduledMin = (ushort)(nServiceStart.Value >> 3); } while (str != null) { string[] stra = str.Split('~'); Platform platform = new Platform(); platform.MinDistanceFromPlatform = double.MaxValue; platform.Arrived = platform.ExternalAudioActivated = false; platform.Name = stra[0]; //platform.Position.X = BaseN.S32ToInt( stra[1] ) + nLastEasting; //platform.Position.Y = BaseN.S32ToInt( stra[2] ) + nLastNorthing; platform.Radius = BaseN.S32ToInt(stra[3]) + nLastRadius; platform.RPEnd = BaseN.S64ToInt(stra[4]) + nLastRP; platform.DistanceToEnd = nRouteLength * (platform.RPEnd - nLastRP) / UTM.cRPScalar; if (stra.Length > 5 && stra[5].Length > 0) { switch (stra[5][0]) { case '1': platform.InternalAudio = true; platform.Timepoint = false; break; case '2': platform.InternalAudio = false; platform.Timepoint = true; break; case '3': platform.InternalAudio = platform.Timepoint = true; break; default: //legacy @ platform.InternalAudio = true; platform.Timepoint = false; break; } } else { platform.InternalAudio = platform.Timepoint = false; } platform.Destination = stra.Length > 6 && stra[6].Length > 0 ? stra[6] : strLastDestination; platform.HeadSign = stra.Length > 7 && stra[7].Length > 0 ? stra[7] : strLastHeadSign; platform.FareSet = stra.Length > 8 && stra[8].Length > 0 ? byte.Parse(stra[8]) : nLastFareSet; platform.NSAReminderSec = platform.InternalAudio ? configRP.NSAReminderSec : (ushort)0; platform.NSAReminderDistanceMin = platform.InternalAudio ? (platform.Radius * 2.0 + 50.0) : 0.0; platform.NSAReminderDistanceMax = platform.InternalAudio ? (platform.Radius * 2.0 + 200.0) : 0.0; platform.DepartureEnabled = false; platform.IgnoreServerRP = false; colNextStop.Add(platform.Name); if (nRP <= platform.RPEnd) { if (nServiceDay > 0 && stra.Length > 9) { string strNSAConn = string.Empty, strNSDConn = string.Empty; for (int n = 9; n < stra.Length; ++n) { bool bMatch = false; string[] straDest = stra[n].Split('§'); for (int m = 2; !bMatch && m < straDest.Length;) { byte nServiceMask = (byte)BaseN.S64ToInt(straDest[m]); if ((nServiceDay & nServiceMask) > 0) { ushort nScheduledMinStart = (ushort)BaseN.S64ToInt(straDest[m + 1]); ushort nScheduledMinEnd = (ushort)BaseN.S64ToInt(straDest[m + 2]); if (nScheduledMinStart <= nScheduledMin && nScheduledMin <= nScheduledMinEnd) { bMatch = true; strNSAConn += vehicle.GetRouteNoForAudio(straDest[0]) + " " + straDest[1] + ". "; strNSDConn += straDest[0] + " " + straDest[1] + ", "; } } m += 3; } } if (strNSAConn.Length > 0) { platform.NSAConn = strNSAConn; platform.NSDConn = strNSDConn.Substring(0, strNSDConn.Length - 2) + ". "; } } queue.Enqueue(platform); } else { ++nNextStopIndex; } //nLastEasting = platform.Position.X; //nLastNorthing = platform.Position.Y; nLastRadius = platform.Radius; nLastRP = platform.RPEnd; strLastDestination = platform.Destination; strLastHeadSign = platform.HeadSign; nLastFareSet = platform.FareSet; str = sr.ReadLine(); } sr.Close(); trip = new Trip(); trip.m_Vehicle = vehicle; trip.m_nRouteTag = nRouteTag; trip.m_nRP = nRP; trip.m_nTripNo = nTripNo; trip.m_nServiceStart = nServiceStart; trip.m_strRouteNo = strRouteNo; trip.m_strRouteNoForAudio = vehicle.GetRouteNoForAudio(strRouteNo); trip.m_ConnMode = configRP.ConnMode; trip.m_SAMode = configSA.SAMode; if (trip.m_SAMode != Vehicle.AVMode.None) { trip.m_strSAPrefix = string.Format(configV.SAPrefixFmt, strRouteNo); trip.m_strSAPrefixForAudio = string.Format(configV.SAPrefixFmt, trip.m_strRouteNoForAudio); trip.m_strServiceAlert = configSA.GetContent(strProjectTag, strRouteNo); if (trip.m_strServiceAlert != null) { trip.m_strServiceAlert2 = trip.m_strServiceAlert.Replace("\r\n", " ").Replace('\n', ' '); } } trip.m_configV = configV; trip.m_fFerry = fFerry; trip.m_nRouteLength = nRouteLength; trip.m_Queue = queue; trip.m_colNextStop = new ReadOnlyCollection <string>(colNextStop); trip.m_nNextStopIndex = nNextStopIndex; trip.m_Platform = trip.m_Queue.Dequeue(); trip.UpdateDistanceToEnd(); // trip.OnNewPlatform(false, true); switch (configRP.FareboxFields) { case Vehicle.FareboxFields.RouteNo: vehicle.QueueRequest(new RequestEventArgs(RequestType.Farebox, new Farebox(strRouteNo, null))); break; case Vehicle.FareboxFields.RouteNoTripNo: vehicle.QueueRequest(new RequestEventArgs(RequestType.Farebox, new Farebox(strRouteNo, nTripNo))); break; case Vehicle.FareboxFields.TripNo: if (nTripNo.HasValue) { vehicle.QueueRequest(new RequestEventArgs(RequestType.Farebox, new Farebox(null, nTripNo))); } break; } } catch (Exception) {} return(trip); }
internal DriverConfig(XmlDocument doc) { m_Doc = doc; m_nVersion = (byte)BaseN.S64ToInt(m_Doc.DocumentElement.GetAttribute("V", string.Empty)); }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); Stream FStream = null; openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "ENC files (*.ENC)|*.ENC"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; // Составляем таблицы для прямого и обратного преобразования byte cod = 0; char sumbol = 'А'; for (int i = 0; i < 32; i++) { Table.Add(cod, sumbol); // Ключ - бит, значение - символ InvTable.Add(sumbol, cod); // Ключ - символ, значение - бит cod++; sumbol++; } if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { if ((FStream = openFileDialog1.OpenFile()) != null) { } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } byte[] md5Hash = ComputeMD5Checksum(openFileDialog1.FileName); BaseN Hachcod = new BaseN(); string strHash = Hachcod.Encode(md5Hash); FStream = openFileDialog1.OpenFile(); var hvost = 5 - FStream.Length % 5; DecBytes = new byte[FStream.Length]; BinaryReader BinReader = new BinaryReader(FStream); while (FStream.Position < FStream.Length) { ulong ind = (ulong)FStream.Position; DecBytes[FStream.Position] = (byte)(BinReader.ReadByte()); } /* * // Заполняем хвосты нулями и добавляем в последний байт длину хвоста * if (hvost == 0) * { * DecBytes = new byte[FStream.Length + 5]; * DecBytes[DecBytes.Count()-1] = 0; * for (var i = FStream.Length; i > DecBytes.Count() - 1; i++) * { * DecBytes[i] = 0; * } * } * else * { * DecBytes = new byte[FStream.Length + hvost]; * DecBytes[DecBytes.Count() - 1] = (byte)hvost; * for (var i = FStream.Length; i > DecBytes.Count() - 1; i++) * { * DecBytes[i] = 0; * } * } * BinaryReader BinReader = new BinaryReader(FStream); * * while (FStream.Position < FStream.Length) * { * ulong ind = (ulong)FStream.Position; * DecBytes[FStream.Position] = (byte)(BinReader.ReadByte()); * * } * ulong buffer; // Буфер для 40 бит * for (var i = 0; i < DecBytes.Count(); i += 5) * { * buffer = 0; * for (int j = 0; j < 5; j++) // Заполняем буфер * { * buffer = (buffer << 8) + DecBytes[i + j]; * } * byte[] byteBuff = new byte[8]; * for (int j = 7; j >= 0; j--) // Заполняем буферный массив * { * byteBuff[j] = (byte)(buffer & 31); * buffer >>= 5; * } * for (int j = 0; j < 8; j++) * { * Bytes.Add(byteBuff[j]); * } * * }*/ // Прямое преобразование (в радиограмму) /*while (FStream.Position < FStream.Length) * { * ulong ind = (ulong)FStream.Position; * DecBytes[FStream.Position] = (byte)(BinReader.ReadByte()); * byte lowBit = (byte)(DecBytes[ind] & lowMask); // Младшие 4 бита байта * byte hiBit = (byte)((DecBytes[ind] & hiMask) >> 4); // Старшие 4 бита байта * // Заполняем список полубайтами * Bytes.Add(hiBit); * Bytes.Add(lowBit); * }*/ var refDec = DecBytes; BaseN triOd = new BaseN(); string alf = strHash + triOd.Encode(refDec); FStream.Close(); string inputText = FormatToRG(alf); progressBar1.Minimum = 0; progressBar1.Maximum = 100; progressBar1.Value = 0; for (int i = 0; i < 100; i++) { progressBar1.Value++; System.Threading.Thread.Sleep(20); } Stream FWStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "txt files (*.txt)|*.txt"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((FWStream = saveFileDialog1.OpenFile()) != null) { UTF8Encoding UTF8WithPreamble = new UTF8Encoding(true); StreamWriter BinWriter = new StreamWriter(FWStream, UTF8WithPreamble); BinWriter.Write(inputText); BinWriter.Close(); FWStream.Close(); } } //progressBar1.Value = 0; Table.Clear(); InvTable.Clear(); }
private void button2_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); Stream FStream = null; openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "txt files (*.txt)|*.txt"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; // Составляем таблицы для прямого и обратного преобразования byte cod = 0; char sumbol = 'А'; for (int i = 0; i < 16; i++) { Table.Add(cod, sumbol); // Ключ - бит, значение - символ InvTable.Add(sumbol, cod); // Ключ - символ, значение - бит cod++; sumbol++; } if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { if ((FStream = openFileDialog1.OpenFile()) != null) { } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } Stream fs = openFileDialog1.OpenFile(); byte[] DecBytes = new byte[fs.Length - 3]; BinaryReader BinReader = new BinaryReader(fs); while (fs.Position < fs.Length) { if (fs.Position < 3) { BinReader.ReadByte(); continue; } DecBytes[fs.Position - 3] = (byte)(BinReader.ReadByte()); } BinReader.Close(); fs.Close(); //Получаем строку и удаляем из нее символы форматирования string Log_txt = Encoding.UTF8.GetString(DecBytes, 0, DecBytes.Length); Log_txt = Log_txt.Replace("\n", ""); Log_txt = Log_txt.Replace(" ", ""); string strHash = Log_txt.Substring(0, 26); var refDec = Log_txt.Substring(26, Log_txt.Length - 26); BaseN triOd = new BaseN(); byte[] alf = triOd.Decode(refDec); /*// Обратное преобразование * foreach (char letter in Log_txt) * { * Bytes.Add(InvTable[letter]); // Создаем список полубайт * } * byte[] WrtBytes = new byte[Bytes.Count()/2]; * for (int i = 0; i < Bytes.Count(); i += 2) * { * byte buf = (byte)((Bytes[i] << 4) + (Bytes[i+1])); // Складываем два полубайта в байт * WrtBytes[i / 2] = buf; * } */ progressBar1.Minimum = 0; progressBar1.Maximum = 100; progressBar1.Value = 0; for (int i = 0; i < 100; i++) { progressBar1.Value++; System.Threading.Thread.Sleep(12); } System.Threading.Thread.Sleep(400); Stream FWStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "ENC files (*.ENC)|*.ENC"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((FWStream = saveFileDialog1.OpenFile()) != null) { BinaryWriter BinWriter = new BinaryWriter(FWStream); BinWriter.Write(alf); BinWriter.Close(); FWStream.Close(); } } byte[] md5Hash = ComputeMD5Checksum(saveFileDialog1.FileName); BaseN Hachcod = new BaseN(); if (strHash != Hachcod.Encode(md5Hash)) { MessageBox.Show("Файл поврежден. Хэш суммы не равны!!!"); } //progressBar1.Value = 0; Table.Clear(); InvTable.Clear(); }
private Base GetMethod() { Base method = null; string alphabet = tbAlphabet.Text; if (tbSpecialChar.Text.Length > 1) throw new ArgumentException("Special char should contains one symbol"); char special = string.IsNullOrWhiteSpace(tbSpecialChar.Text) ? (char)0 : tbSpecialChar.Text[0]; Encoding textEncoding = cmbTextEncoding.SelectedItem != null ? (Encoding)((ComboBoxItem)cmbTextEncoding.SelectedItem).Value : null; bool parallel = cbParallel.Checked; switch (cmbMethod.SelectedItem.ToString()) { case "Base32": method = new Base32(alphabet, special, textEncoding); break; case "Base64": method = new Base64(alphabet, special, textEncoding, parallel); break; case "Base128": method = new Base128(alphabet, special, textEncoding); break; case "Base256": method = new Base256(alphabet, special, textEncoding); break; case "Base1024": method = new Base1024(alphabet, special, textEncoding); break; case "Base4096": method = new Base4096(alphabet, special, textEncoding); break; case "ZBase32": method = new ZBase32(alphabet, special, textEncoding); break; case "Base85": method = new Base85(alphabet, special, cbPrefixPostfix.Checked, textEncoding); break; case "Base91": method = new Base91(alphabet, special, textEncoding); break; case "BaseN": method = new BaseN(alphabet, (uint)nudMaxBitsCount.Value, textEncoding, cbReverseOrder.Checked, parallel); break; case "BaseBigN": method = new BaseBigN(alphabet, (uint)nudMaxBitsCount.Value, textEncoding, cbReverseOrder.Checked, parallel, cbMaxCompression.Checked); break; } tbBitsPerChars.Text = method.BlockBitsCount + "/" + method.BlockCharsCount; tbRatio.Text = ((double)method.BlockBitsCount / method.BlockCharsCount).ToString("0.000000"); nudAlphabetLength.Value = method.CharsCount; return method; }
public object Index([FromForm] string url) { // Create object to return APIResult result = new APIResult() { Status = (int)APIStatus.Failure, Message = "", URL = url, Shortcut = string.Empty, Popularity = 0 }; // Get the URL's SHA512 & SHA256 hash string sha512 = SHA512Hash.GetSHA512Hash(url); string sha256 = SHA256Hash.GetSHA256Hash(url); // Open up a connection to Cassandra CassandraConnection csConnection = new CassandraConnection(); // Get connection session ISession csSession = csConnection.GetSession(); // Lookup database and return the URL's signature if it exists SignatureLookup signatureLookup = new SignatureLookup(csSession); if (signatureLookup.LookupSignature(sha512, sha256, out string signature, out long hits)) { result.Shortcut = this.MakeShortcut(signature); result.Popularity = hits; result.Status = (int)APIStatus.Success; return(Json(result)); } // Get total URL count from the running service long id = 0; try { const string BOT = "<~BOT~>"; const string EOT = "<~EOT~>"; const string COMMAND_COUNT = "COUNT"; string message = string.Format("{0}{1}{2}", BOT, COMMAND_COUNT, EOT); string ip = "127.0.0.1"; int port = 7079; AsyncClientSocket asyncClientSocket = new AsyncClientSocket(); asyncClientSocket.Transmit(ip, port, message, out string response); //SyncClientSocket.Transmit(ip, port, message, out string response); if (response == string.Empty) { result.Message = "Service Unavailable!"; return(Json(result)); } id = long.Parse(response); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } // Prepare dictionary char[] dictionary = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; // Get signature signature = BaseN.ChangeBase(id, dictionary); // Unique signature is now set result.Shortcut = this.MakeShortcut(signature); // Insert the new URL into the database URLInsertion urlInsertion = new URLInsertion(csSession); if (urlInsertion.InsertURL(url, signature, sha512, sha256)) { result.Popularity = 1; result.Status = (int)APIStatus.Success; } return(Json(result)); }
private Base GetMethod() { Base method = null; string alphabet = tbAlphabet.Text; if (tbSpecialChar.Text.Length > 1) { throw new ArgumentException("Special char should contains one symbol"); } char special = string.IsNullOrWhiteSpace(tbSpecialChar.Text) ? (char)0 : tbSpecialChar.Text[0]; Encoding textEncoding = cmbTextEncoding.SelectedItem != null ? (Encoding)((ComboBoxItem)cmbTextEncoding.SelectedItem).Value : null; bool parallel = cbParallel.Checked; switch (cmbMethod.SelectedItem.ToString()) { case "Base32": method = new Base32(alphabet, special, textEncoding); break; case "Base64": method = new Base64(alphabet, special, textEncoding, parallel); break; case "Base128": method = new Base128(alphabet, special, textEncoding); break; case "Base256": method = new Base256(alphabet, special, textEncoding); break; case "Base1024": method = new Base1024(alphabet, special, textEncoding); break; case "Base4096": method = new Base4096(alphabet, special, textEncoding); break; case "ZBase32": method = new ZBase32(alphabet, special, textEncoding); break; case "Base85": method = new Base85(alphabet, special, cbPrefixPostfix.Checked, textEncoding); break; case "Base91": method = new Base91(alphabet, special, textEncoding); break; case "BaseN": method = new BaseN(alphabet, (uint)nudMaxBitsCount.Value, textEncoding, cbReverseOrder.Checked, parallel); break; case "BaseBigN": method = new BaseBigN(alphabet, (uint)nudMaxBitsCount.Value, textEncoding, cbReverseOrder.Checked, parallel, cbMaxCompression.Checked); break; } tbBitsPerChars.Text = method.BlockBitsCount + "/" + method.BlockCharsCount; tbRatio.Text = ((double)method.BlockBitsCount / method.BlockCharsCount).ToString("0.000000"); nudAlphabetLength.Value = method.CharsCount; return(method); }