MonoTorrent magnet link download does not start - c#

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

Related

C# Slack Bot to Slack Channel - using Slash command and not chat

I'd like to send a slash command to a channel of my choice.
I'm using the Newtonsoft Json.NET serializer from NuGet. Currently, I have the following code:
string messageToSend = #"/Kyber test task here";
string channelToSendTo = "#general";
var urlWithAccessToken
= "https://hooks.slack.com/services/TOKEN/SPECIFIC/STUFF";
var client = new SlackClient(urlWithAccessToken);
client.PostMessage(username: "MyBot",
text: messageToSend,
channel: channelToSendTo);
And the SlackClient.cs
public SlackClient(string urlWithAccessToken)
{
_uri = new Uri(urlWithAccessToken);
}
public void PostMessage(string text, string username = null, string channel = null)
{
Payload payload = new Payload()
{
Channel = channel,
Username = username,
Text = text
};
PostMessage(payload);
}
public class Payload
{
[JsonProperty("channel")]
public string Channel { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
It currently just says "/kyber test task here" instead of calling the /kyber slash command.
I've seen the undocumented chat.command command, but it doesn't appear to work with the Slack API now. I was hoping there was another way to do it without using the Legacy App functionality, since it surprises me that I was unable to find an example newer than about 3-4 years ago that didn't use it.
I guess this is the answer, but I asked Slack support about it. They replied:
It sounds like you might be asking about allowing an app to send a message containing the slash command, in order to trigger the slash command.
If so, I'm afraid that's not possible. Instead, since all slash commands essentially trigger a specific API endpoint, you'll need to contact the developers of that slash command to see if they make that endpoint publicly accessible so that you can create your own app mechanism to try and trigger commands to those endpoints.
I'm sorry that I don't have better news for you on this. I hope that info might help you to move forward though. Thanks for checking in on this.
So I think the answer is that the App I'm using doesn't support that functionality, and Slack doesn't/won't either. Thanks anyways for the help.

Xcode Cocoa - Drag Drop from NSTableView to Finder

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. :-)

How to Check a input text is Norwegian language or not in c# [duplicate]

What's the best way to detect the language of a string?
If the context of your code have internet access, you can try to use the Google API for language detection.
http://code.google.com/apis/ajaxlanguage/documentation/
var text = "¿Dónde está el baño?";
google.language.detect(text, function(result) {
if (!result.error) {
var language = 'unknown';
for (l in google.language.Languages) {
if (google.language.Languages[l] == result.language) {
language = l;
break;
}
}
var container = document.getElementById("detection");
container.innerHTML = text + " is: " + language + "";
}
});
And, since you are using c#, take a look at this article on how to call the API from c#.
UPDATE:
That c# link is gone, here's a cached copy of the core of it:
string s = TextBoxTranslateEnglishToHebrew.Text;
string key = "YOUR GOOGLE AJAX API KEY";
GoogleLangaugeDetector detector =
new GoogleLangaugeDetector(s, VERSION.ONE_POINT_ZERO, key);
GoogleTranslator gTranslator = new GoogleTranslator(s, VERSION.ONE_POINT_ZERO,
detector.LanguageDetected.Equals("iw") ? LANGUAGE.HEBREW : LANGUAGE.ENGLISH,
detector.LanguageDetected.Equals("iw") ? LANGUAGE.ENGLISH : LANGUAGE.HEBREW,
key);
TextBoxTranslation.Text = gTranslator.Translation;
Basically, you need to create a URI and send it to Google that looks like:
http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20worled&langpair=en%7ciw&key=your_google_api_key_goes_here
This tells the API that you want to translate "hello world" from English to Hebrew, to which Google's JSON response would look like:
{"responseData": {"translatedText":"שלום העולם"}, "responseDetails": null, "responseStatus": 200}
I chose to make a base class that represents a typical Google JSON response:
[Serializable]
public class JSONResponse
{
public string responseDetails = null;
public string responseStatus = null;
}
Then, a Translation object that inherits from this class:
[Serializable]
public class Translation: JSONResponse
{
public TranslationResponseData responseData =
new TranslationResponseData();
}
This Translation class has a TranslationResponseData object that looks like this:
[Serializable]
public class TranslationResponseData
{
public string translatedText;
}
Finally, we can make the GoogleTranslator class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
namespace GoogleTranslationAPI
{
public class GoogleTranslator
{
private string _q = "";
private string _v = "";
private string _key = "";
private string _langPair = "";
private string _requestUrl = "";
private string _translation = "";
public GoogleTranslator(string queryTerm, VERSION version, LANGUAGE languageFrom,
LANGUAGE languageTo, string key)
{
_q = HttpUtility.UrlPathEncode(queryTerm);
_v = HttpUtility.UrlEncode(EnumStringUtil.GetStringValue(version));
_langPair =
HttpUtility.UrlEncode(EnumStringUtil.GetStringValue(languageFrom) +
"|" + EnumStringUtil.GetStringValue(languageTo));
_key = HttpUtility.UrlEncode(key);
string encodedRequestUrlFragment =
string.Format("?v={0}&q={1}&langpair={2}&key={3}",
_v, _q, _langPair, _key);
_requestUrl = EnumStringUtil.GetStringValue(BASEURL.TRANSLATE) + encodedRequestUrlFragment;
GetTranslation();
}
public string Translation
{
get { return _translation; }
private set { _translation = value; }
}
private void GetTranslation()
{
try
{
WebRequest request = WebRequest.Create(_requestUrl);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadLine();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(Translation));
Translation translation = ser.ReadObject(ms) as Translation;
_translation = translation.responseData.translatedText;
}
}
catch (Exception) { }
}
}
}
Fast answer: NTextCat (NuGet, Online Demo)
Long answer:
Currently the best way seems to use classifiers trained to classify piece of text into one (or more) of languages from predefined set.
There is a Perl tool called TextCat. It has language models for 74 most popular languages. There is a huge number of ports of this tool into different programming languages.
There were no ports in .Net. So I have written one: NTextCat on GitHub.
It is pure .NET Framework DLL + command line interface to it. By default, it uses a profile of 14 languages.
Any feedback is very appreciated!
New ideas and feature requests are welcomed too :)
Alternative is to use numerous online services (e.g. one from Google mentioned, detectlanguage.com, langid.net, etc.).
A statistical approach using digraphs or trigraphs is a very good indicator. For example, here are the most common digraphs in English in order: http://www.letterfrequency.org/#digraph-frequency (one can find better or more complete lists). This method may have a better success rate than word analysis for short snippets of text because there are more digraphs in text than there are complete words.
If you mean the natural (ie human) language, this is in general a Hard Problem. What language is "server" - English or Turkish? What language is "chat" - English or French? What language is "uno" - Italian or Spanish (or Latin!) ?
Without paying attention to context, and doing some hard natural language processing (<----- this is the phrase to google for) you haven't got a chance.
You might enjoy a look at Frengly - it's a nice UI onto the Google Translate service which attempts to guess the language of the input text...
Make a statistical analyses of the string: Split the string into words. Get a dictionary for every language you want to test for. And then find the language that has the highest word count.
In C# every string in memory will be unicode, and is not encoded. Also in text files the encoding is not stored. (Sometimes only an indication of 8-bit or 16-bit).
If you want to make a distinction between two languages, you might find some simple tricks. For example if you want to recognize English from Dutch, the string that contains the "y" is mostly English. (Unreliable but fast).
CLD3 (Compact Language Detector v3) library from Google's Chromium browser
You could wrap the CLD3 library, which is written in C++.
We can use Regex.IsMatch(text, "[\\uxxxx-\\uxxxx]+") to detect an specific language. Here xxxx is the 4 digit Unicode id of a character.
To detect Arabic:
bool isArabic = Regex.IsMatch(yourtext, #"[\u0600-\u06FF]+")
You may use the C# package for language identification from Microsoft Research:
This package implements several algorithms for language
identification, and includes two sets of pre-compiled language
profiles. One set covers 52 languages and was trained on Wikipedia
(i.e. a well-written corpus); the other covers 26 languages and was
constructed from Twitter (i.e. a highly colloquial corpus). The
language identifiers are packaged up as a C# library, and be easily
embedded into other C# projects.
Download the package from the above link.
One alternative is to use 'Translator Text API' which is
... part of the Azure Cognitive Services API collection of machine
learning and AI algorithms in the cloud, and is readily consumable in
your development projects
Here's a quickstart guide on how to detect language from text using this API

How to create transform for .msi file using c#

I'm trying to create a transform for .msi file in C#. Here is my code:
public static void CreateTransforms(string original_MSI, string backup_MSI, string MSTpath, string query)
{
File.Copy(original_MSI, backup_MSI, true);
using (var origDatabase = new Microsoft.Deployment.WindowsInstaller.Database(original_MSI, DatabaseOpenMode.ReadOnly))
{
using (var database = new Microsoft.Deployment.WindowsInstaller.Database(backup_MSI, DatabaseOpenMode.Direct))
{
//database.Execute("Update `Property` Set `Property`.`Value` = 'Test' WHERE `Property`.`Property` = 'ProductName'");
database.Execute(query);
database.GenerateTransform(origDatabase, MSTpath);
database.CreateTransformSummaryInfo(origDatabase, MSTpath, TransformErrors.None, TransformValidations.None);
}
}
}
I got the following error : "This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package." in the step create transform summary info. I used "Microsoft.Deployment.WindowsInstaller.dll" library. Any help would be great.
A quick read of this static method looked correct so I created a console app out of it. It works fine for me on my machine. I would look at your calling method and make sure the data being passed is correct. I get really nervous any time I have a method that takes 4 strings as arguments as that leaves a lot to desire in terms of type safety.
when CreateTransforms start, it open database and it does not close it ...
you must commit and close the database before apply a new transform!
database.GenerateTransform(origDatabase, TRANSFORM);
database.CreateTransformSummaryInfo(origDatabase, TRANSFORM, TransformErrors.None, TransformValidations.None);
database.Commit();
database.Close();

Add an attachment to Bugzilla using XML-RPC in VBA

I am currently developing an Excel macro which allows creating Bugs in a Bugzilla instance.
After some trial and error this now turns out to work fine.
I wanted to enhance the client so that it's also possible to add screenshots to the newly created bug.
The environment I'm using is a little bit tricky:
I have to use MS Excel for my task.
As Excel does not understand XML-RPC, I downloaded an interface DLL (CookComputing.XmlRpcV2.dll from xml-rpc.net) which makes the XML-RPC interface accessible from .NET.
Then I created an additional DLL which can be called from Excel macros (using COM interop).
As already mentioned, this is working fine for tasks like browsing or adding new bugs.
But when adding an attachment to the bug, the image must be converted into a base64 data type. Although this seems to work fine and although the creation of the screenshot seems to succeed, the image seems to be corrupted and cannot be displayed.
Here's what I do to add the image:
The Bugzilla add_attachment method accepts a struct as input:
http://www.bugzilla.org/docs/4.0/en/html/api/Bugzilla/WebService/Bug.html#add_attachment.
This type was defined in C# and is visible also in VBA.
This is the struct definition:
[ClassInterface(ClassInterfaceType.AutoDual)]
public class TAttachmentInputData
{
public string[] ids;
public string data; // base64-encoded data
public string file_name;
public string summary;
public string content_type;
public string comment;
public bool is_patch;
public bool is_private;
public void addId(int id)
{
ids = new string[1];
ids[0] = id.ToString();
}
public void addData(string strData)
{
try
{
byte[] encData_byte = new byte[strData.Length];
encData_byte = System.Text.Encoding.ASCII.GetBytes(strData);
string encodedData = Convert.ToBase64String(encData_byte);
data = new Byte[System.Text.Encoding.ASCII.GetBytes(encodedData).Length];
data = System.Text.Encoding.ASCII.GetBytes(encodedData);
}
catch (Exception e)
{
throw new Exception("Error in base64Encode" + e.Message);
}
}
This is the part in my macro where I would like to add the attachment:
Dim attachmentsStruct As New TAttachmentInputData
fname = attachmentFileName
attachmentsStruct.file_name = GetFilenameFromPath(fname)
attachmentsStruct.is_patch = False
attachmentsStruct.is_private = False
'multiple other definitions
Open fname For Binary As #1
attachmentsStruct.addData (Input(LOF(1), #1))
Close #1
attachmentsStruct.file_name = GetFilenameFromPath(fname)
Call BugzillaClass.add_attachment(attachmentsStruct)
Where BugzillaClass it the interface exposed from my DLL to Excel VBA.
The method add_attachment refers to the XML-RPC method add_attachment.
I assume that my problem is the conversion from the binary file into base64.
This is done using the addData method in my C# DLL.
Is the conversion done correctly there?
Any idea why the images are corrupted?
I think the issue is that you are reading in binary data in the macro, but the addData method is expecting a string. Try declaring the parameter in addData as byte[].

Categories