Uploading to an FTP server - api

I am working on a tiny tiny application that just uploads a file to the FTP server. I have reviewed my code, but I am quite unable to locate the problem. Here is the code,
#include "stdafx.h"
using namespace System;
#include "iostream"
#include <conio.h>
using namespace System;
void UploadFiles(String ^_FileName, String ^_UploadPath, String ^_FTPUser, String ^_FTPPass);
int main ()
{
// Upload file using FTP
UploadFiles("c:\\test.html", "ftp://playbabe.tk/public_html/test.html", "xxxxxx", "xxxxxx");
return 0;
}
void UploadFiles(System::String ^_FileName, System::String ^_UploadPath, System::String ^_FTPUser, System::String ^_FTPPass)
{
System::IO::FileInfo ^_FileInfo = gcnew System::IO::FileInfo(_FileName);
// Create FtpWebRequest object from the Uri provided
System::Net::FtpWebRequest ^_FtpWebRequest = safe_cast<System::Net::FtpWebRequest^>(System::Net::FtpWebRequest::Create(gcnew Uri(_UploadPath)));
// Provide the WebPermission Credintials
_FtpWebRequest->Credentials = gcnew System::Net::NetworkCredential(_FTPUser, _FTPPass);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
_FtpWebRequest->KeepAlive = false;
// set timeout for 20 seconds
_FtpWebRequest->Timeout = 20000;
// Specify the command to be executed.
_FtpWebRequest->Method =System::Net::WebRequestMethods::Ftp.UploadFile;
// Specify the data transfer type.
_FtpWebRequest->UseBinary = true;
// Notify the server about the size of the uploaded file
_FtpWebRequest->ContentLength = _FileInfo->Length;
// The buffer size is set to 2kb
int buffLength = 2048;
array<System::Byte> ^buff = gcnew array<System::Byte>(buffLength);
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
System::IO::FileStream ^_FileStream = _FileInfo->OpenRead();
try
{
// Stream to which the file to be upload is written
System::IO::Stream ^_Stream = _FtpWebRequest->GetRequestStream();
// Read from the file stream 2kb at a time
int contentLen = _FileStream->Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
_Stream->Write(buff, 0, contentLen);
contentLen = _FileStream->Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
_Stream->Close();
delete _Stream;
_FileStream->Close();
delete _FileStream;
}
catch (Exception ^ex)
{
//MessageBox::Show(ex->Message, "Upload Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
std::cout<<"error";
}
getch();
}
It gives two errors in Visual C++ 2010 Express,
Error 1 error C2275: 'System::Net::WebRequestMethods::Ftp' : illegal use of this type as an expression C:\Users\Me\documents\visual studio 2010\Projects\test1\test1\test1.cpp 70
Error 2 error C2228: left of '.UploadFile' must have class/struct/union C:\Users\Me\documents\visual studio 2010\Projects\test1\test1\test1.cpp 70
I am not sure what is going wrong here.

I don't know C++/CLI, but the following statement is certainly wrong:
_FtpWebRequest->Method = System::Net::WebRequestMethods::Ftp.UploadFile;
System::Net::WebRequestMethods::Ftp is a type and, as the error message indicates (you could have given us the line number!) you're trying to use it as an expression.
Are you trying to obtain a pointer to a static member function?
Did you thus mean the following?
_FtpWebRequest->Method = System::Net::WebRequestMethods::Ftp::UploadFile;

Related

How to keep HTTP/2 connection alive till the request / response session is complete?

