MVC5 and IIS 7.5 Configuration - asp.net-mvc-5

I have virtual server where is configured IIS 7.5 to works with ASP.NET MVC.
When I deploy application everything works fine. Only one thing is not working when I run application, maybe I'm wrong but I thought that code is correct.
<script>
$(document).ready(function () {
$("#Subcode").prop("disabled", true);
$("#MasterId").change(function () {
if ($("#MasterId").val() != "Select Master Code") {
var CountryOptions = {};
CountryOptions.url = "/Audit/FindSubCode";
CountryOptions.type = "POST";
CountryOptions.data = JSON.stringify({ master_id: $("#MasterId").val() });
CountryOptions.datatype = "json";
CountryOptions.contentType = "application/json";
CountryOptions.success = function (SubCodeList) {
$("#Subcode").empty();
for (var i = 0; i < SubCodeList.length; i++) {
$("#Subcode").append("<option>" + SubCodeList[i] + "</option>");
}
$("#Subcode").prop("disabled", false);
};
CountryOptions.error = function () { alert("Error in Getting SubCodes!!"); };
$.ajax(CountryOptions);
}
else {
$("#Subcode").empty();
$("#Subcode").prop("disabled", true);
}
});
});
</script>
#Html.DropDownList("MasterId",ViewBag.MasterId as SelectList,"Select Master Code",new { #class = "form-control"})
<select id="Subcode"></select>
And code from controller
public JsonResult FindSubCode(int master_id)
{
List<string> SubCodeList = new List<string>();
switch(master_id)
{
case 1:
SubCodeList.Add("Test");
break;
case 2:
SubCodeList.Add("Test2");
break;
}
return Json(SubCodeList);
}
Why I'm writing this problem as IIS Configuration, because if I run locally this application, everything works fine. But when I run on server I got error from code "Error in Getting SubCodes!!".
I tried to debug and get next error: Error when devug
Any suggestion how I can fix this ?

I don't think it has to do with configuration. Verify your URL.
/Audit/FindSubCode would be pointing to the root of the server which may be a different path to where the application is being served from.
Try not to hard code the path but rather use razor engin UrlHelper to generate the path.
CountryOptions.url = "#(Url.Action("FindSubCode","Audit")";

Related

how to upload a file in vibe.d using the web framework

