FileStream constructor with FileOptions argument. Is this still valid .NET 5? - filestream

According to the .NET 5 documentation for the FileStream class, it still takes a constructor that permits the user to pass in a FileOptions argument.
FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)
Yet in practice, the constructor does not seem to be there. Even when I navigate to decompiled sources, I don't see it there Does anyone know if this is a documentation oversight or am I missing something?
Note that I am building my .NET 5 application with a windows target, if that matters
<TargetFramework>net5.0-windows</TargetFramework>
Also, if it matters, this is what I'm trying to do (which does not build)
string path = Path.Combine(Folder, "temp-lock-delete-me.tmp");
_preventRenameFs = new FileStream(
path,
FileAccess.ReadWrite,
FileShare.Delete | FileShare.Write | FileShare.Read,
4096,
FileOptions.DeleteOnClose);

As per your code you need to add FileMode argument
string path = Path.Combine(Folder, "temp-lock-delete-me.tmp");
_preventRenameFs = new FileStream(
path,
FileMode.OpenOrCreate,// <-- add FileMode
FileAccess.ReadWrite,
FileShare.Delete | FileShare.Write | FileShare.Read,
4096,
FileOptions.DeleteOnClose);

Related

Getting target framework attribute in PowerShell Core

I'm looking for a way to retrieve the target framework attribute (e.g. .NETCoreApp,Version=v2.1) from a DLL when using PowerShell Core, ideally without loading the DLL directly into the main session.
I can do this in Windows PowerShell 5, as it has access to the ReflectionOnlyLoadFrom method...
$dllPath = 'C:\Temp\ADALV3\microsoft.identitymodel.clients.activedirectory.2.28.4\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll'
[Reflection.Assembly]::ReflectionOnlyLoadFrom($dllPath).CustomAttributes |
Where-Object {$_.AttributeType.Name -eq 'TargetFrameworkAttribute'} |
Select -ExpandProperty ConstructorArguments |
Select -ExpandProperty value
However, I realise that this approach isn't available in .NET Core.
Editor's note: Even though the documentation (as of this writing) misleadingly suggests that the ReflectionOnlyLoadFrom method is available in .NET Core, it is not, as explained here.
From what I've seen, it looks likely that I should be able to access the custom attributes that hold the target framework attribute by using an instance of the System.Reflection.Metadata.MetadataReader class that's available in .NET Core (a couple of examples of this in use can be found here: https://csharp.hotexamples.com/examples/System.Reflection.Metadata/MetadataReader/GetCustomAttribute/php-metadatareader-getcustomattribute-method-examples.html ). However, all the constructors for this type seem to use a Byte* type, as the following shows when running from PowerShell Core:
([type] 'System.Reflection.Metadata.MetadataReader').GetConstructors() | % {$_.GetParameters() | ft}
I have no idea how to create a Byte* type in any version of PowerShell. Perhaps there's a method in System.Reflection.Metadata that I should be using before creating the MetadataReader object, but I haven't found it yet.
Apologies for the length of this question, but I'm hoping by sharing my notes I'll help in tracking down the solution. Any advice on how this target framework information can be obtained using PowerShell Core?
After quite a bit of work, I managed to put together a PowerShell script that works (without external dependencies) in PowerShell Core that pulls in the target framework from a DLL:
$dllPath = 'C:\Temp\ADALV3\microsoft.identitymodel.clients.activedirectory.2.28.4\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll'
$stream = [System.IO.File]::OpenRead($dllPath)
$peReader = [System.Reflection.PortableExecutable.PEReader]::new($stream, [System.Reflection.PortableExecutable.PEStreamOptions]::LeaveOpen -bor [System.Reflection.PortableExecutable.PEStreamOptions]::PrefetchMetadata)
$metadataReader = [System.Reflection.Metadata.PEReaderExtensions]::GetMetadataReader($peReader)
$assemblyDefinition = $metadataReader.GetAssemblyDefinition()
$assemblyCustomAttributes = $assemblyDefinition.GetCustomAttributes()
$metadataCustomAttributes = $assemblyCustomAttributes | % {$metadataReader.GetCustomAttribute($_)}
foreach ($attribute in $metadataCustomAttributes) {
$ctor = $metadataReader.GetMemberReference([System.Reflection.Metadata.MemberReferenceHandle]$attribute.Constructor)
$attrType = $metadataReader.GetTypeReference([System.Reflection.Metadata.TypeReferenceHandle]$ctor.Parent)
$attrName = $metadataReader.GetString($attrType.Name)
$attrValBytes = $metadataReader.GetBlobContent($attribute.Value)
$attrVal = [System.Text.Encoding]::UTF8.GetString($attrValBytes)
if($attrName -eq 'TargetFrameworkAttribute') {Write-Output "AttributeName: $attrName, AttributeValue: $attrVal"}
}
$peReader.Dispose()
I'm mostly happy with it, the only issue I'd still like to sort out is that I'm getting some unhandled characters in the string output. I'll try to get rid of them.

Add-CMDeploymentType warning

Im using poweshell to automate creating applications in SCCM 2012, distributing content and deploying them once created.
I have the following code:
New-CMApplication -name $appname -Manufacturer $manu -SoftwareVersion $ver
Which works fine.
However.
Add-CMDeploymentType -MsiInstaller -applicationName $appname -AutoIdentifyFromIntallationFile -InstallationFileLocation $content -ForceForUnknownPublisher $true
Gives me a warning " Failed to get install type's technology and it won't create the deployment type.
As far as I can tell from other sites, I shouldn't need to specifiy and more than that. I've experimented with adding more options on the end but none seem to make a difference.
There isnt very much out there about this error - has anyone got past it before?
I doubt that you'll get Add-CMDeploymentType to do much useful -- at least not in its current form. I once tried and gave up when I noticed that it is missing basic, essential parameters. The documentation does not even mention, for example, detection of any sort. There's not much point in using ConfigMgr Applications without detection, and there's not much point in scripting the creation of DeploymentTypes if you still have to define the detection criteria via the UI.
You might get the odd msi file configured using the Add-CMDeploymentType's AddDeploymentTypeByMsiInstallerX parameter set. In that case you'd be relying on ConfigMgr to work out the detection logic automagically. That may work, but I have had significant issues with the MSI Deployment. I'd avoid that if possible.
I'm not hopeful that the Add-CMDeploymentType will ever become usable. The object tree that underlies Applications is necessarily complex and really doesn't lend itself to interaction using simple PowerShell cmdlets. To completely configure an Application there are hundreds of properties on dozens of objects that you need to access. Many of those objects are contained in dictionary- and array-like collections that have their own special semantics for accessing them. You just can't simplify that into a handful of PowerShell cmdlets.
I'm using the types in the following .dlls to interface with ConfigMgr:
AdminUI.WqlQueryEngine.dll
Microsoft.ConfigurationManagement.ApplicationManagement.dll
Microsoft.ConfigurationManagement.ApplicationManagement.MsiInstaller.dll
As far as I can tell, that is the same API the admin console uses, so you can expect full functionality. You cannot make the same claims about the PowerShell cmdlets. So far I have found a way to access everything I've tried through that API using PowerShell. The basics of accessing that API is documented in the ConfigMgr SDK. It's fairly straightforward to figure out how those objects work using reflection and some experimentation.
When you retrieve an Application using Get-CMApplication you actually get the full object tree with it. The SDMPackageXML object contains a serialized copy of the Application, DeploymentTypes, detection, installers, etc. [Microsoft.ConfigurationManagement.ApplicationManagement.Serialization.SccmSerializer]::DeserializeFromString() works to deserialize that object so you can inspect it for yourself.
I actually gave up on this - As you say - Add-CMDeployment type is completely useless. There was nothing online anywhere that described this error, or how to use it properly - an Application with no detection is pointless and adding it manually later defeats the point in trying to automate it.
PowerShell centre had some examples of how it could be used but neither of these worked...
This link was pretty useful and has everything I needed to create an application without powershell.
link
a bit long but the code was...
Public Sub create_SCCM_application(appname As String, version As String, content_location As String, filename As String, manu As String)
Try
Dim appID As ObjectId = New ObjectId("ScopeId_devscope", "Application_" & Guid.NewGuid().ToString())
Dim app As New Application(appID)
app.Title = appname
app.Version = "1.0"
app.Publisher = manu
app.SoftwareVersion = version
app.AutoInstall = True
Dim dinfo As New AppDisplayInfo
dinfo.Title = appname
dinfo.Version = version
dinfo.Language = Globalization.CultureInfo.CurrentCulture.Name
app.DisplayInfo.Add(dinfo)
Dim dtID As ObjectId = New ObjectId("ScopeId_devscope", "DeploymentType_" & Guid.NewGuid().ToString())
Dim dt As New DeploymentType(dtID, MsiInstallerTechnology.TechnologyId)
dt.Title = appname & " Deployment type"
dt.Version = "1.0"
app.DeploymentTypes.Add(dt)
Dim installer As MsiInstaller = dt.Installer
Dim fakecode As Guid = Guid.NewGuid
installer.ProductCode = "{" & fakecode.ToString & "}"
installer.InstallCommandLine = "msiexec /i " & filename
installer.UninstallCommandLine = "msiexec /x " & filename
installer.AllowUninstall = True
installer.ExecuteTime = 30
installer.MaxExecuteTime = 30
installer.ExecutionContext = ExecutionContext.System
installer.UserInteractionMode = UserInteractionMode.Hidden
installer.DetectionMethod = DetectionMethod.ProductCode
installer.ProductVersion = version
Dim appcont As Content = New Content
installer.Contents.Add(appcont)
appcont.Location = content_location
Dim msifile As New ContentFile
msifile.Name = "_temp.msi"
appcont.Files.Add(msifile)
Dim appxml As XDocument = SccmSerializer.Serialize(app, True)
Dim appinstance As ManagementObject = Nothing
Dim path As ManagementPath = New ManagementPath("SMS_Application")
Dim options As New ObjectGetOptions
Dim appClass As ManagementClass = Nothing
Dim scope As ManagementScope = New ManagementScope("\\devserver\root\Sms\Site_devsitecode")
appClass = New ManagementClass(scope, path, options)
appinstance = appClass.CreateInstance()
appinstance.Properties("SDMPackageXML").Value = appxml
appinstance.Put()
Catch x As System.Exception
Console.WriteLine(x.Message)
End Try
End Sub
Your question regarding the deployment type behaviour is also wierd - We have that same product and it works from an MSI deployment type.

Changing working directory in Scala [duplicate]

How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case.
I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call System.setProperty( "user.dir", "/path/to/dir" ), but as far as I can figure out, calling that line just silently fails and does nothing.
I would understand if Java didn't allow you to do this, if it weren't for the fact that it allows you to get the current working directory, and even allows you to open files using relative file paths....
There is no reliable way to do this in pure Java. Setting the user.dir property via System.setProperty() or java -Duser.dir=... does seem to affect subsequent creations of Files, but not e.g. FileOutputStreams.
The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping.
An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.
The relevant OpenJDK bug was closed in 2008 as "will not fix".
If you run your legacy program with ProcessBuilder, you will be able to specify its working directory.
There is a way to do this using the system property "user.dir". The key part to understand is that getAbsoluteFile() must be called (as shown below) or else relative paths will be resolved against the default "user.dir" value.
import java.io.*;
public class FileUtils
{
public static boolean setCurrentDirectory(String directory_name)
{
boolean result = false; // Boolean indicating whether directory was set
File directory; // Desired current working directory
directory = new File(directory_name).getAbsoluteFile();
if (directory.exists() || directory.mkdirs())
{
result = (System.setProperty("user.dir", directory.getAbsolutePath()) != null);
}
return result;
}
public static PrintWriter openOutputFile(String file_name)
{
PrintWriter output = null; // File to open for writing
try
{
output = new PrintWriter(new File(file_name).getAbsoluteFile());
}
catch (Exception exception) {}
return output;
}
public static void main(String[] args) throws Exception
{
FileUtils.openOutputFile("DefaultDirectoryFile.txt");
FileUtils.setCurrentDirectory("NewCurrentDirectory");
FileUtils.openOutputFile("CurrentDirectoryFile.txt");
}
}
It is possible to change the PWD, using JNA/JNI to make calls to libc. The JRuby guys have a handy java library for making POSIX calls called jnr-posix. Here's the maven info
As mentioned you can't change the CWD of the JVM but if you were to launch another process using Runtime.exec() you can use the overloaded method that lets you specify the working directory. This is not really for running your Java program in another directory but for many cases when one needs to launch another program like a Perl script for example, you can specify the working directory of that script while leaving the working dir of the JVM unchanged.
See Runtime.exec javadocs
Specifically,
public Process exec(String[] cmdarray,String[] envp, File dir) throws IOException
where dir is the working directory to run the subprocess in
If I understand correctly, a Java program starts with a copy of the current environment variables. Any changes via System.setProperty(String, String) are modifying the copy, not the original environment variables. Not that this provides a thorough reason as to why Sun chose this behavior, but perhaps it sheds a little light...
The working directory is a operating system feature (set when the process starts).
Why don't you just pass your own System property (-Dsomeprop=/my/path) and use that in your code as the parent of your File:
File f = new File ( System.getProperty("someprop"), myFilename)
The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like new File("blah.txt"), just build the path to the file yourself.
Let the user pass in the base directory, read it from a config file, fall back to user.dir if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.
I have tried to invoke
String oldDir = System.setProperty("user.dir", currdir.getAbsolutePath());
It seems to work. But
File myFile = new File("localpath.ext");
InputStream openit = new FileInputStream(myFile);
throws a FileNotFoundException though
myFile.getAbsolutePath()
shows the correct path.
I have read this. I think the problem is:
Java knows the current directory with the new setting.
But the file handling is done by the operation system. It does not know the new set current directory, unfortunately.
The solution may be:
File myFile = new File(System.getPropety("user.dir"), "localpath.ext");
It creates a file Object as absolute one with the current directory which is known by the JVM. But that code should be existing in a used class, it needs changing of reused codes.
~~~~JcHartmut
You can use
new File("relative/path").getAbsoluteFile()
after
System.setProperty("user.dir", "/some/directory")
System.setProperty("user.dir", "C:/OtherProject");
File file = new File("data/data.csv").getAbsoluteFile();
System.out.println(file.getPath());
Will print
C:\OtherProject\data\data.csv
You can change the process's actual working directory using JNI or JNA.
With JNI, you can use native functions to set the directory. The POSIX method is chdir(). On Windows, you can use SetCurrentDirectory().
With JNA, you can wrap the native functions in Java binders.
For Windows:
private static interface MyKernel32 extends Library {
public MyKernel32 INSTANCE = (MyKernel32) Native.loadLibrary("Kernel32", MyKernel32.class);
/** BOOL SetCurrentDirectory( LPCTSTR lpPathName ); */
int SetCurrentDirectoryW(char[] pathName);
}
For POSIX systems:
private interface MyCLibrary extends Library {
MyCLibrary INSTANCE = (MyCLibrary) Native.loadLibrary("c", MyCLibrary.class);
/** int chdir(const char *path); */
int chdir( String path );
}
The other possible answer to this question may depend on the reason you are opening the file. Is this a property file or a file that has some configuration related to your application?
If this is the case you may consider trying to load the file through the classpath loader, this way you can load any file Java has access to.
If you run your commands in a shell you can write something like "java -cp" and add any directories you want separated by ":" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.
Use FileSystemView
private FileSystemView fileSystemView;
fileSystemView = FileSystemView.getFileSystemView();
currentDirectory = new File(".");
//listing currentDirectory
File[] filesAndDirs = fileSystemView.getFiles(currentDirectory, false);
fileList = new ArrayList<File>();
dirList = new ArrayList<File>();
for (File file : filesAndDirs) {
if (file.isDirectory())
dirList.add(file);
else
fileList.add(file);
}
Collections.sort(dirList);
if (!fileSystemView.isFileSystemRoot(currentDirectory))
dirList.add(0, new File(".."));
Collections.sort(fileList);
//change
currentDirectory = fileSystemView.getParentDirectory(currentDirectory);

Eclipse OSGI config: relative paths and/or #config.dir-like substitutions?

In my RCP app, I would like to point a property (osgi.java.profile) to a file, and would prefer using paths relative to my installation and config dir.
Is there a definitive spec on what kind of variables are supported in config.ini?
#config.dir seems to be supported, there are references in the builtin, and it's always mentioned as typical example (e.g this SO answer )
However, looking at docs like Eclipse help/Runtime Options, it mentions a few "symbolic locations" like #user.home; however that seems fairly limited and doesn't include #config.dir.
Have even dug into org.eclipse.osgi sources as well, and found no references to this (I did find LocationManager and its hard coded variable substitutions for #user.dir & co).
Can I refer to arbitrary system properties there in some way?
Is this #config.dir a special case, only handled by P2? UPDATE: this seems to be the case.. looking at Eclipse SDK, About .. Configuration dialog shows #config.dir unresolved, probably taken literally by the Equinox..
Thanks for any hints.
I'm late to the party, but hopefully this will help others in the future.
Starting with Eclipse 3.8/4.2 (June 2012), you can substitute Java properties and environment variables into your config.ini file (Eclipse Bug 241192). The Equinox launcher does not support substitution in the eclipse.ini launcher file. The syntax uses dollar signs ($VARIABLE$) to indicate variable substitution:
osgi.configuration.area=$APPDATA$/MyCompany/MyProgram/configuration
osgi.user.area=$APPDATA$/MyCompany/MyProgram/user
osgi.instance.area=$APPDATA$/MyCompany/MyProgram/instance
I imagine you could use something like this for your purposes:
osgi.java.profile=$osgi.install.area$/path/to/profile.txt
You can use a platform URL (Platform URI scheme) to achieve this, i.e.
osgi.java.profile = platform:/config/java_profile.txt
in config.ini, would point to the file java_profile.txt in the current configuration directory.
You might also use existing system properties in config.ini:
osgi.java.profile = ${osgi.configuration.area}/java_profile.txt
From org.eclipse.core.runtime.adaptor.LocationManager, here are the special tokens:
// Data mode constants for user, configuration and data locations.
private static final String NONE = "#none"; //$NON-NLS-1$
private static final String NO_DEFAULT = "#noDefault"; //$NON-NLS-1$
private static final String USER_HOME = "#user.home"; //$NON-NLS-1$
private static final String USER_DIR = "#user.dir"; //$NON-NLS-1$
Why not use two system property variables?
One is named -Dmy.relativepath=filename, which is processed by your code of relative path of eclipse installation folder(workspace or anywhere), another is called -Dmy.path=absolutepath.
The system property is passed to the jvm, you need some tricky(translate the variable in runtime) in the native launcher(like eclipse.exe) if you wants to use variable in its value.
Look how osgi.java.profile is resolved in org.eclipse.osgi.framework.internal.core.Framework:
// check for the java profile property for a url
String propJavaProfile = FrameworkProperties.getProperty(Constants.OSGI_JAVA_PROFILE);
if (propJavaProfile != null)
try {
// we assume a URL
url = new URL(propJavaProfile);
} catch (MalformedURLException e1) {
// try using a relative path in the system bundle
url = findInSystemBundle(propJavaProfile);
}
That means osgi.java.profile must point either to a fully qualified URL, or to a relative path in system bundle (org.eclipse.osgi). This makes impossible usage of installation directory relative path without patching Eclipse.

War file deployment

I wrote a jsp application, and if I generate a war file with eclipse in windows XP, language: tradition Chinese. and deploy to weblogic,
it will have such problem:
inputAdministrator.jsp:251:11: This type name is ambiguous because it matches more than one '*'-import, including 'java.io.*' and 'admin.iguard.businessObject.*'.
DataInput d = (DataInput) dataInput;
^-------^
inputAdministrator.jsp:252:29: Type java.io.DataInput contains no methods named getDept1.
String dept1 = d.getDept1();
^------^
inputAdministrator.jsp:253:26: No match was found for method trim() in type <error>.
String emp2 = d.getEmp2().trim();
^----------------^
inputAdministrator.jsp:253:28: Type java.io.DataInput contains no methods named getEmp2.
String emp2 = d.getEmp2().trim();
^-----^
inputAdministrator.jsp:254:29: Type java.io.DataInput contains no methods named getDept2.
String dept2 = d.getDept2();
^------^
inputAdministrator.jsp:255:33: Type java.io.DataInput contains no methods named getDept_code.
String dept_code = d.getDept_code();
^----------^
inputAdministrator.jsp:256:32: Type java.io.DataInput contains no methods named getStaff_no.
String staff_no = d.getStaff_no();
^---------^
inputAdministrator.jsp:257:32: Type java.io.DataInput contains no methods named getEmp2_por.
String emp2_por = d.getEmp2_por();
^---------^
if I generate the war file in windows xp, simplize Chinese, and deploy to weblogic, everything will be OK.
I don't know how the "text file encoding" setting will affect the generated war file,
how can i make sure that all this things are in sync.
Any one have better solution?
Any suggestions will be appreciated.
Thanks in advance!
did you check it? does text encoding changes in both the j2ee exports as a WAR file?
windows-->preferences-->General-->workspace-->textfileencoding?
it defaults to cp1532
what is the value of textfileencoding variable set in simplize Chinese as compared to tradition Chinese ??
May be the "text file encoding" triggers some kind of recompilation which makes that issue visible.
In any case, could you try first to disambiguate the DataInput usage, by:
adding for example "java.io."(in front of DataInput) everywhere in that source where it is actually a java.io case (leaving a simple DataInput for businessObject usages)
not using import java.io.* (but using CTRL+SHIFT+O for reorganizing the imports)
would that solve the problem, whatever the "text file encoding" is?