Xcode Cocoa - Drag Drop from NSTableView to Finder - c#

I want my MacOS App to be able to Drag a item from NSTableView to an other Application like Logic Pro X, Finder, etc.
The items in this TableViews are classes I created which are representing Files on my HD.
public class AudioFile
{
#region Computed Propoperties
public string Filename { get; set; } = "";
public string Filepath { get; set; } = "";
#endregion
public AudioFile()
{
}
public AudioFile(string filename, string filepath)
{
this.Filename = filename;
this.Filepath = filepath;
}
}
Unfortunately I can't find a solution for Swift or Objective-C which I could translate to C# (Xamarin). Does anyone know one or has some code that could help here?
Thanks for your help!

I know nothing about C#, but you asked for a solution in Swift or Objective-C. That I can help with! The below is Swift 4.
First of all, make sure your ViewController is the table view's data source:
class ViewController: NSViewController, NSTableViewDataSource
You will also need to make that connection either in code or in IB.
You then need to set your table view as a dragging source. Choose the operation you want, usually either .move or .copy:
tableView.setDraggingSourceOperationMask(.move, forLocal: false)
This example assumes that you're using an ArrayController to manage the content of the tableView. You really should be, it makes a host of things easier. Also, this example is for dragging multiple files. (It will work for a single file, but there are other approaches if you only ever want to drag one.)
In your ViewController class, implement this method:
func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
var filePaths = [String]()
// Swift 4 hack--the FilenamesPboardType is missing
let NSFilenamesPboardTypeTemp = NSPasteboard.PasteboardType("NSFilenamesPboardType")
pboard.addTypes([NSFilenamesPboardTypeTemp], owner: nil)
if let audioFiles = audioFilesArrayController.arrangedObjects as? [AudioFile] {
for i in rowIndexes {
filePaths.append(audioFiles[i].Filepath)
}
}
pboard.setPropertyList(filePaths, forType: NSFilenamesPboardTypeTemp)
return true
}
You can learn more about the NSFilenamesPboardTypeTemp hack here.
And that's it! Recompile and you should be able to move one or more of your files by dragging them to a Finder window. Simple. :-)

Related

How to Save Html data from a website to a text file using Xamarin forms and C#

I'm using C# and Xamarin forms to create a phone app that (when a button is pressed) will pull specific html data from a website in and save it into a text file (that the program can read from again later). I started with the tutorial in this video: https://www.youtube.com/watch?v=zvp7wvbyceo if you want to see what I started out with, and here's the code I have so far made using this video https://www.youtube.com/watch?v=wwPx8QJn9Kk, in the the "AboutViewModel.cs" file created in the video:
Image link because this is a new account i guess and i cant embed images or something
Paste of the code itself (but the image gives you a better look at everything):
private Task WebScraper()
{
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load("https://www.flightview.com/airport/DAB-Daytona_Beach-FL/");
foreach (var item in doc.DocumentNode.SelectNodes("//td[#class='c1']"))
{
var itemstring = item;
File.WriteAllText("AirportData.txt", itemstring);
}
return Task.CompletedTask;
}
public ICommand OpenWebCommand { get; }
public ICommand WebScraperCommand { get; }
}
}
The only error i'm getting right now is "Cannot convert 'HtmlAgilityPack.HtmlNode' to 'string'" Which i'm working on fixing but I don't think this is the best solution so anything you have is useful. Thanks :)
HtmlNode is an object, not a simple string. You probably want to use the OuterHtml property, but consult the docs to see if that is the right fit for your use case
string output = string.Empty;
foreach (var item in doc.DocumentNode.SelectNodes("//td[#class='c1']"))
{
output += item.OuterHtml;
}
File.WriteAllText("AirportData.txt", output);
note that you need to specify a path to a writable folder, the root folder of the app is not writable. See https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows

Sparx EA .feap projects images saved as blank

