Trying to Create a Folder, but it creates in different location - asp.net

In my ASP.NET WEbForms app, I want to create a folder and save files in it. In my project I have a folder named CRMImages/Projects. I want to create a sub folder in Projects folder & save images from their. Currently I retrieve images from CRMImages/ as the parent folder.
This is my code that I have on code-behind :
try
{
string pathToCreate = "~/CRMImages/Projects/" + item.ProjectId;
string myFileName = "";
if (!Directory.Exists(Server.MapPath(pathToCreate)))
{
DirectoryInfo di = Directory.CreateDirectory(pathToCreate);
var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
var userName = user.Translate(typeof(System.Security.Principal.NTAccount));
System.Security.AccessControl.DirectorySecurity sec = di.GetAccessControl();
sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(userName,
System.Security.AccessControl.FileSystemRights.Modify,
System.Security.AccessControl.AccessControlType.Allow));
di.SetAccessControl(sec);
Directory.CreateDirectory(pathToCreate);
System.Diagnostics.Debug.WriteLine("FOLDER CREATED PATH : " + di.FullName);
myFileName = pathToCreate + "/projectLogo.png";
System.Diagnostics.Debug.WriteLine("PATH To Save Logo File & NAME : " + myFileName);
/*
if (File.Exists(item.ProjectLogoUrl) ) {
FileUpload projLogoUpload = new FileUpload();
if (projLogoUpload.HasFile) {
myFileName = pathToCreate + "/projectLogo.png";
projLogoUpload.SaveAs(myFileName);
}
// panFileBtn.SaveAs(filePath);
} */
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("EXCEPTION While SAving File : " + ex.Message + "\n *** STACK" + ex.StackTrace);
}
The code executes, but I don't see the folder created in my project folder. Lets say the value of item.ProjectId is "EMP3", the logs that I see on the above code execution is :
FOLDER CREATED PATH : C:\Program Files (x86)\IIS Express\~\CRMImages\Projects\EMP3
PATH To Save Logo File & NAME : ~/CRMImages/Projects/EMP3/projectLogo.png
I checked in IIS Express folder & there this full path is created. Can you say why is it saving in IISExpress & how to create the folder in the /CRMImages/Projects folder that already exists in my project !!
Any help is highly appreciated.
Thanks

You have to replace below line
DirectoryInfo di = Directory.CreateDirectory(pathToCreate);
With
DirectoryInfo di = Directory.CreateDirectory(Server.MapPath(pathToCreate));

Related

FailedToExecuteCommand ghostscript gswin64c.exe on azure

I am trying to convert pdf into images using magickNET and ghostscript. It works well on local and windows VMS servers. But when i push to azure servers it gives me the error saying FailedToExecuteCommand ghostscript gswin64c.exe. Details of error in attachements.
I tried changing the path for ghostscript dll but found no luck. The path is correct and dll file is there. One thing I am sure of. I have put dll inside wwwroot/GhostScriptDll. on error it shows "D:/home/site/wwwroot/wwwroot/GhostScriptDll/gswin64c.exe" which is also correct there are 2's wwwroot.
can someone help me to use ghostscript without webjobs things.
C# code i tried is like this
enter image description here
string rawpath = _hostingEnvironment.WebRootPath + "\\GhostScriptDll"
MagickNET.SetGhostscriptDirectory(rawpath);
MagickReadSettings settings = new MagickReadSettings();
settings.Density = new Density(300, 300);
List<string> intList = new List<string>() { };
using (MagickImageCollection images = new MagickImageCollection())
{
images.Read($"{rawFileLocation}{model.OriginalDocName}", settings);
int page = 1;
string tempName = "";
foreach (MagickImage image in images)
{
tempName = System.IO.Path.GetRandomFileName().Replace(".", string.Empty) + "_processed_" + page + ".png";
image.Write($"{processedFileLocation}{tempName}");
intList.Add(tempName);
page++;
}
}
i doubt in this part of error D:/local/Temp/magick-MB0cs71xMgZUfIHIwbzlzehBIlLL-NED"' (The system cannot find the file specified.
) # error/delegate.c/ExternalDelegateCommand/475 ...i dont find the local/temp/.. folder in server though

Is Extendscript able to duplicate a file using File Object ( File. )?

Want to duplicate a file in a local directory with a new file extension. I don't see any documentation for duplicating a file with the File Object.
I see the ability to File.copy(), etc but nothing having to do with duplicating or saving without a dialog box with a new name and extension.
var targetFile = new File('myFile');
targetFile.saveDlg('newFileName' + 'extension');
To do it by code, you must be more explicit. You can try this:
function duplicateFile(path) {
var content, extension, file, fileOk, name, newFile, newPath;
file = new File(path);
if(!file) {
return
}
fileOk = file.open('r');
if(fileOk){
//Get file extension
name = file.name.split('.');
extension = name.pop();
name.join('.');
//Creating new file
//Becareful with the name, you must to check that a file with the same name doesn't exists
//if you don't want to overwrite it.
name = name + '_copy.' + extension
newPath = file.parent.fsName + '/' + name
newFile = new File(newPath);
fileOk = newFile.open('w');
//Writing content to new file
if (fileOk) {
newFile.write(content);
newFile.close(); //Remember to close the files
}
file.close()
}
}

