Silverlight Socket Constantly Returns With Empty Buffer - silverlight

I am using Silverlight to interact with a proxy application that I have developed but, without the proxy sending a message to the Silverlight application, it executes the receive completed handler with an empty buffer ('\0's). Is there something I'm doing wrong? It is causing a major memory leak.
this._rawBuffer = new Byte[this.BUFFER_SIZE];
SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs();
receiveArgs.SetBuffer(_rawBuffer, 0, _rawBuffer.Length);
receiveArgs.Completed += new EventHandler<SocketAsyncEventArgs>(ReceiveComplete);
this._client.ReceiveAsync(receiveArgs);
if (args.SocketError == SocketError.Success && args.LastOperation == SocketAsyncOperation.Receive)
{
// Read the current bytes from the stream buffer
int bytesRecieved = this._client.ReceiveBufferSize;
// If there are bytes to process else the connection is lost
if (bytesRecieved > 0)
{
try
{
//Find out what we just received
string messagePart = UTF8Encoding.UTF8.GetString(_rawBuffer, 0, _rawBuffer.GetLength(0));
//Take out any trailing empty characters from the message
messagePart = messagePart.Replace('\0'.ToString(), "");
//Concatenate our current message with any leftovers from previous receipts
string fullMessage = _theRest + messagePart;
int seperator;
//While the index of the seperator (LINE_END defined & initiated as private member)
while ((seperator = fullMessage.IndexOf((char)Messages.MessageSeperator.Terminator)) > 0)
{
//Pull out the first message available (up to the seperator index
string message = fullMessage.Substring(0, seperator);
//Queue up our new message
_messageQueue.Enqueue(message);
//Take out our line end character
fullMessage = fullMessage.Remove(0, seperator + 1);
}
//Save whatever was NOT a full message to the private variable used to store the rest
_theRest = fullMessage;
//Empty the queue of messages if there are any
while (this._messageQueue.Count > 0)
{
...
}
}
catch (Exception e)
{
throw e;
}
// Wait for a new message
if (this._isClosing != true)
Receive();
}
}
Thanks in advance.

I assume the second block of code is your ReceiveComplete handler. If so, you should be looking at the SocketAsyncEventArgs.BytesTransferred property to get the count of the bytes received.

Related

strcmp script reading serial monitor failing

I have a script reading the serial monitor and looking for an "OK" response. I am able to capture the OK response in a variable named message and print it to the serial monitor, but when I attempt to use the message variable in an if statement it is not performing as expected. When the variable message = OK the statement below is still giving a false. Does anyone know where the issue might be?
if (strcmp (message,"OK") == 0) {
Serial.println("true");
}
else {
Serial.println("false");
}
The complete code:
//#include <HardwareSerial.h>
const unsigned int MAX_MESSAGE_LENGTH = 12;
void setup() {
Serial2.begin(115200,SERIAL_8N1); //open modem serial port
Serial.println("serial ports are open");
}
void loop() {
Serial2.write("AT\r\n");
while (Serial2.available() > 0){
//Create a place to hold the incoming message
static char message[MAX_MESSAGE_LENGTH];
static unsigned int message_pos = 0;
//Read the next available byte in the serial receive buffer
char inByte = Serial2.read();
//Message coming in (check not terminating character) and guard for over message size
if ( inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1) )
{
//Add the incoming byte to our message
message[message_pos] = inByte;
message_pos++;
}
//Full message received...
else
{
//Add null character to string
message[message_pos] = '\0';
//Print the message (or do other things)
Serial.println("loop");
delay(100);
Serial.println(message);
//Reset for the next message
message_pos = 0;
if (strcmp (message,"OK") == 0) {
Serial.println("true");
}
else {
Serial.println("false");
}
}
}
delay(5000);
}
Serial monitor looks like this:
22:11:51.970 -> serial ports are open
22:12:16.984 -> loop
22:12:17.078 -> AT
22:12:17.078 -> false
22:12:17.078 -> loop
22:12:17.171 -> OK
22:12:17.171 -> false
22:12:17.171 -> loop
22:12:17.266 -> AT
22:12:17.266 -> false
22:12:17.266 -> loop
22:12:17.360 -> OK
22:12:17.360 -> false
The received response is "OK\r\n", so the actual message is "OK\r". It helps for debugging if you temporarily print each received character.
To ignore the echo of the command, insert another strcmp() for it and react accordingly, for example do nothing.

