Issues with Hex.encodeHexString(byte[] hexStringByteArray); - hex

I was used Hex.encodeHexString(byte[] hexStringByteArray); api for convert byte array to String but in two different situations not able to get the excepted values.
Excepted String tcpPort = "1443";
In byte array [5,-93] --> In Hex String : 05a3
byte[] value1 = new byte[]{[5, -93]};
String tcpPort1 = Hex.encodeHexString(value1); // Incorrect value 05a3
Excepted String bufferSize = "0578";
In byte array [[5, 120] --> In Hex String : 0578
String bufferSize = "0578"; // in byte array [5,120]
byte[] value2 = new byte[]{[5, 120]};
String bufferSize = Hex.encodeHexString(value1); --- Correct value 0578
1 is incorrect and 2 is correct. Please help on this. I have to correct both values in same way.

Related

Get value from JArray item with has inconsistent values

I'm reading a JSON file from an external partner which is not totally consistent (and they are not changing it anytime soon).
I want to check the value of the field bathroom and store that in an integer. So here's a mapping of the potential values there are and what I would like to get:
"" = 0
= 0 (here no value is present)
2 = 2
"2" = 2
But whatever I try (see below) I get the error:
Input string was not in a correct format.
Dim json as string = "[{""bathrooms"": """"}, {""bathrooms"": }, {""bathrooms"": 2},{""bathrooms"": ""1""}]"
Dim iBathrooms As Integer
Dim jsonArray As Newtonsoft.Json.Linq.JArray = JArray.Parse(json)
For Each item In jsonArray
iBathrooms= If(item.Value(Of Integer?)("bathrooms"), 0)
iBathrooms = If(CType(item("bathrooms"), Integer?), 0)
Int32.TryParse(item("bathrooms").Value(Of Integer).ToString, iBathrooms)
Next
I already checked here: Get value from JToken that may not exist (best practices)
If the problem with the JSON is consistently that it is missing the value, you could insert, say, an empty string:
Dim json As String = "[{""bathrooms"": """"}, {""bathrooms"": }, {""bathrooms"": 2},{""bathrooms"": ""1""}]"
Dim re = New Text.RegularExpressions.Regex(":\s*}")
Dim json2 = re.Replace(json, ": """"}")
Console.WriteLine(json2)
Outputs:
[{"bathrooms": ""}, {"bathrooms": ""}, {"bathrooms": 2},{"bathrooms": "1"}]
which is valid JSON.
Then you could check if the value can be parsed as an integer:
Dim json As String = "[{""bathrooms"": """"}, {""bathrooms"": """"}, {""bathrooms"": 2},{""bathrooms"": ""1""}]"
Dim re = New Text.RegularExpressions.Regex(":\s*}")
json = re.Replace(json, ": """"}")
Dim nBathrooms As Integer
Dim jsonArray As Newtonsoft.Json.Linq.JArray = JArray.Parse(json)
For Each item In jsonArray
Dim q = item("bathrooms")
If q IsNot Nothing AndAlso Integer.TryParse(q.Value(Of Object).ToString(), nBathrooms) Then
Console.WriteLine(nBathrooms)
Else
Console.WriteLine("Not specified.")
End If
Next

separating decimal numbers with commas in asp.net eg:1,23,456

I tried this format, got output as 1,234,567,890.00
but I need in this format
1,23,567
decimal unitPrice = 1234567890.00m;
TextBox1.Text = Convert.ToDecimal(unitPrice).ToString("##,#0.00");
I guess you can do this by creating a custom number format info for your needs...example is here for your reference -
int yourNumber = 111234;
NumberFormatInfo nfo = new NumberFormatInfo();
nfo.CurrencyGroupSeparator = ",";
nfo.NumberGroupSizes = new int[] { 3, 2 };
string str = yourNumber.ToString("N0", nfo);
Response.Write("answer is : " + str);

How to compare two string in asp.net vb

I am Developing a web apps in Asp.net using vb.net language and i comparing two string using
"=" and
"String.Equals()"
but i get always false result
Dim decod As Decoder = Encoding.UTF8.GetDecoder()
Dim totByt As Byte() = Convert.FromBase64String(Request("numType"))
Dim chrCount As Integer = decod.GetCharCount(totByt, 0, totByt.Length)
Dim deco_char(chrCount) As Char
decod.GetChars(totByt, 0, totByt.Length, deco_char, 0)
Dim str As New String(deco_char)
If str = "MO" Or str.Equals("Mo") Then
//Do somthing
End If
Please see my Watch window output
Please tell me why this give me false condition and how to solve it.
Check out the documentation for String.Equals() and look at the possible values for 3rd parameter comparisionType
String.Equals("MO", str, StringComparison.OrdinalIgnoreCase))
The str variable has a length of 3, instead of 2, causing it to be different than "MO".
Proof:
Dim decod As Decoder = Encoding.UTF8.GetDecoder()
Dim totByt As Byte() = Convert.FromBase64String("TU8=")
Dim chrCount As Integer = decod.GetCharCount(totByt, 0, totByt.Length)
Dim deco_char(chrCount) As Char
decod.GetChars(totByt, 0, totByt.Length, deco_char, 0)
Dim str As New String(deco_char)
Dim result1 = str.StartsWith("MO") ' is true
Dim result2 = str.Equals("MO") ' is false
Dim length = str.Length ' is 3
So obviously str is not the same as "MO".
Remember that if you declare an array like:
Dim deco_char(2) ' an array of 3 elements
...the indexes of the elements range from 0 through 2, so it contains 3 elements.
Solution: if you replace line 4 with:
Dim deco_char(chrCount-1) As Char
.. it will work, because now (in your specific case) your array is of size 2 instead of 3.
Try this :
str.Equals("MO", StringComparison.CurrentCultureIgnoreCase);