I am currently using HttpDeclarePushto exploit the Server Push feature in HTTP/2.
I am able to successfully create all the parameters that this function accepts. But the issue is when HttpDeclarePushexecutes it returns a value of 1229 (ERROR_CONNECTION_INVALID) - https://learn.microsoft.com/en-us/windows/desktop/debug/system-error-codes--1000-1299-.
On further investigation I found that the HttpHeaderConnection in _HTTP_HEADER_ID (https://learn.microsoft.com/en-us/windows/desktop/api/http/ne-http-_http_header_id) is actually passed in the function as 'close'. That implies that on every request response the server closes the connection and that is also happening in my case, I checked it in the log.
Here is the code.
class http2_native_module : public CHttpModule
{
public:
REQUEST_NOTIFICATION_STATUS OnBeginRequest(IN IHttpContext * p_http_context, IN IHttpEventProvider * p_provider)
{
HTTP_REQUEST_ID request_id;
const HTTPAPI_VERSION version = HTTPAPI_VERSION_2;
auto pHttpRequest = p_http_context->GetRequest();
auto phttpRequestRaw = pHttpRequest->GetRawHttpRequest();
HANDLE p_req_queue_handle = nullptr;
auto isHttp2 = phttpRequestRaw->Flags;
try {
const auto request_queue_handle = HttpCreateRequestQueue(version, nullptr, nullptr, NULL, &p_req_queue_handle);
const auto verb = phttpRequestRaw->Verb;
const auto http_path = L"/polyfills.0d74a55d0dbab6b8c32c.js"; //ITEM that I want to PUSH to client
const auto query = nullptr;
request_id = phttpRequestRaw->RequestId;
auto headers = phttpRequestRaw->Headers;
auto connId = phttpRequestRaw->ConnectionId;
WriteEventViewerLog(L"OnBeginRequest - Entering HTTPDECLAREPUSH");
headers.KnownHeaders[1].pRawValue = NULL;
headers.KnownHeaders[1].RawValueLength = 0;
const auto is_success = HttpDeclarePush(p_req_queue_handle, request_id, verb, http_path, query, &headers);
sprintf_s(szBuffer, "%lu", is_success);
Log("is_success value", szBuffer); //ERROR CODE 1229 here
HttpCloseRequestQueue(p_req_queue_handle);
}
catch (std::bad_alloc & e)
{
auto something = e;
}
return RQ_NOTIFICATION_CONTINUE;
}
I even tried to update the header connection value as below but it still gives me 1229.
headers.KnownHeaders[1].pRawValue = NULL;
headers.KnownHeaders[1].RawValueLength = 0;
I understand from https://http2.github.io/http2-spec/ that HTTP/2 actually ignores the content in HTTP HEADERs and uses some other mechanism as part of its FRAME.
This brings us to the next question on how we can keep the connection OPEN and is it something related to the FRAME (similar to HEADER) that HTTP2 uses, if so, how C++ or rather Microsoft helps us to play and exploit with the FRAME in HTTP2?

vb.net stream reader reads from a .accdb and .xml file without an error [duplicate]

How can I test whether a file that I'm opening in C# using FileStream is a "text type" file? I would like my program to open any file that is text based, for example, .txt, .html, etc.
But not open such things as .doc or .pdf or .exe, etc.
In general: there is no way to tell.
A text file stored in UTF-16 will likely look like binary if you open it with an 8-bit encoding. Equally someone could save a text file as a .doc (it is a document).
While you could open the file and look at some of the content all such heuristics will sometimes fail (eg. notepad tries to do this, by careful selection of a few characters notepad will guess wrong and display completely different content).
If you have a specific scenario, rather than being able to open and process anything, you should be able to do much better.
I guess you could just check through the first 1000 (arbitrary number) characters and see if there are unprintable characters, or if they are all ascii in a certain range. If the latter, assume that it is text?
Whatever you do is going to be a guess.
As others have pointed out there is no absolute way to be sure. However, to determine if a file is binary (which can be said to be easier than determining if it is text) some implementations check for consecutive NUL characters. Git apparently just checks the first 8000 chars for a NUL and if it finds one treats the file as binary. See here for more details.
Here is a similar C# solution I wrote that looks for a given number of required consecutive NUL. If IsBinary returns false then it is very likely your file is text based.
public bool IsBinary(string filePath, int requiredConsecutiveNul = 1)
{
const int charsToCheck = 8000;
const char nulChar = '\0';
int nulCount = 0;
using (var streamReader = new StreamReader(filePath))
{
for (var i = 0; i < charsToCheck; i++)
{
if (streamReader.EndOfStream)
return false;
if ((char) streamReader.Read() == nulChar)
{
nulCount++;
if (nulCount >= requiredConsecutiveNul)
return true;
}
else
{
nulCount = 0;
}
}
}
return false;
}
To get the real type of a file, you must check its header, which won't be changed even the extension is modified. You can get the header list here, and use something like this in your code:
using(var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
using(var reader = new BinaryReader(stream))
{
// read the first X bytes of the file
// In this example I want to check if the file is a BMP
// whose header is 424D in hex(2 bytes 6677)
string code = reader.ReadByte().ToString() + reader.ReadByte().ToString();
if (code.Equals("6677"))
{
//it's a BMP file
}
}
}
I have a below solution which works for me.This is general solution which check all types of Binary file.
/// <summary>
/// This method checks whether selected file is Binary file or not.
/// </summary>
public bool CheckForBinary()
{
Stream objStream = new FileStream("your file path", FileMode.Open, FileAccess.Read);
bool bFlag = true;
// Iterate through stream & check ASCII value of each byte.
for (int nPosition = 0; nPosition < objStream.Length; nPosition++)
{
int a = objStream.ReadByte();
if (!(a >= 0 && a <= 127))
{
break; // Binary File
}
else if (objStream.Position == (objStream.Length))
{
bFlag = false; // Text File
}
}
objStream.Dispose();
return bFlag;
}
public bool IsTextFile(string FilePath)
using (StreamReader reader = new StreamReader(FilePath))
{
int Character;
while ((Character = reader.Read()) != -1)
{
if ((Character > 0 && Character < 8) || (Character > 13 && Character < 26))
{
return false;
}
}
}
return true;
}

Why NoPointerExcepeion when decompression by apache compress?

click and see The NoPointerExcepeion
I generate tar.gz files and send 2 others 4 decompress, but their progrem has error above(their progrem was not created by me), only one file has that error.
But when using command 'tar -xzvf ***' on my computer and their computer, no problem occured...
So I want 2 know what was wrong in my progrem below:
public static void archive(ArrayList<File> files, File destFile) throws Exception {
TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(destFile));
taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
for (File file : files) {
//LOG.info("file Name: "+file.getName());
archiveFile(file, taos, "");
}
}
private static void archiveFile(File file, TarArchiveOutputStream taos, String dir) throws Exception {
TarArchiveEntry entry = new TarArchiveEntry(dir + file.getName());
entry.setSize(file.length());
taos.putArchiveEntry(entry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
taos.write(data, 0, count);
}
bis.close();
taos.closeArchiveEntry();
}
The stack trace looks like a bug in Apache Commons Compress https://issues.apache.org/jira/browse/COMPRESS-223 that has been fixed with version 1.7 (released almost three years ago).

