Trusted Scripts Setting in Windows Registry or IE - c#

I am creating a directory of files for an internal website. The user will access the page and insert the location and filename and submit the information to a database. I tried using file upload to open Windows Explorer so the user can locate the file and path. However, asp file upload will not allow me to capture the path on the client side. Since this is an internal website, does Internet Explorer or Windows Registry have a permissions setting for trusted scripts similar to trusted sites?
I created a JQuery Script to copy the the path to a textbox but I get a error message saying "C:\fakepath\test.pdf". test.pdf is the filename but c:\fakepath is not the path. I have tried multiple server variables but those just tell the paths on the server end.
<script>
$(document).ready(function(){
$("#button").click(function(){
$("#text1").val($("#text").val());
});
});
</script>
<input type="file" id="text" />
<input type="text" id="text1" />
<input type="button" value="Click Me!" id="button" />

To access the local path you need to use ActiveX object in your web page. It can help you to get the path in IE.
For working with Files and directory you should make a server object as Scripting.FileSystemObject then with GetDirectory() method can get a directory object.
Sample code:
var Fo =new ActiveXObject("Scripting.FileSystemObject");
var StrOut = new String();
var FileName = new String();
var Extention = new String();
function FindFile(FOo)
{
var FSo = new Enumerator(FOo.Files);
for(i=0;!FSo.atEnd();FSo.moveNext())
{
if(FileName == "*" || FSo.item().name.slice(0,FSo.item().name.lastIndexOf(".")).toLowerCase().indexOf(FileName)>-1)
if(Extention == "*" || FSo.item().name.slice(FSo.item().name.lastIndexOf(".")+1).toLowerCase().indexOf(Extention)>-1){
StrOut += "<tr "+ ((i%2)? "":"bgcolor=#DDAA55") +"><td width=50%><font class=find>" + FSo.item().path + "</font></td><td width=25%><font class=find>" + FSo.item().type + "</font></td><td width=50%><font class=find>"+ String(FSo.item().size/(1024*1024)).slice(0,3) +" MB</font></td></tr>";
i++
}
}
}
function Scan()
{
FileName = (search.value.lastIndexOf(".")>-1)? search.value.slice(0,search.value.lastIndexOf(".")):(search.value.length>0)? search.value.toLowerCase():"*"; //Get Searched File Name
Extention = (search.value.lastIndexOf(".")>-1)? search.value.slice(search.value.lastIndexOf(".")+1).toLowerCase():"*"; // Get Searched File Extention Name
if(path.value.length>0 && Fo.FolderExists(path.value)){
StrOut = "<table border=0 width=100% cellspacing=0>"
FindFile(Fo.GetFolder(path.value));
outPut.innerHTML = StrOut+"</table>";
}
else alert("Insert Correct Path Address");
}
For detailed information and example code, You can refer link below and download the sample file.
Find files with JavaScript

Related

