how can i get xml fid digitalpersona - c#

I have an application in Xamarin forms that uses digital persona which I adapted successfully from this code of Android java
The problem is that this app returns only a byte[] array of a fingerprint, so i need to send fid xml to web service so i can compare validate fingers
but i dont know how
heres is the class that i use to parse stream from digital persona to array byte
public class UruImage
{
private static int IMAGE_HEIGHT = 290;
private static int IMAGE_WIDTH = 384;
private static int QUALITY = 75;
private static string LOG_TAG = "U.are.U-Image ";
// Raw data
private short unknown_00;
private byte[] unknown_07 = new byte[9];
private byte[] unknown_2E = new byte[18];
public short num_lines;
public short width;
public sbyte key_number;
public byte[] flags_num_lines = new byte[30];
public byte[] data;
// setter & getter
public void createFromData(ByteBuffer sData) //throws IOException
{
try
{
//tengo duda con lo indices en codigo java esta sData.GetShort(); sin index
sData.Order(ByteOrder.LittleEndian);
unknown_00 = sData.Short;
System.Console.WriteLine(LOG_TAG+" unknown_00: " + Convert.ToString(unknown_00));
width = sData.Short;
System.Console.WriteLine(LOG_TAG+ "width: " + Convert.ToString(width));
num_lines = sData.Short;
System.Console.WriteLine(LOG_TAG+ "num_lines: " + Convert.ToString(num_lines));
key_number = sData.Get();
System.Console.WriteLine(LOG_TAG+ "key_number: " + Convert.ToString(key_number));
sData.Get(unknown_07, 0, 9);
System.Console.WriteLine(LOG_TAG+ "unknown_07: " + bytesToHex(unknown_07));
sData.Get(flags_num_lines, 0, 30);
System.Console.WriteLine(LOG_TAG, "flags_num_lines: " + bytesToHex(flags_num_lines));
sData.Get(unknown_2E, 0, 18);
System.Console.WriteLine(LOG_TAG+ "unknown_2E: " + bytesToHex(unknown_2E));
data = new byte[(num_lines + 1) * width]; // extra line for decoding
sData.Get(data, 0, num_lines * width);
}
catch (Exception ex) {
System.Console.WriteLine(" createFromData " + ex.Message + " " + ex.ToString());
throw new Java.IO.IOException();
}
}
public Byte[] getImageBitmap()
{
try
{
int dataOffset = 0;
int[] pixels = new int[IMAGE_WIDTH * IMAGE_HEIGHT];
int i = 0;
for (int y = 0; y < IMAGE_HEIGHT; y++)
{
for (int x = 0; x < IMAGE_WIDTH; x++)
{
int gray = data[dataOffset + i] & 0xff;
pixels[i] = unchecked((int)0xff000000) | gray << 16 | (gray << 8) | gray;
i++;
}
}
Bitmap bm = Bitmap.CreateBitmap(pixels, IMAGE_WIDTH, IMAGE_HEIGHT, Bitmap.Config.Argb8888);
MemoryStream bs = new MemoryStream();
bm.Compress(Bitmap.CompressFormat.Jpeg, QUALITY, bs);
return bs.ToArray();
}
catch (System.Exception ex) {
System.Console.WriteLine("Get Image bitmap" + ex.Message + " " + ex.StackTrace);
}
return new MemoryStream().ToArray();
}
public byte[] getPgm()
{
return data;
}
public void invert()
{
try
{
int length = width * num_lines;
int i;
//duda con conversion de valor byte max_value = 0xFFFFFFFF;
byte max_value = unchecked((byte)0xFFFFFFFF);
for (i = 0; i < length; i++)
{
data[i] = (byte)(max_value - data[i]);
}
}
catch (System.Exception ex) {
System.Console.WriteLine("Invert "+ex.Message);
}
}
protected static char[] hexArray = "0123456789ABCDEF".ToCharArray();
private static String bytesToHex(byte[] bytes)
{
char[] hexChars = new char[bytes.Length * 2];
for (int j = 0; j < bytes.Length; j++)
{
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[(uint)v >> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}

Related

ARC4 encryption not working correctly server side

I have a socket.io client which sends data to each other where encryption is based on ARC4.
I tried multiple different scenarios but it keeps failing to decrypt anything and I'm not sure why.
The class: ARC4_New
public class ARC4_New
{
private int i;
private int j;
private byte[] bytes;
public const int POOLSIZE = 256;
public ARC4_New()
{
bytes = new byte[POOLSIZE];
}
public ARC4_New(byte[] key)
{
bytes = new byte[POOLSIZE];
this.Initialize(key);
}
public void Initialize(byte[] key)
{
this.i = 0;
this.j = 0;
for (i = 0; i < POOLSIZE; ++i)
{
this.bytes[i] = (byte)i;
}
for (i = 0; i < POOLSIZE; ++i)
{
j = (j + bytes[i] + key[i % key.Length]) & (POOLSIZE - 1);
this.Swap(i, j);
}
this.i = 0;
this.j = 0;
}
private void Swap(int a, int b)
{
byte t = this.bytes[a];
this.bytes[a] = this.bytes[b];
this.bytes[b] = t;
}
public byte Next()
{
this.i = ++this.i & (POOLSIZE - 1);
this.j = (this.j + this.bytes[i]) & (POOLSIZE - 1);
this.Swap(i, j);
return this.bytes[(this.bytes[i] + this.bytes[j]) & 255];
}
public void Encrypt(ref byte[] src)
{
for (int k = 0; k < src.Length; k++)
{
src[k] ^= this.Next();
}
}
public void Decrypt(ref byte[] src)
{
this.Encrypt(ref src);
}
}
public System.Numerics.BigInteger RandomInteger(int bitSize)
{
var integerData = new byte[bitSize / 8];
_numberGenerator.NextBytes(integerData);
integerData[integerData.Length - 1] &= 0x7f;
return new System.Numerics.BigInteger(integerData);
}
My script which generates a key:
System.Numerics.BigInteger DHPrivate = RandomInteger(256);
System.Numerics.BigInteger DHPrimal = RandomInteger(256);
System.Numerics.BigInteger DHGenerated = RandomInteger(256);
if (DHGenerated > DHPrimal)
{
System.Numerics.BigInteger tempG = DHGenerated;
DHGenerated= DHPrimal;
DHPrimal = tempG;
}
Then with those values I generate a public key:
System.Numerics.BigInteger DHPublic = System.Numerics.BigInteger.ModPow(DHGenerated, DHPrivate, DHPrimal);
Then I encrypt this key:
string pkey = EncryptY(CalculatePublic, DHPublic);
(Additional code for the encryption below)
protected virtual string EncryptY(Func<System.Numerics.BigInteger, System.Numerics.BigInteger> calculator, System.Numerics.BigInteger value)
{
byte[] valueData = Encoding.UTF8.GetBytes(value.ToString());
valueData = PKCSPad(valueData);
Array.Reverse(valueData);
var paddedInteger = new System.Numerics.BigInteger(valueData);
System.Numerics.BigInteger calculatedInteger = calculator(paddedInteger);
byte[] paddedData = calculatedInteger.ToByteArray();
Array.Reverse(paddedData);
string encryptedValue = Utils.Converter.BytesToHexString(paddedData).ToLower();
return encryptedValue.StartsWith("00") ? encryptedValue.Substring(2) : encryptedValue;
}
protected virtual byte[] PKCSPad(byte[] data)
{
var buffer = new byte[128 - 1];
int dataStartPos = (buffer.Length - data.Length);
buffer[0] = (byte)Padding;
Buffer.BlockCopy(data, 0, buffer, dataStartPos, data.Length);
int paddingEndPos = (dataStartPos - 1);
bool isRandom = (Padding == PKCSPadding.RandomByte);
for (int i = 1; i < paddingEndPos; i++)
{
buffer[i] = (byte)(isRandom ?
_numberGenerator.Next(1, 256) : byte.MaxValue);
}
return buffer;
}
After all that I sent the string PKEY to the server.
And after decrypting the string, the server gets the public key which is for example: 127458393
When I connect both my client and server using: 127458393
Like:
BigInteger key = System.Numerics.BigInteger.Parse("127458393");
client = new ARC4_New(PrimalDing.ToByteArray());
My client sends a string like:
client.Encrypt(BYTE_HERE);
And my server reads it like:
client.Decrypt(BYTE_HERE);
But it fails, and gets a random unreadable string.
What am I doing wrong here?
I managed to fix the issue
For some reason, my server was and is reversing the bytes i used in the ARC4 client..
So i simple reverse it now as a hotfix
System.Numerics.BigInteger temp = System.Numerics.BigInteger.Parse(textBox1.Text);
client = new ARC4_New(temp.ToByteArray().Reverse().ToArray());

access class impossible

I created a class that I called "Descripteurs". I want to call this class to create a csv file. So I have called my list of descriptors created in the class " Descriptors ".
I can't not associate my positions of pixel with descriptors to store it in my csv.
I should have with every pixel in my image the descriptors in the class " Descripteurs"(moyenne, number of black pixel, number of white pixel.....). The csv should have the position in each pixel and all the descriptors calculated in the class "Descripteurs ". I don't know if there is a thread problem or not.
My function is here:
public bool StoreIntoCsv(string pathOriginalPicture, string pathOriginalPictureWithOnlyOneLayer, int classe, BackgroundWorker worker, DoWorkEventArgs e)
{
//preprocessing of the original picture and the original picture with only one layer
Descripteurs featuresPathOriginal = new Descripteurs(new Bitmap(pathOriginalPicture));// m_constructeur de la classe Descripteurs
Bitmap binaryOriginalPictureWithOnlyOneLayer = new Bitmap(pathOriginalPictureWithOnlyOneLayer); // correspond à l'image binaire avec le L.
//we want to get the class of the picture
string[] res = pathOriginalPicture.Split('\\');
string classeName = res[res.Count() - 2]; // count = compter
//retrieving the file path of the csv
string pathFolder = pathOriginalPicture.Split('.').First();// le split divise la chaine en sous chaine en fonction des caractères
pathFolder = pathFolder.Remove(pathFolder.LastIndexOf('\\'));
string pathCsv = pathFolder + "\\" + classeName + ".csv";
libaforge.AForge.IntPoint pixel = new libaforge.AForge.IntPoint();
//open the stream
using (StreamWriter stream = File.AppendText(pathCsv)) //streamwriter permet d'écrire dans un fichier
{
//browse all the picture
for (int x = 0; x < binaryOriginalPictureWithOnlyOneLayer.Width; x = x + 2)
{
for (int y = 0; y < binaryOriginalPictureWithOnlyOneLayer.Height; y = y + 2)
{
//the user stop the application
if (worker.CancellationPending)//checks for cancel request
{
e.Cancel = true;
return false;
}
//we know, where is it the pixel black on the data set training
if (binaryOriginalPictureWithOnlyOneLayer.GetPixel(x, y).ToArgb() == Color.Black.ToArgb())
{
pixel.X = x;
pixel.Y = y;
WriteLineToCsv(pixel, featuresPathOriginal.Extract_Desscripteurs(pixel), classe, stream);
}
}
}
return true;
}
}
My class "Descripteurs is here:
namespace ProjetPRD
{
extern alias libaforge;
public class Descripteurs
{
//private Bitmap _imageLidar;
private static Bitmap image;
public Descripteurs(Bitmap img)
{
image = img;
}
//public static List <double> Extract_Desscripteurs(Bitmap image)
//public static List <double> Extract_Desscripteurs(libaforge.AForge.IntPoint pixel)
public double[] Extract_Desscripteurs(libaforge.AForge.IntPoint pixel)
{
int pixel_Central = 0;
double Moy2_Haut_Gauche = 0;
double Moy3_Haut_Droite = 0;
double Moy4_Bas_Gauche = 0;
double Moy5_Bas_Droite = 0;
int Difference = 0; // pour calculer la difference entre la valeur max et la valeur min de notre masc
int Nb_PNoir_Haut_Gauche = 0;
int Nb_PBlanc_Haut_Gauche = 0;
int Nb_PGris_Haut_Gauche = 0;
int Nb_PNoir_Haut_Droite = 0;
int Nb_PBlanc_Haut_Droite = 0;
int Nb_PGris_Haut_Droite = 0;
int Nb_PNoir_Bas_Gauche = 0;
int Nb_PBlanc_Bas_Gauche = 0;
int Nb_PGris_Bas_Gauche = 0;
int Nb_PNoir_Bas_Droite = 0;
int Nb_PBlanc_Bas_Droite = 0;
int Nb_PGris_Bas_Droite = 0;
List<double> caracteristique = new List <double>();
lock (image )
{
BitmapData bmd = new BitmapData();
try
{
Rectangle Rect = new Rectangle(0, 0, image.Width, image.Height);
bmd = image.LockBits(Rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
//System.Drawing.Imaging.BitmapData bmpData = bmd.LockBits(Rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,bmd.PixelFormat);
unsafe
{
byte* Ptr = (byte*)bmd.Scan0;
for (int j = 0; j < bmd.Height; j++)
{
for (int i = 0; i < bmd.Width; i++)
{
//initialisation des différents éléments du masque 3*3
int couleur1 = Ptr[j * bmd.Width + i];
int couleur2 = Ptr[j * bmd.Width + (i + 1)];
int couleur3 = Ptr[j * bmd.Width + (i + 2)];
int couleur4 = Ptr[(j + 1) * bmd.Width + i];
pixel_Central = Ptr[(j + 1) * bmd.Width + (i + 1)];
int couleur6 = Ptr[(j + 1) * bmd.Width + (i + 2)];
int couleur7 = Ptr[(j + 2) * bmd.Width + (i)];
int couleur8 = Ptr[(j + 2) * bmd.Width + (i + 1)];
int couleur9 = Ptr[(j + 2) * bmd.Width + (i + 2)];
//faire la moyenne de chaque bloc de 4
Moy2_Haut_Gauche = (couleur1 + couleur2 + couleur4 + pixel_Central) / 4;
Moy3_Haut_Droite = (couleur2 + couleur3 + pixel_Central + couleur6) / 4;
Moy4_Bas_Gauche = (couleur4 + pixel_Central + couleur7 + couleur8) / 4;
Moy5_Bas_Droite = (pixel_Central + couleur6 + couleur8 + couleur9) / 4;
//remplir la liste des caractéristiques
caracteristique.Add(pixel_Central);
caracteristique.Add(Moy2_Haut_Gauche);
caracteristique.Add(Moy3_Haut_Droite);
caracteristique.Add(Moy4_Bas_Gauche);
caracteristique.Add(Moy5_Bas_Droite);
int[] tab_Difference = { couleur1, couleur2, couleur3, couleur4, pixel_Central, couleur6, couleur7, couleur8, couleur9 };
Difference = tab_Difference.Max() - tab_Difference.Min();
int[] tab = { couleur1, couleur2, couleur4, pixel_Central };
for (int k = 0; k < tab.Length; k++)
{
if (tab[k] < 60)
{
Nb_PNoir_Haut_Gauche++;
}
else
{
if (tab[k] > 180)
{
Nb_PBlanc_Haut_Gauche++;
}
else
{
Nb_PGris_Haut_Gauche++;
}
}
}
int[] tab2 = { couleur2, couleur3, pixel_Central, couleur6 };
for (int m = 0; m < tab2.Length; m++)
{
if (tab2[m] < 60)
{
Nb_PNoir_Haut_Droite++;
}
else
{
if (tab2[m] > 180)
{
Nb_PBlanc_Haut_Droite++;
}
else
{
Nb_PGris_Haut_Droite++;
}
}
}
int[] tab3 = { couleur4, pixel_Central, couleur7, couleur8 };
for (int n = 0; n < tab3.Length; n++)
{
if (tab3[n] < 60)
{
Nb_PNoir_Bas_Gauche++;
}
else
{
if (tab3[n] > 180)
{
Nb_PBlanc_Bas_Gauche++;
}
else
{
Nb_PGris_Bas_Gauche++;
}
}
}
int[] tab4 = { pixel_Central, couleur6, couleur8, couleur9 };
for (int n = 0; n < tab4.Length; n++)
{
if (tab4[n] < 60)
{
Nb_PNoir_Bas_Droite++;
}
else
{
if (tab4[n] > 180)
{
Nb_PBlanc_Bas_Droite++;
}
else
{
Nb_PGris_Bas_Droite++;
}
}
}
caracteristique.Add(Difference);
caracteristique.Add(Nb_PNoir_Haut_Gauche);
caracteristique.Add(Nb_PNoir_Haut_Droite);
caracteristique.Add(Nb_PNoir_Bas_Gauche);
caracteristique.Add(Nb_PNoir_Bas_Droite);
caracteristique.Add(Nb_PBlanc_Haut_Gauche);
caracteristique.Add(Nb_PBlanc_Haut_Droite);
caracteristique.Add(Nb_PBlanc_Bas_Gauche);
caracteristique.Add(Nb_PBlanc_Bas_Droite);
caracteristique.Add(Nb_PGris_Haut_Gauche);
caracteristique.Add(Nb_PGris_Haut_Droite);
caracteristique.Add(Nb_PGris_Bas_Gauche);
caracteristique.Add(Nb_PGris_Bas_Droite);
}
}
//mesCaracteristiques = caracteristique.ToArray();
}
}
finally
{
image.UnlockBits(bmd);
}
//e.Graphics.DrawImage(bmd, 0, 150);
//return mesCaracteristiques;
return caracteristique.ToArray();
}
}
}
}
I don't know if i was clear with my explication but i really need help.

C# - Sending a WebSocket Message to the client

I followed the following tutorial to setup a websocket server in C#:
https://developer.mozilla.org/pt-BR/docs/WebSockets/Writing_WebSocket_server
After this, i wrote a part where it would decode a normal message and display it to me in a console.
Now, i want to be able to send this message back to the client (exactly what ws://echo.websocket.org does)
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Threading.Tasks;
namespace sockecho
{
class Program
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
Console.WriteLine("Server has started on 127.0.0.1:80.{0}Waiting for a connection...", Environment.NewLine);
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
NetworkStream stream = client.GetStream();
//enter to an infinite cycle to be able to handle every change in stream
while (true)
{
while (!stream.DataAvailable) ;
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
//translate bytes of request to string
String data = Encoding.UTF8.GetString(bytes);
if (new Regex("^GET").IsMatch(data))
{
#region startdata
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine + "Connection: Upgrade" + Environment.NewLine + "Upgrade: websocket" + Environment.NewLine + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + Environment.NewLine
+ Environment.NewLine);
stream.Write(response, 0, response.Length);
string responsel = Encoding.UTF8.GetString(response);
Console.WriteLine(responsel);
#endregion
}
else
{
//stream.Write(bytes, 0, bytes.Length);
string decodedmessage = GetMessage(bytes);
Console.WriteLine(decodedmessage);
byte[] toBytes = Encoding.ASCII.GetBytes(decodedmessage);
stream.Write(toBytes, 0, toBytes.Length);
}
}
}
private static string GetMessage (Byte[] bytes)
{
string DETEXT = "";
if (bytes[0] == 129)
{
int position = 0;
int Type = 0;
ulong length = 0;
if (bytes[1] - 128 >= 0 && bytes[1] - 128 <= 125)
{
length = (ulong)bytes[1] - 128;
position = 2;
}
else if (bytes[1] - 128 == 126)
{
Type = 1;
length = (ulong)256 * bytes[2] + bytes[3];
position = 4;
}
else if (bytes[1] - 128 == 127)
{
Type = 2;
for (int i = 0; i < 8; i++)
{
ulong pow = Convert.ToUInt64(Math.Pow(256, (7 - i)));
length = length + bytes[2 + i] * pow;
position = 10;
}
}
else
{
Type = 3;
Console.WriteLine("error 1");
}
if (Type < 3)
{
Byte[] key = new Byte[4] { bytes[position], bytes[position + 1], bytes[position + 2], bytes[position + 3] };
Byte[] decoded = new Byte[bytes.Length - (4 + position)];
Byte[] encoded = new Byte[bytes.Length - (4 + position)];
for (long i = 0; i < bytes.Length - (4 + position); i++) encoded[i] = bytes[i + position + 4];
for (int i = 0; i < encoded.Length; i++) decoded[i] = (Byte)(encoded[i] ^ key[i % 4]);
DETEXT = Encoding.UTF8.GetString(decoded);
}
}
else
{
Console.WriteLine("error 2: " + bytes[0].ToString());
}
return DETEXT;
}
}
}

Extract a table from PDF

I need a help with iText in C#. I'm trying to extract a table from a PDF file and save this into a new CSV file, keeping the values in the correct places. For this, I thought the solution was to create a two-dimensional array to organize the data.
Extracting all information from PDF with iText, I saw it was possible to get some numerical data that seemed to be the position of a piece of text on the page and I organized my array based these indexes. It didn’t work, the text was completely dispersed in various different cells. Now, I want to know what this values means, because they don't follow a "correct" order and I want to know if is possible to organize the future table with this.
I'm using ";" as delimiter cell.
For testing, I'm using this PDF
http://www.americana.sp.gov.br/americanaV5/download/contasPublicas/Despesa_Categoria_Economica_2014.pdf
Here's my code:
protected void Button2_Click(object sender, EventArgs e)
{
try
{
TextBox2.Text = "";
byte[] conteudo = download(TextBox1.Text);
if (conteudo != null)
{
PdfReader leitorp = new PdfReader(conteudo);
ITextExtractionStrategy estrategia = new SimpleTextExtractionStrategy();
List<Celula> celulas = new List<Celula>();
int i, j;
for (i = 1; i <= leitorp.NumberOfPages; i++)
{
//Total and crude extraction of all information from text in PDF via iText, separate lines in an array of strings.
string[] linhas = (Encoding.UTF8.GetString(Encoding.Convert(Encoding.Default, Encoding.UTF8, leitorp.GetPageContent(i)))).Split('\n');
for (j = 1; j < linhas.Length; j++)
{
if (linhas[j].Length > 2)
{
if (linhas[j].Substring(0, 2).Equals("BT"))
{
string[] campos = linhas[j].Split(' ');
Celula umacelula = new Celula();
umacelula.coluna = float.Parse(campos[1]);
umacelula.linha = float.Parse(campos[2]);
linhadodebug = j;
int t1 = linhas[j].IndexOf('(');
int t2 = linhas[j].LastIndexOf(')');
umacelula.conteudo = System.Text.RegularExpressions.Regex.Replace((linhas[j].Substring(linhas[j].IndexOf('(') + 1, (linhas[j].LastIndexOf(')') - 1 - linhas[j].IndexOf('(')))), #"\s\s+", "");
celulas.Add(umacelula);
}
}
}
}
leitorp.Close();
string[] totallinhas = new string[celulas.Count];
string[] totalcolunas = new string[celulas.Count];
for (i = 0; i < celulas.Count; i++)
{
totallinhas[i] = celulas[i].linha.ToString();
totalcolunas[i] = celulas[i].coluna.ToString();
}
totallinhas = totallinhas.Distinct().ToArray();
totalcolunas = totalcolunas.Distinct().ToArray();
Array.Sort(totallinhas);
Array.Reverse(totallinhas);
Array.Sort(totalcolunas);
Array.Reverse(totalcolunas);
string[,] matriz = new string[totallinhas.Length + 1, totalcolunas.Length + 1];
for (i = 1; i < totallinhas.Length; i++)
{
matriz[i, 0] = totallinhas[i - 1].ToString();
}
for (i = 1; i < totalcolunas.Length; i++)
{
matriz[0, i] = totalcolunas[i - 1].ToString();
}
int z;
for (i = 0; i < celulas.Count(); i++)
{
for (j = 1; j < matriz.GetLength(0); j++)
{
for (z = 1; z < matriz.GetLength(1); z++)
{
if ((celulas[i].linha.ToString().Equals(matriz[j, 0])) && (celulas[i].coluna.ToString().Equals(matriz[0, z])))
{
matriz[j, z] = celulas[i].conteudo.ToString();
}
}
}
}
StringWriter texto = new StringWriter();
for (i = 0; i < matriz.GetLength(0); i++)
{
for (j = 0; j < matriz.GetLength(1); j++)
{
texto.Write(matriz[i, j] + ";");
}
texto.WriteLine();
}
Response.ContentType = "text/plain";
Response.AddHeader("content-disposition", "attachment;filename=" + string.Format("teste-{0}.csv", string.Format("{0:ddMMyyyy}", DateTime.Today)));
Response.Clear();
using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
{
writer.Write(texto.ToString());
}
Response.End();
}
}
catch (Exception E)
{
TextBox2.Text = "Erro Button2_Click: " + E.Message + " # " + linhadodebug.ToString();
}
}
And here, the struct of celula (cell) and method to download the file:
public struct Celula
{
public float coluna;
public float linha;
public string conteudo;
public Celula(float coluna, float linha, string conteudo)
{
this.coluna = coluna;
this.linha = linha;
this.conteudo = conteudo;
}
public Celula(Celula celula)
{
this.coluna = celula.coluna;
this.linha = celula.linha;
this.conteudo = celula.conteudo;
}
}
protected byte[] download(string url)
{
try
{
WebRequest endereco = HttpWebRequest.Create(url);
Stream leitor = endereco.GetResponse().GetResponseStream();
MemoryStream memoria = new MemoryStream();
byte[] conteudo = null;
int count = 0;
do
{
byte[] buffer = new byte[1024];
count = leitor.Read(buffer, 0, 1024);
memoria.Write(buffer, 0, count);
}
while (leitor.CanRead && count > 0);
// Converte da memória direto para bytes
conteudo = memoria.ToArray();
if (conteudo != null)
{
return conteudo;
}
else
{
TextBox2.Text = "Error: download null.";
return null;
}
}
catch (Exception E)
{
TextBox2.Text = "Error download: " + E.Message;
return null;
}
}
This is a non-profit project. I hope you can help me. Thank you!

Get longest substring between two strings

I have two words,
britanicaeng and
britanicahin
I need to find out the longest common word between these i.e, britanica.
How can I do this in C# ?
Try this method:
public static string FindLongestCommonSubstring(string s1, string s2)
{
int[,] a = new int[s1.Length + 1, s2.Length + 1];
int row = 0; // s1 index
int col = 0; // s2 index
for (var i = 0; i < s1.Length; i++)
for (var j = 0; j < s2.Length; j++)
if (s1[i] == s2[j])
{
int len = a[i + 1, j + 1] = a[i, j] + 1;
if (len > a[row, col])
{
row = i + 1;
col = j + 1;
}
}
return s1.Substring(row - a[row, col], a[row, col]);
}
Usage example:
Console.WriteLine(FindLongestCommonSubstring("britanicaeng", "britanicahin"));
I refactored the C++ code from Ashutosh Singh at https://iq.opengenus.org/longest-common-substring-using-rolling-hash/ to create a rolling hash approach in C# - this will find the substring in O(N * log(N)^2) time and O(N) space
using System;
using System.Collections.Generic;
public class RollingHash
{
private class RollingHashPowers
{
// _mod = prime modulus of polynomial hashing
// any prime number over a billion should suffice
internal const int _mod = (int)1e9 + 123;
// _hashBase = base (point of hashing)
// this should be a prime number larger than the number of characters used
// in my use case I am only interested in ASCII (256) characters
// for strings in languages using non-latin characters, this should be much larger
internal const long _hashBase = 257;
// _pow1 = powers of base modulo mod
internal readonly List<int> _pow1 = new List<int> { 1 };
// _pow2 = powers of base modulo 2^64
internal readonly List<long> _pow2 = new List<long> { 1L };
internal void EnsureLength(int length)
{
if (_pow1.Capacity < length)
{
_pow1.Capacity = _pow2.Capacity = length;
}
for (int currentIndx = _pow1.Count - 1; currentIndx < length; ++currentIndx)
{
_pow1.Add((int)(_pow1[currentIndx] * _hashBase % _mod));
_pow2.Add(_pow2[currentIndx] * _hashBase);
}
}
}
private class RollingHashedString
{
readonly RollingHashPowers _pows;
readonly int[] _pref1; // Hash on prefix modulo mod
readonly long[] _pref2; // Hash on prefix modulo 2^64
// Constructor from string:
internal RollingHashedString(RollingHashPowers pows, string s, bool caseInsensitive = false)
{
_pows = pows;
_pref1 = new int[s.Length + 1];
_pref2 = new long[s.Length + 1];
const long capAVal = 'A';
const long capZVal = 'Z';
const long aADif = 'a' - 'A';
unsafe
{
fixed (char* c = s)
{
// Fill arrays with polynomial hashes on prefix
for (int i = 0; i < s.Length; ++i)
{
long v = c[i];
if (caseInsensitive && capAVal <= v && v <= capZVal)
{
v += aADif;
}
_pref1[i + 1] = (int)((_pref1[i] + v * _pows._pow1[i]) % RollingHashPowers._mod);
_pref2[i + 1] = _pref2[i] + v * _pows._pow2[i];
}
}
}
}
// Rollingnomial hash of subsequence [pos, pos+len)
// If mxPow != 0, value automatically multiply on base in needed power.
// Finally base ^ mxPow
internal Tuple<int, long> Apply(int pos, int len, int mxPow = 0)
{
int hash1 = _pref1[pos + len] - _pref1[pos];
long hash2 = _pref2[pos + len] - _pref2[pos];
if (hash1 < 0)
{
hash1 += RollingHashPowers._mod;
}
if (mxPow != 0)
{
hash1 = (int)((long)hash1 * _pows._pow1[mxPow - (pos + len - 1)] % RollingHashPowers._mod);
hash2 *= _pows._pow2[mxPow - (pos + len - 1)];
}
return Tuple.Create(hash1, hash2);
}
}
private readonly RollingHashPowers _rhp;
public RollingHash(int longestLength = 0)
{
_rhp = new RollingHashPowers();
if (longestLength > 0)
{
_rhp.EnsureLength(longestLength);
}
}
public string FindCommonSubstring(string a, string b, bool caseInsensitive = false)
{
// Calculate max neede power of base:
int mxPow = Math.Max(a.Length, b.Length);
_rhp.EnsureLength(mxPow);
// Create hashing objects from strings:
RollingHashedString hash_a = new RollingHashedString(_rhp, a, caseInsensitive);
RollingHashedString hash_b = new RollingHashedString(_rhp, b, caseInsensitive);
// Binary search by length of same subsequence:
int pos = -1;
int low = 0;
int minLen = Math.Min(a.Length, b.Length);
int high = minLen + 1;
var tupleCompare = Comparer<Tuple<int, long>>.Default;
while (high - low > 1)
{
int mid = (low + high) / 2;
List<Tuple<int, long>> hashes = new List<Tuple<int, long>>(a.Length - mid + 1);
for (int i = 0; i + mid <= a.Length; ++i)
{
hashes.Add(hash_a.Apply(i, mid, mxPow));
}
hashes.Sort(tupleCompare);
int p = -1;
for (int i = 0; i + mid <= b.Length; ++i)
{
if (hashes.BinarySearch(hash_b.Apply(i, mid, mxPow), tupleCompare) >= 0)
{
p = i;
break;
}
}
if (p >= 0)
{
low = mid;
pos = p;
}
else
{
high = mid;
}
}
// Output answer:
return pos >= 0
? b.Substring(pos, low)
: string.Empty;
}
}

Categories

Resources