Sign a string using PFX/P12 certificate in Windows using C

I currently have a project that already sign the string that I need in C#, using the PFX certificate, but, now, I'm having to convert parts of that project to C to make it compatible with other projects...
I found this article in MSDN https://learn.microsoft.com/en-us/windows/win32/seccrypto/example-c-program-signing-a-message-and-verifying-a-message-signature which shows how to encrypt and sign the string by loading the certificate from windows store....
But the result of this example is not as expected, because in my case I just need to sign the string and not encrypt and sign, I checked if there was any function to sign only, but I didn't find...
Another point, how do I load a .PFX / .P12 file, and use it with windows functions, instead of having to install the certificate on the computer ...
My method for signing the string in C# is this:
public byte[] SignString(string mensagem)
{
var certificado = SearchCertificate();
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificado);
signer.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1"); //SHA256
ContentInfo content = new ContentInfo(new Oid(Configuration.ContentOid), new System.Text.UTF8Encoding().GetBytes(mensagem));
SignedCms signedCms = new SignedCms(content, false);
signedCms.ComputeSignature(signer, false);
var signedStringBytes = signedCms.Encode();
return signedStringBytes;
}
The Encode function of the SignedCms class uses the wincrypt.h library internally and calls the methods CryptMsgOpenToEncode, CryptMsgUpdate and CryptMsgGetParam.
The Microsoft documentation also contains a full example
#pragma comment(lib, "crypt32.lib")
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void MyHandleError(char *s);
void main(void)
{
//-------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Declare and initialize variables.
BYTE* pbContent = (BYTE*) "Security is our only business.";
// a byte pointer
DWORD cbContent = strlen((char *) pbContent)+1;
// the size of the message
HCERTSTORE hStoreHandle;
HCRYPTPROV hCryptProv;
PCCERT_CONTEXT pSignerCert; // signer's certificate
PCCERT_CONTEXT pRecipCert; // receiver's certificate
LPWSTR pswzRecipientName = L"Hortense";
LPWSTR pswzCertSubject = L"Full Test Cert";
PCERT_INFO RecipCertArray[1];
DWORD ContentEncryptAlgSize;
CRYPT_ALGORITHM_IDENTIFIER ContentEncryptAlgorithm;
CMSG_ENVELOPED_ENCODE_INFO EnvelopedEncodeInfo;
DWORD cbEncodedBlob;
BYTE *pbEncodedBlob;
DWORD cbSignedBlob;
BYTE *pbSignedBlob;
HCRYPTMSG hMsg;
DWORD HashAlgSize;
CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
CMSG_SIGNER_ENCODE_INFO SignerEncodeInfo;
CERT_BLOB SignerCertBlob;
CERT_BLOB SignerCertBlobArray[1];
CMSG_SIGNER_ENCODE_INFO SignerEncodeInfoArray[1];
CMSG_SIGNED_ENCODE_INFO SignedMsgEncodeInfo;
//-------------------------------------------------------------------
// Begin processing. Display the original message.
printf("The original message => %s\n",pbContent);
//-------------------------------------------------------------------
// Acquire a cryptographic provider.
if(CryptAcquireContext(
&hCryptProv, // address for handle to be returned
NULL, // use the current user's logon name
NULL, // use the default provider
PROV_RSA_FULL, // provider type
0)) // zero allows access to private keys
{
printf("Context CSP acquired. \n");
}
else
{
if ( GetLastError() == NTE_BAD_KEYSET)
{
printf("A Usable private key was not found \n");
printf("in the default key container. Either a \n");
printf("private key must be generated in that container \n");
printf("or CryptAquireCertificatePrivateKey can be used \n");
printf("to gain access to the needed private key.");
}
MyHandleError("CryptAcquireContext failed.");
}
//-------------------------------------------------------------------
// Open the My system certificate store.
if(hStoreHandle = CertOpenStore(
CERT_STORE_PROV_SYSTEM,
0,
NULL,
CERT_SYSTEM_STORE_CURRENT_USER,
L"MY"))
{
printf("The MY system store is open. \n");
}
else
{
MyHandleError( "Error getting store handle.");
}
//-------------------------------------------------------------------
// Get the signer's certificate. This certificate must be in the
// My store, and its private key must be available.
if(pSignerCert = CertFindCertificateInStore(
hStoreHandle,
MY_ENCODING_TYPE,
0,
CERT_FIND_SUBJECT_STR,
pswzCertSubject,
NULL))
{
printf("Found certificate for %S.\n",pswzCertSubject);
}
else
{
MyHandleError("Signer certificate not found.");
}
//-------------------------------------------------------------------
// Initialize the algorithm identifier structure.
HashAlgSize = sizeof(HashAlgorithm);
memset(&HashAlgorithm, 0, HashAlgSize); // initialize to zero
HashAlgorithm.pszObjId = szOID_RSA_MD5; // initialize the
// necessary member
//-------------------------------------------------------------------
// Initialize the CMSG_SIGNER_ENCODE_INFO structure.
memset(&SignerEncodeInfo, 0, sizeof(CMSG_SIGNER_ENCODE_INFO));
SignerEncodeInfo.cbSize = sizeof(CMSG_SIGNER_ENCODE_INFO);
SignerEncodeInfo.pCertInfo = pSignerCert->pCertInfo;
SignerEncodeInfo.hCryptProv = hCryptProv;
SignerEncodeInfo.dwKeySpec = AT_KEYEXCHANGE;
SignerEncodeInfo.HashAlgorithm = HashAlgorithm;
SignerEncodeInfo.pvHashAuxInfo = NULL;
//-------------------------------------------------------------------
// Create an array of one.
// Note: The current program is set up for only a single signer.
SignerEncodeInfoArray[0] = SignerEncodeInfo;
//-------------------------------------------------------------------
// Initialize the CMSG_SIGNED_ENCODE_INFO structure.
SignerCertBlob.cbData = pSignerCert->cbCertEncoded;
SignerCertBlob.pbData = pSignerCert->pbCertEncoded;
//-------------------------------------------------------------------
// Initialize the array of one CertBlob.
SignerCertBlobArray[0] = SignerCertBlob;
memset(&SignedMsgEncodeInfo, 0, sizeof(CMSG_SIGNED_ENCODE_INFO));
SignedMsgEncodeInfo.cbSize = sizeof(CMSG_SIGNED_ENCODE_INFO);
SignedMsgEncodeInfo.cSigners = 1;
SignedMsgEncodeInfo.rgSigners = SignerEncodeInfoArray;
SignedMsgEncodeInfo.cCertEncoded = 1;
SignedMsgEncodeInfo.rgCertEncoded = SignerCertBlobArray;
SignedMsgEncodeInfo.rgCrlEncoded = NULL;
//-------------------------------------------------------------------
// Get the size of the encoded, signed message BLOB.
if(cbSignedBlob = CryptMsgCalculateEncodedLength(
MY_ENCODING_TYPE, // message encoding type
0, // flags
CMSG_SIGNED, // message type
&SignedMsgEncodeInfo, // pointer to structure
NULL, // inner content OID
cbContent)) // size of content
{
printf("%d, the length of data calculated. \n",cbSignedBlob);
}
else
{
if ( GetLastError() == NTE_BAD_KEYSET)
{
printf("A Usable private key was not found \n");
printf("in the default key container. Either a \n");
printf("private key must be generated in that container \n");
printf("or CryptAquireCertificatePRivateKey can be used \n");
printf("to gain access to the needed private key.");
}
MyHandleError("Getting cbSignedBlob length failed.");
}
//-------------------------------------------------------------------
// Allocate memory for the encoded BLOB.
if(pbSignedBlob = (BYTE *) malloc(cbSignedBlob))
{
printf("Memory has been allocated for the signed message. \n");
}
else
{
MyHandleError("Memory allocation failed.");
}
//-------------------------------------------------------------------
// Open a message to encode.
if(hMsg = CryptMsgOpenToEncode(
MY_ENCODING_TYPE, // encoding type
0, // flags
CMSG_SIGNED, // message type
&SignedMsgEncodeInfo, // pointer to structure
NULL, // inner content OID
NULL)) // stream information (not used)
{
printf("The message to be encoded has been opened. \n");
}
else
{
MyHandleError("OpenToEncode failed.");
}
//-------------------------------------------------------------------
// Update the message with the data.
if(CryptMsgUpdate(
hMsg, // handle to the message
pbContent, // pointer to the content
cbContent, // size of the content
TRUE)) // last call
{
printf("Content has been added to the encoded message. \n");
}
else
{
MyHandleError("MsgUpdate failed.");
}
//-------------------------------------------------------------------
// Get the resulting message.
if(CryptMsgGetParam(
hMsg, // handle to the message
CMSG_CONTENT_PARAM, // parameter type
0, // index
pbSignedBlob, // pointer to the BLOB
&cbSignedBlob)) // size of the BLOB
{
printf("Message encoded successfully. \n");
}
else
{
MyHandleError("MsgGetParam failed.");
}
//-------------------------------------------------------------------
// pbSignedBlob now points to the encoded, signed content.
//-------------------------------------------------------------------
// Get a pointer to the recipient certificate.
// For this program, the recipient's certificate must also be in the
// My store. At this point, only the recipient's public key is needed.
// To open the enveloped message, however, the recipient's
// private key must also be available.
if(pRecipCert=CertFindCertificateInStore(
hStoreHandle,
MY_ENCODING_TYPE, // use X509_ASN_ENCODING
0, // no dwFlags needed
CERT_FIND_SUBJECT_STR, // find a certificate with a
// subject that matches the
// string in the next parameter
pswzRecipientName, // the Unicode string to be found
// in a certificate's subject
NULL)) // NULL for the first call to the
// function
// in all subsequent
// calls, it is the last pointer
// returned by the function
{
printf("Certificate for %S found. \n", pswzRecipientName);
}
else
{
MyHandleError("Could not find the countersigner's "
"certificate.");
}
//-------------------------------------------------------------------
// Initialize the first element of the array of CERT_INFOs.
// In this example, there is only a single recipient.
RecipCertArray[0] = pRecipCert->pCertInfo;
//-------------------------------------------------------------------
// Initialize the symmetric-encryption algorithm identifier
// structure.
ContentEncryptAlgSize = sizeof(ContentEncryptAlgorithm);
memset(&ContentEncryptAlgorithm,
0,
ContentEncryptAlgSize); // initialize to zero
//-------------------------------------------------------------------
// Initialize the necessary members. This particular OID does not
// need any parameters. Some OIDs, however, will require that
// the other members be initialized.
ContentEncryptAlgorithm.pszObjId = szOID_RSA_RC4;
//-------------------------------------------------------------------
// Initialize the CMSG_ENVELOPED_ENCODE_INFO structure.
memset(&EnvelopedEncodeInfo,
0,
sizeof(CMSG_ENVELOPED_ENCODE_INFO));
EnvelopedEncodeInfo.cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO);
EnvelopedEncodeInfo.hCryptProv = hCryptProv;
EnvelopedEncodeInfo.ContentEncryptionAlgorithm =
ContentEncryptAlgorithm;
EnvelopedEncodeInfo.pvEncryptionAuxInfo = NULL;
EnvelopedEncodeInfo.cRecipients = 1;
EnvelopedEncodeInfo.rgpRecipients = RecipCertArray;
//-------------------------------------------------------------------
// Get the size of the encoded message BLOB.
if(cbEncodedBlob = CryptMsgCalculateEncodedLength(
MY_ENCODING_TYPE, // message encoding type
0, // flags
CMSG_ENVELOPED, // message type
&EnvelopedEncodeInfo, // pointer to structure
szOID_RSA_signedData, // inner content OID
cbSignedBlob)) // size of content
{
printf("Length of the encoded BLOB will be %d.\n",cbEncodedBlob);
}
else
{
MyHandleError("Getting enveloped cbEncodedBlob length failed.");
}
//--------------------------------------------------------------------
// Allocate memory for the encoded BLOB.
if(pbEncodedBlob = (BYTE *) malloc(cbEncodedBlob))
{
printf("Memory has been allocated for the BLOB. \n");
}
else
{
MyHandleError("Enveloped malloc operation failed.");
}
//-------------------------------------------------------------------
// Open a message to encode.
if(hMsg = CryptMsgOpenToEncode(
MY_ENCODING_TYPE, // encoding type
0, // flags
CMSG_ENVELOPED, // message type
&EnvelopedEncodeInfo, // pointer to structure
szOID_RSA_signedData, // inner content OID
NULL)) // stream information (not used)
{
printf("The message to encode is open. \n");
}
else
{
MyHandleError("Enveloped OpenToEncode failed.");
}
//-------------------------------------------------------------------
// Update the message with the data.
if(CryptMsgUpdate(
hMsg, // handle to the message
pbSignedBlob, // pointer to the signed data BLOB
cbSignedBlob, // size of the data BLOB
TRUE)) // last call
{
printf("The signed BLOB has been added to the message. \n");
}
else
{
MyHandleError("Enveloped MsgUpdate failed.");
}
//-------------------------------------------------------------------
// Get the resulting message.
if(CryptMsgGetParam(
hMsg, // handle to the message
CMSG_CONTENT_PARAM, // parameter type
0, // index
pbEncodedBlob, // pointer to the enveloped,
// signed data BLOB
&cbEncodedBlob)) // size of the BLOB
{
printf("Enveloped message encoded successfully. \n");
}
else
{
MyHandleError("Enveloped MsgGetParam failed.");
}
//-------------------------------------------------------------------
// Clean up.
CertFreeCertificateContext(pRecipCert);
if(CertCloseStore(
hStoreHandle,
CERT_CLOSE_STORE_CHECK_FLAG))
{
printf("The certificate store closed without a certificate "
"left open. \n");
}
else
{
printf("The store closed but a certificate was still open. \n");
}
if(hMsg)
CryptMsgClose(hMsg);
if(hCryptProv)
CryptReleaseContext(hCryptProv,0);
} // end main
//-------------------------------------------------------------------
// This example uses the function MyHandleError, a simple error
// handling function to print an error message and exit
// the program.
// For most applications, replace this function with one
// that does more extensive error reporting.
void MyHandleError(char *s)
{
fprintf(stderr,"An error occurred in running the program. \n");
fprintf(stderr,"%s\n",s);
fprintf(stderr, "Error number %x.\n", GetLastError());
fprintf(stderr, "Program terminating. \n");
exit(1);
} // end MyHandleError