Create folders and upload text files to server (php) in Unity3D (C#)

What I have :
I have a simple module that would convert a string to a text file & store it in my server
C#/Unity Code
private IEnumerator UploadUserData(string _fileName)
{
string _data = ("With text name " + System.DateTime.Now.ToString ());
string _postDataURL = "https://nameofserver.com/upload.php"
WWWForm _form = new WWWForm ();
_form.AddField ("name", _fileName);
_form.AddField ("data", _data);
UnityWebRequest _wwwRequest = UnityWebRequest.Post (_postDataURL, _form);
yield return _wwwRequest.Send ();
while (!_wwwRequest.isDone)
{ yield return null;}
if (_wwwRequest.error != null)
{
Debug.Log (_wwwRequest.error);
}
else
{
Debug.Log ("Uploaded");
}
Debug.Log (_wwwRequest.downloadHandler.text);
}
Server Side PHP
<?php
if(isset($_POST['name']) && isset($_POST['data'])){
file_put_contents($_POST['name'].".txt", $_POST['data']);
echo "uploaded.";
}else{
echo "invalid file uploaded.";
}
?>
Request
I want to build a system where I could upload files to specific folders. Let's say I to upload a text file (filename.txt) to a folder name "Folder1".
From php side
The php side should create a folder "Folder1" if it is not present
then upload the text file "filename.txt" to that folder
if "Folder1" exist in that directory, then I would like the php
script to upload that text file "filename.txt" to the existing folder
"Folder1"
From Unity Side
How should I mention the folder name from Unity webrequest?
Thank you very much for your time. Much appreciate it.
Like I was ranting at you on IRC, you should avoid allowing your file paths to be dictated by, or even include, data supplied by a user or even a user-accessible API.
I would suggest something along the lines of:
// always have something define the absolute path to your application root,
// then build your paths/filenames relative to that.
// let's say this is /usr/local/myapp/config/config.php
define('APPROOT', realpath(__DIR__ . '/..')); // APPROOT == '/usr/local/myapp'
define('USERUPLOADS', APPROOT . '/user_uploads');
// userid SHOULD be something you control, not a username or anything specified
// by the user. the focus is to prevent malformed and/or malevolent user data
// from breaking out of the upload directory sandbox.
function acceptUploadedUserData($userid, $name, $data) {
$userdir = USERUPLOADS . '/' . $userid;
if( ! is_dir($userdir) ) {
mkdir($userdir);
}
// just kinda baseline "OK"
if( strpos('..', $name) !== false || strpos('/', $name) !== false ) {
throw new Exception('Specified name cannot contain .. or /');
}
file_put_contents($userdir . '/' . $name, $data);
// better yet don't let the user have *any* control over any part of the path
// but also allows you to specify *any* string as the filename.
file_put_contents($userdir . '/' . md5($name), $data);
}
acceptUploadedUserData($_SESSION['user_id'], $_POST['name'], $_POST['data']);

How do I get the folder for the currently open file in c#

I am writing a wizard that pulls information from a database like file. This wizard doesn't get compiled, it just runs on command. I am not sure the correct term for that.
The issue is, I need to enter more information which will manipulate the database, and I want to store the values into a csv file that I use to manipulate the database.
So the question is: How do I get the folder for the currently open file in a c# application so that I can save a csv file to that folder?
edit: The path needs to be dynamic. Each database file is stored in a separate folder. I need the wizard to save to which ever folder I just opened the file from.
edit2 :
I am not opening the file programmatically. The file is being open by the user in the application. So, the user opens a file, and a bunch of database information is displayed. He then runs a wizard on that data where he can enter some coefficients, etc .. and that will change the information in the database file. I need to be able to store the coefficients he enters into the folder that contains the database file that he opened. I cannot access / change the application code, only the wizard code.
Thanks
Something like this?
var file = "C:\\Users\\Me\\Desktop\\Test.txt";
var fileLocation = file.Substring(0, file.LastIndexOf("\\"));
You can use this:
string path = Path.GetFullPath(Directory.GetCurrentDirectory()).TrimEnd(Path.DirectorySeparatorChar);
string directoryName = Path.GetFileName(path);
I found this solution in this thread
Get the (last part of) current directory name in C#
Try
//Or where ever the database returns the file is stored
var filename = "C:\\Temp\\File\\Test.txt";
var path = System.IO.Path.GetDirectoryName(filename);
Should return C:\Temp\File
Source : https://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
Try using DirectoryInfo to get information about any directory:
using System;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
if (di != null)
{
FileInfo[] subFiles = di.GetFiles();
if (subFiles.Length > 0)
{
Console.WriteLine("Files:");
foreach (FileInfo subFile in subFiles)
{
Console.WriteLine(" " + subFile.Name + " (" + subFile.Length + " bytes) " + "Directory name: "
+ di.Name + " Directory full name: " + di.FullName);
}
}
Console.ReadKey();
}
}
}
}