I am still new to Vibe.d so forgive me if I am missing something obvious.
I want to upload a file in Vibe.d using the web framework. However, all the examples I find, including the one in the book 'D Web Development', are not using the web framework. If I insert the non-web-framework example to my app, it crashes. It would suck if I have to abandon the web framework just for the sake of one feature, which is file upload.
The Vibe.d documentation is a good effort and I appreciate it but until now it is rather sparse and the examples are few and far between.
Here are some snippets of my code:
shared static this()
{
auto router = new URLRouter;
router.post("/upload", &upload);
router.registerWebInterface(new WebApp);
//router.get("/", staticRedirect("/index.html"));
//router.get("/ws", handleWebSockets(&handleWebSocketConnection));
router.get("*", serveStaticFiles("public/"));
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, router);
conn = connectMongoDB("127.0.0.1");
appStore = new WebAppStore;
}
void upload(HTTPServerRequest req, HTTPServerResponse res)
{
auto f = "filename" in req.files;
try
{
moveFile(f.tempPath, Path("./public/uploaded/images") ~ f.filename);
}
catch(Exception e)
{
copyFile(f.tempPath, Path("./public/uploaded/images") ~ f.filename);
}
res.redirect("/uploaded");
}
Can I still access the HTTPServerRequest.files using the web framework? How? Or do I still need it? Meaning, is there another way without using HTTPServerRequest.files?
Thanks a lot!
I have totally forgotten about this question. I remember how frustrating it was when you cannot readily find an answer to a question that seems to be elementary to those who already know.
Make sure you state 'multipart/form-data' in the enctype of your form:
form(method="post", action="new_employee", enctype="multipart/form-data")
Then a field in that form should include an input field of type 'file', something like this:
input(type="file", name="picture")
In the postNewEmployee() method of your web framework class, get the file through request.files:
auto pic = "picture" in request.files;
Here is a sample postNewEmployee() method being passed an Employee struct:
void postNewEmployee(Employee emp)
{
Employee e = emp;
string photopath = "No photo submitted";
auto pic = "picture" in request.files;
if(pic !is null)
{
string ext = extension(pic.filename.name);
string[] exts = [".jpg", ".jpeg", ".png", ".gif"];
if(canFind(exts, ext))
{
photopath = "uploads/photos/" ~ e.fname ~ "_" ~ e.lname ~ ext;
string dir = "./public/uploads/photos/";
mkdirRecurse(dir);
string fullpath = dir ~ e.fname ~ "_" ~ e.lname ~ ext;
try moveFile(pic.tempPath, NativePath(fullpath));
catch (Exception ex) copyFile(pic.tempPath, NativePath(fullpath));
}
}
e.photo = photopath;
empModel.addEmployee(e);
redirect("list_employees");
}
When I tried to learn Vibe.d again, I again became aware of the dearth of tutorials, so I wrote a tutorial myself while everything is fresh as a learner:
https://github.com/reyvaleza/vibed
Hope you find this useful.
Put the upload function inside the WebApp class and use it to handle the form post form(action="/upload", method ="post")
class WebApp {
addUpload(HTTPServerRequest req, ...)
{
auto file = file in req.files;
...
}
}
You can try hunt-framework, Hunt Framework is a high-level D Programming Language Web framework that encourages rapid development and clean, pragmatic design. It lets you build high-performance Web applications quickly and easily.
Sample code for action:
#Action
string upload()
{
string message;
if (request.hasFile("file1"))
{
auto file = request.file("file1");
if (file.isValid())
{
// File save path: file.path()
// Origin name: file.originalName()
// File extension: file.extension()
// File mimetype: file.mimeType()
if (file.store("uploads/myfile.zip"))
{
message = "upload is successed";
}
else
{
message = "save as error";
}
}
else
{
message = "file is not valid";
}
}
else
{
message = "not get this file";
}
return message;
}

Electron: get full path of uploaded file