CMSIS-RTOS osMessageGet function

I have been working on a software based on CMSIS-RTOS and I have a problem with
function osMessageGet. My software consists of four RTOS tasks and two of them
exchange data via osMessageQueue in conjunction with osPool. One task (Task_100ms) is a producer and second task (Task_200ms) is a consumer.
Task_100ms receives data from CAN bus and creates structures containing the received data. The producer allocates memory on pool (flash_pool) using function osPoolAlloc and receives pointer to allocated memory. Producer copies the content of exchanged structure onto the memory block in pool using this pointer and puts copy of this pointer onto the queue (flash_queue) using function osMessagePut (please see the put_program_chunk function code below).
Task_200ms tries to retrieve the pointers from flash_queue using osMessageGet function (please see the program_chunk function code below). As long as the queue is empty consumer waits and everything is OK. Then a first pointer is put onto flash_queue by Task_100ms. Task_200ms calls osMessageGet function and this results in uC reset in case the timeout for osMessageGet is set to osWaitForever. In case the timeout for osMessageGet is set to 0 software reset isn't invoked. But in both cases (timeout equal 0 or osWaitForever) when I step through the code in Eclipse I am not able to achieve the immediately following statement after osMessageGet function call.
Can anybody give me any advice where a cause of my problems could be? I can send
you whole source code if it is needed. Thanks in advance for any suggestions.
BOOL put_program_chunk(main_controller_req_t req){
main_controller_req_t *p_req;
BOOL retval;
BOOL no_memory = FALSE;
/*!!!*/
osStatus status;
uint8_t tmp;
// allocate memory in pool
p_req = (main_controller_req_t *)osPoolAlloc(flash_pool);
if(p_blk == NULL){
printf("No more space in flash pool.\r\n");
}
if(p_req != NULL){
*p_req = req;
// insert the prepared request into the transmission queue
// put the message into the queue
// wait 5 ms?
status = osMessagePut(flash_queue, (uint32_t)(p_req), 5);
/*!!!*/
if(status == osOK){
tmp = 1;
}else{
tmp = 0;
}
}else{
no_memory = TRUE;
}
if(no_memory){
retval = FALSE;
}else{
retval = TRUE;
}
return retval;
}
void program_chunk(void){
osEvent event;
osStatus status;
main_controller_req_t *p_req;
main_controller_req_t req;
pdt_result_t result;
// !!!
uint8_t tmp;
// retrieve the data block from the message queue
event = osMessageGet(flash_queue, 0);
// !!!
tmp++;
/*
if(event.status == osEventMessage){
p_req = ((main_controller_req_t *)(event.value.p));
// copy the content of memory block in receiving pool
req = *p_req;
// free the memory in pool
status = osPoolFree(flash_pool, p_req);
// Normal (=000000) or Boot (=BOOTBL) mode?
if(*req.mode == 0 && *(req.mode + 1) == 0 && *(req.mode + 2) == 0 &&
*(req.mode + 3) == 0 && *(req.mode + 4) == 0 && *(req.mode + 5) == 0){
// Normal mode
// program chunk for the Slot_0 or Slot_1?
if(((req.flash_page_number >= 0x01) && (req.flash_page_number < MAX_AC_PAGE)) ||
((req.flash_page_number == MAX_AC_PAGE) && (req.flash_block_number <= MAX_AC_BLOCK))){
#ifdef APP_DEBUG
printf("AC programming!\r\n");
#endif
// yes - program the retrieved program chunk
result = pdt_app_program_chunk(req.data_block, 32);
// according to the result send the short flash write response message - page and block OK
send_short_flash_load_write_resp((result == PDT_RESULT_OK) ? TRUE : FALSE, FALSE, req.flash_page_number, req.flash_block_number);
// if unsuccessful programming
if(result != PDT_RESULT_OK){
// go into WAIT_TO_FLASH_LOAD_COMPLETE
SetLogicSignal(LGoWtFlshLdCmpl);
}
// program chunk for Motor Controller?
}else if(((req.flash_page_number == MAX_AC_PAGE) && (req.flash_block_number > MAX_AC_BLOCK && req.flash_block_number <= MAX_MC_BLOCK)) ||
((req.flash_page_number > MAX_AC_PAGE) && (req.flash_page_number <= MAX_MC_PAGE))){
#ifdef APP_DEBUG
printf("MC programming!\r\n");
#endif
// yes - program the retrieved program chunk
result = pdt_mc_update_internal_motor_controller_chunk(req.data_block, 32);
// according to the result send the short flash write response message - page and block OK
send_short_flash_load_write_resp((result == PDT_RESULT_OK) ? TRUE : FALSE, FALSE, req.flash_page_number, req.flash_block_number);
// end of the binary?
if((req.flash_page_number == NO_PAGES) && (req.flash_block_number == BLOCKS_IN_PAGE) && result == PDT_RESULT_OK){
result = pdt_mc_update_motor_controller();
// invoke SW reset
result = pdt_app_switch_application();
// if unsuccessful programming
}else if(result != PDT_RESULT_OK){
// go into WAIT_TO_FLASH_LOAD_COMPLETE
SetLogicSignal(LGoWtFlshLdCmpl);
}
// wrong destination address?
}else{
#ifdef APP_DEBUG
printf("Wrong destination address!\r\n");
#endif
// wrong data block destination
send_short_flash_load_write_resp(FALSE, TRUE, req.flash_page_number, req.flash_block_number);
// go into WAIT_TO_FLASH_LOAD_COMPLETE
SetLogicSignal(LGoWtFlshLdCmpl);
}
}
}
*/
}