Issues with writing BLOB data in chunk (8k)

I'm trying to write BLOB data on to a word file. Here is my code
Dim reportID As Integer
reportID = table1.report_output_data_id
Dim aSqlStr As String = "SELECT file_data FROM table2 WHERE report_output_data_id = " + Convert.ToString(reportID )
Dim reader As SqlDataReader = CType(WebSession.DataObjectFactory.GetDataProvider("EGDatabase"), cDataProviderSQL).PopulateDataReader(aSqlStr)
' The size of the BLOB buffer.
Dim bufferSize As Integer = 8192
' The BLOB byte() buffer to be filled by GetBytes.
Dim outByte(bufferSize - 1) As Byte
' The bytes returned from GetBytes.
Dim retval As Long
' The starting position in the BLOB output.
Dim startIndex As Long = 0
Do While reader.Read()
' Reset the starting byte for a new BLOB.
startIndex = 0
' Read bytes into outByte() and retain the number of bytes returned.
retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize)
' Continue while there are bytes beyond the size of the buffer.
Do While retval = bufferSize
Response.BinaryWrite(outByte)
' Reposition start index to end of the last buffer and fill buffer.
startIndex += bufferSize
retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize)
Loop
Response.BinaryWrite(outByte)
Loop
reader.Close()
I'm writing 8k at a time as I had out of memory issues earlier when data is large say 1GB. Instead of the above code, If I use
Response.BinaryWrite(table2.file_data)
Everything works fine.
So please tell me whats the issue in using sqldatareader?
The file size currently I'm considering is 31794 bytes
FYI: I'm using CommandBehavior.SequentialAccess
Junk data was getting added on to the file while writing the BLOB data.
For example for a file size 33959 bytes
Loop 1 will process 0 - 8192 bytes ( increments of 8k)
Loop 2 8192 - 16384
Loop 3 16384 - 24576
Loop 4 24576 - 32768
Loop 5 32768 - 33959 ( actual file size)
retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize)
Here in the loop 5 we have only 1191 bytes. So in the outbyte array the first 1191 items will be replaced with the bytes read by reader at this point of time which is 1191 but the remaining items in the outbyte array will still hold junk values ( that is present from previous loops) as the outbyte array is 8k in size.
So used a new outbyte array instead of the default one(8k) if remaining data to be written is less than 8k. Here is the code changes.
Dim aSqlStr As String = "SELECT datalength(file_data),file_data FROM table2 WHERE report_output_data_id = " + Convert.ToString(reportID )
Dim reader As SqlDataReader = CType(WebSession.DataObjectFactory.GetDataProvider("EGDatabase"), cDataProviderSQL).PopulateDataReader(aSqlStr)
' The size of the BLOB buffer.
Dim bufferSize As Integer = 8192
' The BLOB byte() buffer to be filled by GetBytes.
Dim outByte(bufferSize - 1) As Byte
' The bytes returned from GetBytes.
Dim retval As Long
' The starting position in the BLOB output.
Dim startIndex As Long = 0
Do While reader.Read()
' Get file size from BLOB buffer.
fileSize = reader.GetInt32(0)
If fileSize > bufferSize Then
' Reset the starting byte for a new BLOB.
startIndex = 0
' Read bytes into outByte() and retain the number of bytes returned.
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize)
' Continue while there are bytes beyond the size of the buffer.
Do While retval = bufferSize
Response.BinaryWrite(outByte)
' Reposition start index to end of the last buffer and fill buffer.
startIndex += bufferSize
Dim aRemainingBytes = fileSize - startIndex
If Not aRemainingBytes < bufferSize Then
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize)
Else
Dim outByteRemaining(aRemainingBytes - 1) As Byte
retval = reader.GetBytes(1, startIndex, outByteRemaining, 0, aRemainingBytes)
Response.BinaryWrite(outByteRemaining)
End If
Loop
Else
Response.BinaryWrite(aReportOutput.GetRelatedPropertyValue("ReportOutputData.FileData"))
End If
Loop
reader.Close()

