Creation of torrent using monotorrent - c#

I am trying to create a torrent file with monotorrent package using C#.
I already created the torrent file with the torrent creator but I want to add some other options that I can't find in the torrent creator methods or properties.
Options that I am looking for :
adding tracking url(S),
Web seed URL(S),
Source,
Optimize alignment.
Here is a snippet of my code:
string filepath = ofd.FileName;
PathDirectoryTxt.Text = filepath;
MonoTorrent.Common.TorrentCreator torrentcreaotr = new MonoTorrent.Common.TorrentCreator();
ITorrentFileSource fileSource = new TorrentFileSource(filepath);
torrentcreaotr.Comment = CommentsRichTxt.Text;
torrentcreaotr.CreatedBy = "Google using " + VersionInfo.ClientVersion;
torrentcreaotr.Publisher = "www.itsitus.com";
if ((PrivateTorrentCheckbox.Checked))
{
torrentcreaotr.Private = true;
}
else if (!PrivateTorrentCheckbox.Checked)
{
torrentcreaotr.Private = false;
}
string savepath = sfd.FileName;
torrentcreaotr.Create(fileSource, savepath);
MessageBox.Show("torrent file has been created successfully !");

Have you tried setting the 'Announce' property with the URL for your tracker, or setting the 'Announces' if you have tracker tiers/fallbacks? Similarly, Webseeds are set using the GetrightHttpSeed property.

Related

Save browser data in CefSharp

I have an Windows Form Application which utilises CefSharp.
A while ago I used a chunk of code that saves the state of the browser such as login details etc so that the user does not have to log in multiple times.
This is the code I used:
private static bool _hasRun;
CefSettings settings = new CefSettings();
if (!_hasRun)
{
Cef.Initialize(new CefSettings { CachePath = "MyCachePath", PersistSessionCookies = true });
}
_hasRun = true;
string cache_dir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\CEF";
settings.CachePath = cache_dir;
settings.CefCommandLineArgs.Add("persist_session_cookies", "1");
string link = Domain;
chrome = new ChromiumWebBrowser(link);
this.tabPage2.Controls.Add(chrome);
chrome.Dock = DockStyle.Fill;
This code runs fine in my old application but when using this on my most recent app I receive this error message:
Any suggestions?
You must provide a full path.
non-absolute: "MyCachepath"
absolute: "C:\users\username\documents\MyCachepath"
why did it work in older projects?
Some project types and versions automaticallly translate an relative path into an absolute path like so:
environment.CurrentDirectory + #"\MyCachepath"

automate downloading a file using c# programmatically