In addin for Sparx EA I use this code to get pictures and assign to entity. Then I use images from entities, to, as example, save at some folders or insert in word report etc (from this answer)
/// <summary>
/// Access to diagram image without using clipboard
/// </summary>
/// <param name="projectInterface">Ea Sparx interface</param>
/// <param name="eaDiagramGuid">Guid of the diagramm</param>
/// <returns></returns>
public static Image GetDiagramImage(this Project projectInterface, Guid eaDiagramGuid, ApplicationLogger _logger)
{
Image diagramImage;
try
{
var diagramByGuid = projectInterface.GUIDtoXML(eaDiagramGuid.ToString("B"));
string tempFilename = string.Format("{0}{1}{2}", Path.GetTempPath(), Guid.NewGuid().ToString(), ".png");
bool imageToFileSuccess = projectInterface.PutDiagramImageToFile(diagramByGuid, tempFilename, FileExtensionByName);
if (imageToFileSuccess)
{
using (var imageStream = new MemoryStream(File.ReadAllBytes(tempFilename)))
{
diagramImage = Image.FromStream(imageStream);
}
File.Delete(tempFilename);
}
else
{
throw new Exception(string.Format("Image to file exprot fail {0}", projectInterface.GetLastError()));
}
}
catch (Exception e)
{
throw;
}
return diagramImage;
}
The problem is - it works if project I work with saved as .eap file.
If it's .feap file, which, as I believe means that it works with Firebird database (instead of Access), all saved/exproted to report images are blank, like this down below
Why does it happens and is there workaround?
UPD
It works if I use projectInterface.PutDiagramImageOnClipboard instead but I don't wont to use clipboard at all
UPD 2
After some experiments today at the morning (at my timezone, gmt+3, it's still morning) I found out that the problem was with GUIDs register!
After I decided to apply .toUpper() here
var diagramByGuid = projectInterface.GUIDtoXML(eaDiagramGuid.ToString("B").ToUpper());
it started work fine!
Strange thing thou that if project is *.EAP type everything works even when guid is not in upper register!
UPD3
Well, unfortunately, I was wrong. Some pictures are still blank. But somehow that changes got impact on diagrams, I keep testing this stuff.
And some of the pictures are appeared twice or in wrong place.
But it's kinda interesting (if I could say so) behaviour.
UPD 4
I was wrong in my UPD2 part! GUID can contain down register symbols as well as upper ones.
So, first I removed that part.
What I done next - I started to pass GUID directly from diagram, so signature changed like that
public static Image GetDiagramImage(this Project projectInterface, string eaDiagramGuid, ApplicationLogger _logger)
and eaDiagramGuid should be passed right from EA.Diagram object.
When we parse it as Guid by Guid.Parse(eaDiagramGuid) it convert everything in lowercase like here
so, thats why I got the problem.
But for some reason it was not appeared in *.EAP type of projects!
Also it strange that register matters in that case, really. Seems like GUID in common and GUID in sparx ea are different things!
Okay, as I founded out here, the thing is, in case of *.FEAP all items GUIDs are surprisingly case sensetive.
So, my mistake was to store item GUID as Guid type - when we use Guid.Parse(myGuidString) function and then we converting it back to string - all symbols are appers to be in lowercase.
Also, I got my answer from support (they were surprisingly fast, I really like that)
Hello Danil,
Running over the Stack Overflow - it sounds like it's effectively
answered. The core point is that the Feap files are case sensitive.
To be technical, the collation used for our Firebird databases is case
sensitive.
So, in the Automation script you do need to adhere to the case.
So, I just change things to work directly with GUID string from project item like
Image diagramImage = _eaProjectInterface.GetDiagramImage(diagram.DiagramGUID, _logger);
and function now look like this
public static Image GetDiagramImage(this Project projectInterface, string eaDiagramGuid, ApplicationLogger _logger)
{
Image diagramImage;
try
{
var diagramByGuid = projectInterface.GUIDtoXML(eaDiagramGuid);
string tempFilename = string.Format("{0}{1}{2}", Path.GetTempPath(), Guid.NewGuid().ToString(), ".png");
bool imageToFileSuccess = projectInterface.PutDiagramImageToFile(diagramByGuid, tempFilename, FileExtensionByName);
if (imageToFileSuccess)
{
using (var imageStream = new MemoryStream(File.ReadAllBytes(tempFilename)))
{
diagramImage = Image.FromStream(imageStream);
}
File.Delete(tempFilename);
}
else
{
throw new Exception(string.Format("Image to file exprot fail {0}", projectInterface.GetLastError()));
}
}
catch (Exception e)
{
throw;
}
return diagramImage;
}
So, this means that Sparx EA *.FEAP project GUIDs are NOT really GUIDs but just string-keys (as I assume).
Be careful when your work with them :-)

