MP3 TagLib search and copy issue - taglib-sharp

Greetings to all of you.
My problem is:
I need to search through user selected folder that contains MP3 files and check which file(s) has or contains specified tag. If it does, i will copy it to specified folder. I have managed to do something, but only partially, cause for example, i manage to copy genre "Pop" files, but not "Blues" files.
Getting contains to work is a total nightmare, cant get it to work at all.
Code:
try
{
FolderBrowserDialog folder = new FolderBrowserDialog();
DialogResult result = folder.ShowDialog();
string genre = "Blues";
var matchingFiles = Directory.GetFiles(folder.SelectedPath, "*.mp3", SearchOption.AllDirectories).Where(x =>
{
var f = TagLib.File.Create(x);
return (((TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2)).JoinedGenres == genre);
});
foreach (string f in matchingFiles)
{
System.IO.File.Copy(f, Path.Combine(#"destinationFolder", new FileInfo(f).Name));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Any help is welcome.
Problem solved:
try
{
FolderBrowserDialog folder = new FolderBrowserDialog();
DialogResult result = folder.ShowDialog();
string upit = search.Text;
var matchingFiles = Directory.GetFiles(folder.SelectedPath, "*.mp3", SearchOption.AllDirectories).Where(x =>
{
var f = TagLib.File.Create(x);
return (((TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2)).Comment != null && ((TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2)).Comment.Contains(upit));
}
);
foreach (string f in matchingFiles)
{
System.IO.File.Copy(f, Path.Combine(path, new FileInfo(f).Name));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
}

Related

How to get the File Extension from a string Path

I've got file path saved in variable and I want to get the file type extension by using path package https://pub.dev/packages/path So far I managed to do it by splitting the string like this
final path = "/some/path/to/file/file.dart";
print(path.split(".").last); //prints dart
Is there any way to achieve this with path package?
You can use the extension function in the path package to get the extension from a file path:
import 'package:path/path.dart' as p;
final path = '/some/path/to/file/file.dart';
final extension = p.extension(path); // '.dart'
If your file has multiple extensions, like file.dart.js, you can specify the optional level parameter:
final extension = p.extension('file.dart.js', 2); // '.dart.js'
No need of any extension. You can try below code snippet.
String getFileExtension(String fileName) {
try {
return "." + fileName.split('.').last;
} catch(e){
return null;
}
}
This small function can parse filepath or url and find basename, extension and absolute path. It doesn't check file path exist and not check basename is folder or file.
Map parsePath(String filepath) {
Map p1 = new Map();
int ind1 = filepath.indexOf("://");
if (ind1 > 0) {
p1["fullpath"] = filepath;
} else {
p1["fullpath"] = File(filepath).absolute.path;
}
p1["path"] = filepath;
List<String> v = filepath.split("/");
if (v.length > 1) {
p1["basename"] = v.last;
} else if (filepath.split("\\").length > 1) {
p1["basename"] = filepath.split("\\").last;
} else {
p1["basename"] = v.last;
}
p1["extension"] = p1["basename"].split('.').last;
if (p1["basename"] == p1["extension"]) p1["extension"] = "";
return p1;
}

How To Find data by passing List of IMongoQuery

Below is my code where i am passing List showing no error during building solution but during run time its showing error.
An Array value cannot be written to the root level of a BSON document.
My Code Is :
public IQueryable<Folder> GetFolderByIdList(List<IMongoQuery> GraphIdList)
{
if (ApplicationDbContext.ServerIsDown) return null;
_FolderList.Clear();
if (!GraphIdList.Any())
{
return null;
}
var FolderData = db.Folder.Find(GraphIdList.ToBsonDocument()).ToList();
if (FolderData.Count() > 0)
{
foreach (Folder item in FolderData)
{
_FolderList.Add(item);
}
}
var result = _FolderList.AsQueryable();
return result;
}
and below is my code what i have pass in GraphIdList
var UserFilesData = planetDriveObj.GetFilesOfFolder(
Query.And(
Query<UserFiles>.EQ(u => u.CreatorUserID, userInfoId),
Query<UserFiles>.Matches(u => u.Title, fileTitle)));
foreach(var c in UserFilesData.ToList())
{
idList.Add(Query.And(
Query<Graph>.EQ(u => u.GraphID, c.GraphID),
Query<Graph>.EQ(u => u.isHidden, true)));
}
var GraphData = GraphRepObj.getGraphDataBYIdList(idList);

Handling concurrency exceptions when passing the objects ids and timestamps using jQuery

I have the following business scenario inside my Asp.net MVC 4 asset management system :-
Scenario 1) A user selects multiple servers , then he selects a Rack Tag ,and click on
assign . so the selected servers will be assigned to the new Rack.
Scenario 2) And i want to check for any concurrency exception , if for example the selected
servers have been modified by another user since they were retrieved .
so i have wrote the following jQuery which will send the object ids+timestamps to the action method:-
$('body').on("click", "#transferSelectedAssets", function () {
var boxData = [];
$("input[name='CheckBoxSelection']:checked").each(function () {
boxData.push($(this).val());
});
var URL = "#Url.Content("~/Server/TransferSelectedServers")";
$.ajax({
type: "POST",
url: URL,
data: { ids: boxData.join(","), rackTo: $("#rackIDTo").val()}
,
success: function (data) {
addserver(data); })});
and inside the action method i have the following code:-
public ActionResult TransferSelectedServers(string ids, int? rackTo)
{
if (ModelState.IsValid)
{
try
{
var serverIDs = ids.Split(',');
int i = 0;
foreach (var serverinfo in serverIDs)
{
var split = serverinfo.Split('~');
var name = split[0];
//System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] bytearray = Encoding.Default.GetBytes(split[1]);
i++;
var server = repository.FindServer_JTechnology(Int32.Parse(name));
if (server == null)
return Json(new { IsSuccess = false, reload = true, description = " Some Servers might have been deleted, Transferre process has been cancelled .", rackid = rackFrom }, JsonRequestBehavior.AllowGet);
server.RackID = rackTo;
server.timestamp = bytearray;
string ADusername = User.Identity.Name.Substring(User.Identity.Name.IndexOf("\\") + 1);
repository.InsertOrUpdateServer(server, ADusername, server.Technology.IT360ID.Value, server.IT360SiteID, new bool(), server.Technology);
}
repository.Save();
return Json(new { IsSuccess = true, description = i + " Server/s Transferred Successfully To Rack " + }, JsonRequestBehavior.AllowGet);
}
catch (DbUpdateConcurrencyException e)
{
return Json(new { IsSuccess = false, reload = true, description = "records has been modified by antoehr user" }, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new { IsSuccess = false, reload = true, description = " Server/s Can not Be Transferred to the Selected Rack " }, JsonRequestBehavior.AllowGet);
}
}
return RedirectToAction("Details", new { id = rackTo });
}
and the repository method looks as follow:-
public void InsertOrUpdateServer(TMSServer server, string username, long assetid, long? siteid = 0, bool isTDMHW = false, Technology t = null)
{
server.IT360SiteID = siteid.Value;
tms.Entry(server).State = EntityState.Modified;
var technology = tms.Technologies.Single(a => a.TechnologyID == server.TMSServerID);
technology.IsManaged = t.IsManaged;
tms.Entry(technology).State = EntityState.Modified;
InsertOrUpdateTechnologyAudit(auditinfo);
}
}
but currently if two users selects the same servers and assign them to tow different racks , no concurrency exception will be raised ?
Can anyone advice ? baring in mind that if two users edit single object then one of them will get an concurrent exception message. so my timestamp column is defined correctly.
Thanks

How to make a column with a string and pixbuf in GtkTreeview?

I'm working in a app with Gtk+2 and i need to implement a File treeview.
the actual code it's:
public FileTree() {
store = new TreeStore(2,typeof(string),typeof(string));
this.change_dir( "/dir/path" );
set_model( store );
// File icon
var pixbuf = new Gtk.CellRendererPixbuf();
var column = new Gtk.TreeViewColumn();
column.set_title("");
column.pack_start(pixbuf, false);
column.add_attribute(pixbuf,"stock-id",0);
column.set_alignment(1.0f);
append_column (column);
// File name
Gtk.CellRenderer cell = new Gtk.CellRendererText();
insert_column_with_attributes(-1,"", cell, "text", 1);
// Do some visual configs
this.config();
}
and change_dir():
public void change_dir( string path ) {
File repo_dir = File.new_for_path( path );
try {
generate_list( repo_dir, null, new Cancellable());
} catch ( Error e ) {
stderr.printf("Error: %s\n", e.message);
}
}
public void generate_list (
File file,
TreeIter? parent = null,
Cancellable? cancellable = null
) throws Error {
// Enumerator
FileEnumerator enumerator = file.enumerate_children (
"standard::*",
FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
cancellable
);
FileInfo info = null;
TreeIter iter;
while(cancellable.is_cancelled() == false && ((info = enumerator.next_file(cancellable)) != null ))
{
// Check if not it's in the omited files.
if( ! (info.get_name() in IGNORED ) ) {
// Check if is a dir or a file
if( info.get_file_type() == FileType.DIRECTORY ) {
this.store.append( out iter, parent);
this.store.set(iter, 0, STOCK_DIRECTORY, 1, info.get_name());
File subdir = file.resolve_relative_path(info.get_name());
this.generate_list(subdir, iter, cancellable );
} else {
// It's a file
this.store.append( out iter, parent);
this.store.set(iter, 0, STOCK_FILE, 1, info.get_name());
}
}
}
if ( cancellable.is_cancelled()) {
throw new IOError.CANCELLED ("Operation was cancelled");
}
}
This it's showing two columns in ( first with a folder/file icon and the second one the name of the folder/file)
it's some way to do this in one single column??
EDIT: it could be some hack to set the icon at the side of the name, the actual code shows the icon and the string but when i expand a column, the strings moves a little to the right and there's a blank space between the icon and string.
With the method of the TreeViewColumn, pack_start(), I Just append any cell renderer to the column.
(in C this is like http://developer.gnome.org/gtk/unstable/gtk-question-index.html (see 5.3))
so, just modified:
// File icon
var pixbuf = new Gtk.CellRendererPixbuf();
var column = new Gtk.TreeViewColumn();
column.set_title("");
column.pack_start(pixbuf, false);
column.add_attribute(pixbuf,"stock-id",0);
column.set_alignment(1.0f);
append_column (column);
// File name
Gtk.CellRenderer cell = new Gtk.CellRendererText();
insert_column_with_attributes(-1,"", cell, "text", 1);
with:
// File icon
var pixbuf = new Gtk.CellRendererPixbuf();
column.set_title("");
column.pack_start(pixbuf, false);
column.add_attribute(pixbuf,"stock-id",0);
// The name of the file.
var cell = new Gtk.CellRendererText();
column.pack_start(cell, false);
column.add_attribute(cell,"text",1);
append_column (column);
And there it is :)

multiple file upload using html5 drag-and-drop fails as multiple files get same content

I need to transfer all the files dropped on an element to a server using HTML5 drag and drop.
I provided the corresponding js code below. I have a servlet in the server side to collect the files and put it in a folder. This is working fine if I drop 1 or 2 files on the page. But, if i drop 4-10 files, all the files are getting created in the server but multiple files are set to same content and some files content is 0K.
Can any of you please tell me how to achieve the correct behavior.
My requirement is similar to gmail attachments!!
Any solution which makes a sequential upload of files is much appreciable.
/*
* Upload files to the server using HTML 5 Drag and drop from the folders on your local computer
*/
function uploader(place, status, target, show) {
// Upload image files
upload = function(file) {
// Firefox 3.6, Chrome 6, WebKit
if(window.FileReader) {
// Once the process of reading file
this.loadEnd = function() {
bin = reader.result;
xhr = new XMLHttpRequest();
xhr.open('POST', target+'?up=true', false);
var body = bin;
xhr.setRequestHeader('content-type', 'multipart/form-data;');
xhr.setRequestHeader("file-name", file.name );
xhr.setRequestHeader("mime-type", file.type );
// Firefox 3.6 provides a feature sendAsBinary ()
if(xhr.sendAsBinary != null) {
xhr.sendAsBinary(body);
// Chrome 7 sends data but you must use the base64_decode on the PHP side
} else {
xhr.open('POST', target+'?up=true&base64=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
document.getElementById(show).appendChild(newFile);
}
if (status) {
document.getElementById(status).innerHTML = 'Loaded : 100%<br/>Next file ...';
}
};
// Loading errors
this.loadError = function(event) {
switch(event.target.error.code) {
case event.target.error.NOT_FOUND_ERR:
document.getElementById(status).innerHTML = 'File not found!';
break;
case event.target.error.NOT_READABLE_ERR:
document.getElementById(status).innerHTML = 'File not readable!';
break;
case event.target.error.ABORT_ERR:
break;
default:
document.getElementById(status).innerHTML = 'Read error.';
}
};
// Reading Progress
this.loadProgress = function(event) {
if (event.lengthComputable) {
var percentage = Math.round((event.loaded * 100) / event.total);
document.getElementById(status).innerHTML = 'Loaded : '+percentage+'%';
}
};
// Preview images
this.previewNow = function(event) {
bin = preview.result;
var img = document.createElement("img");
img.className = 'addedIMG';
img.file = file;
img.src = bin;
document.getElementById(show).appendChild(img);
};
reader = new FileReader();
// Firefox 3.6, WebKit
if(reader.addEventListener) {
reader.addEventListener('loadend', this.loadEnd, false);
if (status != null)
{
reader.addEventListener('error', this.loadError, false);
reader.addEventListener('progress', this.loadProgress, false);
}
// Chrome 7
} else {
reader.onloadend = this.loadEnd;
if (status != null)
{
reader.onerror = this.loadError;
reader.onprogress = this.loadProgress;
}
}
var preview = new FileReader();
// Firefox 3.6, WebKit
if(preview.addEventListener) {
preview.addEventListener('loadend', this.previewNow, false);
// Chrome 7
} else {
preview.onloadend = this.previewNow;
}
// The function that starts reading the file as a binary string
reader.readAsBinaryString(file);
// Preview uploaded files
if (show) {
preview.readAsDataURL(file);
}
// Safari 5 does not support FileReader
} else {
xhr = new XMLHttpRequest();
xhr.open('POST', target+'?up=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(file);
if (status) {
document.getElementById(status).innerHTML = 'Loaded : 100%';
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
document.getElementById(show).appendChild(newFile);
}
}
};
// Function drop file
this.drop = function(event) {
event.preventDefault();
var dt = event.dataTransfer;
var files = dt.files;
for (var i = 0; i<files.length; i++) {
var file = files[i];
upload(file);
}
};
// The inclusion of the event listeners (DragOver and drop)
this.uploadPlace = document.getElementById(place);
this.uploadPlace.addEventListener("dragover", function(event) {
event.stopPropagation();
event.preventDefault();
}, true);
this.uploadPlace.addEventListener("drop", this.drop, false);
}
Thank you.
I spent sometimes this morning in analyzing the same code from html5uploader. With some lucks, I found the root cause.
Change reader = new FileReader(); to var reader = new FileReader(); should solve the issue.
I bet this is because javascripts behaviour of auto-declaring undeclared variable as global variable. This caused the reader variable being reused by all the uploade(file) calls when more than one file is dropped to the browser.
Cheers!