asp.net MVC saving relative path in database as not the full path - sql-server-2008

asp.net MVC saving relative path in database as
~/Content/Uploads/11thMay.jpg
not the full path as
D:/Projects/HRMV2/CubicHRMWeb/Content/Uploads/11thMay.jpg
I wanted to save relative path but in DB full path was being saved.
How can I do it?
thanks.

If your question is "How to save as full path", please try this
string path = Path.Combine(Server.MapPath("~/Content/img/Company/LogoFiles"), filename);
If your question is "How to save as relative path", please try this
[HttpPost]
public ActionResult Save(HttpPostedFileBase myFile)
{
string filename = myFile.FileName;
string relativeFileName = "~/Content/Uploads/" + filename;// relative path
return View();
}

this code doesn't allow to save the relative path, when you try it, the totality of filename is setted and not just the filename.if you insert a breakpoint at this point, you must obtain a thing like
"/content/Uploads/C:Document/Picture/father.jpeg"
and not the relative path which you will want it like
"/content/Uploads/father.jpeg"

in order to save the relative path of a document , you ought to use the getfilename property of system.io as show in the below example.
I suppose that you want to do it in the post method of your controller which contains a model or httppostedfilebase
in my example, i have a model with httppostedfilebase property named imagefichier, so you can get the document name by doing this
var lefilename = System.IO.Path.GetFileName(model.imagefichier.FileName);
//Suppose that you want to save it in your root web file
//like ~/Images/Administrateur/leilename,you can do it like this
string cheminbdd = "~/Images/Administrateur/" + lefilename;
//it is cheminbdd that you can save in your database as your relative path

Related

How can I use an Excel file as test data correctly?

How can I best use an Excel file as input for an xUnit test? Note that I do not want to use the data inside the Excel, but the Excel itself.
Let's say I have a UnitTests project, where I want to place some Excel files, that I need to put in my tests:
[Fact]
public void Constructor_ShouldReadExcelFile()
{
var mapping = new ExcelMapping("excelfiles/test1.xlsx");
Assert.True(mapping.Valid);
}
but, when running that, the CurrentWorkingDirectory is set to the bin\Debug\net7.0 dir, and I need to make a relative path:
[Fact]
public void Constructor_ShouldReadExcelFile()
{
var mapping = new ExcelMapping("../../../excelfiles/test1.xlsx");
Assert.True(mapping.Valid);
}
This will work, but is this the "right" way?
Your solution looks fine to me.
I often need to retrieve test data files for unit tests and generally proceed as follows. The test data are also under version control but in a different folder than the unit tests. In my unit test class, I define a relative path for the test data and make a member for the absolute path:
const string testDataRelativePath = #"..\..\..\..\excelfiles\";
string testDataFolderAbsolutePath;
The relative path is relative to the project folder where the unit test dll is output.
In the constructor of the test class I define a value for the absolute path.
using System.IO;
using System.Reflection;
public class MyTestClass
{
public MyTestClass()
{
string projectDir = getProjectDir();
testDataFolderAbsolutePath = Path.GetFullPath(Path.Combine(projectDir, testDataRelativePath));
}
internal static string getProjectDir()
{
Assembly assembly = Assembly.GetExecutingAssembly();
return directoryPathNameFromAssemblyCodeBase(assembly);
}
internal static string directoryPathNameFromAssemblyCodeBase(Assembly assembly)
{
Uri codeBaseUrl = new Uri(assembly.CodeBase);
string codeBasePath = Uri.UnescapeDataString(codeBaseUrl.AbsolutePath);
return Path.GetDirectoryName(codeBasePath);
}
// ... Tests ...
}
In the test itself, I then do something like this:
string excelFilePath = Path.Combine(testDataFolderAbsolutePath, "test1.xlsx");
I find that this gives better results on the plurality of systems on which the tests are running.

ASP.NET Core Read in html file from www root and replace parameters