MonoTorrent magnet link download does not start

I strongly believe that MonoTorrent library can do this, but it is probably due to the lack of documentation that I haven't been able to get it working.
To start with, MonoTorrent seems to be able to successfully download original torrents by using the following code:
https://smuxi.im/wiki/monotorrent/Managing_Torrents
But due to the increase of Magnet Links popularity, I would like to get magnet links working as well. The "trick" of getting .torrent out of them (like using the ones that µTorrent generates) doesn't work for me either even when using the same code as above. It stays stuck like this, founding 1-3 peers per second but making no progress:
StackOverflow best question / answer at this topic was MonoTorrent - Magnet link to Torrent file but unfortunately the answer didn't even match MonoTorrent constructors which are the following:
public TorrentManager(Torrent torrent, string savePath, TorrentSettings settings);
public TorrentManager(MagnetLink magnetLink, string savePath, TorrentSettings settings, string torrentSave);
public TorrentManager(Torrent torrent, string savePath, TorrentSettings settings, string baseDirectory);
public TorrentManager(InfoHash infoHash, string savePath, TorrentSettings settings, string torrentSave, IList<RawTrackerTier> announces);
Finally I went to try some other code, apparently you need to need to either pass it a MagnetLink or InfoHash, so I gave it a go with InfoHash like the following:
ClientEngine engine;
TorrentManager manager;
string savePath;
public TorrentDownload(string savePath)
{
this.engine = new ClientEngine(new EngineSettings());
this.savePath = savePath;
}
public void DownloadMagnet(string hash)
{
manager = new TorrentManager(InfoHash.FromHex(hash), savePath, new TorrentSettings(), savePath, new List<RawTrackerTier>());
engine.Register(manager);
manager.Start();
}
Am I missing something that my download doesn't even start? No errors / no crashes

Where to find my GUID on my c# solution

Hello I have been having issues with MonoGame when building I get the glbind... error in the opengl32.dll so I was suggested to find my GUID and it sounds like a simple task but i have looked in the project folder files and cant find it I found one which is
<ProjectGuid>{325BCA73-8459-49AF-9C31-D4A268BF8A1A}</ProjectGuid>
but im looking for one like this
<ProjectTypeGuids>{9B831FEF-F496-498F-9FE8-180DA5CB4258};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
here is a image of my file folder and the main "collisions".csproj file where I found the one GUID. I have done some research but i cant seem to find an answer as to where to look.
HERE
More accuretly im looking for the Projecttypeguids so I can delete one of them to see if that solves my problem as suggested here....I recognized what i worded at the top is kind of vague sorry
Here
The first example you gave is the GUID of your project. Hence ProjectGuid.
The second is a list of the GUIDs of the project types of your project. Hence ProjectTypeGuids.
If you are looking for the GUID of your project, the first example is giving you the correct answer.
The screenshot you linked to shows a project that does not have any type GUIDs listed. If present, the value is mostly used by development tools (e.g. VS uses it to figure out what items to include in the context menus for adding new items.) If there is no project type GUID your project will still "work" for the most part, but you will likely encounter odd behavior in your IDE of choice.
The project type GUID values in your question are correct for a project that is a C# application that uses the MonoGame plugin. If your project file is missing that tag, just add it yourself with whichever GUIDs you want your project to have.
(The list of well-known GUIDs can be found here, though the MonoGame one I had to look up on Google.)
First you didn't mentioned what you're using winforms or wpf.
OK whatever.The ProjectTypeGuids is not supported in winforms you can find them if you're using wpf.
If you're using wpf you can use this code:
public string GetProjectTypeGuids(EnvDTE.Project proj)
{
string projectTypeGuids = "";
object service = null;
Microsoft.VisualStudio.Shell.Interop.IVsSolution solution = null;
Microsoft.VisualStudio.Shell.Interop.IVsHierarchy hierarchy = null;
Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject aggregatableProject = null;
int result = 0;
service = GetService(proj.DTE, typeof(Microsoft.VisualStudio.Shell.Interop.IVsSolution));
solution = (Microsoft.VisualStudio.Shell.Interop.IVsSolution)service;
result = solution.GetProjectOfUniqueName(proj.UniqueName, hierarchy);
if (result == 0)
{
aggregatableProject = (Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject) hierarchy;
result = aggregatableProject.GetAggregateProjectTypeGuids(projectTypeGuids);
}
return projectTypeGuids;
}
public object GetService(object serviceProvider, System.Type type)
{
return GetService(serviceProvider, type.GUID);
}
public object GetService(object serviceProviderObject, System.Guid guid)
{
object service = null;
Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider = null;
IntPtr serviceIntPtr;
int hr = 0;
Guid SIDGuid;
Guid IIDGuid;
SIDGuid = guid;
IIDGuid = SIDGuid;
serviceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)serviceProviderObject;
hr = serviceProvider.QueryService(SIDGuid, IIDGuid, serviceIntPtr);
if (hr != 0)
{
System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hr);
}
else if (!serviceIntPtr.Equals(IntPtr.Zero))
{
service = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(serviceIntPtr);
System.Runtime.InteropServices.Marshal.Release(serviceIntPtr);
}
return service;
}
it's from here

