How to replace the hosts file on C# - hosts

I just want to know how can I completely replace the user's hosts file with another one?
Note: I wana give the user just my .exe compiled file(With my own hosts file attached to it) and after running the exe file the user's hosts file should be replaced with my own hosts file I attached to my exe file.

Simple way, you can use IO library.
string path = "system32\\drivers\\etc\\hosts";
string hostfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), path);
const string checkIP = "127.0.0.1 localhost";
if (!File.ReadAllLines(hostfile).Contains(checkIP))
File.AppendAllLines(hostfile, new string[] {checkIP});
Do not forget, your program must run with administrator privileges, otherwise you will get an UnauthorizedAccessException exception.

Related

How to read config file in electronjs app

It's my first time using Electron JS and nodejs. I've built a small app that reads some records from a database and updates them. Everything is working fine. I have a config file with the database credentials but when I build a portable win app, I cannot figure out how to read the config file that I would like to place next to the exe. I would like to have easy access to the file, so I could run the same app on different databases.
Can anyone tell me if what I want is possible and how? I already tried to get the exe location but I couldn't. I also read a lot of topics here but nothing seems to solve my problem (I might be doing something wrong).
I'm using electron-builder to build my app.
Thanks in advance.
Edit #1
My Config file is
{
"user" :"X",
"password" :"X",
"server":"X",
"database":"X",
"options":
{
"trustedconnection": true,
"enableArithAbort" : true,
"trustServerCertificate": true
}
}
This is what I've and works when I run the project with npm start
const configRootPath = path.resolve(__dirname,'dbConfig.json');
dbConfig = JSON.parse(fs.readFileSync(configRootPath, { encoding: 'utf-8' }));
However, when I build it, the app is looking for the file in another location different from the one where the executable is.
Use of Electron's app.getPath(name) function will get you the path(s) you are after, irrespective of which OS (Operating System) you are using.
Unless your application writes your dbConfig.json file, it may be difficult for your user to understand exactly where they should place their database config file as each OS will run and store your application data in a different directory. You would need to be explicit to the user as to where to place their config file(s). Alternatively, your application could create the config file(s) on the user's behalf (automatically or through a html form) and save it to a location 'known' to the application.
A common place where application specific config files are stored is in the user's application data directory. With the application name automatically amended to the directory, it can be found as shown below.
const electronApp = require('electron').app;
let appUserDataPath = electronApp.getPath('userData');
console.log(appUserDataPath );
In your use case, the below would apply.
const electronApp = require('electron').app;
const nodeFs = require('fs');
const nodePath = require('path');
const configRootPath = nodePath.join(electronApp.getPath('userData'), 'dbConfig.json');
dbConfig = JSON.parse(nodeFs.readFileSync(configRootPath, 'utf-8'));
console.log(configRootPath);
console.log(dbConfig);
You can try electron-store to store config.
Electron doesn't have a built-in way to persist user preferences and other data. This module handles that for you, so you can focus on building your app. The data is saved in a JSON file named config.json in app.getPath('userData').

Using Grails to store image but could not store outside CATALINA_HOME in production

I'm using Grails 2.5.6 to store uploaded images to folder on a server.
The following are my code to store the image
mpr.multiFileMap.file.each{fileData->
CommonsMultipartFile file = fileData
File convFile = new File(file.getOriginalFilename());
file.transferTo(convFile);
/** Processing File **/
File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
convFile.renameTo(uploadedFile)
}
I have no problem running on development (MacOSX High Sierra)
But when i deployed on production (Ubuntu 14.04 server), i could not save the file outside CATALINA_HOME directory.
I have checked the permission and ownership of the destination directory, but still, the directory was created but the file was never stored.
For Example, i've tried to store the file on /home/tomcat/ directory (/home directory was in separate partition with tomcat which stored it /var), the directory was created, but the file was never stored.
When i put the destination directory within CATALINA_HOME folder, everything works fine. But this was not the scenario i want to do.
You say your destination directory is on another partition, so maybe another filesystem is used on this partition.
Or if you look on the javadoc of the renameTo method it is said :
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make
sure that the rename operation was successful.
...
#return true if and only if the renaming succeeded;
false otherwise
Thus I think the renameTo method is not able to move the file, don't know why but you can rewrite your code like this :
mpr.multiFileMap.file.each{fileData->
CommonsMultipartFile file = fileData
File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
// String originalFilename = file.getOriginalFilename()
// you can store originalFilename in database for example
if(!uploadedFile.getParentFile().exists()) {
uploadedFile.getParentFile().mkdirs()
// You can set permissions on the target directory if you desired, using PosixFilePermission
}
file.transferTo(uploadedFile)
}

Can I preserve a folder's contents in my project directory when I queue a new Build in TFS?

