File upload after rename the file in zend - file-upload

This is my form
class Admin_Form_RoomtypeForm extends Zend_Form
{
public function init()
{
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Name :');
$imagePath = '/home/dinuka/image';
$image = new Zend_Form_Element_File('image');
$image->setLabel('Image URL :');
$image->setDestination($imagePath);
$image->addValidators(array(array('IsImage', false)));
$submit = new Zend_Form_Element_Submit('submit');
$this->addElements(array($name, $image, $submit));
}
}
This is my controller
class Admin_RoomtypesController extends Zend_Controller_Action
{
public function addAction()
{
$form = new Admin_Form_RoomtypeForm();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
$form->populate($formData);
$name = $form->getValue('name');
}
}
}
Now i want to upload file after change file name as $name value. How can i do it?

I had to do something like this for one of my projects, except i needed unique filenames. This isn't a perfect solution, but it may put you on the right track:
<?php
class My_Filter_UniqueFilename implements Zend_Filter_Interface
{
public function filter($value)
{
$upload_dir = pathinfo($value, PATHINFO_DIRNAME);
$ext = pathinfo($value, PATHINFO_EXTENSION);
$filename = $upload_dir . "/" . md5(microtime()) . "." . $ext;
$result = rename($value, $filename);
if($result === true) {
return $upload_dir . $filename;
}
require_once 'Zend/Filter/Exception.php';
throw new Zend_Filter_Exception(sprintf("File '%s' could not be renamed. An error occured while processing the file.", $value));
}
}

Finally I done it as following.
-Form -
class Admin_Form_RoomtypeForm extends Zend_Form
{
public function init()
{
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Name :');
$image = new Zend_Form_Element_File('image');
$image->setLabel('Image URL :');
$image->addValidators(array(array('IsImage', false)));
$submit = new Zend_Form_Element_Submit('submit');
$this->addElements(array($name, $image, $submit));
}
}
-Controller -
class Admin_RoomtypesController extends Zend_Controller_Action
{
public function addAction()
{
$form = new Admin_Form_RoomtypeForm();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
$form->populate($formData);
$name = $form->getValue('name');
$image = $form->getValue('image');
$temp = explode(".", $image);
$ext = $temp[count($temp)-1];
$imageName = $name .'.'. $ext;
$fullPath = $imagePath ."/". $imageName;
copy("/tmp/". $image, $fullPath);
}
}
}
default image is upload to /tmp folder. We can change it using setDestination() method as my example.
Thank for All

Related

Download the file as a zip in ASP.NET Core

I am designing an educational site. When the user downloads a training course, I want this download (training course) to be done in the form of compression (zipper), please give a solution
My code:
public Tuple<byte[],string,string> DownloadFile(long episodeId)
{
var episode=_context.CourseEpisodes.Find(episodeId);
string filepath = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot/courseFiles",
episode.FileName);
string fileName = episode.FileName;
if(episode.IsFree)
{
byte[] file = System.IO.File.ReadAllBytes(filepath);
return Tuple.Create(file, "application/force-download",fileName);
}
if(_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
if(IsuserIncorse(_httpContextAccessor.HttpContext.User.Identity.Name,
episode.CourseId))
{
byte[] file = System.IO.File.ReadAllBytes(filepath);
return Tuple.Create(file, "application/force-download", fileName);
}
}
return null;
}
I write a demo to show how to download zip file from .net core:
First , Add NuGet package SharpZipLib , create an Image Folder in wwwroot and put some picture in it.
controller
public class HomeController : Controller
{
private IHostingEnvironment _IHosting;
public HomeController(IHostingEnvironment IHosting)
{
_IHosting = IHosting;
}
public IActionResult Index()
{
return View();
}
public FileResult DownLoadZip()
{
var webRoot = _IHosting.WebRootPath;
var fileName = "MyZip.zip";
var tempOutput = webRoot + "/Images/" + fileName;
using (ZipOutputStream IzipOutputStream = new ZipOutputStream(System.IO.File.Create(tempOutput)))
{
IzipOutputStream.SetLevel(9);
byte[] buffer = new byte[4096];
var imageList = new List<string>();
imageList.Add(webRoot + "/Images/1202.png");
imageList.Add(webRoot + "/Images/1data.png");
imageList.Add(webRoot + "/Images/aaa.png");
for (int i = 0; i < imageList.Count; i++)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(imageList[i]));
entry.DateTime= DateTime.Now;
entry.IsUnicodeText = true;
IzipOutputStream.PutNextEntry(entry);
using (FileStream oFileStream = System.IO.File.OpenRead(imageList[i]))
{
int sourceBytes;
do
{
sourceBytes = oFileStream.Read(buffer, 0, buffer.Length);
IzipOutputStream.Write(buffer, 0, sourceBytes);
}while (sourceBytes > 0);
}
}
IzipOutputStream.Finish();
IzipOutputStream.Flush();
IzipOutputStream.Close();
}
byte[] finalResult = System.IO.File.ReadAllBytes(tempOutput);
if (System.IO.File.Exists(tempOutput)) {
System.IO.File.Delete(tempOutput);
}
if (finalResult == null || !finalResult.Any()) {
throw new Exception(String.Format("Nothing found"));
}
return File(finalResult, "application/zip", fileName);
}
}
when I click the downloadZip ,it will download a .zip file
The simple example that follows illustrates the use of the static ZipFile.CreateFromDirectory method which, despite the fact that it is in the System.IO.Compression namespace , actually resides in the System.IO.Compression.FileSystem assembly, so you need to add a reference to that in your controller.
[HttpPost]
public FileResult Download()
{
List<string> files = new List<string> { "filepath1", "filepath2" };
var archive = Server.MapPath("~/archive.zip");
var temp = Server.MapPath("~/temp");
// clear any existing archive
if (System.IO.File.Exists(archive))
{
System.IO.File.Delete(archive);
}
// empty the temp folder
Directory.EnumerateFiles(temp).ToList().ForEach(f => System.IO.File.Delete(f));
// copy the selected files to the temp folder
files.ForEach(f => System.IO.File.Copy(f, Path.Combine(temp, Path.GetFileName(f))));
// create a new archive
ZipFile.CreateFromDirectory(temp, archive);
return File(archive, "application/zip", "archive.zip");
}
Answer from Source - MikesDotNetting