Can i Read code from a file and and let that code run in an application

I am developing an Desktop Application in WPF using C# .
For the sake of simplicity, Assume my Application has functions which draw lines in said direction goleft() , goright() , goforward() , goback() .
when any of these function is called a line of one inch will be drawn on screen.
I want to make application where user will write code in a file in any editor (say notepad) and save that file in some fixed format (say .abc or .xyz)
Imaginary Example :
(section_start)
For(int i = 0 ; i<= 20 ; i++ )
{
if(i<5)
goforward();
else if(i==5)
goleft();
else if(i < 10)
forward();
.......
........
}
(section_End)
Can i make application which should be capable of reading this file and execute code which is written in between of (section_start) and (section_End). and only if possible can check for syntax errors too... (Not compulsory).
Please guide me on this issue :
Disclosure : My actual Application is somewhat else and could not discuss here due to my company's rules.
Thanks to all who replied to my question. Stackoverflow is fantastic site , i have found the roadmap where to go , till today morning i did not have any clue but now i can go ahead , thanks all of you once again
Will ask question again if i get stucked somewhere
You can read the file content using FileInfo and get the code you need to execute.
Then you can execute the code using CSharpCodeProvider like in this post:
using (Microsoft.CSharp.CSharpCodeProvider foo =
new Microsoft.CSharp.CSharpCodeProvider())
{
var res = foo.CompileAssemblyFromSource(
new System.CodeDom.Compiler.CompilerParameters()
{
GenerateInMemory = true
},
"public class FooClass { public string Execute() { return \"output!\";}}"
);
var type = res.CompiledAssembly.GetType("FooClass");
var obj = Activator.CreateInstance(type);
var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
}
You can choose CodeDOM or IL Emit
More help on CodeDOM
More information on IL Generator / Emit
This is called scripting your application if I understand correctly. C# does not support this out of the box. One thing to look into could be the new Roselyn compiler from Microsoft (it is a new take on the C# compiler, which lets you do just this).
For more info on Roselyn check out:
http://blogs.msdn.com/b/csharpfaq/archive/2011/12/02/introduction-to-the-roslyn-scripting-api.aspx
I've only seen a demo of it, but it looks very promissing, and should solve your problem.
It's not clear what kind of code you want compiled but here is a guide on how to compile code code with C#.
You could use IronPython to handle the script.
Here's an example of how to do this:
First you need a navigation object to perform the operations on:
public class NavigationObject
{
public int Offset { get; private set; }
public void GoForwards()
{
Offset++;
}
public void GoBackwards()
{
Offset--;
}
}
Then the code to execute the file:
public void RunNavigationScript(string filePath, NavigationObject navObject)
{
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("navigation", navObject);
var source = engine.CreateScriptSourceFromFile(filePath);
try
{
source.Execute(scope);
}
catch(Exception
{
}
}
The script file can then take the form of something like:
for x in range(0,20):
if x == 5:
navigation.GoBackwards()
else:
navigation.GoForwards()

Categories