powerfun-new-net/Unility/CommonHelper.cs

67 lines
2.1 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2021-07-07 09:49:36 +08:00
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using TurfCS;
namespace OnlineUserPool.Unility
{
public class CommonHelper
{
public static double GetDistances(double lon, double lat, double lon1, double lat1)
{
var pt1 = Turf.Point(new double[] { lon, lat });
var pt2 = Turf.Point(new double[] { lon1, lat1 });
var value = Turf.Distance(pt1, pt2, "kilometers") * 1000;
return Math.Round(value, 2);
}
public static int GenerateRandomInteger(int min = 0, int max = int.MaxValue)
{
var randomNumberBuffer = new byte[10];
new RNGCryptoServiceProvider().GetBytes(randomNumberBuffer);
return new Random(BitConverter.ToInt32(randomNumberBuffer, 0)).Next(min, max);
}
2021-07-07 09:49:36 +08:00
public static byte[] Compress(string text)
{
var bytes = Encoding.UTF8.GetBytes(text);
return Compress(bytes);
}
public static byte[] Compress(byte[] bytes)
{
//var bytes = Encoding.Unicode.GetBytes(text);
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
gs.Write(bytes, 0, bytes.Length);
}
return mso.ToArray();
}
}
public static string Decompress(byte[] data)
{
// Read the last 4 bytes to get the length
byte[] lengthBuffer = new byte[4];
Array.Copy(data, data.Length - 4, lengthBuffer, 0, 4);
int uncompressedSize = BitConverter.ToInt32(lengthBuffer, 0);
var buffer = new byte[uncompressedSize];
using (var ms = new MemoryStream(data))
{
using (var gzip = new GZipStream(ms, CompressionMode.Decompress))
{
gzip.Read(buffer, 0, uncompressedSize);
}
}
return Encoding.UTF8.GetString(buffer);
}
}
}