How to find files in a folder in an ASP.NET application using C#? - asp.net

I have created an Asp.net application.
It contains a folder called PDF and a folder called Requirement just beneath that.
I have a link in another page called Requirement.
If i click on that link i need to find all the files in the folder PDF/Requirement.

var getFileName = Directory.GetFiles(Server.MapPath("~/PDF/Requirement")); // Collection Of file name with extention.
var getFileNameExcludeSomeExtension1 = from f in Directory.GetFiles(Server.MapPath("~/PDF/Requirement"))
where Path.GetExtension(f) != ".scc" && Path.GetExtension(f) != ".db"
select Path.GetFileNameWithoutExtension(f); // Collection Of file name with extention and filtering.
var getFileNameExcludeSomeExtension2 = from f in Directory.GetFiles(Server.MapPath("~/PDF/Requirement"))
where Path.GetExtension(f) != ".scc" && Path.GetExtension(f) != ".db"
select Path.GetFileName(f); // Collection Of file name with out extention and filtering.

I suggest to use EnumerateFiles as this Regex to find a file in folder and if you tried GetFiles dont because of performance you could see difference in this What is the difference between Directory.EnumerateFiles vs Directory.GetFiles?

Related

Script to Move Files in Alfresco

In Alfresco users can use rules to move files. How do I programmatically move a file from one folder to another?
Do you have an example?
I am using Alfresco 7.0 Share/Community version
Using Script :
var backupFolder = space.childByNamePath('testfolder');
if (backupFolder == null)
{
backupFolder = space.createFolder('testfolder');
}
document.move(backupFolder );
Ref : https://hub.alfresco.com/t5/alfresco-content-services-hub/javascript-api-cookbook/ba-p/293260
https://docs.alfresco.com/content-services/6.1/develop/reference/repo-root-objects-ref/

Xamarin - CachedImage - Access the downloaded file

I am using the CachedImage component of ffimageloading. I have a kind of gallery with a carousel view.
All the images are loaded through an internet URL, they are not local images. I would like to add the image sharing function. But I don't want to download the file again, I would like to know if there is a way to access the file that the CachedImage component already downloaded to be able to reuse it in the share function.
try using MD5Helper
var path = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey")'
Thanks Jason
I share with you how part of my code is:
var key = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey");
var imagePath = await ImageService.Instance.Config.DiskCache.GetFilePathAsync(key);
var tempFile = Path.Combine(Path.GetTempPath(), "test.jpg");
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
File.Copy(imagePath, tempFile);
await Share.RequestAsync(new ShareFileRequest
{
Title = "Test",
File = new ShareFile(tempFile)
});
The temporary file I believe, since the cached file has no extension and the applications do not recognize the type.

sub folder in document library as rootNode for user

I want a sub folder within Document library as rootNode in Alfresco Shave 4.2
For Example In Document Library the folder path is Documents > XYZ > User1. When user accesses Document Library by default the content in Documents > XYZ > User1 should be displayed instead of content in Document. If we customize rootNode property from below code which is part of toobar.get.js it should work..I replaced rootNode with XYZ and it works. But rootNode="XYZ/User1" does not work
Not sure how to speciy the sub folder ?
var docListToolbar = {
id: "DocListToolbar",
name: "Alfresco.DocListToolbar",
options: {
siteId: (page.url.templateArgs.site != null) ? page.url.templateArgs.site :"",
rootNode: toolbar.rootNode != null ? toolbar.rootNode : "",
hideNavBar: Boolean(toolbar.preferences.hideNavBar),
googleDocsEnabled: toolbar.googleDocsEnabled,
repositoryBrowsing: toolbar.rootNode != null,
useTitle: (useTitle == "true"),
syncMode: toolbar.syncMode != null ? toolbar.syncMode : "",
createContentByTemplateEnabled: model.createContentByTemplateEnabled,
createContentActions: model.createContent
}
};
model.widgets = [docListToolbar];
since edit online is not present in My Files we created a cutom site in Alfreso Share as a custom My Files section.
Maybe it's a bit late but I would suggest to create a custom site page, almost the same as document library, but with changed root node. And then you can easily replace Document Library page with custom one in site settings.
I have a quite nice example here: http://streetturtle.ninja/jekyll/update/2014/10/23/alf-custom-doclibrary-site-page/. It is almost the same as you want, but the root node changes according to the logged user.

Manually use precompiled handlebars templates