I have a project where I need to automatically download and process an excel file from a public web site.
the site is the following:
http://apps.ahca.myflorida.com/dm_web/(S(rhlzd0ac2qwvvccbyp3lx2or))/doc_results_fo.aspx
you can see a link called Export Results which downloads the excel file. This link does a postback and I have been looking all over the place to find a way to automate it without success.
This is the last code I tried:
try
{
byte[] b = webClient.DownloadData("http://apps.ahca.myflorida.com/dm_web/(S(eha2oijpqo5mro1aywok4lly))/doc_results_fo.aspx");
string s = System.Text.Encoding.UTF8.GetString(b);
var __EVENTVALIDATION = ExtractVariable(s, "__EVENTVALIDATION");
var forms = new NameValueCollection();
forms["__EVENTTARGET"] = "lbtSpreadsheet";
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = ExtractVariable(s, "__VIEWSTATE");
forms["mTbdate"] = "11%2F15%2F2011";
forms["__EVENTVALIDATION"] = __EVENTVALIDATION;
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var responseData = webClient.UploadValues(#"http://apps.ahca.myflorida.com/dm_web/(S(eha2oijpqo5mro1aywok4lly))/doc_results_fo.aspx", "POST", forms);
System.IO.File.WriteAllBytes(#"c:\tmp\FLORIDA.xls", responseData);
}
catch (Exception ex)
{
Console.Write(ex.StackTrace);
}
}
private static string ExtractVariable(string s, string valueName)
{
string tokenStart = valueName + "\" value=\"";
string tokenEnd = "\" />";
int start = s.IndexOf(tokenStart) + tokenStart.Length;
int length = s.IndexOf(tokenEnd, start) - start;
return s.Substring(start, length);
}
This is supposed to get the value of view state and other fields and issue a POST , but when I run it the file that gets downloaded is the page itself and not the excel file.
I am not sure if this is possible using WebClient, or I should use WebBrowser control (or similar controls), or maybe an atomated browsing tool that I can record a sequence of steps and run it every x days.
Any help will be greatly appreciated.
Thank you
I figured it out using Selenium .NET
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.SetPreference("browser.download.folderList", 2);
firefoxProfile.SetPreference("browser.download.dir", strFullpath);
firefoxProfile.SetPreference("browser.helperApps.neverAsk.openFile", "application/vnd.ms-Excel");
firefoxProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms-Excel");
IWebDriver driver = new FirefoxDriver(firefoxProfile);
driver.Navigate().GoToUrl(link);
driver.FindElement(By.Id(lookup)).Click();
driver.Quit();

Cannot upload Image to a SharePoint List

I'm working with a Visual WebPart and I want to upload a image from my FileUpload control to a SharePoint list. This is the code I'm using but I can't get it to work, (Title, prodnum, color, etc is working, but not image). I've also installed SparQube.
This is my ListView:
.
protected void Button_Save_Click(object sender, EventArgs e)
{
SPSite currentSite = SPContext.Current.Site;
SPList myList = currentSite.RootWeb.Lists.TryGetList("SharePointDatabase");
try
{
if (myList != null && FileUpload_Pic.PostedFile != null && FileUpload_Pic.HasFile)
{
SPListItem listItem = myList.Items.Add();
listItem["Title"] = TextBox_Name.Text;
listItem["ProductNumber"] = TextBox_ProdNum.Text;
listItem["Color"] = TextBox_Color.Text;
listItem["ListPrice"] = TextBox_ListPrice.Text;
listItem["MoreInformation"] = TextBox_MoreInfo.Text;
string fileName = Path.GetFileName(FileUpload_Pic.PostedFile.FileName);
listItem["Image"] = fileName;
listItem.Update();
TextBox_Search.Text = string.Empty;
TextBox_Name.Text = string.Empty;
TextBox_MoreInfo.Text = string.Empty;
TextBox_ProdNum.Text = string.Empty;
TextBox_Color.Text = string.Empty;
TextBox_ListPrice.Text = string.Empty;
Label_Exception.Text = "Saved to Database list.";
Dispose();
}
}
catch (Exception x)
{
Label_Exception.Text = x.Message;
}
}
You can add file as stream directly from File Upload to specific web using following method and then add the file path to the list as shown in below example,
SPContext.Current.Web.Files.Add(String.Concat(SPContext.Current.Web.Site.RootWeb.Url, path), stream, true);
path is relative path for the image. in user case file name.
stream can get using FileUpload.FileContent in file upload control
Then add this path to the list as below.
listItem["Image"] = path;
This is work for all the browsers.
Are you sure the SPList has Atachment Upload enabled?
I had made the expierience that the normal ribbon button isn't greyed out although the list is not able to hold itemattachments.
SPList list = new SPList(); // Sample
list.EnableAttachments = false; //set
bool attachmentsAllowed = list.EnableAttachments; //get
What Type of field is "Image"? It's not the attachments folder...
An other way to save your Image is to upload it to a library and use a "Hyperlink" field.
Use this as help: http://www.sharepoint-tips.com/2007/10/code-practices-gettingsetting-values.html
Check out this question: https://sharepoint.stackexchange.com/questions/49481/exception-when-adding-attachment/49485
There are some problems, when you are using FileUpload control in standard edit/add pages.

.Net library to move / copy a file while preserving timestamps

Does anyone know of a .Net library where a file can be copied / pasted or moved without changing any of the timestamps. The functionality I am looking for is contained in a program called robocopy.exe, but I would like this functionality without having to share that binary.
Thoughts?
public static void CopyFileExactly(string copyFromPath, string copyToPath)
{
var origin = new FileInfo(copyFromPath);
origin.CopyTo(copyToPath, true);
var destination = new FileInfo(copyToPath);
destination.CreationTime = origin.CreationTime;
destination.LastWriteTime = origin.LastWriteTime;
destination.LastAccessTime = origin.LastAccessTime;
}
When executing without administrative privileges Roy's answer will throw an exception (UnauthorizedAccessException) when attempting to overwrite existing read only files or when attempting to set the timestamps on copied read only files.
The following solution is based on Roy's answer but extends it to overwrite read only files and to change the timestamps on copied read only files while preserving the read only attribute of the file all while still executing without admin privilege.
public static void CopyFileExactly(string copyFromPath, string copyToPath)
{
if (File.Exists(copyToPath))
{
var target = new FileInfo(copyToPath);
if (target.IsReadOnly)
target.IsReadOnly = false;
}
var origin = new FileInfo(copyFromPath);
origin.CopyTo(copyToPath, true);
var destination = new FileInfo(copyToPath);
if (destination.IsReadOnly)
{
destination.IsReadOnly = false;
destination.CreationTime = origin.CreationTime;
destination.LastWriteTime = origin.LastWriteTime;
destination.LastAccessTime = origin.LastAccessTime;
destination.IsReadOnly = true;
}
else
{
destination.CreationTime = origin.CreationTime;
destination.LastWriteTime = origin.LastWriteTime;
destination.LastAccessTime = origin.LastAccessTime;
}
}
You can read and write all the timestamps there are, using the FileInfo class:
CreationTime
LastAccessTime
LastWriteTime
You should be able to read the values you need, make whatever changes you wish and then restore the previous values by using the properties of FileInfo.

Creating application shortcut in a directory

How do you create an application shortcut (.lnk file) in C# or using the .NET framework?
The result would be a .lnk file to the specified application or URL.
It's not as simple as I'd have liked, but there is a great class call ShellLink.cs at
vbAccelerator
This code uses interop, but does not rely on WSH.
Using this class, the code to create the shortcut is:
private static void configStep_addShortcutToStartupGroup()
{
using (ShellLink shortcut = new ShellLink())
{
shortcut.Target = Application.ExecutablePath;
shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
shortcut.Description = "My Shorcut Name Here";
shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
shortcut.Save(STARTUP_SHORTCUT_FILEPATH);
}
}
Nice and clean. (.NET 4.0)
Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
dynamic shell = Activator.CreateInstance(t);
try{
var lnk = shell.CreateShortcut("sc.lnk");
try{
lnk.TargetPath = #"C:\something";
lnk.IconLocation = "shell32.dll, 1";
lnk.Save();
}finally{
Marshal.FinalReleaseComObject(lnk);
}
}finally{
Marshal.FinalReleaseComObject(shell);
}
That's it, no additional code needed. CreateShortcut can even load shortcut from file, so properties like TargetPath return existing information. Shortcut object properties.
Also possible this way for versions of .NET unsupporting dynamic types. (.NET 3.5)
Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
object shell = Activator.CreateInstance(t);
try{
object lnk = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[]{"sc.lnk"});
try{
t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[]{#"C:\whatever"});
t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[]{"shell32.dll, 5"});
t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null);
}finally{
Marshal.FinalReleaseComObject(lnk);
}
}finally{
Marshal.FinalReleaseComObject(shell);
}
I found something like this:
private void appShortcutToDesktop(string linkName)
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
{
string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + app);
writer.WriteLine("IconIndex=0");
string icon = app.Replace('\\', '/');
writer.WriteLine("IconFile=" + icon);
writer.Flush();
}
}
Original code at sorrowman's article "url-link-to-desktop"
After surveying all possibilities I found on SO I've settled on ShellLink:
//Create new shortcut
using (var shellShortcut = new ShellShortcut(newShortcutPath)
{
Path = path
WorkingDirectory = workingDir,
Arguments = args,
IconPath = iconPath,
IconIndex = iconIndex,
Description = description,
})
{
shellShortcut.Save();
}
//Read existing shortcut
using (var shellShortcut = new ShellShortcut(existingShortcut))
{
path = shellShortcut.Path;
args = shellShortcut.Arguments;
workingDir = shellShortcut.WorkingDirectory;
...
}
Apart of being simple and effective, the author (Mattias Sjögren, MS MVP) is some sort of COM/PInvoke/Interop guru, and perusing his code I believe it is more robust than the alternatives.
It should be mentioned that shortcut files can also be created by several commandline utilities (which in turn can be easily invoked from C#/.NET). I never tried any of them, but I'd start with NirCmd (NirSoft have SysInternals-like quality tools).
Unfortunately NirCmd can't parse shortcut files (only create them), but for that purpose TZWorks lp seems capable. It can even format its output as csv. lnk-parser looks good too (it can output both HTML and CSV).
Donwload IWshRuntimeLibrary
You also need to import of COM library IWshRuntimeLibrary. Right click on your project -> add reference -> COM -> IWshRuntimeLibrary -> add and then use the following code snippet.
private void createShortcutOnDesktop(String executablePath)
{
// Create a new instance of WshShellClass
WshShell lib = new WshShellClass();
// Create the shortcut
IWshRuntimeLibrary.IWshShortcut MyShortcut;
// Choose the path for the shortcut
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
MyShortcut = (IWshRuntimeLibrary.IWshShortcut)lib.CreateShortcut(#deskDir+"\\AZ.lnk");
// Where the shortcut should point to
//MyShortcut.TargetPath = Application.ExecutablePath;
MyShortcut.TargetPath = #executablePath;
// Description for the shortcut
MyShortcut.Description = "Launch AZ Client";
StreamWriter writer = new StreamWriter(#"D:\AZ\logo.ico");
Properties.Resources.system.Save(writer.BaseStream);
writer.Flush();
writer.Close();
// Location for the shortcut's icon
MyShortcut.IconLocation = #"D:\AZ\logo.ico";
// Create the shortcut at the given path
MyShortcut.Save();
}
Similar to IllidanS4's answer, using the Windows Script Host proved the be the easiest solution for me (tested on Windows 8 64 bit).
However, rather than importing the COM type manually through code, it is easier to just add the COM type library as a reference. Choose References->Add Reference..., COM->Type Libraries and find and add "Windows Script Host Object Model".
This imports the namespace IWshRuntimeLibrary, from which you can access:
WshShell shell = new WshShell();
IWshShortcut link = (IWshShortcut)shell.CreateShortcut(LinkPathName);
link.TargetPath=TargetPathName;
link.Save();
Credit goes to Jim Hollenhorst.

Categories

Resources