InternetReadFile's output to string gives a "ÌÌÌÌÌÌ" sequence in C

I am trying to read the text content of a HTTP Post Response body using InternetReadFile. However, all it contains is a string of "Ì" (-52 when converted to int).
Could this be encoding related? Is it that what is being returned is not a string at all?
Am I missing a step required to read the output?
Please note that I know for a fact that this message body contains plain text (based on logs).
Here is the code:
Ptr = (char *)OutBuffer;
while(TRUE)
{
// read the server response
//
if(!InternetReadFile(RequestHandle,Ptr,Length ,&BytesRead))
{
Rc = GetLastError();
InternetCloseHandle(RequestHandle );
SetLastError(Rc);
return(ACE_HTTP_ERROR);
}
if(BytesRead == 0) // end of data
break;
TotalLength += BytesRead;
Ptr += BytesRead;
if(TotalLength >= *OutBufferLength)
{
InternetCloseHandle(RequestHandle );
SetLastError(ERROR_INSUFFICIENT_BUFFER);
*OutBufferLength = TotalLength;
return(ACE_HTTP_NO_ENOUGH_SPACE);
}
}
*OutBufferLength = TotalLength;
At this point, Ptr, when read as a char array, contains nothing but a sequence of 'Ì'.

Reading and parsing text file exception-C#