Issue while changing the profile picture after deploying the code in server

I'm using twitter bootstrap. I'm changing the profile picture. I'm just saving the picture in a folder and retrieving it again. It works fine in local system but it is not working after deploying the code in the server. But picture is getting saved in the folder and not getting Changed in .aspx page. When i log out and log in again,its getting refreshed.
Here is my code :
<img runat="server" id="ImgPic" />
<input type="file" id="fileUpload" runat="server"/>
Change
<asp:Button ID="btnChangeUserPic" runat="server" OnClick="btnChangeUserPic_Click"
class="hidden" />
function ChangePicture(){
$('#btnChangeUserPic').click();
}
protected void btnChangeUserPic_Click(object sender, EventArgs e)
{
try
{
string filePath = Server.MapPath("~/Upload/Images/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string file = fileUpload.PostedFile.FileName.ToLower();
HttpPostedFile hpfFile = fileUpload.PostedFile;
if (file != "")
{
string fileExtn = Path.GetExtension(hpfFile.FileName).ToLower();
if (fileExtn == ".jpg")
{
string filename = filePath +System.IO.Path.GetFileName(hpfFile.FileName);
if (File.Exists(filename))
{
File.Delete(filename);
}
hpfFile.SaveAs(filename);
ImgPic.src= filename;
}
}
}
catch (Exception ex)
{
}
}
The Picture should get updated in master page also.
Thank you all in advance for your response.
I'm not 100% sure what you mean by 'getting refreshed' but.. the filepath on your server is not going to be the same as on you local machine. Use Server.MapPath instead of a simple string;
http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
Also check you permissions to the folder and show us the code in whatever UI page that actually displays the picture, how is that getting set?
My guess (there's not enough info) is that ImgPic.src is holding the URL for the img tag. This would explain why it works locally but not on the server, because you've set
ImgPic.src= filename;
it should be set to the URL, not the mapped path.
If it's not that please post info on where the img is getting it's src set.

How to write a kml file to publicly accessible server?

I want to render a KML file in google maps from my asp.net MVC 3 app.
From Google Maps JavaScript API V3, I'm using KmlLayer('url') to render the kml in google maps.
I have read that kml file needs to be in a publicly accessible server. I could render the kml file locally with third party javascripts but they can be prone to errors.
(Loading a local .kml file using google maps?)
The kml files I want to render are stored in a SQL server database as byte arrays. So for one Kml file I have to write the byte array into a path with kml extension. I have done this with File.WriteAllBytes(path, byte), where path = local path and byte = byte array from Database. THis is done in the Controller of MVC app.
This is the code:
public ActionResult MapView(int id)
{
Incident inc = db.Incidents.Find(id);
if (inc.IncidentDatas.Count != 0)
{
ViewBag.ListKmlUrls = kmlFileStore(inc);
}
return View(inc);
}
public List<string> kmlFileStore(Incident inc)
{
List<string> listKmlUrls = new List<string>();
// Specify a "currently active folder"
string activeDir = #"c:\incident" + inc.incId + #"\incidentData";
//Create a new subfolder under the current active folder
string newPath = System.IO.Path.Combine(activeDir, "kmlFiles");
// Create the subfolder
System.IO.Directory.CreateDirectory(newPath);
String url;
foreach(var d in inc.IncidentDatas) {
url = #"c:\incident" + inc.incId + #"\incidentData\kmlFiles\" + d.id + ".kml";
//dataContent is byte[]
System.IO.File.WriteAllBytes(url, d.dataContent);
listKmlUrls.Add(url);
}
return listKmlUrls;
}
The idea is the view will access the list of urls through viewbag to pass urls to javascript method KmlLayer(...). But the urls here are only local paths.
So how can the MVC app store the kml file to a publicly accessible server so that it can pass a url to KmlLayer(...)? This would have to be done programmatically.
I'm currently accessing my MVC app and database from localhost. I have a static Ip and name. I would also like to publish the app and database for online access. Not sure how to proceed, please give me some advice/guidance. Thanks.
There are some problem to make kml file publicly accessible. Say the file location must be accessible by google.
If you want to embed Google Earth in website then there are three methods of importing KML into the plugin.
1. KmlNetworkLink
2. fetchKml
3. ParseKml
Both 1 & 2 need kml file stored in server that must publicly accessible but 3. ParseKml works better way.
<head>
<title>parsekml_example.html</title>
<script src="//www.google.com/jsapi?key=ABQIAAAA5El50zA4PeDTEMlv-sXFfRSsTL4WIgxhMZ0ZK_kHjwHeQuOD4xTdBhxbkZWuzyYTVeclkwYHpb17ZQ"></script>
<script type="text/javascript">
var ge;
var placemark;
var object;
google.load("earth", "1");
function init() {
google.earth.createInstance('map3d', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
var kmlString = ''
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<kml xmlns="http://www.opengis.net/kml/2.2">'
+ '<Document>'
+ ' <Camera>'
+ ' <longitude>-122.444633</longitude>'
+ ' <latitude>37.801899</latitude>'
+ ' <altitude>139.629438</altitude>'
+ ' <heading>-70.0</heading>'
+ ' <tilt>75</tilt>'
+ ' </Camera>'
+ ' <Placemark>'
+ ' <name>Placemark from KML string</name>'
+ ' <Point>'
+ ' <coordinates>-122.448425,37.802907,0</coordinates>'
+ ' </Point>'
+ ' </Placemark>'
+ '</Document>'
+ '</kml>';
var kmlObject = ge.parseKml(kmlString);
ge.getFeatures().appendChild(kmlObject);
ge.getView().setAbstractView(kmlObject.getAbstractView());
}
function failureCB(errorCode) {
}
google.setOnLoadCallback(init);
</script>
</head>
<body>
<div id="map3d" style="height: 400px; width: 600px;">
</div>
</body>
For more detail see http://code.google.com/apis/earth/documentation/kml.html

Getting the new filename of a file saved with ajax AsyncFileUpload?

I'm saving a file with the asyncfileupload ajax plugin from the ajax toolkit and when I save it I'm changing the filename (to avoid multiple files with the same name).
After the file is uploaded, the user needs to know what the file has been named so I'm using this javascript code on the onclientuploadcomplete event.
function UploadComplete(sender, args) {
alert(args.get_fileName());
}
This works except it gets the old name, not the new name (which is determined server-side). Is there any way to get it to return the new name rather than the old name? Or any work around to achieve this?
This is my code in the code behind the get the new filename:
string filename = DateTime.Now.ToString("dMyHmsf") + e.filename;
string strPath = MapPath("~/SavedImages/") + filename;
AsyncFileUpload1.SaveAs(strPath);
I got the answer from http://forums.asp.net/post/4139037.aspx It works for me...
copied code from there:
<asp:ToolkitScriptManager runat="server">
</asp:ToolkitScriptManager>
<!--This script snippet must be located below the ScriptManager-->
<script type="text/javascript">
Sys.Extended.UI.AsyncFileUpload.prototype.newFileName = null; //I did not use this line
function uploadcomplete(sender, e) {
alert(sender.newFileName);
}
</script>
<asp:AsyncFileUpload ID="AsyncFileUpload1" OnClientUploadComplete="uploadcomplete"
runat="server" OnUploadedComplete="AsyncFileUpload1_UploadedComplete1" />
the code behind:
protected void AsyncFileUpload1_UploadedComplete1(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this,
this.GetType(), "newfile",
"window.parent.$find('" + AsyncFileUpload1.ClientID + "').newFileName='newfile.jpg';", true);
}
How about writing the filename to a hiddenfield in the codebehind and the reading that value in your clientside code?

Categories

Resources