AES EncryptN BADA solution

I would like to know what could be the problem in the code below.
I'm part of a university team developing solutions in Bada using NFC and server connections. To encrypt the comunication we have though use Aes encryption, but I'm stopped in the following error:
String
ReadForm::aesEncryp(Osp::Base::String ip, Osp::Base::String mac, Osp::Base::String msg)
{
AppLog("<<<<<<<<<<<<<< aesEncrypt Start >>>>>>>>>>>>>>>>>>>>>>>>>");
Osp::Text::Utf8Encoding utf8Enc;
Osp::Text::AsciiEncoding* dato = new Osp::Text::AsciiEncoding();
result r;
//msg
ByteBuffer* pbuffer=dato->GetBytesN(msg);
AppLog("asigno mensaje: %ls", msg.GetPointer());
int messageLen; // msg.GetLength()*8;
r=dato->GetByteCount(msg,messageLen);
AppLog("obtiene bytes: %s", GetErrorMessage(r));
byte message[messageLen+1];
r=pbuffer->GetArray(message,0,messageLen);
AppLog("Establece mensaje en array: %s", GetErrorMessage(r));
// KEY: 16 bytes
int secretKeyLen;
ip="xxxxxxxxxxxxx";
r=dato->GetByteCount(ip,secretKeyLen);
AppLog("obtiene bytes: %s", GetErrorMessage(r));
pbuffer=null;
pbuffer=dato->GetBytesN(ip);
byte secretKey[secretKeyLen+1];
r=pbuffer->GetArray(secretKey,0,secretKeyLen);
AppLog("Establece key en array: %s", GetErrorMessage(r));
// IV: 16 bytes
int ivectorLen;
String ivM="xxxxxxxxxxxx";
pbuffer=null;
pbuffer=dato->GetBytesN(ivM);
r=dato->GetByteCount(ivM,ivectorLen);
AppLog("obtiene bytes: %s", GetErrorMessage(r));
byte ivector[ivectorLen+1];
r=pbuffer->GetArray(ivector,0,ivectorLen);
AppLog("Establece vector en array: %s", GetErrorMessage(r));
String transformation;
ISymmetricCipher *pCipher = null;
SecretKeyGenerator *pKeyGen = null;
ISecretKey *pKey = null;
ByteBuffer input;
ByteBuffer *pOutput = null;
ByteBuffer keyBytes;
ByteBuffer iv;
//msg
input.Construct(messageLen+1);
input.SetArray(message, 0, messageLen);
input.Flip();
//key
keyBytes.Construct(secretKeyLen+1);
keyBytes.SetArray(secretKey, 0, 16);
keyBytes.Flip();
//vector
iv.Construct(ivectorLen);
iv.SetArray(ivector, 0, ivectorLen);
iv.Flip();
//cifrado
pCipher = new AesCipher();
transformation = "CBC/128/NOPADDING";
pCipher->Construct(transformation,CIPHER_ENCRYPT);
AppLog("AesCipher construct:%s", GetErrorMessage(r));
pKeyGen = new SecretKeyGenerator();
pKeyGen->Construct(keyBytes);
pKey = pKeyGen->GenerateKeyN();
if (pKey==null){
r = GetLastResult();
AppLog("Generate -> pKey Esnulo: %s",GetErrorMessage(r));
}
r=pCipher->SetKey(*pKey);
AppLog("AesCipher setKey:%s", GetErrorMessage(r));
r=pCipher->SetInitialVector(iv);
AppLog("AesCipher setInitialVector:%s", GetErrorMessage(r));
//encripto
pOutput = pCipher->EncryptN(input); <---------- returns null why!!!!!!!!!!!
if (pOutput==null){
r = GetLastResult();
AppLog("pOutput nulo: %s",GetErrorMessage(r));
}
AppLog("Encriptado");
//preparo para devolver
Osp::Text::AsciiEncoding* as = new Osp::Text::AsciiEncoding();
as->GetString(*pOutput,ResultadoAes);
AppLog("aes= %ls", ResultadoAes.GetPointer() );
AppLog("<<<<<<<<<<<<<< aesEncrypt Finish >>>>>>>>>>>>>>>>>>>>>>>>>");
return ResultadoAes;
}
The input and keylength should be multiple of 16.
What i understand from your code, your message length is multiple of 8.
Also since you are using NOPADDING, when you are constructing bytebuffer for input and keybytes, please make sure that they are exactly multiple of 16.
Finally, incase you are still getting problem, please post what error message you are getting from
r = GetLastResult()

Resources