Convert g722 audio to WAV using NAudio

I'm starting to write a Windows Service that will convert G.722 audio files into WAV files and I'm planning on using the NAudio library.
After looking at the NAudio demos, I've found that I will need to use the G722Codec to decode the audio data from the file but I'm having trouble figuring out how to read the G722 file. Which reader should I use?\
The G722 files are 7 kHz.
I'm working my way through the Pluralsight course for NAudio but it would be great to get a small code sample.
I got it working with the RawSourceWaveStreambut then tried to simply read the bytes of the file, decode using the G722 Codec and write the bytes out to a wave file. It worked.
private readonly G722CodecState _state = new G722CodecState(64000, G722Flags.SampleRate8000);
private readonly G722Codec _codec = new G722Codec();
private readonly WaveFormat _waveFormat = new WaveFormat(8000, 1);
public MainWindow()
{
InitializeComponent();
var data = File.ReadAllBytes(#"C:\Recordings\000-06Z_chunk00000.g722");
var output = Decode(data, 0, data.Length);
using (WaveFileWriter waveFileWriter = new WaveFileWriter(#"C:\Recordings\000-06Z_chunk00000.wav", _waveFormat))
{
waveFileWriter.Write(output, 0, output.Length);
}
}
private byte[] Decode(byte[] data, int offset, int length)
{
if (offset != 0)
{
throw new ArgumentException("G722 does not yet support non-zero offsets");
}
int decodedLength = length * 4;
var outputBuffer = new byte[decodedLength];
var wb = new WaveBuffer(outputBuffer);
int decoded = _codec.Decode(_state, wb.ShortBuffer, data, length);
return outputBuffer;
}

CreateFile2 returns access denied error in Windows 8

I have written the following lines of code to open a file under InstalledFolder directory:
Platform::String^ locationPath = Platform::String::Concat(Package::Current->InstalledLocation->Path, "\\Assets\\Logo.png");
CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
extendedParams.lpSecurityAttributes = nullptr;
extendedParams.hTemplateFile = nullptr;
Wrappers::FileHandle file(
CreateFile2(
locationPath->Data(),
GENERIC_READ,
0,
OPEN_EXISTING,
&extendedParams
)
);
DWORD e = GetLastError();
if (file.Get() == INVALID_HANDLE_VALUE)
{
throw ref new Platform::FailureException();
}
The CreateFile2 returns access denied error. Can anyone please help me out?
As suggested by JP Alioto, I have tried with WinRT File I/O as the following
create_task(StorageFile::GetFileFromApplicationUriAsync(ref new Windows::Foundation::Uri("ms-appx:///Assets/Logo.png")))
.then([=](StorageFile^ f)
{
auto p = create_task(f->OpenAsync(FileAccessMode::Read));
p.wait();
});
I still get the following error at p.wait():
An invalid parameter was passed to a function that considers invalid parameters fatal
Thanks,
You are passing 0 for dwShareMode. The documentation for CreateFile2 says that this value...
Prevents other processes from opening a file or device if they request delete, read, or write access. Exclusive access to a file or directory is only granted if the application has write access to the file.
You do not have write access to files within the package, which is why you get the access denied error. You need to set the share mode to FILE_SHARE_READ.