CreateFile2 returns access denied error in Windows 8 - 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.

Related

Problem with getting rights data [for execution / read / write] file

I'm writing a program that should output a meta-info (size, permissions to execute / read / write, time of last modification) of all files from the specified directory.
I received information about all the information, except the rights to execute / read / write.
I tried to get this info using PosixFilePermissions, but when added to the List I get Exception in thread "main" java.lang.UnsupportedOperationException.
Maybe you should use some other library? Or did I make a mistake somewhere? I would be grateful for any advice!
fun long(path:Path) : MutableList<String> {
var listOfFiles = mutableListOf<String>()
val files = File("$path").listFiles()
var attr: BasicFileAttributes
Arrays.sort(files, NameFileComparator.NAME_COMPARATOR)
files.forEach {
if (it.isFile) {
attr = Files.readAttributes<BasicFileAttributes>(it.toPath(), BasicFileAttributes::class.java)
listOfFiles.add("${it.name} ${attr.size()} ${attr.lastModifiedTime()}" +
" ${PosixFilePermissions.toString(Files.getPosixFilePermissions(it.toPath()))}")
}
else listOfFiles.add("dir ${it.name}")
}
return listOfFiles
}
PosixFilePermissions are only usable for POSIX-compatible file systems (Linux etc.).
For a Windows system, the permissions have to be accessed directly:
file.canRead()
file.canWrite()
file.canExecute()

Unable to update unidata from .NET

I've been attempting for the last couple of days to update unidata using sample code as a basis using .NET without success. I can read the database successfully and view the raw data within visual studio. The error reported back is a out of range error. The program is attempting to update the unit price of a purchase order.
Error:
{" Error on Socket Receive. Index was outside the bounds of the array.POD"}
[IBMU2.UODOTNET.UniFileException]: {" Error on Socket Receive. Index was outside the bounds of the array.POD"}
Data: {System.Collections.ListDictionaryInternal}
HelpLink: null
HResult: -2146232832
InnerException: null
Message: " Error on Socket Receive. Index was outside the bounds of the array.POD"
Source: "UniFile Class"
StackTrace: " at IBMU2.UODOTNET.UniFile.Write()\r\n at IBMU2.UODOTNET.UniFile.Write(String aRecordID, UniDynArray aRecordData)\r\n at ReadXlsToUnix.Form1.TestUpdate(String PO_LINE_SHIP, String price) in c:\Users\xxx\Documents\Visual Studio 2013\Projects\ReadXlsToUnix\ReadXlsToUnix\Form1.cs:line 330"
TargetSite: {Void Write()}
failing Test Code is:
private void TestUpdate(string PO_LINE_SHIP,string price)
{
UniFile pod =null;
UniSession uniSession =null;
//connection string
uniSession = UniObjects.OpenSession("unixMachine", "userid", Properties.Settings.Default.PWD, "TRAIN", "udcs");
//open file
pod = uniSession.CreateUniFile("POD");
//read data
pod.Read(PO_LINE_SHIP);
//locking strategy
pod.UniFileLockStrategy = 1;
pod.UniFileReleaseStrategy = 1;
if (pod.RecordID == ""){
pod.UnlockRecord();
}
//replace existing value with one entered by user
pod.Record.Replace(4, (string)uniSession.Iconv(price, "MD4"));
try
{
pod.Write(pod.RecordID,pod.Record); //RecordId and Record both show correctly hover/immediate window
//pod.Write() fails with same message
}
catch (Exception err)
{
MessageBox.Show("Error" + err);
}
pod.Close();
UniObjects.CloseSession(uniSession);
}
}
Running on HP UX 11.31 unidata 7.2 and using UODOTNET.dll 2.2.3.7377
Any help greatly appreciated.
This is the write record version and have also tried writefield functionality with same error.
Rajan - thanks for the update and link. I have tried unsuccessfully to read/update my unidata tables using the U2 Toolkit. I can however read/update a file I have created within the same account. Does this mean there is a missing entry somewhere VOC, DICT for example.

Read data from excel data by JSPDynpage

Please help me with the below issue.
I have to read data from excel .
I have created JSPDynpage component and followd below link :
http://help.sap.com/saphelp_sm40/helpdata/en/63/9c0e41a346ef6fe10000000a1550b0/frameset.htm below is my code. I am trying to read excel file using apache poi 3.2 API
try
{
FileUpload fu = (FileUpload)
this.getComponentByName("myfileupload");
// this is the temporary file
if (fu != null) {
// Output to the console to see size and UI.
System.out.println(fu.getSize());
System.out.println(fu.getUI());
// Get file parameters and write it to the console
IFileParam fileParam = fu.getFile();
System.out.println(fileParam);
// Get the temporary file name
File f = fileParam.getFile();
String fileName = fileParam.getFileName();
// Get the selected file name and write ti to the console
ivSelectedFileName = fu.getFile().getSelectedFileName();
File fp = new File(ivSelectedFileName);
myLoc.errorT("#fp#"+fp);
try {
//
**FileInputStream file = new FileInputStream(fp);** --> error at this line
HSSFWorkbook workbook = new HSSFWorkbook(file);
myLoc.errorT("#workbook#"+workbook);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
myLoc.errorT("#sheet#"+sheet);
//
} catch(Exception ioe) {
myLoc.errorT("#getLocalizedMessage# " + ioe.getLocalizedMessage());
}
Error :
#getLocalizedMessage# C:\Documents and Settings\10608871\Desktop\test.xls (The system cannot find the path specified)
at line FileInputStream file = new FileInputStream(fp);
I have created the PAR file and deploying it on server.
Thanks in Advance,
Aliya Khan.
i resolved the problem, i was passing the worng parameter instead of f
FileInputStream file = new FileInputStream(f);

CreateFile2 error in WinRT project (ERROR_NOT_SUPPORTED_IN_APPCONTAINER)

I just working on some file management api in WinRT. I successfully created folder in ../Packages/myApp/LocalState/ but when I try to create new file (CreateFile2) in that folder I get this
error 4252: ERROR_NOT_SUPPORTED_IN_APPCONTAINER
This functionality is not supported in the context of an app container.
code:
localFolder = L"C:\\Users\\Tomas\\AppData\\Local\\Packages\\myApp\\LocalState\\my";
CreateDirectory(localFolder.c_str(),NULL);
localFolder += L"\\MyFile.txt";
CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams;
pCreateExParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
pCreateExParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
pCreateExParams.lpSecurityAttributes = NULL;
pCreateExParams.hTemplateFile = NULL;
HANDLE myfile = CreateFile2(localFolder.c_str(), GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, OPEN_ALWAYS, &pCreateExParams);
int error = GetLastError();
What I'm doing wrong? Should I set some options in manifest?
Thank you for your help
Already found the problem - in pCreateExParams struct was some undefined values in .dwFileFlags and .dwSecurityQosFlags. So this works fine:
CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams = {0};

Uploading to an FTP server

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;