I am trying to create a printable page that says
Hi, [Member]
We have blah blah....[MemberLocation]
Thanks. Please contact [MemberPhone]
Replacing the [Member] tags with data from the model.
I figured the best way is to save an html on wwwroot.
So I saved the above in member.html on wwwroot/staticfiles/member.html
I am having a hard time reading this file into my code.
I was hoping to do something like
memberString = System.IO.File.ReadAllText("staticfiles/member.html").ToString();
Then do something like
var memberName = model.Name;
memberString = memberString.replace([Member], memberName)
Obviously this isn't working. I can't read the file that way.
I have tried creating a service that reads the file
public class ReturnHTML
{
private readonly IHostEnvironment _env;
public ReturnHTML(IHostEnvironment env)
{
_env = env;
}
public string ReturnHTMLPage()
{
var path = Path.Combine(_env.ContentRootPath, "StaticFiles/member.html");
var htmlString = System.IO.File.ReadAllText(path);
return htmlString.ToString();
}
}
Add this a singleton in my startup.cs
But I can't figure out how to inject this and get this string.
So my question is, what is the best way to create a printable page that I can supply values to?
There are third party stuff out there that create pdf and docs that you can template. But I am not interested in third party tools. Is there any native way of doing this?

How can I saved my outputs in specific folder in cplex?

I have an OPL project in Cplex, and I get all my outputs as csv files. All of them are saved in a folder of my project; however, I want to know how can I give it a specific path? I want to save them where I get all my inputs. Is there any way that I do it?
tuple t
{
string firstname;
int number;
}
{t} s={<"Nicolas",2>,<"Alexander",3>};
execute
{
var f=new IloOplOutputFile("c:\\temp\\export.csv");
for(var i in s)
{
f.writeln(i.firstname,";",i.number,";");
}
f.close();
}
writes the result in the folder "c:/temp".
I changed a bit https://www.ibm.com/developerworks/community/forums/html/topic?id=3fd44d41-210b-4b81-a005-819530d6377b&ps=25
I supposed you use an IloOplOutputFile to create the output? In that case note that you can specify an arbitrary path as a constructor argument (see for example Alex's answer). Moreover, notice that the IloOplModel class has a function resolvePath that resolves the path of a resource. So you can do something like
var path = thisOplModel.resolvePath("inputfile");
to get the path to one of your input files. From that you can construct a path for your output files.

Cakephp 3.0 ROOT variable gets set wrong

After a stock install and creation of a basic controller, the environment variables are being set wrong.
For example, ROOT gets set as follows:
/var/www/html/appname/src//var/www/html/appname
In other words, the Apache webserver DocumentRoot is being appended to it.
Why?
What I learned is that if I specify the absolute path to the file in a controller, the Apache DocumentRoot gets appended to the ROOT variable. For example:
public function getFile() {
// disable the default layout for the view
$this->viewBuilder()->layout(false);
$path = ROOT . '/file/file.txt';
$this->response->file($path, array('download' => true));
return $this->response;
}
The browser cannot find the file at location /var/www/html/app/src//var/www/html/app/src/file/file.txt
However the following works as expected:
public function getFile() {
// disable the default layout for the view
$this->viewBuilder()->layout(false);
$path = '/file/file.txt';
$this->response->file($path, array('download' => true));
return $this->response;
}
The ROOT location seems to get automatically pre-prended to the path I have set above. I was not aware of this and haven't read anything about it in the documentation, so I am still not sure why it works this way.

How would I go about loading a JSON file using Laravel?

I have a JSON file that I'd like to load using Laravel. I'm learning Laravel and would like to know the right way to do this. I have the JSON files in a folder called json in the public folder.
In my routes.php I have the following:
Route::get('/json/{jsonfile}', array(
'as' => 'load-json',
'uses' => 'JSONController#loadJSON'
));
In JSONController I have:
public function loadJSON($jsonfile) {
// not sure what to do here
return View::make('json.display')
->with('jsonfile', $jsonfile);
}
Also is my naming convention ok or do you have better suggestions?
Always be careful when allowing a user inputed data to decide what files to read and write. Here is simple code that will take in the filename and look in the apps/storage/json folder. I'm less familiar with what Illuminate does to protect against system injections but you might want at the very least to make sure that 'filename' doesn't contain anything but alphanumeric characters with a validator.
Unless the JSON (or any file) needs to be public you shouldn't keep it in the public folder. This way they must go through your app (and permissions) to view it. Also you can have more restrictive permissions outside the public folder.
public function loadJSON($filename) {
$path = storage_path() . "/json/${filename}.json"; // ie: /var/www/laravel/app/storage/json/filename.json
if (!File::exists($path)) {
throw new Exception("Invalid File");
}
$file = File::get($path); // string
// Verify Validate JSON?
// Your other Stuff
}