I am parsing big text files and it's working fine for some time but after few minutes it give me exception (An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.Core.dll
Additional information: Access to the path is denied.)
I get exception on below mention line.
accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
Below is my function
public static void CityStateZipAndZip4(string FilePath,long offset,long length,string spName)
{
try
{
long indexBreak = offset;
string fileName = Path.GetFileName(FilePath);
if (fileName.Contains(".txt"))
fileName = fileName.Replace(".txt", "");
System.IO.FileStream file = new System.IO.FileStream(#FilePath, FileMode.Open,FileAccess.Read, FileShare.Read );
Int64 b = file.Length;
MemoryMappedFile MemoryMapped = MemoryMappedFile.CreateFromFile(file, fileName, b, MemoryMappedFileAccess.Read, null, HandleInheritability.Inheritable, false);
using (MemoryMapped)
{
//long offset = 182; // 256 megabytes
//long length = 364; // 512 megabytes
MemoryMappedViewAccessor accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
byte byteValue;
int index = 0;
int count = 0;
StringBuilder message = new StringBuilder();
do
{
if (indexBreak == index)
{
count = count + 1;
accessor.Dispose();
string NewRecord = message.ToString();
offset = offset + indexBreak;
length = length + indexBreak;
if (NewRecord.IndexOf("'") != -1)
{ NewRecord = NewRecord.Replace("'", "''"); }
// string Sql = "insert into " + DBTableName + " (ID, DataString) values( " + count + ",'" + NewRecord + "')";
string Code = "";
if (spName == AppConfig.sp_CityStateZip)
{
Code = NewRecord.Trim().Substring(0, 1);
}
InsertUpdateAndDeleteDB(spName, NewRecord.Trim (), Code);
accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
message = new StringBuilder();
index = 0;
//break;
}
byteValue = accessor.ReadByte(index);
if (byteValue != 0)
{
char asciiChar = (char)byteValue;
message.Append(asciiChar);
}
index++;
} while (byteValue != 0);
}
MemoryMapped.Dispose();
}
catch (FileNotFoundException)
{
Console.WriteLine("Memory-mapped file does not exist. Run Process A first.");
}
}
Somewhere deep in resource processing code we have something like this:
try {
// Try loading some strings here.
} catch {
// Oops, could not load strings, try another way.
}
Exception is thrown and handled already, it would never show up in your application. The only way to see it is to attach debugger and observe this message.
As you could see from the code, it has nothing to do with your problem. The real problem here is what debugger shows you something you should not see.
Run the solution without debugging mode and it works fine.
This exception means that your program does not get Read access to the file from Windows.
Have you made sure that this file is not locked when your program tries to read it ?
For example, it could be a file that your own program is currently using.
If not, try to run your program as an Administrator and see if it makes a difference.

Resources