I'm buildind now GUI using Electron. (like PhoneGap for desktop apps)
Is there a way to enable full path for file checked in <input type="file">?
Insted of C:\fakepath\dataset.zip now. (the directory name isn't "fakepath", but that is the value of document.getElementById("myFile").value)
Or, is there other way to select a file?
Electron adds a path property to File objects, so you can get the real path from the input element using:
document.getElementById("myFile").files[0].path
<script>
const electron = require('electron');
const { ipcRenderer } = electron;
const ko = require('knockout')
const fs = require('fs');
const request = require('request-promise');
// replace with your own paths
var zipFilePath = 'C:/Users/malco/AppData/Roaming/Wimpsdata/Wimpsdata.zip';
var uploadUri = 'http://localhost:59887/api/Collector/Upload'
var request = require('request');
request.post({
headers: { 'content-type': 'application/zip' },
url: uploadUri,
body: fs.createReadStream(zipFilePath)
}, function (error, response, body) {
console.log(body);
location.href = 'ScanResults.html';
});
</script>
ASP .NET WebAPI Conontroller
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Wimps.Services.Business;
namespace Wimps.Services.Controllers
{
public class CollectorController : ApiController
{
public async Task<bool> Upload()
{
try
{
var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];
var provider = new MultipartFormDataStreamProvider(fileuploadPath);
var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
foreach (var header in Request.Content.Headers)
{
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
Byte[] byteArray = await content.ReadAsByteArrayAsync();
string newFileName = Guid.NewGuid().ToString();
string newFilePath = fileuploadPath + "\\" + newFileName + ".zip";
if (File.Exists(newFilePath))
{
File.Delete(newFilePath);
}
File.WriteAllBytes(newFilePath, byteArray);
string unzipTo = fileuploadPath + "\\" + newFileName;
Directory.CreateDirectory(unzipTo);
DirectoryInfo di = new DirectoryInfo(unzipTo);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
ZipFile.ExtractToDirectory(newFilePath, unzipTo);
return true;
}
catch (Exception e)
{
// handle exception here
return false;
}
}
}
}
Need to add key to web config for file upload
<configuration>
<appSettings>
... other keys here
<add key="FileUploadLocation" value="C:\Temp\Uploads" />
</appSettings>
rest of app config
...
...
It is not possible to do what you are trying for security reasons, according this answer How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?.
However you could do a work around like I did in an electron project I worked on.
Create a HTML button
Then in the renderer process create an event listener to the button you created before.
const ipc = require('electron').ipcRenderer;
const buttonCreated = document.getElementById('button-created-id');
buttonCreated.addEventListener('click', function (event) {
ipc.send('open-file-dialog-for-file')
});
Then in the main process you use the showOpenDialog to choose a file and then send the full path back to the renderer process.
ipc.on('open-file-dialog-for-file', function (event) {
if(os.platform() === 'linux' || os.platform() === 'win32'){
dialog.showOpenDialog({
properties: ['openFile']
}, function (files) {
if (files) event.sender.send('selected-file', files[0]);
});
} else {
dialog.showOpenDialog({
properties: ['openFile', 'openDirectory']
}, function (files) {
if (files) event.sender.send('selected-file', files[0]);
});
}});
Then in the renderer process you get the full path.
ipc.on('selected-file', function (event, path) {
console.log('Full path: ', path);
});
Thus you can have a similar behaviour than the input type file and get the full path.
The accepted answer works great for the original question, but the answer from #Piero-Divasto works a lot better for my purposes.
What I needed was the pathname of a directory which may be rather large. Using the accepted answer, this can block the main process for several seconds while it processes the directory contents. Using dialog.showOpenDialog(...) gets me a near-instant response. The only difference is that dialog.showOpenDialog doesn't take a callback function anymore, and instead returns a promise:
ipcMain.on("open-file-dialog-for-dir", async event => {
const dir = await dialog.showOpenDialog({ properties: ["openDirectory"] });
if (dir) {
event.sender.send("selected-dir", dir.filePaths[0]);
}
});
<script>const electron = require('electron');</script>
<button id="myFile" onclick="this.value=electron.remote.dialog.showOpenDialog()[0]">UpdateFile</button>
Now, the document.getElementById("myFile").value would contain the full path of the chosen file.
As answered by Vadim Macagon:
let { path } = document.getElementById("myFile").files[0]
Since there is no included interface for this for TypeScript as of this answer, to use this you have to cast the File to another type
let { path } = document.getElementById("myFile").files[0] as any
or, if you would rather not use any
interface ElectronFile extends File {
path: string;
}
let { path } = document.getElementById("myFile").files[0] as ElectronFile

VBS to SFTP WinSCP

I am trying to put log files into a SFTP Server. When I try to run I get error Line 1 Char 28 Syntax error. Anyone have any Idea to different code they got working for VBS? Looking for something simple.
cscript Transfer.vbs /type:winscp /SourceFolder:PATH TO LOG DIR /FTPType:sftp /FTPSite: SFTPSITE:PORT /FTPUser:USER /FTPPass:PASS
<job>
<reference object="WinSCP.Session" />
<script language="JScript">
try
{
// Setup session options
var sessionOptions = WScript.CreateObject("WinSCP.SessionOptions");
sessionOptions.Protocol = Protocol_Sftp;
sessionOptions.HostName = "SFTP";
sessionOptions.UserName = "USER";
sessionOptions.Password = "PASS";
var session = WScript.CreateObject("WinSCP.Session");
try
{
// Connect
session.Open(sessionOptions);
// Upload files
var transferOptions = WScript.CreateObject("WinSCP.TransferOptions");
transferOptions.TransferMode = TransferMode_Binary;
var transferResult = session.PutFiles("c:\\Users\PATH TO LOGS\\*", "/", false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
for (var enumerator = new Enumerator(transferResult.Transfers); !enumerator.atEnd(); enumerator.moveNext())
{
WScript.Echo("Upload of " + enumerator.item().FileName + " succeeded");
}
}
finally
{
// Disconnect, clean up
session.Dispose();
}
}
catch (e)
{
WScript.Echo("Error: " + e.message);
WScript.Quit(1);
}
</script>
</job>`
So I just had to install the SDK for Windows machine. Register the .dll file that winscp gives you. Also register via Com as well. Thakn you for looking into it

module is not defined error

I am using nodejs in my meteor app and I added packages using mrt add npm and then in my client directory in packages.json I added skimlinksjs and its version and it is added to my app.
When I tried to using them in my app in server side code like this,
var res;
var skim = Meteor.require('skimlinksjs');
var apili = Meteor.require('/config.js');
skim.setup(apili.key);
skim.query({
searchFor: "title:\"moto g\"",
fq: "country:US"
}, function(err,data) {
res=data.skimlinksProductAPI.numFound;
}
);
return res;
and my config.js file is like this
module.exports = {
key: "xxxxxxx"
}
whenI'm running this application it is showing error like
module not defined
What went wrong with my code or is there any need to install other packages?
I just got the answer
Write this function in server side code
function returnAllResult()
{
var skimlinks = Meteor.require('skimlinksjs');
skimlinks.setup("xxx");
var skimlinks_query = Async.wrap(skimlinks.query);
var result = skimlinks_query({
searchFor: "title:\"moto g\"",
fq: "country:US",
rows:5
});
return result;
}
to know about asynchronous functions watch this
and then in my server side methods call this
apiresult:function()
{
var response = returnAllResult();
return response.skimlinksProductAPI.products[0].merchant;
}
that's it working fine now. Hope this helps someone

Cycling images in a live tile

I have a winJS app that is a working launcher for a steam game. I'd like to get it to cycle through 5 images even while not running.
It uses only the small tile — there are no wide tiles images for this app.
Here's the code:
(function () {
"use strict";
WinJS.Namespace.define("Steam", {
launch: function launch(url) {
var uri = new Windows.Foundation.Uri(url);
Windows.System.Launcher.launchUriAsync(uri).then(
function (success) {
if (success) {
// File launched
window.close();
} else {
// File launch failed
}
}
);
}
});
WinJS.Namespace.define("Tile", {
enqueue: function initialize() {
var updaterHandle = Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication();
updaterHandle.enableNotificationQueue(true);
return updaterHandle;
},
update: function update () {
var template = Windows.UI.Notifications.TileTemplateType.tileSquareImage;
var tileXml = Windows.UI.Notifications.TileUpdateManager.getTemplateContent(template);
var randIndx = Math.floor(Math.random() * 5);
var randUpdatetime = 1000 * 3 * (((randIndx == 0) ? 1 : 0) + 1); // let the base image stay longer
var tileImageAttributes = tileXml.getElementsByTagName("image");
tileImageAttributes[0].setAttribute("src", "ms-appx:///images/Borderlands2/borderlands_2_" + randIndx + "_sidyseven.png");
tileImageAttributes[0].setAttribute("alt", "Borderlands 2");
var tileNotification = new Windows.UI.Notifications.TileNotification(tileXml);
var currentTime = new Date();
tileNotification.expirationTime = new Date(currentTime.getTime() + randUpdatetime);
tileNotification.tag = "newTile";
var updater = Tile.enqueue();
updater.update(tileNotification);
setTimeout('Tile.update();', randUpdatetime);
}
});
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
setTimeout('Steam.launch("steam://rungameid/49520");', 800);
args.setPromise(WinJS.UI.processAll().then(function () {
return WinJS.Navigation.navigate("/default.html", args).then(function () {
Tile.update();
});
}));
}
};
app.start();
})();
Notes:
The code currently does not cycle the image, instead either
apparently never changing, or after launch replacing the application
name text with a tiny view of the default image. This reverts to the
text after a short time, and the cycle may repeat. It never shows a
different image (neither in the small image it erroneously shows, nor
in the main tile).
When I run in debug and set a breakpoint at the
TileUpdater.update(TileNotification) stage, I can verify in the
console that the image src attribute is set to a random image
just as I wanted:
>>>>tileNotification.content.getElementsByTagName("image")[0].getAttribute("src")
"ms-appx:///images/Borderlands2/borderlands_2_4_sidyseven.png"
But this never actually displays on the tile.
These image files are included in the solution, and they appear in the proper directory in the Solution Explorer.
If the image src attribute is set properly in debug then the image may not have the proper "Build Action".
In the 'Properties' of each image, set "Build Action" to "Resource".

Resources