create zip file and downloading it using asp.net

in a project asp.net, I generate invoices with active reports and I save them in pdf format. there I want to create a zip file dynamically and add the pdf invoices then downloading this file zip in client side. help me please.
string zipFileName = "a.zip";
using (var zip = new ZipFile())
{
System.IO.File.Delete(fileDir + "/" + zipFileName);
zip.AddDirectory(fileDir + "/");
zip.CompressionLevel = CompressionLevel.Level5;
zip.CompressionMethod = CompressionMethod.BZip2;
zip.Save(fileDir + "/" + zipFileName);
}

Displaying image using Image control in button click event

I am creating image comparison (images exists in directory) web based application. It compares images exists in particular directory with provided image. It compares each image with matching percentage but not displaying images from related directory even i have given the image url to that images also. When i write response.write then it shows matching percentage with that matching image, but not displaying images.
I have written code for that as follows :
protected void btnnew_Click(object sender, EventArgs e)
{
Bitmap searchImage;
try
{
//Image for comparing other images that are exists in directory
searchImage = new Bitmap(#"D:\kc\ImageCompare\Images\img579.jpg");
}
catch (ArgumentException)
{
return;
}
string dir = "D:\\kc\\ImageCompare\\Images";
DirectoryInfo dir1 = new DirectoryInfo(dir);
FileInfo[] files = null;
try
{
files = dir1.GetFiles("*.jpg");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Bad directory specified");
return;
}
double sim;
foreach (FileInfo f in files)
{
sim = Math.Round(GetDifferentPercentageSneller(searchImage, new Bitmap(f.FullName)), 3);
if (sim >= 0.95)
{
Image1.ImageUrl = dir + files[0];
Image2.ImageUrl = dir + files[1];
Response.Write("Perfect match with Percentage" + " " + sim + " " + f);
Response.Write("</br>");
}
else
{
Response.Write("Not matched" + sim);
}
}
}
ASP.NET pages follows control based development - so generally, you don't directly write to a response but rather update text for control such as label or literal.
As far as image goes, for image to visible in the browse, you need to set the url that is accessible from the browser. In above code, you are setting the physical file path and which is not going to be accessible as a URL from same/different machine. You need either to map a virtual directory to your image storage location and then generate a url for the same (by appending virtual directory path & file name) or to write a file serving handler (ashx) that would take the image partial path and serve the image (i.e. send its data to browser).

Convert a single file aspx to code behind

I'm working on a web site (not a web application) in VS 2008 .Net 3.5 and it uses the single file .aspx model where the server code is included in the head portion of the html instead of using a .aspx.cs code behind page.
I'd like to quickly convert the files to use the code-behind model, but so far the only way I can do this is by removing the file, creating a new, code-behind aspx page of the same name, then manually copying in the aspx related code to the .aspx page and the server code to the .aspx.cs page.
Is there a faster way to do this?
I have seen two article that seem to answer this question, but unfortunately don't:
Working with Single-File Web Forms Pages in Visual Studio .NET and
How do you convert an aspx or master page file to page and code behind?
Both offer a simple solution whereby VS does the leg work, you just point it to a file and shoot. For whatever reason, they aren't working. The first article seems to refer to VS 2002 and the second seems to refer to a web application.
Is there any hope for a web site?
Also, maybe I'm seeing this the wrong way, is there an advantage to the single page model? I do plan on converting the whole web site to a web application soon, does the single page model work well in web applications?
If manual conversion is too time-intensive, and the automatic conversion isn't working, I think your only other option would be to build your own converter. You could write a simple console app which takes a directory path on the command line and processes every file in that directory. This isn't too hard - here, I'll get you started:
using System;
using System.IO;
class Program
{
const string ScriptStartTag = "<script language=\"CS\" runat=\"server\">";
const string ScriptEndTag = "</script>";
static void Main(string[] args)
{
DirectoryInfo inPath = new DirectoryInfo(args[0]);
DirectoryInfo outPath = new DirectoryInfo(args[0] + "\\codebehind");
if (!outPath.Exists) inPath.CreateSubdirectory("codebehind");
foreach (FileInfo f in inPath.GetFiles())
{
if (f.FullName.EndsWith(".aspx"))
{
// READ SOURCE FILE
string fileContents;
using (TextReader tr = new StreamReader(f.FullName))
{
fileContents = tr.ReadToEnd();
}
int scriptStart = fileContents.IndexOf(ScriptStartTag);
int scriptEnd = fileContents.IndexOf(ScriptEndTag, scriptStart);
string className = f.FullName.Remove(f.FullName.Length-5).Replace("\\", "_").Replace(":", "_");
// GENERATE NEW SCRIPT FILE
string scriptContents = fileContents.Substring(
scriptStart + ScriptStartTag.Length,
scriptEnd-(scriptStart + ScriptStartTag.Length)-1);
scriptContents =
"using System;\n\n" +
"public partial class " + className + " : System.Web.UI.Page\n" +
"{\n" +
" " + scriptContents.Trim() +
"\n}";
using (TextWriter tw = new StreamWriter(outPath.FullName + "\\" + f.Name + ".cs"))
{
tw.Write(scriptContents);
tw.Flush();
}
// GENERATE NEW MARKUP FILE
fileContents = fileContents.Remove(
scriptStart,
scriptEnd - scriptStart + ScriptEndTag.Length);
int pageTagEnd = fileContents.IndexOf("%>");
fileContents = fileContents.Insert(PageTagEnd,
"AutoEventWireup=\"true\" CodeBehind=\"" + f.Name + ".cs\" Inherits=\"" + className + "\" ");
using (TextWriter tw = new StreamWriter(outPath.FullName + "\\" + f.Name))
{
tw.Write(fileContents);
tw.Flush();
}
}
}
}
}
30 minutes coding, 30 minutes debugging. There are some obvious bugs - like, if your code contains a closing script tag anywhere inside, then it won't get exported correctly. The results won't be pretty, but this should take care of 90% of your code, and you should be able to clean up any problem results manually. There, does that help?
Basically you need to create a class file. Inherit the class from System.Web.UI.Page and then change the page directive of the page to point to the code behind.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_Default" %>
Where Inherits is the name of your class file, and the CodeBehind is the code file you just created. You might need to reload the project to get the solution explorer to display the file nested, but even if you don't it should work.
You can also check out the accepted answer to for an alternative. How does IIS know if it's serving a Web Site or a Web Application project?
I don't know of a shortcut way to be honest.
Your probably best bet is to create a new page and copy paste across until everything works, then delete your source, rename your new file to the old name and rebuild.
Not ideal, but probably the quickest/cleanest/safest way to port over.
Thanks alot! Here is a slighlty modified version if your code is written i VB.Net. Just compile and run the converter in every folder that contains aspx sites.
using System.IO;
namespace Converter
{
class Program
{
const string ScriptStartTag = "<script runat=\"server\">";
const string ScriptEndTag = "</script>";
static void Main(string[] args)
{
string currentDirectory = System.Environment.CurrentDirectory;
var inPath = new DirectoryInfo(currentDirectory);
var outPath = new DirectoryInfo(currentDirectory);
if (!outPath.Exists) inPath.CreateSubdirectory("codebehind");
foreach (FileInfo f in inPath.GetFiles())
{
if (f.FullName.EndsWith(".aspx"))
{
// READ SOURCE FILE
string fileContents;
using (TextReader tr = new StreamReader(f.FullName))
{
fileContents = tr.ReadToEnd();
}
int scriptStart = fileContents.IndexOf(ScriptStartTag);
int scriptEnd = fileContents.IndexOf(ScriptEndTag, scriptStart);
string className = f.FullName.Remove(f.FullName.Length - 5).Replace("\\", "_").Replace(":", "_");
// GENERATE NEW SCRIPT FILE
string scriptContents = fileContents.Substring(
scriptStart + ScriptStartTag.Length,
scriptEnd - (scriptStart + ScriptStartTag.Length) - 1);
scriptContents =
"Imports System\n\n" +
"Partial Public Class " + className + " \n Inherits System.Web.UI.Page\n" +
"\n" +
" " + scriptContents.Trim() +
"\nEnd Class\n";
using (TextWriter tw = new StreamWriter(outPath.FullName + "\\" + f.Name + ".vb"))
{
tw.Write(scriptContents);
tw.Flush();
}
// GENERATE NEW MARKUP FILE
fileContents = fileContents.Remove(
scriptStart,
scriptEnd - scriptStart + ScriptEndTag.Length);
int pageTagEnd = fileContents.IndexOf("%>");
fileContents = fileContents.Insert(pageTagEnd,
"AutoEventWireup=\"false\" CodeBehind=\"" + f.Name + ".vb\" Inherits=\"" + className + "\" ");
using (TextWriter tw = new StreamWriter(outPath.FullName + "\\" + f.Name))
{
tw.Write(fileContents);
tw.Flush();
}
}
}
}
}
}
if your aspx file has 2 sections and your are able to split it in a mechanical way why you don't write just a small parser to automate the work? Shouldn't be hard, it's just plain text manipulation and a recursive file find.

Resources