I have a problem. I am using Team Foundation Server 2017 RTM. I have a build definition that will deploy my app to a development server running Windows Server 2012 R2. My app allows users to upload images and PDFs. When this is done, a folder named Media is created in my project's root directory and the files are uploaded here. The problem is, whenever I queue a new build, this folder gets destroyed and all the links to the media don't point to anything. I am rather new at managing and setting up TFS so I was wondering if there is any way I can preserve the contents of my media folder whenever I queue a new build. Any ideas?
Ok, so I spent my whole day looking at this.
In my C# code I create a directory like so:
// -- Create a new file name that is unique
string fileExtension = Path.GetExtension(upload.FileName);
Guid fileGuid = Guid.NewGuid();
string fileName = fileGuid + fileExtension;
// -- Create the directory and upload the image to that directory
string mediaDirectory = Server.MapPath("~/Media/");
Directory.CreateDirectory(mediaDirectory);
string filePath = Path.Combine(mediaDirectory, fileName);
upload.SaveAs(filePath);
I would then set the image url on the Media object like:
string imageUrl = "/Media/" + fileName;
So now, instead of storing the image in the database, I am just storing the URL to the image.
This was creating the directory in the app directory where I can store the files:
Which is cool but as I mentioned, this directory will be destroyed every time I queue a new build. How I fixed this was to modify where I stored the images:
// -- Create a new file name that is unique
string fileExtension = Path.GetExtension(upload.FileName);
Guid fileGuid = Guid.NewGuid();
string fileName = fileGuid + fileExtension;
// -- Create the directory and upload the image to that directory
// The Media directory will be created on the C drive root
string mediaDirectory = #"c:\Media";
Directory.CreateDirectory(mediaDirectory);
string filePath = Path.Combine(mediaDirectory, fileName);
upload.SaveAs(filePath);
Now my Media folder is created on the server's C drive and won't be destroyed whenever I queue a new build. Since the app can't access files outside the app directory, I needed a way to access those files in the Media directory. What I did was create a new virtual folder in IIS that points to the Media folder and gave it the alias Media:
This will now let me have access to all those files I put in the Media directory and will properly display the images when needed. I really hope this helps someone because I spent way too long looking at this.
According to your description, there is a concept of working directory in the build agent. If you set clean=true in the build definition, this will delete the previous build output when you query a new build. Not sure where you Media folder located, avoid to create/put it in some directory on the build agent such as Build.ArtifactStagingDirectory
The local path on the agent where any artifacts are copied to before
being pushed to their destination. For example: c:\agent_work\1\a.
A typical way to use this folder is to publish your build artifacts
with the Copy files and Publish build artifacts steps.
Note: This directory is purged before each new build, so you don't have to clean it up yourself.
More details about the folder path in build/release, you could refer this tutorial-- Predefined variables

read file from res folder blackberry

I want to read file from "res" folder on blackberry. The file that i used is a file javascript.
I used this code InputStream in = classs.getResourceAsStream("file.js");. But i get "could not find this path" and I use also
String srcFile = "/res/ressourcesWeb/file.js";
FileConnection srcConn = (FileConnection) Connector.open(srcFile, Connector.READ);
InputStream in = srcConn.openInputStream();
but i got an exception.
Can any one help me to read the file and give me the right path that should I use?
Your res folder has to be inside src folder to be accessed from your code.
src folder is the root folder of your project package. And all folders outside of src folder are invisible for the code at runtime.
Check this post for more details: Blackberry runtime error: FRIDG: could not find img/logo.png
There's file location principle described.
You actually do not need to put your resources under the src folder for them to be accessible from your code.
That is one way to do it, but I don't think it's the best way. Files under the src folder should really be source code, not images, or other resources. For JavaScript resources, it's debatable whether those should be under src or not. Most projects I've seen have used the src folder for only Java source code.
In any case, if you would like to keep your file (or other resources, like images) outside the src folder, you can do so. The BlackBerry plugin for Eclipse actually sets it up like this by default, when you create a new project. There is a res folder at the top level, next to (not under) src.
If you have
src\
src\com\mycompany\myapp\
res\
res\resourcesWeb\
res\resourcesWeb\file.js
Then, you can open the file like this:
String jsPath = "/resourcesWeb/file.js";
InputStream input = getClass().getResourceAsStream(jsPath);
byte [] content = IOUtilities.streamToBytes(input);
String contentAsString = new String(content);
P.S. You also can probably do this:
String jsPath = "/file.js";
InputStream input = getClass().getResourceAsStream(jsPath);
and not specify the path to the resource. Obviously, this will only work if there are no naming conflicts in your resource folders (e.g. you don't have /res/resourcesWeb/file.js and also /res/otherPath/file.js)

How to call input file which is qlready in the package

In my Hadoop Map Reduce application I have one input file.I want that when I execute the jar of my application, then the input file will automatically be called.To do this I code one class to specify the input,output and file itself but from where I am calling the file, there I want to specify the file path. To do that I have used this code:
QueriesTest.class.getResourceAsStream("/src/main/resources/test")
but it is not working (cannot read the input file from the generated jar)
so I have used this one
URL url = this.getClass().getResource("/src/main/resources/test") here I am getting the problem of URL. So please help me out. I am using Hadoop 0.21.
I'm not sure what you want to tell us with your resource loading, but the usual way to add an input file is this:
Configuration conf = new Configuration();
Job job = new Job(conf);
Path in = new Path("YOUR_PATH_IN_HDFS");
FileInputFormat.addInputPath(job, in);
job.setInputFormatClass(TextInputFormat.class); // could be a sequencefile also
// set the other stuff
job.waitForCompletion(true);
Make sure your file resides in HDFS then.

Resources