How to manually use the precompiled handlebars.js templates?
Let's say, we have
source = "<p>Hello, my name is {{name}}</p>"
data = { name: "Joe" }
Currently, I have
template = Handlebars.compile(source)
render: -> template(data)
The source is coming from the database, and in order to cut down on the compilation time, I want to use a compilation step, precompiling the template server side with Handlebars.precompile(source) and then using something like:
template = precompiled_template
render: -> precompiled_template(data)
The precompiled_template is a string with function definition, so that doesn't work.
Also, I've found that Hanlebars.compile(source)() == Handlebars.precompile(source), but after browsing the source codes of handlebars, it's compilers and runtime, I'm still not sure how to achieve this.
if you did not find the right question till now, the answer is pretty simple.
Handlebars comes with a C pre-compiler on the command line, if you can access your shell you can simple just compile your templates each separated or merge them together into one file.
you can install Handlebars via npm / or build it on your system.
on the shell you can access the help file
$> Handlebars [ENTER]
You will see a help file like >
- f --output Output File etc etc ..
- m --min Minimize Output
$> Handlebars mysupertemplate.handlebars -f compiled.js -m ("-m" if
you want to minify the js file)
To run Handlebars.compile in the browser is a huge loss in performance, so it's worth a try to precompile on the server before sending the file to the browser.
To register Handlebars templates in your browser you have to load them like this:
var obj = {"foo":"bar"}
var template = require("./mytemplate-file.js") // require.js example
template = template(Handlebars) // Pass Handlebars Only if the template goes mad asking for his Father
var html = Handlebars.templates[template-name](obj)
For example if you have more then one template registered in the "templates-file" you will be able to access after the require call all templates by name using
var html = Handlebars.templates["templateName"]({"foo":"bar"});
You can go even further by register all the know helper within the file and / or making custom helpers for partials like so..
*// This will be the helper in you app.js file*
Handlebars.registerHelper("mypartials", function(partialName, data) {
var partial = Handlebars.registerPartial(partialName) || data.fn
Handlebars.partials[partialName] = partial
})
And in your template file you can put this...
{{#mypartial "divPartial"}}
<div id="block"><h2>{{foo}}</h2><p>{{bar}}</p></div>
{{/mypartial}}
{{#mypartial "formPartial"}}
<form id="foo"><input type="text" value="{{foo}}" name="{{bar}}"></form>
{{/mypartial}}
Now you can access this files by calling
var html = Handlebars.partials["divPartial"]({"foo":"bar","bar":"foo"})
var formHtml = Handlebars.partials["formPartial"]({"bar":"bar","foo":"foo"})
Hope this helped a bit ..
This speed test http://jsperf.com/handlebars-compile-vs-precompile/3 gave the answer.
Apparently, one solution is to eval() that resulting string and it will work.
The code is
var data = { name: "Greg" };
var source = "<p>Howdy, {{ name }}</p>";
eval("var templateFunction = " + Handlebars.precompile(source));
var template = Handlebars.template(templateFunction);
template(data);
=> "<p>Howdy, Greg</p>"
Of course one needs to be careful with eval and probably a better solution exists.

Add filter to FileUpload Control

How to add filter to the fileupload control in asp.net? I want a filter for Word Template File (.dot).
You could also do a javascript alternative to filtering it server side (you'd probably want to do that as well) but this saves the client from spending the time waiting on an upload to finish just to find out it was the wrong type.
http://javascript.internet.com/forms/upload-filter.html
So basically you just run a javascript function on submit that parses off the extension of the uploaded file and gives them an alert if its not of the right type.
You could also use document.forms[0].submit(); instead of passing the form reference through (as ASP.NET really only uses a single form (unless your doing something funky))
string fileName = fuFiles.FileName;
if(fileName.Contains(".dot"))
{
fuFiles.SaveAs(Server.MapPath("~/Files/" + fileName));
}
If you mean to filter the file extensions client/side, with the standard browser's file selector, isn't possible.
To do that you have to use a mixed type of upload, such as SWFUpload, based on a flash uploader system (that's a really nice techinque: it allows you to post more than a file at time).
The only thing you can do in standard mode is to filter the already posted file, and I suggest to use System.IO.Path namespace utility:
if (Path.GetExtension(upFile.FileName).ToUpper().CompareTo(".DOT") == 0)
{
/* do what you want with file here */
}
Check the filename of the uploaded file serverside:
FileUpload1.PostedFile.FileName
Unless you want to use java or something similar on the client, there's really not much you can do for filtering uploaded files before they're sent to the server.
Here I have a small method that I used to filter which types of files can be uploaded by the fileupload control named fuLogo.
if (fuLogo.HasFile)
{
int counter = 0;
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]);
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++;
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
fuLogo.SaveAs(logo);
}
basically, I first Iterates through the directory to see if a file already exists. Should the file exist, (example picture0.gif) , it will increase the counter (to picture1.gif). It prevents that different users will overwrite each other's pictures should their pictures have the same name.

Resources