Unable to unload DLL in .NET Core 3

I am trying to unload an external assemble but it still sitting in the memory and I can not delete the dll file. Here is my code - What am I doing wrong ?
The uploaded dll is very simple - just 1 class and one method. no dependencies.
I had a look at many samples and see no issue in the code but it still does not work.
Thank you !
class SimpleUnloadableAssemblyLoadContext : AssemblyLoadContext
{
public SimpleUnloadableAssemblyLoadContext( ) : base(isCollectible: true)
{
}
protected override Assembly Load(AssemblyName name)
{
return null;
}
}
public class PluginLoader2
{
[MethodImpl(MethodImplOptions.NoInlining)]
public string getExternalText()
{
string res = "";
var sourcesPath = Path.Combine(Environment.CurrentDirectory, "Plugins");
string[] fileEntries = Directory.GetFiles(sourcesPath);
foreach (string fileName in fileEntries)
{
SimpleUnloadableAssemblyLoadContext context = new SimpleUnloadableAssemblyLoadContext();
WeakReference w_r = new WeakReference(context, trackResurrection: true);
var myAssembly = context.LoadFromAssemblyPath(fileName);
context.Unload();
for (var i = 0; i < 10 && w_r.IsAlive; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
res += "<br /><br />" + fileName + " live status is " + w_r.IsAlive.ToString();
}
return res;
}
}

How to register the cache button in ASP.NET

I have created the cache button to clear all the .json files. Its perfectly working fine in local machine. But when i uploaded in server the cache button is not working.
After uploading in server, when i click on clear cache button the message is displaying as cache(.json files) has been cleared but actually all .json files is remain as it is.
Please help me in this isuue.
below is the code
#region Delete Cache Functions
public bool FnDeleteCache(string directoryName)
{
try
{
var di = new DirectoryInfo(rootDirectory + directoryName);
di.Attributes &= ~FileAttributes.ReadOnly;
if (CacheAttribute() == true)
{
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(rootDirectory + directoryName);
foreach (System.IO.FileInfo file in directory.GetFiles())
{
if (file.Name != null)
file.Delete();
}
return true;
}
}
catch
{
return false;
}
return false;
}
public bool FnDeleteCache(string directoryName, string FileName)
{
var di = new DirectoryInfo(rootDirectory + directoryName);
di.Attributes &= ~FileAttributes.ReadOnly;
if (CacheAttribute() == true)
{
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(rootDirectory + directoryName);
foreach (System.IO.FileInfo file in directory.GetFiles())
{
if (file.Name.Contains(FileName))
{
file.Delete();
return true;
}
}
}
return false;
}
#endregion
Thank you.

Coded UI Testing Without UIMAP

I have working in coded ui project. I have trying to coded ui test without UIMAP.In this requirement using following code in c#.
[TestMethod]
public void CodedUITestMethod1()
{
var app = ApplicationUnderTest.Launch("C:\\Windows\\System32\\calc.exe", "%windir%\\System32\\calc.exe");
WinWindow calWindow = app.SearchFor<WinWindow>(new { Name = "Calculator" },new { ClassName = "CalcFrame" });
WinButton buttonAdd = calWindow.Container.SearchFor<WinButton>(new { Name = "Add" });
WinButton buttonEqual = calWindow.Container.SearchFor<WinButton>(new { Name = "Equals" });
WinButton button1 = calWindow.Container.SearchFor<WinButton>(new { Name = "1" });
WinButton button2 = calWindow.Container.SearchFor<WinButton>(new { Name = "2" });
WinButton button3 = calWindow.Container.SearchFor<WinButton>(new { Name = "3" });
WinText txtResult = calWindow.Container.SearchFor<WinText>(new { Name = "Result" });
//do all the operations
Mouse.Click(button2);
Mouse.Click(buttonAdd);
Mouse.Click(button3);
Mouse.Click(buttonEqual);
//evaluate the results
Assert.AreEqual("5", txtResult.DisplayText);
//close the application
app.Close();
}
I have referred following dll's
Microsoft.VisualStudio.QualityTools.CodedUITestFramework
Microsoft.VisualStudio.QualityTools.UnitTestFramework
Microsoft.VisualStudio.TestTools.UITest.Common
Microsoft.VisualStudio.TestTools.UITest.Extension
Microsoft.VisualStudio.TestTools.UITesting
But,Above the code raise the error like
'Microsoft.VisualStudio.TestTools.UITesting.ApplicationUnderTest' does not contain a definition for 'SearchFor' and no extension method 'SearchFor' accepting a first argument of type
'Microsoft.VisualStudio.TestTools.UITesting.ApplicationUnderTest' could be found (are you missing a using directive or an assembly reference?)
I don't know what is this issue. Please help for this task.
Thanks in Advance.
CodedUIExtension File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UITesting;
namespace CodedUITest
{
public static class CodedUIExtension
{
public static T SearchFor<T>(this UITestControl _this, dynamic searchProperties, dynamic filterProperties = null) where T : UITestControl, new()
{
T ctrl = new T();
ctrl.Container = _this;
IEnumerable<string> propNames = ((object)searchProperties).GetPropertiesForObject();
foreach (var item in propNames)
{
ctrl.SearchProperties.Add(item, ((object)searchProperties).GetPropertyValue(item).ToString());
}
object s = filterProperties;
if (s != null)
{
propNames = ((object)filterProperties).GetPropertiesForObject();
foreach (var item in propNames)
{
ctrl.SearchProperties.Add(item, ((object)filterProperties).GetPropertyValue(item).ToString());
}
}
return ctrl as T;
}
private static IEnumerable<string> GetPropertiesForObject(this object _this)
{
return (from x in _this.GetType().GetProperties() select x.Name).ToList();
}
private static object GetPropertyValue(this object _this, string propName)
{
var prop = (from x in _this.GetType().GetProperties() where x.Name == propName select x).FirstOrDefault();
return prop.GetValue(_this);
}
}
}
Testmethod
[TestMethod]
public void CodedUITestMethod1()
{
try
{
//ProcessStartInfo processStartInfo = new ProcessStartInfo(#"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CodedUITestBuilder.exe ");
//processStartInfo.Arguments = #"/standalone";
//ApplicationUnderTest app = ApplicationUnderTest.Launch(processStartInfo);
ApplicationUnderTest app = ApplicationUnderTest.Launch("C:\\Windows\\System32\\calc.exe", "%windir%\\System32\\calc.exe");
WinWindow calWindow = new WinWindow();
calWindow = app.SearchFor<WinWindow>(
/* pass search properties */
new { Name = "Calculator" },
/*pass filter properties if needed */
new { ClassName = "CalcFrame" });
WinButton buttonAdd = calWindow.Container.SearchFor<WinButton>(new { Name = "Add" });
WinButton buttonEqual = calWindow.Container.SearchFor<WinButton>(new { Name = "Equals" });
WinButton button1 = calWindow.Container.SearchFor<WinButton>(new { Name = "1" });
WinButton button2 = calWindow.Container.SearchFor<WinButton>(new { Name = "2" });
WinButton button3 = calWindow.Container.SearchFor<WinButton>(new { Name = "3" });
WinText txtResult = calWindow.Container.SearchFor<WinText>(new { Name = "Result" });
//do all the operations
Mouse.Click(button2);
Mouse.Click(buttonAdd);
Mouse.Click(button3);
Mouse.Click(buttonEqual);
//evaluate the results
Assert.AreEqual("5", txtResult.DisplayText);
//close the application
app.Close();
}
catch (Exception e)
{
}
}
I hope this is working sample for code ui without uimap

system.io.file.exists not working in mvc4

I am removing the image from kendo upload control.
This is my code
public ActionResult Remove(string[] fileNames)
{
if (fileNames != null)
{
foreach (var fullName in fileNames)
{
var fileName = Path.GetFileName(fullName);
var physicalPath = Server.MapPath(Path.Combine(("~/AssetAttachments"),fileName));
if (System.IO.File.Exists(physicalPath))
{
System.IO.File.Delete(physicalPath);
}
}
}
return Content("");
}
Physicalpath i have is E:\karthik related\JPL\Dev\Src\AssetTrackingSystem\AssetTrackingSystem\AssetAttachments\Attach3.jpg
Even though file and directory available
if (System.IO.File.Exists(physicalPath))
is returning false and coming out of condition.
Your help will be appreciated.
Try this:
foreach (var fullName in fileNames)
{
var physicalPath = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/AssetAttachments"), fullName);
if (System.IO.File.Exists(physicalPath))
{
System.IO.File.Delete(physicalPath);
}
}
Try with this,
FileInfo fi = new FileInfo(Path.Combine(("~/AssetAttachments"),fileName));
if (fi.Exists)
{
fi.Delete();
}